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.

test(api): cover the scene gate, share card, forged feed, skills catalog and stage host contracts

nirholas331026448ca0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ba166a415..bb71dca0d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-08-16
- **A mistyped id on the signal marketplace answers plainly, and the live feed links to the right chain**: The signal marketplace identifies a feed or a subscription by a number. Anything that was not one (a typo, a stray word, an empty box) went straight to the database, which threw the whole query out, so the caller got an opaque "something went wrong" and our alerting recorded a fault that was never a fault. Pausing a feed, killing or resyncing a subscription, and subscribing to a feed each now answer with a plain "that is not a valid id" instead. Separately, the paid live signal stream built its Solscan links from whichever network the request named rather than the one the feed actually publishes on, so a subscriber could be handed devnet explorer links for a mainnet call; the feed's own record now decides, and every proof link lands on the chain the trade really happened on. (`/signals`) `[fix]`
+- **An expired X connection now offers to reconnect instead of sending you to the login page**: Posting a Walk screenshot or clip to X goes through your connected X account. When that connection could no longer be renewed, the share endpoint answered with the same code it uses for a signed-out visitor, so the capture panel told an already signed-in user to sign in to three.ws and linked them to the login page, which fixed nothing. That case now comes back as its own answer with the X connect link attached, and the panel offers a Reconnect X button that takes you straight to the flow that repairs it. The share caption also lost a stray dash. (`/walk`) `[fix]`
- **Avatar Studio trait library: the mirror can no longer be pointed at someone else's server**: Avatar Studio loads its hair, clothing and accessory traits through a three.ws address that mirrors the open-source trait library, so your browser never talks to an outside CDN. The list of where those traits live was being written using the address in the incoming request, and that address can be set by whoever sends the request. Because the mirror is cached at the edge for a day, one crafted request could have left every Avatar Studio visitor loading trait files from a stranger's server for the next 24 hours. That list is now written the same way for everybody, with no part of it taken from the request, so there is nothing left to steer. Three smaller repairs went in alongside it: asking the mirror how big a file is no longer answers with the compressed size (a trait manifest claimed 2 KB and delivered 20 KB), the mirror will not hand back a web page or script even if the upstream library ever served one, and a failure at the library now answers plainly as either not found or mirror is down instead of passing its raw status through as ours. (`/avatar-studio`) `[security, fix]`
- **Live stage hosts stop swallowing hyphens, and only confirmed tippers get greeted by name**: Two repairs to the Living Stages host. The cleanup pass that tidies the host's spoken line was stripping hyphens along with the invisible characters it was meant to remove, so every show heard "on chain" where the host said "on-chain" and "state of the art" for "state-of-the-art"; punctuation now survives and only invisible characters are removed. Separately, the host's memory of returning regulars counted tips whose on-chain settlement had not been confirmed yet, which meant anyone could post an unconfirmed tip under a name of their choosing and hear the host greet it aloud. That memory now reads confirmed tips only, matching the public leaderboard. Smaller repairs in the same pass: a stage that has not opened its first show is no longer cached as empty at the edge, an over-long coin address is refused instead of quietly trimmed into a different plaza, and the running tip total is written before the response returns. (`/stage`) `[fix, security]`
- **Memory seeding reads Farcaster with no vendor key, and X now works from the app credentials we already hold**: The memory-seeding demo asks a GitHub, X or Farcaster handle what it can learn about you in public, then writes a short memory seed your agent can carry. Two of those three connectors were showing a "connector not configured" card to everyone, because each insisted on a vendor key nobody had set. Farcaster now reads through the same failover the rest of the platform uses: an indexer when a key exists, and a public Farcaster hub with no key at all otherwise, so it returns real profiles and casts on any deployment. Anything the keyless lane genuinely cannot know, such as follower counts, is now shown as unknown instead of zero. The X connector accepts the app key and secret the platform already stores, exchanging them for a read-only token itself, so it no longer needs a separate token provisioned by hand. A mistyped Farcaster name now comes back as not found rather than as an upstream outage, and all four endpoints are documented in the API reference for the first time. (`/demos/memory-seed`) `[fix, improvement, docs]`
diff --git a/chat/src/SkillsMarketplaceModal.svelte b/chat/src/SkillsMarketplaceModal.svelte
index ae8d8ff13..00060add5 100644
--- a/chat/src/SkillsMarketplaceModal.svelte
+++ b/chat/src/SkillsMarketplaceModal.svelte
@@ -293,6 +293,20 @@
// install / uninstall
+ // Install/uninstall are cookie-session mutations, so the API requires a
+ // single-use CSRF token (api/_lib/csrf.js). Tokens are consumed per request,
+ // so this always mints a fresh one rather than caching.
+ async function csrfToken() {
+ try {
+ const r = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) return null;
+ const j = await r.json();
+ return j?.data?.token ?? j?.token ?? null;
+ } catch {
+ return null;
+ }
+ }
+
async function toggleInstall(skill, e) {
e?.stopPropagation();
if (!$currentUser) { notify('Sign in to install skills', 'info'); return; }
@@ -327,7 +341,12 @@
try {
const method = wasInstalled ? 'DELETE' : 'POST';
- const res = await fetch(`/api/skills/${skill.id}/install`, { method, credentials: 'include' });
+ const csrf = await csrfToken();
+ const res = await fetch(`/api/skills/${skill.id}/install`, {
+ method,
+ credentials: 'include',
+ headers: csrf ? { 'x-csrf-token': csrf } : {},
+ });
if (!res.ok) throw new Error('Request failed');
if (!wasInstalled) {
const data = await res.json().catch(() => null);
diff --git a/data/changelog.json b/data/changelog.json
index 945df7312..22a2bda25 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": "An expired X connection now offers to reconnect instead of sending you to the login page",
+ "summary": "Posting a Walk screenshot or clip to X goes through your connected X account. When that connection could no longer be renewed, the share endpoint answered with the same code it uses for a signed-out visitor, so the capture panel told an already signed-in user to sign in to three.ws and linked them to the login page, which fixed nothing. That case now comes back as its own answer with the X connect link attached, and the panel offers a Reconnect X button that takes you straight to the flow that repairs it. The share caption also lost a stray dash.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/walk"
+ },
{
"date": "2026-08-16",
"title": "The wallet balance API stops calling a rejected upload a validation error",
diff --git a/prompts/swarm-100/api-skills-01.md b/prompts/swarm-100/api-skills-01.md
deleted file mode 100644
index cd06df44c..000000000
--- a/prompts/swarm-100/api-skills-01.md
+++ /dev/null
@@ -1,108 +0,0 @@
-# API audit: api/skills batch 01 (8 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/skills/[id].js
-- api/skills/[id]/install.js
-- api/skills/[id]/rate.js
-- api/skills/categories.js
-- api/skills/index.js
-- api/skills/license-onchain.js
-- api/skills/mint.js
-- api/skills/review.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-skills-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/public/changelog.json b/public/changelog.json
index f5282f828..356ba5dc8 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-16T07:20:44.194Z",
+ "generated_at": "2026-08-16T07:25:09.580Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,16 @@
"fix"
]
},
+ {
+ "date": "2026-08-16",
+ "type": "update",
+ "title": "An expired X connection now offers to reconnect instead of sending you to the login page",
+ "summary": "Posting a Walk screenshot or clip to X goes through your connected X account. When that connection could no longer be renewed, the share endpoint answered with the same code it uses for a signed-out visitor, so the capture panel told an already signed-in user to sign in to three.ws and linked them to the login page, which fixed nothing. That case now comes back as its own answer with the X connect link attached, and the panel offers a Reconnect X button that takes you straight to the flow that repairs it. The share caption also lost a stray dash.",
+ "link": "/walk",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-08-16",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index d2e911986..1dc8f2f34 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>fix</category>
<description>The signal marketplace identifies a feed or a subscription by a number. Anything that was not one (a typo, a stray word, an empty box) went straight to the database, which threw the whole query out, so the caller got an opaque &quot;something went wrong&quot; and our alerting recorded a fault that was never a fault. Pausing a feed, killing or resyncing a subscription, and subscribing to a feed each now answer with a plain &quot;that is not a valid id&quot; instead. Separately, the paid live signal stream built its Solscan links from whichever network the request named rather than the one the feed actually publishes on, so a subscriber could be handed devnet explorer links for a mainnet call; the feed's own record now decides, and every proof link lands on the chain the trade really happened on.</description>
</item>
+ <item>
+ <title>An expired X connection now offers to reconnect instead of sending you to the login page</title>
+ <link>https://three.ws/walk</link>
+ <guid isPermaLink="false">2026-08-16:An expired X connection now offers to reconnect instead of sending you to the login page</guid>
+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Posting a Walk screenshot or clip to X goes through your connected X account. When that connection could no longer be renewed, the share endpoint answered with the same code it uses for a signed-out visitor, so the capture panel told an already signed-in user to sign in to three.ws and linked them to the login page, which fixed nothing. That case now comes back as its own answer with the X connect link attached, and the panel offers a Reconnect X button that takes you straight to the flow that repairs it. The share caption also lost a stray dash.</description>
+ </item>
<item>
<title>Avatar Studio trait library: the mirror can no longer be pointed at someone else's server</title>
<link>https://three.ws/avatar-studio</link>
diff --git a/public/features.json b/public/features.json
index f764b5152..6008f0d77 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-08-16T07:20:43.954Z",
+ "generated_at": "2026-08-16T07:25:09.436Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/marketplace.js b/src/marketplace.js
index 3dd918a30..8a6be7cba 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -17,6 +17,7 @@ import {
bindMobileSidebar,
bindDetailExtras,
} from './marketplace-detail.js';
+import { consumeCsrfToken } from './api.js';
import { onchainBadgeHTML } from './shared/onchain-badge.js';
import { safeUrl } from './safe-url.js';
import { walletChipHTML, walletChipEl, wireWalletChips } from './shared/agent-wallet-chip.js';
@@ -2762,9 +2763,13 @@ async function toggleSkillInstall(id) {
btn.disabled = true;
btn.textContent = wasInstalled ? 'Removing…' : 'Installing…';
try {
+ // Install/uninstall are cookie-session mutations: the API requires a
+ // single-use CSRF token (api/_lib/csrf.js).
+ const csrf = await consumeCsrfToken().catch(() => null);
const r = await fetch(`${API}/skills/${encodeURIComponent(id)}/install`, {
method: wasInstalled ? 'DELETE' : 'POST',
credentials: 'include',
+ headers: csrf ? { 'x-csrf-token': csrf } : {},
});
if (r.status === 401) {
location.href = `/login?next=${encodeURIComponent(location.pathname + location.search)}`;
diff --git a/tests/api-agent-memory.test.js b/tests/api-agent-memory.test.js
index e051eeaf3..4f124b74d 100644
--- a/tests/api-agent-memory.test.js
+++ b/tests/api-agent-memory.test.js
@@ -105,7 +105,7 @@ describe('agent-memory auth', () => {
it('GET without session or bearer returns empty list (200)', async () => {
// Public embeds boot this fetch on every page load. Returning an empty
// list (instead of 401) keeps the console clean for anonymous viewers.
- const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111' });
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
@@ -116,7 +116,7 @@ describe('agent-memory auth', () => {
const req = mkReq({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { content: 'hi' } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { content: 'hi' } },
});
const res = mkRes();
await handler(req, res);
@@ -124,7 +124,7 @@ describe('agent-memory auth', () => {
});
it('DELETE without auth returns 401', async () => {
- const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/mem-1' });
+ const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/33333333-3333-4333-8333-333333333333' });
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(401);
@@ -135,7 +135,7 @@ describe('agent-memory auth', () => {
authenticateBearerMock.mockResolvedValue({ userId: 'u1' });
queueSql([{ user_id: 'u1' }], []); // ownership check, then list
- const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111' });
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
@@ -174,7 +174,7 @@ describe('agent-memory validation', () => {
const req = mkReq({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1' },
+ body: { agentId: '11111111-1111-4111-8111-111111111111' },
});
const res = mkRes();
await handler(req, res);
@@ -184,7 +184,7 @@ describe('agent-memory validation', () => {
it('GET for nonexistent agent returns empty list (200)', async () => {
queueSql([]); // no agent row
- const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=missing' });
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=44444444-4444-4444-8444-444444444444' });
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
@@ -193,7 +193,7 @@ describe('agent-memory validation', () => {
it('GET for agent owned by another user returns empty list (200)', async () => {
queueSql([{ user_id: 'someone-else' }]);
- const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111' });
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
@@ -222,7 +222,7 @@ describe('agent-memory list', () => {
[
{
id: 'm1',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'project',
content: 'note',
tags: ['t'],
@@ -234,7 +234,7 @@ describe('agent-memory list', () => {
],
);
- const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111' });
const res = mkRes();
await handler(req, res);
@@ -243,7 +243,7 @@ describe('agent-memory list', () => {
expect(body.entries).toHaveLength(1);
expect(body.entries[0]).toMatchObject({
id: 'm1',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'project',
content: 'note',
tags: ['t'],
@@ -256,7 +256,7 @@ describe('agent-memory list', () => {
it('applies type filter when provided', async () => {
queueSql([{ user_id: 'u1' }], []);
- const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1&type=feedback' });
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111&type=feedback' });
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
@@ -270,7 +270,7 @@ describe('agent-memory list', () => {
[
{
id: 'm2',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'user',
content: '',
tags: null,
@@ -281,7 +281,7 @@ describe('agent-memory list', () => {
},
],
);
- const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111' });
const res = mkRes();
await handler(req, res);
const body = parseBody(res);
@@ -304,7 +304,7 @@ describe('agent-memory upsert', () => {
[
{
id: 'generated-id',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'project',
content: 'hello',
tags: [],
@@ -319,7 +319,7 @@ describe('agent-memory upsert', () => {
const req = mkReq({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { content: 'hello' } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { content: 'hello' } },
});
const res = mkRes();
await handler(req, res);
@@ -333,8 +333,8 @@ describe('agent-memory upsert', () => {
[{ user_id: 'u1' }],
[
{
- id: 'client-id',
- agent_id: 'a1',
+ id: '55555555-5555-4555-8555-555555555555',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'user',
content: 'c',
tags: [],
@@ -350,15 +350,15 @@ describe('agent-memory upsert', () => {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: {
- agentId: 'a1',
- entry: { id: 'client-id', type: 'user', content: 'c', salience: 0.9 },
+ agentId: '11111111-1111-4111-8111-111111111111',
+ entry: { id: '55555555-5555-4555-8555-555555555555', type: 'user', content: 'c', salience: 0.9 },
},
});
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(201);
- expect(parseBody(res).entry.id).toBe('client-id');
+ expect(parseBody(res).entry.id).toBe('55555555-5555-4555-8555-555555555555');
});
it('returns 409 when id collides with another agents memory', async () => {
@@ -368,7 +368,7 @@ describe('agent-memory upsert', () => {
const req = mkReq({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { id: 'stolen-id', content: 'x' } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { id: '66666666-6666-4666-8666-666666666666', content: 'x' } },
});
const res = mkRes();
await handler(req, res);
@@ -382,7 +382,7 @@ describe('agent-memory upsert', () => {
const req = mkReq({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { content: 'x' } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { content: 'x' } },
});
const res = mkRes();
await handler(req, res);
@@ -395,7 +395,7 @@ describe('agent-memory upsert', () => {
[
{
id: 'm1',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'project', // server normalized
content: 'x',
tags: [],
@@ -410,7 +410,7 @@ describe('agent-memory upsert', () => {
const req = mkReq({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { type: 'not-a-real-type', content: 'x' } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { type: 'not-a-real-type', content: 'x' } },
});
const res = mkRes();
await handler(req, res);
@@ -427,8 +427,8 @@ describe('agent-memory delete', () => {
});
it('deletes a memory owned by the user', async () => {
- queueSql([{ id: 'mem-1', user_id: 'u1' }], []); // lookup, then delete
- const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/mem-1' });
+ queueSql([{ id: '33333333-3333-4333-8333-333333333333', user_id: 'u1' }], []); // lookup, then delete
+ const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/33333333-3333-4333-8333-333333333333' });
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
@@ -437,15 +437,15 @@ describe('agent-memory delete', () => {
it('returns 404 for nonexistent memory', async () => {
queueSql([]);
- const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/nope' });
+ const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/77777777-7777-4777-8777-777777777777' });
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(404);
});
it('returns 403 when memory belongs to another user', async () => {
- queueSql([{ id: 'mem-1', user_id: 'other' }]);
- const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/mem-1' });
+ queueSql([{ id: '33333333-3333-4333-8333-333333333333', user_id: 'other' }]);
+ const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/33333333-3333-4333-8333-333333333333' });
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(403);
@@ -479,7 +479,7 @@ describe('agent-memory size + payload limits', () => {
return Promise.resolve([
{
id: 'x',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'project',
content: capturedContent,
tags: [],
@@ -494,7 +494,7 @@ describe('agent-memory size + payload limits', () => {
const req = mkReq({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { content: huge } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { content: huge } },
});
const res = mkRes();
await handler(req, res);
@@ -528,7 +528,7 @@ describe('agent-memory size + payload limits', () => {
it('caps list limit at 500', async () => {
queueSql([{ user_id: 'u1' }], []);
- const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=a1&limit=99999' });
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111&limit=99999' });
const res = mkRes();
await handler(req, res);
expect(res.statusCode).toBe(200);
@@ -549,3 +549,128 @@ describe('agent-memory CORS', () => {
expect(res.headers['access-control-allow-methods']).toMatch(/DELETE/);
});
});
+
+// ── Malformed input ───────────────────────────────────────────────────────
+//
+// agent_identities.id and agent_memories.id are uuid columns, and `since` /
+// `limit` are interpolated straight into the query. Every case below used to
+// reach Postgres (or `new Date().toISOString()`) with a value it rejects and
+// answer 500 for what is plainly a caller mistake. Where `sqlQueue` is left
+// empty the mock throws on any sql call, so these fail if validation ever stops
+// short-circuiting ahead of the query.
+
+const VALID_AGENT = '11111111-1111-4111-8111-111111111111';
+
+describe('agent-memory rejects malformed input before it reaches Postgres', () => {
+ beforeEach(() => {
+ getSessionUserMock.mockResolvedValue({ id: 'u1' });
+ });
+
+ it('GET with a non-uuid agentId returns 400', async () => {
+ const req = mkReq({ method: 'GET', url: '/api/agent-memory?agentId=not-a-uuid' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseBody(res).error_description).toMatch(/uuid/);
+ });
+
+ it('GET clamps an out-of-range since instead of throwing a RangeError', async () => {
+ queueSql([{ user_id: 'u1' }], []);
+ const req = mkReq({
+ method: 'GET',
+ url: `/api/agent-memory?agentId=${VALID_AGENT}&since=999999999999999999`,
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('GET falls back to the default for a negative limit', async () => {
+ queueSql([{ user_id: 'u1' }], []);
+ const req = mkReq({ method: 'GET', url: `/api/agent-memory?agentId=${VALID_AGENT}&limit=-1` });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ });
+
+ it('POST with a non-uuid agentId returns 400', async () => {
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: 'not-a-uuid', entry: { content: 'hi' } },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseBody(res).error_description).toMatch(/uuid/);
+ });
+
+ it('POST with a non-object entry returns 400', async () => {
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: VALID_AGENT, entry: 'oops' },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseBody(res).error_description).toMatch(/object/);
+ });
+
+ it('POST with a non-uuid entry.id returns 400', async () => {
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: VALID_AGENT, entry: { id: 'client-generated', content: 'hi' } },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseBody(res).error_description).toMatch(/entry\.id/);
+ });
+
+ it('POST with an unparseable timestamp returns 400', async () => {
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: { agentId: VALID_AGENT, entry: { content: 'hi', createdAt: 'not-a-date' } },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseBody(res).error_description).toMatch(/timestamps/);
+ });
+
+ it('POST coerces a string salience and non-array tags into column-safe values', async () => {
+ queueSql(
+ [{ user_id: 'u1' }],
+ [
+ {
+ id: '33333333-3333-4333-8333-333333333333',
+ agent_id: VALID_AGENT,
+ content: 'hi',
+ tags: [],
+ salience: 0.5,
+ },
+ ],
+ );
+ const req = mkReq({
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: {
+ agentId: VALID_AGENT,
+ entry: { content: 'hi', salience: 'very high', tags: 'not-an-array' },
+ },
+ });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(201);
+ });
+
+ it('DELETE with a non-uuid memory id returns 404', async () => {
+ const req = mkReq({ method: 'DELETE', url: '/api/agent-memory/not-a-uuid' });
+ const res = mkRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+});
diff --git a/tests/api-creations-gallery.test.js b/tests/api-creations-gallery.test.js
new file mode 100644
index 000000000..87d00262f
--- /dev/null
+++ b/tests/api-creations-gallery.test.js
@@ -0,0 +1,230 @@
+// /api/creations, the creator-gallery + remix-economy overlay on top of the
+// Loom feed. Covers the two defects the batch-05 API audit found, plus the
+// dispatcher's success and failure paths:
+//
+// 1. Aggregation depth. creations.js reads a SCAN_CAP (600) deep slice of the
+// Loom feed to rank creators and trending assets, but loom.readFeed used
+// to clamp EVERY caller to the public MAX_LIMIT (120). Creator counts and
+// gallery pagination silently stopped at 120 items no matter how much the
+// feed actually held.
+// 2. Overlay round-trips. Enriching that slice did a getMeta + getChildren
+// per creation. enrichAll batches both, so the shape it returns must stay
+// byte-identical to the per-item path it replaced.
+//
+// Redis is left unconfigured so both modules run on their documented in-process
+// fallback, which is the same code path dev and CI take.
+import { describe, it, expect, beforeAll } from 'vitest';
+
+const { writeCreation, readFeed } = await import('../api/loom.js');
+const { default: handler } = await import('../api/creations.js');
+
+const GLB = (n) => `https://three.ws/models/audit-${n}.glb`;
+
+function mkReq({ method = 'GET', url = '/api/creations', body = null } = {}) {
+ const headers = { host: 'three.ws' };
+ if (body != null) headers['content-type'] = 'application/json';
+ return {
+ method,
+ url,
+ headers,
+ body: body ?? undefined,
+ socket: { remoteAddress: '198.51.100.7' },
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ queueMicrotask(() => {
+ cb(Buffer.from(JSON.stringify(body)));
+ this._endCb?.();
+ });
+ } else if (event === 'end') {
+ this._endCb = cb;
+ if (body == null) queueMicrotask(() => cb());
+ }
+ },
+ };
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ chunks: [],
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ writeHead(code, headers = {}) {
+ this.statusCode = code;
+ for (const [k, v] of Object.entries(headers)) this.setHeader(k, v);
+ },
+ write(s) {
+ this.chunks.push(String(s));
+ return true;
+ },
+ end(b) {
+ if (b) this.chunks.push(String(b));
+ this.writableEnded = true;
+ },
+ get json() {
+ return JSON.parse(this.chunks.join(''));
+ },
+ };
+}
+
+async function call(opts) {
+ const res = mkRes();
+ await handler(mkReq(opts), res);
+ return res;
+}
+
+// 150 seeded creations: deliberately more than loom's public MAX_LIMIT (120) so
+// a re-introduced clamp shows up as a missing tail rather than a passing test.
+const SEEDED = 150;
+const OLDEST_AUTHOR = 'deep-catalog-creator';
+
+beforeAll(async () => {
+ for (let i = 0; i < SEEDED; i++) {
+ await writeCreation({
+ id: `audit-seed-${String(i).padStart(3, '0')}`,
+ prompt: `a stylized robot number ${i}`,
+ glbUrl: GLB(i),
+ previewImageUrl: null,
+ // The first writes are the OLDEST (writeCreation unshifts), so this
+ // author sits past the 120-item cut-off in the newest-first feed.
+ author: i < 5 ? OLDEST_AUTHOR : `creator-${i % 7}`,
+ tier: null,
+ backend: null,
+ createdAt: 1_700_000_000_000 + i * 1000,
+ });
+ }
+});
+
+describe('loom readFeed depth', () => {
+ it('honors an internal scan deeper than the public MAX_LIMIT', async () => {
+ const deep = await readFeed(600, NaN);
+ expect(deep.length).toBe(SEEDED);
+ });
+
+ it('still returns only what was asked for on a shallow read', async () => {
+ const shallow = await readFeed(10, NaN);
+ expect(shallow.length).toBe(10);
+ });
+});
+
+describe('/api/creations aggregation depth', () => {
+ it('counts creations past the 120-item mark for a creator', async () => {
+ const res = await call({ url: `/api/creations?op=creator&id=${OLDEST_AUTHOR}` });
+ expect(res.statusCode).toBe(200);
+ // All five of this author's items live in the oldest tail of the feed.
+ expect(res.json.creator.creationCount).toBe(5);
+ expect(res.json.creations).toHaveLength(5);
+ });
+
+ it('reports a total covering the whole scanned feed, so pagination reaches the tail', async () => {
+ const first = await call({ url: '/api/creations?limit=36' });
+ expect(first.json.total).toBe(SEEDED);
+ expect(first.json.hasMore).toBe(true);
+
+ const last = await call({ url: '/api/creations?limit=36&page=4' });
+ expect(last.json.creations.length).toBe(SEEDED - 4 * 36);
+ expect(last.json.hasMore).toBe(false);
+ });
+
+ it('aggregates every creator in the feed, not just the newest page', async () => {
+ const res = await call({ url: '/api/creations?op=creators&limit=50' });
+ expect(res.statusCode).toBe(200);
+ const keys = res.json.creators.map((c) => c.key);
+ expect(keys).toContain(OLDEST_AUTHOR);
+ const total = res.json.creators.reduce((n, c) => n + c.creationCount, 0);
+ expect(total).toBe(SEEDED);
+ });
+});
+
+describe('/api/creations publish and remix lineage', () => {
+ it('publishes, links a remix, and reflects the lineage in item + trending', async () => {
+ const parent = await call({
+ method: 'POST',
+ body: {
+ op: 'publish',
+ prompt: 'a lowpoly fantasy knight',
+ glbUrl: GLB('parent'),
+ author: 'audit-parent',
+ title: 'Knight',
+ tags: ['knight', 'armor'],
+ type: 'character',
+ style: 'lowpoly',
+ license: 'remix-royalty',
+ },
+ });
+ expect(parent.statusCode).toBe(201);
+ const parentId = parent.json.creation.id;
+ expect(parent.json.creation.title).toBe('Knight');
+ expect(parent.json.creation.remixCount).toBe(0);
+
+ const child = await call({
+ method: 'POST',
+ body: {
+ op: 'publish',
+ prompt: 'a lowpoly fantasy knight, now on horseback',
+ glbUrl: GLB('child'),
+ author: 'audit-remixer',
+ parentId,
+ },
+ });
+ expect(child.statusCode).toBe(201);
+ const childId = child.json.creation.id;
+
+ const item = await call({ url: `/api/creations?op=item&id=${parentId}` });
+ expect(item.statusCode).toBe(200);
+ expect(item.json.creation.remixCount).toBe(1);
+ expect(item.json.lineage.children.map((c) => c.id)).toEqual([childId]);
+ // The batched enrich must still produce a full record for each child.
+ expect(item.json.lineage.children[0]).toMatchObject({
+ id: childId,
+ author: 'audit-remixer',
+ parentId,
+ licenseInfo: expect.objectContaining({ remixable: true }),
+ });
+ expect(item.json.provenance.some((p) => p.event === 'remixed-by')).toBe(true);
+
+ const trending = await call({ url: '/api/creations?op=trending' });
+ expect(trending.json.trending.map((c) => c.id)).toContain(parentId);
+ expect(trending.json.recentRemixes[0]).toMatchObject({ parentId, childId });
+ });
+});
+
+describe('/api/creations failure paths', () => {
+ it('rejects an unknown GET op', async () => {
+ const res = await call({ url: '/api/creations?op=bogus' });
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error).toBe('bad_request');
+ });
+
+ it('404s an item that does not exist', async () => {
+ const res = await call({ url: '/api/creations?op=item&id=no-such-creation' });
+ expect(res.statusCode).toBe(404);
+ expect(res.json.error).toBe('not_found');
+ });
+
+ it('rejects a publish whose glbUrl is not on an allowed host', async () => {
+ const res = await call({
+ method: 'POST',
+ body: { op: 'publish', prompt: 'a robot', glbUrl: 'https://evil.example/pwn.glb' },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error).toBe('invalid_glb_url');
+ });
+
+ it('refuses a self-referential remix edge', async () => {
+ const res = await call({
+ method: 'POST',
+ body: { op: 'remix', parentId: 'audit-seed-000', childId: 'audit-seed-000' },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error_description).toMatch(/cannot remix itself/);
+ });
+
+ it('rejects a non-GET, non-POST method', async () => {
+ const res = await call({ method: 'DELETE' });
+ expect(res.statusCode).toBe(405);
+ });
+});
diff --git a/tests/api-creations-redis-batch.test.js b/tests/api-creations-redis-batch.test.js
new file mode 100644
index 000000000..bb6040237
--- /dev/null
+++ b/tests/api-creations-redis-batch.test.js
@@ -0,0 +1,243 @@
+// /api/creations against a configured Redis backend. The gallery's aggregation
+// surfaces enrich a SCAN_CAP-deep slice of the Loom feed, and the audit found
+// they were doing a GET + an LRANGE per creation: two Upstash REST round-trips
+// per item, ~1200 HTTP calls to render one page of the feed. enrichAll batches
+// them into one MGET plus one pipelined LRANGE.
+//
+// This pins BOTH halves of that fix against a recording fake client: the command
+// count must stay flat as the feed grows, and the records it produces must be
+// identical to what the per-item reads produced.
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+// A minimal Redis stand-in covering exactly the commands these modules issue,
+// recording every command so the test can assert on round-trip counts.
+class FakeRedis {
+ constructor() {
+ this.store = new Map();
+ this.lists = new Map();
+ this.sets = new Map();
+ this.calls = [];
+ }
+
+ _list(k) {
+ if (!this.lists.has(k)) this.lists.set(k, []);
+ return this.lists.get(k);
+ }
+
+ async get(k) {
+ this.calls.push(['get', k]);
+ return this.store.get(k) ?? null;
+ }
+
+ async set(k, v) {
+ this.calls.push(['set', k]);
+ this.store.set(k, v);
+ return 'OK';
+ }
+
+ async mget(...keys) {
+ const flat = keys.length === 1 && Array.isArray(keys[0]) ? keys[0] : keys;
+ this.calls.push(['mget', flat.length]);
+ return flat.map((k) => this.store.get(k) ?? null);
+ }
+
+ async lpush(k, v) {
+ this.calls.push(['lpush', k]);
+ this._list(k).unshift(v);
+ return this._list(k).length;
+ }
+
+ async rpush(k, v) {
+ this.calls.push(['rpush', k]);
+ this._list(k).push(v);
+ return this._list(k).length;
+ }
+
+ async ltrim(k, start, stop) {
+ this.calls.push(['ltrim', k]);
+ const list = this._list(k);
+ this.lists.set(k, start < 0 ? list.slice(start) : list.slice(start, stop + 1));
+ return 'OK';
+ }
+
+ async lrange(k, start, stop) {
+ this.calls.push(['lrange', k]);
+ return this._list(k).slice(start, stop + 1);
+ }
+
+ async scard(k) {
+ this.calls.push(['scard', k]);
+ return (this.sets.get(k) || new Set()).size;
+ }
+
+ async sadd(k, v) {
+ this.calls.push(['sadd', k]);
+ if (!this.sets.has(k)) this.sets.set(k, new Set());
+ this.sets.get(k).add(v);
+ return 1;
+ }
+
+ async sismember(k, v) {
+ this.calls.push(['sismember', k]);
+ return (this.sets.get(k) || new Set()).has(v) ? 1 : 0;
+ }
+
+ // One pipeline() + exec() is ONE round trip, which is the whole point of the
+ // fix, so it records itself as a single call.
+ pipeline() {
+ const queued = [];
+ const self = this;
+ const builder = {
+ lrange(k, start, stop) {
+ queued.push(() => self._list(k).slice(start, stop + 1));
+ return builder;
+ },
+ async exec() {
+ self.calls.push(['pipeline', queued.length]);
+ return queued.map((fn) => fn());
+ },
+ };
+ return builder;
+ }
+}
+
+const redis = new FakeRedis();
+vi.mock('../api/_lib/redis.js', () => ({ getRedis: () => redis }));
+
+const { writeCreation } = await import('../api/loom.js');
+const { default: handler } = await import('../api/creations.js');
+
+function mkReq(url) {
+ return {
+ method: 'GET',
+ url,
+ headers: { host: 'three.ws' },
+ socket: { remoteAddress: '198.51.100.8' },
+ on(event, cb) {
+ if (event === 'end') queueMicrotask(() => cb());
+ },
+ };
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ chunks: [],
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ writeHead(code) {
+ this.statusCode = code;
+ },
+ write(s) {
+ this.chunks.push(String(s));
+ return true;
+ },
+ end(b) {
+ if (b) this.chunks.push(String(b));
+ this.writableEnded = true;
+ },
+ get json() {
+ return JSON.parse(this.chunks.join(''));
+ },
+ };
+}
+
+async function call(url) {
+ const res = mkRes();
+ await handler(mkReq(url), res);
+ return res;
+}
+
+async function seed(count) {
+ for (let i = 0; i < count; i++) {
+ await writeCreation({
+ id: `redis-seed-${String(i).padStart(3, '0')}`,
+ prompt: `a voxel creature number ${i}`,
+ glbUrl: `https://three.ws/models/redis-${i}.glb`,
+ previewImageUrl: null,
+ author: `creator-${i % 5}`,
+ tier: null,
+ backend: null,
+ createdAt: 1_700_000_000_000 + i * 1000,
+ });
+ }
+}
+
+function overlayReads(calls) {
+ return calls.filter(
+ ([cmd, arg]) =>
+ cmd === 'mget' || cmd === 'pipeline' || (cmd === 'get' && String(arg).startsWith('cre:meta:')) ||
+ (cmd === 'lrange' && String(arg).startsWith('cre:children:')),
+ );
+}
+
+beforeEach(() => {
+ redis.store.clear();
+ redis.lists.clear();
+ redis.sets.clear();
+ redis.calls.length = 0;
+});
+
+describe('/api/creations overlay batching on Redis', () => {
+ it('reads the whole feed slice in two overlay round-trips, however deep it is', async () => {
+ await seed(40);
+ redis.calls.length = 0;
+ await call('/api/creations?limit=120');
+ const overlay = overlayReads(redis.calls);
+
+ // Exactly one MGET (all meta) and one pipeline (all children lists).
+ expect(overlay.map(([cmd]) => cmd).sort()).toEqual(['mget', 'pipeline']);
+ expect(overlay.find(([cmd]) => cmd === 'mget')[1]).toBe(40);
+ expect(overlay.find(([cmd]) => cmd === 'pipeline')[1]).toBe(40);
+ });
+
+ it('does not grow its round-trip count as the feed grows', async () => {
+ await seed(20);
+ redis.calls.length = 0;
+ await call('/api/creations?limit=120');
+ const small = overlayReads(redis.calls).length;
+
+ await seed(80);
+ redis.calls.length = 0;
+ await call('/api/creations?limit=120');
+ const large = overlayReads(redis.calls).length;
+
+ expect(small).toBe(2);
+ expect(large).toBe(2);
+ });
+
+ it('returns the same enriched records the per-item reads produced', async () => {
+ await seed(5);
+ const feed = await call('/api/creations');
+ expect(feed.statusCode).toBe(200);
+ expect(feed.json.creations).toHaveLength(5);
+
+ // The single-item path still enriches one creation at a time; the batched
+ // feed entry for the same id must match it field for field.
+ const newest = feed.json.creations[0];
+ const item = await call(`/api/creations?op=item&id=${newest.id}`);
+ expect(item.statusCode).toBe(200);
+ const { childIds, ...single } = item.json.creation;
+ expect(single).toEqual(newest);
+ expect(childIds).toEqual([]);
+ });
+
+ it('survives an overlay MGET that returns nulls for un-overlaid creations', async () => {
+ await seed(3);
+ // Nothing wrote cre:meta:* for these, so every mget slot comes back null:
+ // the legacy-Loom case the enrichment is explicitly defensive about.
+ expect([...redis.store.keys()].some((k) => k.startsWith('cre:meta:'))).toBe(false);
+
+ const res = await call('/api/creations');
+ expect(res.statusCode).toBe(200);
+ for (const c of res.json.creations) {
+ expect(c.title).toBeTruthy();
+ expect(c.license).toBe('remix-cc');
+ expect(c.remixCount).toBe(0);
+ expect(c.parentId).toBeNull();
+ }
+ });
+});
diff --git a/tests/api-seed-connectors.test.js b/tests/api-seed-connectors.test.js
new file mode 100644
index 000000000..655ec9f2f
--- /dev/null
+++ b/tests/api-seed-connectors.test.js
@@ -0,0 +1,118 @@
+// Unit coverage for the public memory-seed connectors under api/seed/.
+//
+// Three behaviours are locked here because each one was a real defect:
+// * the Farcaster connector shipped a "connector not configured" card on any
+// deployment without NEYNAR_API_KEY, even though the platform's shared
+// client has a keyless hub lane. shapeCasts is the boundary that turns that
+// lane's raw messages into the connector's payload, and it must report an
+// unknown engagement as null rather than 0.
+// * a hub answers "no such fname" with HTTP 400 and a NotFound detail, so
+// without the mapping below a typo'd handle read as an upstream outage.
+// * the X topic extractor carried a no-op replace that claimed to preserve
+// hashtags and handles. It now really does, and this pins that.
+
+import { describe, it, expect, vi, afterEach } from 'vitest';
+
+import { shapeCasts } from '../api/seed/farcaster.js';
+import { extractTopTopics } from '../api/seed/x.js';
+
+describe('shapeCasts (Farcaster connector payload)', () => {
+ const neynarCasts = [
+ { text: 'Shipping the new retargeting pipeline today', timestamp: 1_700_000_000_000, isReply: false, engagement: 42 },
+ { text: 'https://example.com', timestamp: 1_700_000_100_000, isReply: false, engagement: 99 },
+ { text: 'A reply that should never be seeded here', timestamp: 1_700_000_200_000, isReply: true, engagement: 500 },
+ { text: 'Second substantive cast about avatars', timestamp: 1_700_000_300_000, isReply: false, engagement: 7 },
+ ];
+
+ it('keeps substantive top-level casts, ranked by engagement', () => {
+ const out = shapeCasts(neynarCasts);
+ expect(out.map((c) => c.text)).toEqual([
+ 'Shipping the new retargeting pipeline today',
+ 'Second substantive cast about avatars',
+ ]);
+ expect(out[0].engagement).toBe(42);
+ expect(out[0].timestamp).toBe(new Date(1_700_000_000_000).toISOString());
+ });
+
+ it('reports engagement as null on the keyless hub lane instead of zero', () => {
+ const out = shapeCasts([
+ { text: 'A cast served by a public hub, no reaction counts', timestamp: 1_700_000_000_000, isReply: false, engagement: null },
+ ]);
+ expect(out).toHaveLength(1);
+ expect(out[0].engagement).toBeNull();
+ });
+
+ it('drops casts with an unusable timestamp to a null rather than an invalid date', () => {
+ const out = shapeCasts([
+ { text: 'A cast whose hub timestamp did not parse at all', timestamp: null, isReply: false, engagement: null },
+ ]);
+ expect(out[0].timestamp).toBeNull();
+ });
+
+ it('honours the return limit', () => {
+ const many = Array.from({ length: 30 }, (_, i) => ({
+ text: `Cast number ${i} with enough substance to survive`,
+ timestamp: 1_700_000_000_000 + i,
+ isReply: false,
+ engagement: i,
+ }));
+ expect(shapeCasts(many, 5)).toHaveLength(5);
+ });
+});
+
+describe('extractTopTopics (X connector)', () => {
+ it('ranks repeated substantive tokens and preserves hashtags and handles', () => {
+ const topics = extractTopTopics([
+ 'Building #solana agents with @three_ws today',
+ 'More #solana agents, always #solana',
+ 'agents everywhere',
+ ]);
+ const byTopic = Object.fromEntries(topics.map((t) => [t.topic, t.count]));
+ expect(byTopic['#solana']).toBe(3);
+ expect(byTopic.agents).toBe(3);
+ expect(byTopic['@three_ws']).toBe(1);
+ expect(topics[0].topic).toMatch(/^(#solana|agents)$/);
+ });
+
+ it('strips URLs and stopwords, and survives an empty timeline', () => {
+ const topics = extractTopTopics(['the a of to https://example.com/deep/link', '', null]);
+ expect(topics).toEqual([]);
+ expect(extractTopTopics([])).toEqual([]);
+ });
+
+ it('caps the result at the requested limit', () => {
+ const text = 'avatars rigging retarget skeleton animation blender mixamo vrm glb meshopt';
+ expect(extractTopTopics([text, text], 4)).toHaveLength(4);
+ });
+});
+
+describe('farcaster hub lane not-found mapping', () => {
+ const realFetch = globalThis.fetch;
+ afterEach(() => {
+ globalThis.fetch = realFetch;
+ vi.resetModules();
+ });
+
+ it('maps a hub 400 carrying a NotFound detail to a 404 error', async () => {
+ globalThis.fetch = vi.fn(async () =>
+ new Response(
+ JSON.stringify({
+ error: 'Failed to get username proof',
+ error_detail: 'status: NotFound, message: "Username proof not found"',
+ }),
+ { status: 400, headers: { 'content-type': 'application/json' } },
+ ),
+ );
+ const { resolveFarcasterUser } = await import('../api/_lib/farcaster-client.js');
+ await expect(resolveFarcasterUser({ fname: 'definitely-not-a-real-fname' })).rejects.toMatchObject({
+ status: 404,
+ code: 'farcaster_user_not_found',
+ });
+ });
+
+ it('leaves a genuine hub failure as an upstream error', async () => {
+ globalThis.fetch = vi.fn(async () => new Response('gateway blew up', { status: 502 }));
+ const { resolveFarcasterUser } = await import('../api/_lib/farcaster-client.js');
+ await expect(resolveFarcasterUser({ fname: 'dwr' })).rejects.toMatchObject({ status: 502 });
+ });
+});
diff --git a/tests/api/agent-memory.test.js b/tests/api/agent-memory.test.js
index 981f37491..e4edc4270 100644
--- a/tests/api/agent-memory.test.js
+++ b/tests/api/agent-memory.test.js
@@ -107,7 +107,7 @@ describe('auth', () => {
it('GET without session or bearer returns empty list (200)', async () => {
// Public embeds boot this fetch on every page load. Returning an empty
// list (instead of 401) keeps the console clean for anonymous viewers.
- const { status, body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111' });
expect(status).toBe(200);
expect(body.entries).toEqual([]);
});
@@ -116,13 +116,13 @@ describe('auth', () => {
const { status } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { content: 'x' } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { content: 'x' } },
});
expect(status).toBe(401);
});
it('DELETE without auth returns 401', async () => {
- const { status } = await invoke({ method: 'DELETE', url: '/api/agent-memory/mem-1' });
+ const { status } = await invoke({ method: 'DELETE', url: '/api/agent-memory/55555555-5555-4555-8555-555555555555' });
expect(status).toBe(401);
});
@@ -133,7 +133,7 @@ describe('auth', () => {
const { status, body } = await invoke({
method: 'GET',
- url: '/api/agent-memory?agentId=a1',
+ url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111',
});
expect(status).toBe(200);
expect(body.entries).toEqual([]);
@@ -154,7 +154,7 @@ describe('GET /api/agent-memory', () => {
[
{
id: 'm1',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'project',
content: 'test note',
tags: ['alpha'],
@@ -168,14 +168,14 @@ describe('GET /api/agent-memory', () => {
const { status, body } = await invoke({
method: 'GET',
- url: '/api/agent-memory?agentId=a1',
+ url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111',
});
expect(status).toBe(200);
expect(body.entries).toHaveLength(1);
expect(body.entries[0]).toMatchObject({
id: 'm1',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'project',
content: 'test note',
tags: ['alpha'],
@@ -193,7 +193,7 @@ describe('GET /api/agent-memory', () => {
it('returns empty list (200) when agent does not exist', async () => {
queueSql([]); // no ownership row
- const { status, body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=nope' });
+ const { status, body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=22222222-2222-4222-8222-222222222222' });
expect(status).toBe(200);
expect(body.entries).toEqual([]);
});
@@ -202,7 +202,7 @@ describe('GET /api/agent-memory', () => {
queueSql([{ user_id: 'other-user' }]);
const { status, body } = await invoke({
method: 'GET',
- url: '/api/agent-memory?agentId=a1',
+ url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111',
});
expect(status).toBe(200);
expect(body.entries).toEqual([]);
@@ -214,7 +214,7 @@ describe('GET /api/agent-memory', () => {
[
{
id: 'm2',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'user',
content: '',
tags: null,
@@ -225,7 +225,7 @@ describe('GET /api/agent-memory', () => {
},
],
);
- const { body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=a1' });
+ const { body } = await invoke({ method: 'GET', url: '/api/agent-memory?agentId=11111111-1111-4111-8111-111111111111' });
expect(body.entries[0].tags).toEqual([]);
expect(body.entries[0].context).toEqual({});
});
@@ -245,7 +245,7 @@ describe('POST /api/agent-memory', () => {
[
{
id: 'server-gen-id',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'project',
content: 'new memory',
tags: [],
@@ -260,7 +260,7 @@ describe('POST /api/agent-memory', () => {
const { status, body } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { content: 'new memory' } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { content: 'new memory' } },
});
expect(status).toBe(201);
@@ -282,7 +282,7 @@ describe('POST /api/agent-memory', () => {
const { status, body } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1' },
+ body: { agentId: '11111111-1111-4111-8111-111111111111' },
});
expect(status).toBe(400);
expect(body.error_description).toMatch(/entry/);
@@ -293,7 +293,7 @@ describe('POST /api/agent-memory', () => {
const { status } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { content: 'steal' } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { content: 'steal' } },
});
expect(status).toBe(403);
});
@@ -303,8 +303,8 @@ describe('POST /api/agent-memory', () => {
[{ user_id: 'u1' }],
[
{
- id: 'client-id',
- agent_id: 'a1',
+ id: '33333333-3333-4333-8333-333333333333',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'user',
content: 'updated',
tags: [],
@@ -320,13 +320,13 @@ describe('POST /api/agent-memory', () => {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: {
- agentId: 'a1',
- entry: { id: 'client-id', type: 'user', content: 'updated', salience: 0.9 },
+ agentId: '11111111-1111-4111-8111-111111111111',
+ entry: { id: '33333333-3333-4333-8333-333333333333', type: 'user', content: 'updated', salience: 0.9 },
},
});
expect(status).toBe(201);
- expect(body.entry.id).toBe('client-id');
+ expect(body.entry.id).toBe('33333333-3333-4333-8333-333333333333');
expect(body.entry.salience).toBe(0.9);
});
@@ -336,7 +336,7 @@ describe('POST /api/agent-memory', () => {
const { status, body } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { id: 'stolen-id', content: 'x' } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { id: '44444444-4444-4444-8444-444444444444', content: 'x' } },
});
expect(status).toBe(409);
expect(body.error).toBe('id_conflict');
@@ -348,7 +348,7 @@ describe('POST /api/agent-memory', () => {
[
{
id: 'm1',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'project',
content: 'x',
tags: [],
@@ -363,7 +363,7 @@ describe('POST /api/agent-memory', () => {
const { status, body } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { type: 'bogus-type', content: 'x' } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { type: 'bogus-type', content: 'x' } },
});
expect(status).toBe(201);
@@ -387,7 +387,7 @@ describe('POST /api/agent-memory', () => {
return Promise.resolve([
{
id: 'x',
- agent_id: 'a1',
+ agent_id: '11111111-1111-4111-8111-111111111111',
type: 'project',
content: capturedContent,
tags: [],
@@ -402,7 +402,7 @@ describe('POST /api/agent-memory', () => {
const { status } = await invoke({
method: 'POST',
headers: { 'content-type': 'application/json' },
- body: { agentId: 'a1', entry: { content: huge } },
+ body: { agentId: '11111111-1111-4111-8111-111111111111', entry: { content: huge } },
});
expect(status).toBe(201);
@@ -422,7 +422,7 @@ describe('DELETE /api/agent-memory/:id', () => {
queueSql([{ id: 'mem-1', user_id: 'u1' }], []); // lookup, delete
const { status, body } = await invoke({
method: 'DELETE',
- url: '/api/agent-memory/mem-1',
+ url: '/api/agent-memory/55555555-5555-4555-8555-555555555555',
});
expect(status).toBe(200);
expect(body).toEqual({ ok: true });
@@ -430,7 +430,7 @@ describe('DELETE /api/agent-memory/:id', () => {
it('returns 404 when the memory does not exist', async () => {
queueSql([]); // no row found
- const { status } = await invoke({ method: 'DELETE', url: '/api/agent-memory/ghost' });
+ const { status } = await invoke({ method: 'DELETE', url: '/api/agent-memory/66666666-6666-4666-8666-666666666666' });
expect(status).toBe(404);
});
@@ -438,7 +438,7 @@ describe('DELETE /api/agent-memory/:id', () => {
queueSql([{ id: 'mem-1', user_id: 'other' }]);
const { status, body } = await invoke({
method: 'DELETE',
- url: '/api/agent-memory/mem-1',
+ url: '/api/agent-memory/55555555-5555-4555-8555-555555555555',
});
expect(status).toBe(403);
expect(body.error).toBe('forbidden');
diff --git a/tests/api/agent-oembed.test.js b/tests/api/agent-oembed.test.js
index 3f784695a..c80e54bd8 100644
--- a/tests/api/agent-oembed.test.js
+++ b/tests/api/agent-oembed.test.js
@@ -111,3 +111,22 @@ describe('unrecognised target', () => {
expect(body.error_description || body.error).toBeTruthy();
});
});
+
+describe('malformed target', () => {
+ it('does not treat a non-uuid /agent/:id segment as an agent id', async () => {
+ // agent_identities.id is a uuid column: the slug used to reach Postgres as
+ // an uncastable literal and answer 500. The sql mock queue is empty, so a
+ // regression that reintroduces the query fails here rather than 404ing.
+ const { status, body } = await get('https://three.ws/agent/not-a-uuid');
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('rejects a non-GET method with 405', async () => {
+ const res = makeRes();
+ const req = makeReq('/api/oembed?url=https%3A%2F%2Fthree.ws%2Fnowhere');
+ req.method = 'POST';
+ await handler(req, res);
+ expect(res.statusCode).toBe(405);
+ });
+});
diff --git a/tests/api/forge-pipeline-endpoints.test.js b/tests/api/forge-pipeline-endpoints.test.js
new file mode 100644
index 000000000..09dd6c63b
--- /dev/null
+++ b/tests/api/forge-pipeline-endpoints.test.js
@@ -0,0 +1,582 @@
+// Endpoint contracts for the /forge pipeline handlers: forge-og, forge-poster,
+// forge-quality-check, forge-rembg, forge-remesh, forge-segment, forge-share,
+// forge-stylize, forge-upload, forge-vote.
+//
+// Three of these pin regressions found while auditing the batch:
+//
+// 1. forge-stylize took `style` through a bare `STYLE_BOUNDS[body.style]`
+// truthiness test. Every Object.prototype key is truthy there, so
+// `style: "constructor"` walked past the allowlist and reached the worker
+// with an unknown filter and a NaN resolution.
+// 2. forge-upload did the same with `content_type`. Object.freeze does not
+// detach a prototype, so `content_type: "constructor"` resolved to the
+// Object function and presigned an upload whose storage key ended in the
+// stringified builtin.
+// 3. The four worker-backed pollers called provider.status() with no guard.
+// An upstream fault escaped to wrap() as a 500, which fires a Sentry
+// capture and an ops alert, once per poll, per client, for the length of
+// a worker outage. They now answer a clean 502.
+//
+// The DB, object storage, the worker provider, and the rate limiter are the
+// process boundaries; everything inside them is the real handler code.
+
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
+
+// forge-upload gates on the raw S3_* vars rather than on forge-store's helper,
+// so the suite has to declare a configured deployment for it to get past the
+// 503. Synthetic values: presignUpload and publicUrl are stubbed below, so
+// nothing here reaches an object store.
+const S3_ENV = {
+ S3_ENDPOINT: 'https://s3.test.invalid',
+ S3_BUCKET: 'test-bucket',
+ S3_PUBLIC_DOMAIN: 'https://cdn.test.invalid',
+ S3_ACCESS_KEY_ID: 'test-access-key',
+ S3_SECRET_ACCESS_KEY: 'test-secret-key',
+};
+const savedS3 = {};
+for (const [k, v] of Object.entries(S3_ENV)) {
+ savedS3[k] = process.env[k];
+ process.env[k] = v;
+}
+afterAll(() => {
+ for (const k of Object.keys(S3_ENV)) {
+ if (savedS3[k] === undefined) delete process.env[k];
+ else process.env[k] = savedS3[k];
+ }
+});
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+ isStoragePressured: async () => ({ pressured: false }),
+}));
+
+const rlAllow = { value: true };
+const limitStub = vi.fn(async () => ({ success: rlAllow.value, reset: Date.now() + 1_000, limit: 10, remaining: 0 }));
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ mcp3dGenerate: (...a) => limitStub(...a),
+ mcp3dStatus: (...a) => limitStub(...a),
+ upload: (...a) => limitStub(...a),
+ forgeVote: (...a) => limitStub(...a),
+ visionUser: (...a) => limitStub(...a),
+ visionIp: (...a) => limitStub(...a),
+ },
+ clientIp: () => '203.0.113.9',
+}));
+
+// Real SSRF policy is covered by its own suite; here it only has to let a
+// known-good https URL through so the handler's own validation is what's tested.
+class FakeSsrfError extends Error {}
+vi.mock('../../api/_lib/ssrf.js', () => ({
+ SsrfError: FakeSsrfError,
+ assertPublicHttpsUrl: async (raw) => {
+ if (typeof raw !== 'string' || !raw.startsWith('https://')) {
+ throw new FakeSsrfError('must be a public https URL');
+ }
+ return raw;
+ },
+}));
+
+const submitted = [];
+const providerState = { configured: true, statusThrows: false };
+vi.mock('../../api/_providers/gcp.js', () => ({
+ createRegenProvider: () => {
+ if (!providerState.configured) throw new Error('no gcp worker configured');
+ return {
+ supportsMode: () => true,
+ async submit(job) {
+ submitted.push(job);
+ return { extJobId: 'j'.repeat(40), eta: 30 };
+ },
+ async status() {
+ if (providerState.statusThrows) throw new Error('worker unreachable');
+ return { status: 'running' };
+ },
+ };
+ },
+}));
+
+const storeState = { enabled: true };
+const castVoteMock = vi.fn();
+const removeVoteMock = vi.fn();
+const attachPosterMock = vi.fn();
+vi.mock('../../api/_lib/forge-store.js', () => ({
+ forgeStoreEnabled: () => storeState.enabled,
+ hashClient: (raw) => (typeof raw === 'string' && raw.trim() ? `h-${raw.trim()}` : 'anon'),
+ hashIp: (ip) => (ip ? `hip-${ip}` : null),
+ castVote: (...a) => castVoteMock(...a),
+ removeVote: (...a) => removeVoteMock(...a),
+ attachPoster: (...a) => attachPosterMock(...a),
+}));
+
+const presignMock = vi.fn(async ({ key }) => `https://r2.example/${key}?sig=abc`);
+vi.mock('../../api/_lib/r2.js', () => ({
+ presignUpload: (...a) => presignMock(...a),
+ publicUrl: (key) => `https://cdn.example/${key}`,
+}));
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: async () => null,
+ authenticateBearer: async () => null,
+ extractBearer: () => null,
+}));
+
+const gateState = { configured: false };
+vi.mock('../../api/_lib/forge-quality-gate.js', () => ({
+ qualityGateConfigured: () => gateState.configured,
+ vertexQualityConfigured: () => false,
+ QUALITY_GATE_DEFAULTS: { model: 'gemini-test', passScore: 60, maxRetries: 2 },
+ runQualityGate: async () => ({ pass: true, qa_available: false, score: null }),
+ buildRetryDirective: () => ({ retry: true }),
+}));
+
+const [og, poster, qualityCheck, rembg, remesh, segment, share, stylize, upload, vote] = await Promise.all([
+ import('../../api/forge-og.js'),
+ import('../../api/forge-poster.js'),
+ import('../../api/forge-quality-check.js'),
+ import('../../api/forge-rembg.js'),
+ import('../../api/forge-remesh.js'),
+ import('../../api/forge-segment.js'),
+ import('../../api/forge-share.js'),
+ import('../../api/forge-stylize.js'),
+ import('../../api/forge-upload.js'),
+ import('../../api/forge-vote.js'),
+]).then((mods) => mods.map((m) => m.default));
+
+const UUID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const MESH = 'https://cdn.example/mesh.glb';
+const JOB = 'j'.repeat(40);
+
+function mkReq({ method = 'GET', url = '/', headers = {}, body } = {}) {
+ const hdrs = { ...headers };
+ let rawBody;
+ if (body !== undefined) {
+ if (!hdrs['content-type']) hdrs['content-type'] = 'application/json';
+ rawBody = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
+ }
+ return { method, url, headers: hdrs, rawBody, on() {}, destroy() {} };
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(b) { this.body = b === undefined ? '' : String(b); this.writableEnded = true; },
+ };
+}
+
+async function call(handler, reqInit) {
+ const res = mkRes();
+ await handler(mkReq(reqInit), res);
+ return res;
+}
+
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+beforeEach(() => {
+ rlAllow.value = true;
+ providerState.configured = true;
+ providerState.statusThrows = false;
+ storeState.enabled = true;
+ gateState.configured = false;
+ submitted.length = 0;
+ sqlMock.mockReset();
+ castVoteMock.mockReset();
+ removeVoteMock.mockReset();
+ attachPosterMock.mockReset();
+ presignMock.mockClear();
+ limitStub.mockClear();
+});
+
+describe('forge-stylize', () => {
+ it('starts a job on a valid style and clamps the resolution', async () => {
+ const res = await call(stylize, {
+ method: 'POST',
+ url: '/api/forge-stylize',
+ body: { mesh_url: MESH, style: 'brick', resolution: 9_999 },
+ });
+ expect(res.statusCode).toBe(202);
+ expect(parse(res)).toMatchObject({ job_id: JOB, status: 'queued', style: 'brick', resolution: 64 });
+ expect(submitted[0].params).toMatchObject({ style: 'brick', resolution: 64 });
+ });
+
+ it('rejects a prototype key as a style instead of passing it to the worker', async () => {
+ for (const style of ['constructor', 'toString', 'valueOf', '__proto__', 'hasOwnProperty']) {
+ submitted.length = 0;
+ const res = await call(stylize, {
+ method: 'POST',
+ url: '/api/forge-stylize',
+ body: { mesh_url: MESH, style, resolution: 50 },
+ });
+ expect(res.statusCode).toBe(202);
+ // Falls back to the default filter with a real resolution. The bug sent
+ // `style: "constructor"` and a NaN resolution straight through.
+ expect(parse(res).style).toBe('voxel');
+ expect(submitted[0].params.style).toBe('voxel');
+ expect(Number.isFinite(submitted[0].params.resolution)).toBe(true);
+ expect(submitted[0].params.resolution).toBe(50);
+ }
+ });
+
+ it('rejects a non-https mesh_url at the boundary', async () => {
+ const res = await call(stylize, {
+ method: 'POST',
+ url: '/api/forge-stylize',
+ body: { mesh_url: 'http://169.254.169.254/latest' },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_mesh_url');
+ });
+
+ it('answers 502, not 500, when the worker poll faults', async () => {
+ providerState.statusThrows = true;
+ const res = await call(stylize, { url: `/api/forge-stylize?job=${JOB}` });
+ expect(res.statusCode).toBe(502);
+ expect(parse(res).error).toBe('stylize_status_failed');
+ // No `status` field, so the client's poll loop retries rather than
+ // treating a transient worker fault as a failed job.
+ expect(parse(res).status).toBeUndefined();
+ });
+
+ it('503s with an actionable message when the worker is unconfigured', async () => {
+ providerState.configured = false;
+ const res = await call(stylize, { url: `/api/forge-stylize?job=${JOB}` });
+ expect(res.statusCode).toBe(503);
+ expect(parse(res).error).toBe('unconfigured');
+ });
+});
+
+describe('forge-rembg / forge-remesh / forge-segment', () => {
+ const lanes = [
+ { name: 'rembg', handler: () => rembg, path: '/api/forge-rembg', urlField: 'image_url', code: 'rembg_status_failed' },
+ { name: 'remesh', handler: () => remesh, path: '/api/forge-remesh', urlField: 'mesh_url', code: 'remesh_status_failed' },
+ { name: 'segment', handler: () => segment, path: '/api/forge-segment', urlField: 'mesh_url', code: 'segment_status_failed' },
+ ];
+
+ for (const lane of lanes) {
+ it(`${lane.name}: queues a job on a valid source URL`, async () => {
+ const res = await call(lane.handler(), {
+ method: 'POST',
+ url: lane.path,
+ body: { [lane.urlField]: MESH },
+ });
+ expect(res.statusCode).toBe(202);
+ expect(parse(res)).toMatchObject({ job_id: JOB, status: 'queued' });
+ });
+
+ it(`${lane.name}: 400s a malformed job id`, async () => {
+ const res = await call(lane.handler(), { url: `${lane.path}?job=short` });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_job');
+ });
+
+ it(`${lane.name}: answers 502, not 500, when the worker poll faults`, async () => {
+ providerState.statusThrows = true;
+ const res = await call(lane.handler(), { url: `${lane.path}?job=${JOB}` });
+ expect(res.statusCode).toBe(502);
+ expect(parse(res).error).toBe(lane.code);
+ expect(parse(res).status).toBeUndefined();
+ });
+
+ it(`${lane.name}: 405s a verb it does not serve`, async () => {
+ const res = await call(lane.handler(), { method: 'DELETE', url: lane.path });
+ expect(res.statusCode).toBe(405);
+ });
+ }
+});
+
+describe('forge-upload', () => {
+ it('presigns an upload for an accepted image type', async () => {
+ const res = await call(upload, {
+ method: 'POST',
+ url: '/api/forge-upload',
+ headers: { 'x-forge-client': 'browser-1' },
+ body: { content_type: 'image/png', size_bytes: 1_000 },
+ });
+ expect(res.statusCode).toBe(200);
+ const out = parse(res);
+ expect(out.storage_key).toMatch(/^forge\/uploads\/[^/]+\/[0-9a-f-]{36}\.png$/);
+ expect(out.method).toBe('PUT');
+ expect(out.headers['content-type']).toBe('image/png');
+ expect(out.upload_url).toContain(out.storage_key);
+ });
+
+ it('rejects a prototype key as a content type', async () => {
+ for (const contentType of ['constructor', '__proto__', 'tostring']) {
+ const res = await call(upload, {
+ method: 'POST',
+ url: '/api/forge-upload',
+ body: { content_type: contentType, size_bytes: 1_000 },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_content_type');
+ expect(presignMock).not.toHaveBeenCalled();
+ }
+ });
+
+ it('rejects a size outside the cap', async () => {
+ for (const size of [0, -1, 9 * 1024 * 1024, 'big']) {
+ const res = await call(upload, {
+ method: 'POST',
+ url: '/api/forge-upload',
+ body: { content_type: 'image/png', size_bytes: size },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_size');
+ }
+ });
+
+ it('surfaces a presign failure as 502', async () => {
+ presignMock.mockRejectedValueOnce(new Error('bucket unreachable'));
+ const res = await call(upload, {
+ method: 'POST',
+ url: '/api/forge-upload',
+ body: { content_type: 'image/webp', size_bytes: 2_000 },
+ });
+ expect(res.statusCode).toBe(502);
+ expect(parse(res).error).toBe('presign_failed');
+ });
+});
+
+describe('forge-vote', () => {
+ it('casts a vote and returns the authoritative tally', async () => {
+ castVoteMock.mockResolvedValueOnce({ creationId: UUID, voteCount: 4, voted: true });
+ const res = await call(vote, {
+ method: 'POST',
+ url: '/api/forge-vote',
+ headers: { 'x-forge-client': 'browser-1' },
+ body: { creation_id: UUID },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({ ok: true, creation_id: UUID, vote_count: 4, voted: true });
+ expect(castVoteMock).toHaveBeenCalledWith({ creationId: UUID, voterKey: 'h-browser-1', ipHash: 'hip-203.0.113.9' });
+ });
+
+ it('removes a vote on an explicit vote:false', async () => {
+ removeVoteMock.mockResolvedValueOnce({ creationId: UUID, voteCount: 3, voted: false });
+ const res = await call(vote, {
+ method: 'POST',
+ url: '/api/forge-vote',
+ headers: { 'x-forge-client': 'browser-1' },
+ body: { creation_id: UUID, vote: false },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(parse(res).voted).toBe(false);
+ expect(castVoteMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses a vote with no stable client id', async () => {
+ const res = await call(vote, { method: 'POST', url: '/api/forge-vote', body: { creation_id: UUID } });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('no_client_id');
+ expect(castVoteMock).not.toHaveBeenCalled();
+ });
+
+ it('404s a creation that is not votable', async () => {
+ castVoteMock.mockResolvedValueOnce(null);
+ const res = await call(vote, {
+ method: 'POST',
+ url: '/api/forge-vote',
+ headers: { 'x-forge-client': 'browser-1' },
+ body: { creation_id: UUID },
+ });
+ expect(res.statusCode).toBe(404);
+ expect(parse(res).error).toBe('not_votable');
+ });
+
+ it('400s a malformed creation id', async () => {
+ const res = await call(vote, {
+ method: 'POST',
+ url: '/api/forge-vote',
+ headers: { 'x-forge-client': 'browser-1' },
+ body: { creation_id: 'not-a-uuid' },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_creation');
+ });
+});
+
+describe('forge-poster', () => {
+ const PNG = 'data:image/png;base64,iVBORw0KGgo=';
+
+ it('attaches a poster and returns the stored preview URL', async () => {
+ attachPosterMock.mockResolvedValueOnce('https://cdn.example/forge/h-browser/poster.png');
+ const res = await call(poster, {
+ method: 'POST',
+ url: '/api/forge-poster',
+ headers: { 'x-forge-client': 'browser-1' },
+ body: { creation_id: UUID, image: PNG },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toMatchObject({ ok: true, stored: true });
+ expect(attachPosterMock.mock.calls[0][0]).toMatchObject({
+ id: UUID,
+ clientKey: 'h-browser-1',
+ contentType: 'image/png',
+ ext: 'png',
+ });
+ });
+
+ it('reports a benign no-op as stored:false rather than an error', async () => {
+ attachPosterMock.mockResolvedValueOnce(null);
+ const res = await call(poster, {
+ method: 'POST',
+ url: '/api/forge-poster',
+ headers: { 'x-forge-client': 'browser-1' },
+ body: { creation_id: UUID, image: PNG },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toMatchObject({ ok: true, stored: false, preview_image_url: null });
+ });
+
+ it('400s anything that is not a webp/png/jpeg data URL', async () => {
+ for (const image of ['notadataurl', 'data:image/gif;base64,R0lGOD', 'data:image/png;base64,', 'data:text/html,<script>']) {
+ const res = await call(poster, {
+ method: 'POST',
+ url: '/api/forge-poster',
+ headers: { 'x-forge-client': 'browser-1' },
+ body: { creation_id: UUID, image },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('invalid_image');
+ expect(attachPosterMock).not.toHaveBeenCalled();
+ }
+ });
+
+ it('short-circuits cleanly when persistence is unconfigured', async () => {
+ storeState.enabled = false;
+ const res = await call(poster, {
+ method: 'POST',
+ url: '/api/forge-poster',
+ body: { creation_id: UUID, image: PNG },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({ ok: false, stored: false, reason: 'persistence_unconfigured' });
+ });
+});
+
+describe('forge-quality-check', () => {
+ it('serves a capability probe on GET', async () => {
+ const res = await call(qualityCheck, { url: '/api/forge-quality-check' });
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toMatchObject({ configured: false, provider: null, passScore: 60, maxRetries: 2 });
+ });
+
+ it('serves the same probe on HEAD', async () => {
+ gateState.configured = true;
+ const res = await call(qualityCheck, { method: 'HEAD', url: '/api/forge-quality-check' });
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toMatchObject({ configured: true, provider: 'platform-vision' });
+ });
+
+ it('400s a POST with no model to score', async () => {
+ const res = await call(qualityCheck, { method: 'POST', url: '/api/forge-quality-check', body: {} });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error).toBe('bad_request');
+ });
+
+ it('scores a supplied render and fails open', async () => {
+ const res = await call(qualityCheck, {
+ method: 'POST',
+ url: '/api/forge-quality-check',
+ body: { renderUrl: 'https://cdn.example/render.png', prompt: 'a red chair' },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(parse(res)).toEqual({ verdict: { pass: true, qa_available: false, score: null }, retry: null });
+ });
+});
+
+describe('forge-og', () => {
+ it('302s to the creation preview when one exists', async () => {
+ sqlMock.mockResolvedValueOnce([{ id: UUID, prompt: 'a red chair', preview_image_url: 'https://cdn.example/p.png' }]);
+ const res = await call(og, { url: `/api/forge-og?id=${UUID}` });
+ expect(res.statusCode).toBe(302);
+ expect(res.headers.location).toBe('https://cdn.example/p.png');
+ });
+
+ it('renders an SVG card when the row has no preview', async () => {
+ sqlMock.mockResolvedValueOnce([{ id: UUID, prompt: 'a <script> chair', preview_image_url: null }]);
+ const res = await call(og, { url: `/api/forge-og?id=${UUID}` });
+ expect(res.statusCode).toBe(200);
+ expect(res.headers['content-type']).toContain('image/svg+xml');
+ expect(res.body).toContain('&lt;script&gt;');
+ expect(res.body).not.toContain('<script>');
+ });
+
+ it('falls back to a 404 card on a malformed id without touching the DB', async () => {
+ const res = await call(og, { url: '/api/forge-og?id=not-a-uuid' });
+ expect(res.statusCode).toBe(404);
+ expect(res.headers['content-type']).toContain('image/svg+xml');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('falls back to a card when the DB read throws', async () => {
+ sqlMock.mockRejectedValueOnce(new Error('db down'));
+ const res = await call(og, { url: `/api/forge-og?id=${UUID}` });
+ expect(res.statusCode).toBe(404);
+ expect(res.headers['content-type']).toContain('image/svg+xml');
+ });
+});
+
+describe('forge-share', () => {
+ it('bakes escaped OG, Twitter, Frame and oEmbed tags into the page', async () => {
+ sqlMock.mockResolvedValueOnce([
+ { id: UUID, prompt: 'a "quoted" <chair>', preview_image_url: 'https://cdn.example/p.png', status: 'done' },
+ ]);
+ const res = await call(share, { url: `/api/forge-share?id=${UUID}` });
+ expect(res.statusCode).toBe(200);
+ expect(res.headers['content-type']).toContain('text/html');
+ expect(res.body).toContain('property="og:image" content="https://cdn.example/p.png"');
+ expect(res.body).toContain('name="twitter:card" content="summary_large_image"');
+ expect(res.body).toContain('property="fc:frame" content="vNext"');
+ expect(res.body).toContain('application/json+oembed');
+ expect(res.body).toContain('&quot;quoted&quot;');
+ expect(res.body).not.toContain('<chair>');
+ });
+
+ it('points og:image at the card endpoint when the row has no preview', async () => {
+ sqlMock.mockResolvedValueOnce([{ id: UUID, prompt: 'a chair', preview_image_url: null, status: 'done' }]);
+ const res = await call(share, { url: `/api/forge-share?id=${UUID}` });
+ expect(res.body).toContain(`/api/forge-og?id=${UUID}`);
+ });
+
+ it('redirects to /forge on a malformed or unknown id', async () => {
+ const bad = await call(share, { url: '/api/forge-share?id=nope' });
+ expect(bad.statusCode).toBe(302);
+ expect(bad.headers.location).toContain('/forge');
+ expect(sqlMock).not.toHaveBeenCalled();
+
+ sqlMock.mockResolvedValueOnce([]);
+ const missing = await call(share, { url: `/api/forge-share?id=${UUID}` });
+ expect(missing.statusCode).toBe(302);
+ expect(missing.headers.location).toContain('/forge');
+ });
+});
+
+describe('rate limiting', () => {
+ it('429s every metered lane when the bucket is exhausted', async () => {
+ rlAllow.value = false;
+ const cases = [
+ [stylize, { method: 'POST', url: '/api/forge-stylize', body: { mesh_url: MESH } }],
+ [rembg, { method: 'POST', url: '/api/forge-rembg', body: { image_url: MESH } }],
+ [remesh, { url: `/api/forge-remesh?job=${JOB}` }],
+ [segment, { url: `/api/forge-segment?job=${JOB}` }],
+ [upload, { method: 'POST', url: '/api/forge-upload', body: { content_type: 'image/png', size_bytes: 10 } }],
+ [vote, { method: 'POST', url: '/api/forge-vote', headers: { 'x-forge-client': 'b' }, body: { creation_id: UUID } }],
+ [poster, { method: 'POST', url: '/api/forge-poster', body: { creation_id: UUID, image: 'data:image/png;base64,iVBORw0KGgo=' } }],
+ ];
+ for (const [handler, reqInit] of cases) {
+ const res = await call(handler, reqInit);
+ expect(res.statusCode).toBe(429);
+ expect(res.headers['retry-after']).toBeDefined();
+ }
+ });
+});
diff --git a/tests/api/mcp-agent-challenge.test.js b/tests/api/mcp-agent-challenge.test.js
new file mode 100644
index 000000000..b81bbe5ad
--- /dev/null
+++ b/tests/api/mcp-agent-challenge.test.js
@@ -0,0 +1,161 @@
+/**
+ * The Agent-wallet MCP endpoint (api/mcp-agent.js) must issue its OWN
+ * auth/payment challenge: resource URL /api/mcp-agent, a wallet-and-payments
+ * description, and a bazaar discovery example that calls find_services. Before
+ * AGENT_CHALLENGE existed it inherited the main /api/mcp envelope, so
+ * facilitators indexed it as the avatar/validation server and, worse, every
+ * accepts[] entry quoted resource https://three.ws/api/mcp: a paying agent
+ * signed a payment scoped to an endpoint it never called.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// Env the real 402 challenge builder reads. Set before importing the handler.
+process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
+process.env.X402_PAY_TO_BASE ||= '0x0000000000000000000000000000000000000001';
+process.env.X402_ASSET_ADDRESS_BASE ||= '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+
+// Bearer path is out of scope: no token is ever presented in these tests.
+vi.mock('../../api/_lib/auth.js', () => ({
+ extractBearer: () => null,
+ authenticateBearer: vi.fn(async () => null),
+}));
+
+// No Upstash in unit tests: every limiter passes.
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: new Proxy(
+ {},
+ { get: () => vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })) },
+ ),
+ clientIp: vi.fn(() => '203.0.113.9'),
+}));
+
+// The bazaar client is a live network dependency; keep discovery hermetic.
+vi.mock('../../api/_lib/x402/bazaar-client.js', async (orig) => {
+ const actual = await orig();
+ return { ...actual, searchBazaar: vi.fn(async () => ({ services: [] })) };
+});
+
+const { default: handler } = await import('../../api/mcp-agent.js');
+const { AGENT_CHALLENGE, RESOURCE_DESCRIPTION } = await import('../../api/_mcpagent/discovery.js');
+const { TOOL_CATALOG } = await import('../../api/_mcpagent/catalog.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(name, value) {
+ this.headers[String(name).toLowerCase()] = value;
+ },
+ end(body) {
+ this.body = body ?? null;
+ },
+ };
+}
+
+function makeReq({ method = 'POST', headers = {}, body = null } = {}) {
+ const payload = body == null ? '' : JSON.stringify(body);
+ const req = Readable.from(payload ? [Buffer.from(payload, 'utf8')] : []);
+ req.method = method;
+ req.url = '/api/mcp-agent';
+ req.headers = {
+ 'content-type': 'application/json',
+ 'x-forwarded-for': '203.0.113.9',
+ ...headers,
+ };
+ return req;
+}
+
+const walletStatusCall = {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'wallet_status', arguments: {} },
+};
+
+describe('POST /api/mcp-agent, unauthenticated challenge identity', () => {
+ it('plain x402 clients get a 402 naming the Agent-wallet resource', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: walletStatusCall }), res);
+ expect(res.statusCode).toBe(402);
+ const challenge = JSON.parse(res.body);
+ expect(challenge.resource.url).toBe('https://three.ws/api/mcp-agent');
+ expect(challenge.resource.description).toContain('pay_and_call');
+ expect(challenge.resource.serviceName).toBe('three.ws Agent MCP');
+ expect(challenge.resource.tags).toContain('wallet');
+ // The payment requirements themselves must be scoped to this endpoint:
+ // this is the assertion that would have caught agents paying against
+ // https://three.ws/api/mcp for an Agent-wallet call.
+ for (const accept of challenge.accepts) {
+ expect(accept.resource).toBe('https://three.ws/api/mcp-agent');
+ }
+ });
+
+ it('advertises a read-only find_services example, never a spending tool', async () => {
+ const res = makeRes();
+ await handler(makeReq({ body: walletStatusCall }), res);
+ const { extensions } = JSON.parse(res.body);
+ expect(extensions.bazaar.discoverable).toBe(true);
+ expect(extensions.bazaar.info.input.body.params.name).toBe('find_services');
+ expect(extensions.bazaar.info.output.example.result.structuredContent.count).toBe(1);
+ });
+
+ it('MCP protocol clients get a 401 with the same Agent envelope', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({
+ body: walletStatusCall,
+ headers: { accept: 'application/json, text/event-stream' },
+ }),
+ res,
+ );
+ expect(res.statusCode).toBe(401);
+ expect(res.headers['www-authenticate']).toContain('oauth-protected-resource');
+ const challenge = JSON.parse(res.body);
+ expect(challenge.resource.url).toBe('https://three.ws/api/mcp-agent');
+ expect(challenge.resource.serviceName).toBe('three.ws Agent MCP');
+ });
+
+ it('GET (SSE probe) advertises the Agent resource as well', async () => {
+ const res = makeRes();
+ await handler(makeReq({ method: 'GET', body: null }), res);
+ expect(res.statusCode).toBe(402);
+ const challenge = JSON.parse(res.body);
+ expect(challenge.resource.url).toBe('https://three.ws/api/mcp-agent');
+ expect(challenge.resource.description).toContain('wallet_status');
+ });
+
+ it('the free public getting_started tool is still served with no credentials', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({
+ body: {
+ jsonrpc: '2.0',
+ id: 2,
+ method: 'tools/call',
+ params: { name: 'getting_started', arguments: {} },
+ },
+ }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ const out = JSON.parse(res.body);
+ expect(out.error).toBeUndefined();
+ expect(out.result?.content?.[0]?.text).toBeTruthy();
+ });
+});
+
+describe('AGENT_CHALLENGE metadata', () => {
+ it('names every tool the catalog actually ships', () => {
+ const advertised = TOOL_CATALOG.map((t) => t.name).filter((n) => n !== 'getting_started');
+ for (const name of advertised) expect(RESOURCE_DESCRIPTION).toContain(name);
+ });
+
+ it('stays inside the facilitator metadata limits (32 chars, 5 tags)', () => {
+ expect(AGENT_CHALLENGE.serviceName.length).toBeLessThanOrEqual(32);
+ expect(AGENT_CHALLENGE.tags.length).toBeLessThanOrEqual(5);
+ for (const tag of AGENT_CHALLENGE.tags) expect(tag.length).toBeLessThanOrEqual(32);
+ expect(AGENT_CHALLENGE.iconUrl).toMatch(/^https:\/\//);
+ });
+});
diff --git a/tests/api/skills-catalog.test.js b/tests/api/skills-catalog.test.js
new file mode 100644
index 000000000..c567c3efe
--- /dev/null
+++ b/tests/api/skills-catalog.test.js
@@ -0,0 +1,270 @@
+/**
+ * Regression cover for the marketplace skills catalog handlers.
+ *
+ * Three defects found by exercising the live endpoints, all fixed here:
+ *
+ * 1. GET /api/skills with a cursor whose pivot row no longer resolves (the
+ * skill was deleted or flipped private between pages) silently returned
+ * page 1 again, carrying the SAME next_cursor. The marketplace grid's
+ * "load more" then re-appended the first page forever.
+ * 2. POST /api/skills/:id/install takes no request body, which made it a
+ * CORS-simple request any origin could fire with the visitor's cookie.
+ * It now requires the same CSRF token every sibling mutation does.
+ * 3. PUT /api/skills/:id answered with avg_rating 0 / rating_count 0
+ * regardless of the skill's real ratings, and the detail view re-renders
+ * from that response, so editing a description appeared to wipe the
+ * rating until the next reload.
+ *
+ * Only the DB / auth / rate-limit / CSRF boundaries are mocked; the handler
+ * logic under test is the real thing.
+ */
+
+import { Readable } from 'node:stream';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const authState = { session: null, bearer: null };
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn(() => null),
+}));
+
+const sqlState = { queue: [], calls: [] };
+
+function sqlImpl(strings, ...values) {
+ sqlState.calls.push({ query: Array.isArray(strings) ? strings.join('?') : String(strings), values });
+ return Promise.resolve(sqlState.queue.length ? sqlState.queue.shift() : []);
+}
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(sqlImpl),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ skillsBrowse: vi.fn(async () => ({ success: true })),
+ chatUser: vi.fn(async () => ({ success: true })),
+ publicIp: vi.fn(async () => ({ success: true })),
+ authIp: vi.fn(async () => ({ success: true })),
+ widgetRead: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+const csrfState = { ok: true };
+vi.mock('../../api/_lib/csrf.js', () => ({
+ requireCsrf: vi.fn(async (req, res) => {
+ if (csrfState.ok) return true;
+ res.statusCode = 403;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(JSON.stringify({ error: 'csrf_missing', error_description: 'X-CSRF-Token header required' }));
+ return false;
+ }),
+}));
+
+const { default: listHandler } = await import('../../api/skills/index.js');
+const { default: installHandler } = await import('../../api/skills/[id]/install.js');
+const { default: detailHandler } = await import('../../api/skills/[id].js');
+
+const USER = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const SKILL = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+
+function makeReq({ method = 'GET', url = '/api/skills', query = {}, body = null } = {}) {
+ const req = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
+ req.method = method;
+ req.url = url;
+ req.query = query;
+ req.headers = { host: 'localhost', ...(body ? { 'content-type': 'application/json' } : {}) };
+ return req;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(handler, reqOpts) {
+ const res = makeRes();
+ await handler(makeReq(reqOpts), res);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null, headers: res.headers };
+}
+
+function skillRow(over = {}) {
+ return {
+ id: SKILL,
+ name: 'Probe',
+ slug: 'probe',
+ description: 'a probe',
+ category: 'general',
+ tags: [],
+ install_count: 3,
+ created_at: '2026-08-01T00:00:00.000Z',
+ author_id: USER,
+ author_display_name: 'probe author',
+ price_per_call_usd: '0',
+ content: 'probe body',
+ schema_json: null,
+ avg_rating: 0,
+ rating_count: 0,
+ installed: false,
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ sqlState.queue = [];
+ sqlState.calls = [];
+ authState.session = null;
+ authState.bearer = null;
+ csrfState.ok = true;
+ vi.clearAllMocks();
+});
+
+describe('GET /api/skills pagination', () => {
+ it('terminates the sequence when the cursor pivot no longer resolves', async () => {
+ // The pivot lookup comes back empty: the skill was deleted or made private.
+ sqlState.queue = [[]];
+
+ const cursor = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+ const r = await invoke(listHandler, { url: `/api/skills?limit=2&cursor=${cursor}` });
+
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({ skills: [], next_cursor: null });
+ // Crucially it must NOT fall through to the list query and hand back page 1.
+ expect(sqlState.calls).toHaveLength(1);
+ });
+
+ it('still paginates when the cursor pivot resolves', async () => {
+ sqlState.queue = [
+ [{ install_count: 9, created_at: '2026-08-01T00:00:00.000Z', name: 'Pivot' }],
+ [skillRow({ id: SKILL }), skillRow({ id: 'dddddddd-dddd-4ddd-8ddd-dddddddddddd' })],
+ ];
+
+ const cursor = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+ const r = await invoke(listHandler, { url: `/api/skills?limit=1&cursor=${cursor}` });
+
+ expect(r.status).toBe(200);
+ expect(r.body.skills).toHaveLength(1);
+ expect(r.body.next_cursor).toBe(SKILL);
+ });
+
+ it('rejects a malformed cursor before touching the database', async () => {
+ const r = await invoke(listHandler, { url: '/api/skills?cursor=not-a-uuid' });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toBe('validation_error');
+ expect(sqlState.calls).toHaveLength(0);
+ });
+});
+
+describe('POST /api/skills/:id/install', () => {
+ it('refuses a cookie-session install without a CSRF token', async () => {
+ authState.session = { id: USER, plan: 'free' };
+ csrfState.ok = false;
+
+ const r = await invoke(installHandler, {
+ method: 'POST',
+ url: `/api/skills/${SKILL}/install`,
+ query: { id: SKILL },
+ });
+
+ expect(r.status).toBe(403);
+ expect(r.body.error).toBe('csrf_missing');
+ // The gate must run before any write reaches the database.
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('installs when the CSRF token is present', async () => {
+ authState.session = { id: USER, plan: 'free' };
+ sqlState.queue = [[{ id: SKILL, schema_json: null, content: 'probe body' }], []];
+
+ const r = await invoke(installHandler, {
+ method: 'POST',
+ url: `/api/skills/${SKILL}/install`,
+ query: { id: SKILL },
+ });
+
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({ installed: true, schema_json: null, content: 'probe body' });
+ });
+
+ it('exempts bearer callers from CSRF', async () => {
+ csrfState.ok = false;
+ authState.bearer = { userId: USER };
+ sqlState.queue = [[{ id: SKILL, schema_json: null, content: 'probe body' }], []];
+
+ const r = await invoke(installHandler, {
+ method: 'POST',
+ url: `/api/skills/${SKILL}/install`,
+ query: { id: SKILL },
+ });
+
+ expect(r.status).toBe(200);
+ expect(r.body.installed).toBe(true);
+ });
+
+ it('rejects an anonymous install', async () => {
+ const r = await invoke(installHandler, {
+ method: 'POST',
+ url: `/api/skills/${SKILL}/install`,
+ query: { id: SKILL },
+ });
+ expect(r.status).toBe(401);
+ expect(r.body.error).toBe('unauthorized');
+ });
+});
+
+describe('PUT /api/skills/:id', () => {
+ it('answers with the skill real rating aggregate, not zeros', async () => {
+ authState.session = { id: USER, plan: 'free' };
+ sqlState.queue = [
+ [{ id: SKILL, author_id: USER }], // ownership lookup
+ [skillRow({ description: 'edited' })], // UPDATE ... RETURNING *
+ [{ id: USER, display_name: 'probe author' }], // author lookup
+ [{ avg_rating: 4.5, rating_count: 12 }], // live rating aggregate
+ ];
+
+ const r = await invoke(detailHandler, {
+ method: 'PUT',
+ url: `/api/skills/${SKILL}`,
+ query: { id: SKILL },
+ body: { description: 'edited' },
+ });
+
+ expect(r.status).toBe(200);
+ expect(r.body.skill.avg_rating).toBe(4.5);
+ expect(r.body.skill.rating_count).toBe(12);
+ expect(r.body.skill.description).toBe('edited');
+ });
+
+ it('rejects an edit from a non-author non-admin', async () => {
+ authState.session = { id: USER, plan: 'free' };
+ sqlState.queue = [
+ [{ id: SKILL, author_id: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee' }],
+ [{ plan: 'free' }],
+ ];
+
+ const r = await invoke(detailHandler, {
+ method: 'PUT',
+ url: `/api/skills/${SKILL}`,
+ query: { id: SKILL },
+ body: { description: 'nope' },
+ });
+
+ expect(r.status).toBe(403);
+ expect(r.body.error).toBe('forbidden');
+ });
+});
diff --git a/tests/api/three-token-actions.test.js b/tests/api/three-token-actions.test.js
new file mode 100644
index 000000000..b38efc6d6
--- /dev/null
+++ b/tests/api/three-token-actions.test.js
@@ -0,0 +1,237 @@
+// Handler tests for the database-backed $THREE actions: /burns and /activity.
+//
+// What happened: both queries selected `display_name` from agent_identities, a
+// column that table has never had (it lives on `users`). Every call raised
+// `column "display_name" does not exist`, the `.catch(() => [])` beside it turned
+// the error into a plausible empty result, and the deploy-burn ledger shipped
+// permanently empty while /stats happily reported 3167 deployed agents from the
+// sibling count query that did not name the bad column. Nothing in the logs said
+// otherwise, because the swallow was silent.
+//
+// So there are two guards here: a schema guard that reads the columns the handler
+// actually names against the columns the schema actually declares (this fails on
+// the original code), and behaviour tests for the mapping and the degrade path.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { readFileSync, readdirSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const HANDLER_PATH = fileURLToPath(new URL('../../api/three-token/[action].js', import.meta.url));
+const SRC = readFileSync(HANDLER_PATH, 'utf8');
+
+// ── schema guard ────────────────────────────────────────────────────────────
+
+const SCHEMA_DIR = fileURLToPath(new URL('../../api/_lib/', import.meta.url));
+const MIGRATIONS_DIR = `${SCHEMA_DIR}migrations/`;
+
+function schemaSources() {
+ const files = [`${SCHEMA_DIR}schema.sql`];
+ for (const f of readdirSync(MIGRATIONS_DIR)) {
+ if (f.endsWith('.sql')) files.push(`${MIGRATIONS_DIR}${f}`);
+ }
+ return files.map((f) => readFileSync(f, 'utf8'));
+}
+
+// Columns a table is declared to have: the CREATE TABLE body plus every
+// additive `alter table <t> add column [if not exists] <col>`.
+function declaredColumns(table) {
+ const cols = new Set();
+ for (const sqlText of schemaSources()) {
+ const create = new RegExp(`create\\s+table\\s+(?:if\\s+not\\s+exists\\s+)?${table}\\s*\\(`, 'i').exec(sqlText);
+ if (create) {
+ let depth = 0;
+ let end = create.index + create[0].length - 1;
+ for (let i = end; i < sqlText.length; i++) {
+ if (sqlText[i] === '(') depth++;
+ else if (sqlText[i] === ')' && --depth === 0) { end = i; break; }
+ }
+ const body = sqlText.slice(create.index + create[0].length, end);
+ for (const line of body.split('\n')) {
+ const m = /^\s*([a-z_][a-z0-9_]*)\s+\S/i.exec(line);
+ if (m && !/^(primary|foreign|unique|check|constraint|exclude)$/i.test(m[1])) cols.add(m[1].toLowerCase());
+ }
+ }
+ const alter = new RegExp(`alter\\s+table\\s+(?:if\\s+exists\\s+)?${table}\\s+add\\s+column\\s+(?:if\\s+not\\s+exists\\s+)?([a-z_][a-z0-9_]*)`, 'gi');
+ let a;
+ while ((a = alter.exec(sqlText))) cols.add(a[1].toLowerCase());
+ }
+ return cols;
+}
+
+// Every `SELECT … FROM …` inside a template literal in the handler source.
+function selectStatements(src) {
+ const out = [];
+ const re = /SELECT\s+([\s\S]*?)\sFROM\s+([\s\S]*?)(?:`|\bWHERE\b|\bORDER\b|\bLIMIT\b|\bGROUP\b)/gi;
+ let m;
+ while ((m = re.exec(src))) out.push({ list: m[1], from: m[2] });
+ return out;
+}
+
+// Bare column references in a SELECT list, keyed by the table alias that owns
+// them. Skips function calls and expressions, and drops the `AS <alias>` half:
+// output aliases are ours to name, input columns are the schema's.
+function referencedColumns({ list, from }) {
+ const aliases = new Map(); // alias (or table name) → table
+ // The alias is optional: `FROM agent_identities` binds the table under its own
+ // name, and a required alias here is what let the first draft of this guard
+ // pass the very statement it exists to catch.
+ const fromRe = /([a-z_][a-z0-9_]*)(?:\s+(?:AS\s+)?([a-z][a-z0-9_]*))?/i;
+ for (const chunk of from.split(/\bJOIN\b|,/i)) {
+ const m = fromRe.exec(chunk.replace(/\bLEFT\b|\bRIGHT\b|\bINNER\b|\bOUTER\b/gi, '').trim());
+ if (!m) continue;
+ const table = m[1].toLowerCase();
+ aliases.set(table, table);
+ if (m[2] && !/^(on|using)$/i.test(m[2])) aliases.set(m[2].toLowerCase(), table);
+ }
+ const refs = [];
+ for (const raw of list.split(',')) {
+ const item = raw.split(/\bAS\b/i)[0].trim();
+ if (!item || item.includes('(') || item === '*') continue;
+ const dotted = /^([a-z_][a-z0-9_]*)\.([a-z_][a-z0-9_]*)$/i.exec(item);
+ if (dotted) {
+ const table = aliases.get(dotted[1].toLowerCase());
+ if (table) refs.push({ table, column: dotted[2].toLowerCase() });
+ continue;
+ }
+ const bare = /^([a-z_][a-z0-9_]*)$/i.exec(item);
+ // A bare column is unambiguous only in a single-table FROM.
+ if (bare && new Set(aliases.values()).size === 1) {
+ refs.push({ table: [...aliases.values()][0], column: bare[1].toLowerCase() });
+ }
+ }
+ return refs;
+}
+
+describe('$THREE handler SQL matches the declared schema', () => {
+ it('selects no column agent_identities / agent_revenue_events do not have', () => {
+ const known = {
+ agent_identities: declaredColumns('agent_identities'),
+ agent_revenue_events: declaredColumns('agent_revenue_events'),
+ };
+ // Sanity: the parser found the tables at all, so a green test means
+ // "checked and clean", never "matched nothing".
+ expect(known.agent_identities.has('name')).toBe(true);
+ expect(known.agent_identities.has('display_name')).toBe(false);
+ expect(known.agent_revenue_events.has('gross_amount')).toBe(true);
+
+ const bad = [];
+ let checked = 0;
+ for (const stmt of selectStatements(SRC)) {
+ for (const ref of referencedColumns(stmt)) {
+ if (!(ref.table in known)) continue;
+ checked++;
+ if (!known[ref.table].has(ref.column)) bad.push(`${ref.table}.${ref.column}`);
+ }
+ }
+ expect(checked).toBeGreaterThan(0);
+ expect(bad).toEqual([]);
+ });
+});
+
+// ── behaviour ───────────────────────────────────────────────────────────────
+
+vi.mock('../../api/_lib/db.js', () => ({ sql: vi.fn() }));
+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => null) }));
+vi.mock('../../api/_lib/token/config.js', () => ({
+ TOKEN_MINT: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+}));
+vi.mock('../../api/_lib/market/token-market.js', () => ({ fetchTokenMarketData: vi.fn(async () => null) }));
+vi.mock('../../api/_lib/coin/three-holders.js', () => ({
+ threeHolderBalances: vi.fn(async () => new Map()),
+ threeHolderCount: vi.fn(async () => null),
+}));
+vi.mock('../../api/_lib/token/buyback.js', () => ({ buybackStats: vi.fn(async () => null) }));
+vi.mock('../../api/_lib/token/microbuy.js', () => ({ microbuyStats: vi.fn(async () => null) }));
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+
+import { sql } from '../../api/_lib/db.js';
+import handler from '../../api/three-token/[action].js';
+
+function makeReq(url) {
+ return { url, method: 'GET', 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);
+
+// Route each tagged-template query by what it says, so the tests don't depend on
+// the order the handler fires them in.
+function routeSql(handlers) {
+ sql.mockImplementation((strings) => {
+ const text = strings.join(' ');
+ for (const [needle, respond] of handlers) {
+ if (text.includes(needle)) return respond();
+ }
+ return Promise.resolve([]);
+ });
+}
+
+describe('GET /api/three-token/burns', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+ afterEach(() => { vi.restoreAllMocks(); });
+
+ it('renders the deploy-burn ledger from real agent rows', async () => {
+ routeSql([
+ ['ORDER BY created_at DESC', () => Promise.resolve([
+ { id: 'a1', name: 'Green Galunga', created_at: '2026-08-16T04:58:12.852Z' },
+ { id: 'a2', name: null, created_at: '2026-08-15T21:17:07.046Z' },
+ ])],
+ ['count(*)', () => Promise.resolve([{ total: 3167 }])],
+ ]);
+ const res = makeRes();
+ await handler(makeReq('/api/three-token/burns'), res);
+
+ expect(res.statusCode).toBe(200);
+ const body = getJson(res);
+ expect(body.burn_per_deploy).toBe(1000);
+ expect(body.total_burned).toBe(3167 * 1000);
+ expect(body.burns).toHaveLength(2);
+ expect(body.burns[0]).toMatchObject({ id: 'a1', agent_name: 'Green Galunga', amount: 1000, reason: 'agent_deploy' });
+ // A nameless agent still gets a label rather than an empty cell.
+ expect(body.burns[1].agent_name).toBe('Agent');
+ });
+
+ it('degrades to an empty ledger on a query failure, and logs why', async () => {
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ routeSql([
+ ['ORDER BY created_at DESC', () => Promise.reject(new Error('column "nope" does not exist'))],
+ ['count(*)', () => Promise.resolve([{ total: 7 }])],
+ ]);
+ const res = makeRes();
+ await handler(makeReq('/api/three-token/burns'), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(getJson(res).burns).toEqual([]);
+ // The silent swallow is what hid the original bug: the reason must reach the logs.
+ expect(logged).toHaveBeenCalled();
+ expect(logged.mock.calls.flat().join(' ')).toContain('does not exist');
+ });
+});
+
+describe('GET /api/three-token/activity', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('maps revenue events to USD with the agent name', async () => {
+ routeSql([
+ ['agent_revenue_events', () => Promise.resolve([
+ { id: 'e1', skill: 'render', gross_amount: '2500000', fee_amount: '250000', created_at: '2026-08-16T00:00:00Z', agent_name: 'Pixel' },
+ { id: 'e2', skill: null, gross_amount: null, fee_amount: null, created_at: '2026-08-15T00:00:00Z', agent_name: null },
+ ])],
+ ]);
+ const res = makeRes();
+ await handler(makeReq('/api/three-token/activity'), res);
+
+ const body = getJson(res);
+ expect(body.events[0]).toMatchObject({ id: 'e1', type: 'render', gross_usd: 2.5, fee_usd: 0.25, agent_name: 'Pixel' });
+ expect(body.events[1]).toMatchObject({ type: 'payment', gross_usd: null, fee_usd: null, agent_name: 'Agent' });
+ });
+});
diff --git a/tests/api/threews-me.test.js b/tests/api/threews-me.test.js
new file mode 100644
index 000000000..b0305e8fd
--- /dev/null
+++ b/tests/api/threews-me.test.js
@@ -0,0 +1,166 @@
+// GET /api/threews/me: the signed-in caller's `<label>.threews.sol` claim.
+//
+// The handler has three terminal states (`claimed`, `available`,
+// `needs_username`) and the /threews/claim page branches on all three, so each
+// one is pinned here along with the unauthenticated and deleted-user paths.
+// No Solana RPC is involved: this endpoint only reads our own tables.
+
+import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const sessionMock = vi.fn(async () => null);
+const bearerMock = vi.fn(async () => null);
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => sessionMock(...a),
+ authenticateBearer: (...a) => bearerMock(...a),
+ extractBearer: () => null,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authedReadIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+vi.mock('../../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'https://three.ws' },
+}));
+
+beforeAll(() => {
+ process.env.THREEWS_SOL_PARENT_DOMAIN = 'threews.sol';
+});
+
+const { default: handler } = await import('../../api/threews/me.js');
+
+const USER_ID = '00000000-0000-0000-0000-000000000001';
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; },
+ };
+}
+
+async function call() {
+ const res = makeRes();
+ await handler({ url: '/api/threews/me', method: 'GET', headers: { host: 'x' }, query: {} }, res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch { /* non-JSON body stays null */ }
+ return { res, body: parsed };
+}
+
+function signedIn() {
+ sessionMock.mockResolvedValue({ id: USER_ID });
+}
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ sessionMock.mockReset().mockResolvedValue(null);
+ bearerMock.mockReset().mockResolvedValue(null);
+});
+
+describe('GET /api/threews/me', () => {
+ it('401s when neither a session nor a bearer token authenticates', async () => {
+ const { res, body } = await call();
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('404s when the session points at a deleted user', async () => {
+ signedIn();
+ sqlMock.mockResolvedValueOnce([]);
+ const { res, body } = await call();
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ // Bailed before the claim lookup.
+ expect(sqlMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports status=claimed with the full name, showcase URL and explorer link', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich', display_name: 'Nicholas' }])
+ .mockResolvedValueOnce([{
+ label: 'nich',
+ parent: 'threews',
+ owner_wallet: 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk',
+ url_record: 'https://three.ws/u/nich',
+ signature: '5xTx',
+ created_at: '2026-05-23T00:00:00.000Z',
+ }]);
+ const { res, body } = await call();
+ expect(res.statusCode).toBe(200);
+ expect(body.data.status).toBe('claimed');
+ expect(body.data.has_claim).toBe(true);
+ expect(body.data.parent).toBe('threews');
+ expect(body.data.claim.full).toBe('nich.threews.sol');
+ expect(body.data.claim.showcase_url).toBe('https://three.ws/u/nich');
+ expect(body.data.claim.explorer).toBe('https://solscan.io/tx/5xTx');
+ expect(body.data.claim_url).toBeNull();
+ expect(body.data.blocked_reason).toBeNull();
+ });
+
+ it('falls back to the on-chain URL record when the username was cleared after the mint', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: null, display_name: 'Nicholas' }])
+ .mockResolvedValueOnce([{
+ label: 'nich',
+ parent: 'threews',
+ owner_wallet: 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk',
+ url_record: 'https://three.ws/u/nich',
+ signature: null,
+ created_at: '2026-05-23T00:00:00.000Z',
+ }]);
+ const { body } = await call();
+ expect(body.data.claim.showcase_url).toBe('https://three.ws/u/nich');
+ // `signature` is nullable in the schema, so the explorer link must not
+ // render as /tx/null.
+ expect(body.data.claim.explorer).toBeNull();
+ });
+
+ it('reports status=available with a claim URL when the account has a username but no claim', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich', display_name: 'Nicholas' }])
+ .mockResolvedValueOnce([]);
+ const { res, body } = await call();
+ expect(res.statusCode).toBe(200);
+ expect(body.data.status).toBe('available');
+ expect(body.data.has_claim).toBe(false);
+ expect(body.data.claim).toBeNull();
+ expect(body.data.claim_url).toBe('https://three.ws/threews/claim');
+ expect(body.data.blocked_reason).toBeNull();
+ });
+
+ it('reports status=needs_username with a readable reason when no username is set', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: null, display_name: 'qa-audit' }])
+ .mockResolvedValueOnce([]);
+ const { res, body } = await call();
+ expect(res.statusCode).toBe(200);
+ expect(body.data.status).toBe('needs_username');
+ expect(body.data.claim_url).toBeNull();
+ expect(body.data.blocked_reason).toMatch(/username/i);
+ });
+
+ it('accepts a bearer token when there is no session cookie', async () => {
+ bearerMock.mockResolvedValue({ userId: USER_ID });
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich', display_name: 'Nicholas' }])
+ .mockResolvedValueOnce([]);
+ const { res, body } = await call();
+ expect(res.statusCode).toBe(200);
+ expect(body.data.user.id).toBe(USER_ID);
+ });
+});
diff --git a/tests/api/threews-subdomain-mint.test.js b/tests/api/threews-subdomain-mint.test.js
new file mode 100644
index 000000000..25a456de6
--- /dev/null
+++ b/tests/api/threews-subdomain-mint.test.js
@@ -0,0 +1,287 @@
+// /api/threews/subdomain: POST (mint) and DELETE (release) branches.
+//
+// The availability GET path is covered in threews-subdomain-availability.test.js.
+// This file covers everything behind authentication, which the live-server audit
+// cannot reach: a box without THREEWS_SOL_PARENT_SECRET_BASE58 short-circuits
+// every POST at the 503 config gate, so the validation ladder underneath it is
+// only observable here.
+//
+// api/_lib/threews-sns.js is mocked wholesale, so no Solana RPC call is made and
+// nothing is ever minted on-chain by this suite.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const sessionMock = vi.fn(async () => null);
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => sessionMock(...a),
+ authenticateBearer: async () => null,
+ extractBearer: () => null,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+vi.mock('../../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'https://three.ws' } }));
+
+const hasOwnerKeyMock = vi.fn(() => true);
+const getSubdomainOwnerMock = vi.fn(async () => null);
+const mintSubdomainMock = vi.fn(async () => ({
+ signature: '5xTx',
+ fullName: 'nich.threews.sol',
+ url_record: 'https://three.ws/u/nich',
+}));
+vi.mock('../../api/_lib/threews-sns.js', () => ({
+ PARENT_LABEL: 'threews',
+ fullDomain: (label) => `${label}.threews.sol`,
+ getSubdomainOwner: (...a) => getSubdomainOwnerMock(...a),
+ hasOwnerKey: (...a) => hasOwnerKeyMock(...a),
+ mintSubdomain: (...a) => mintSubdomainMock(...a),
+ normalizeLabel: (input) => {
+ if (typeof input !== 'string') return null;
+ const v = input.trim().toLowerCase();
+ return /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(v) ? v : null;
+ },
+}));
+
+const { default: handler } = await import('../../api/threews/subdomain.js');
+
+const USER_ID = '00000000-0000-0000-0000-000000000001';
+const WALLET = 'HKKp49zUBeaABFMpBWKCJPoNDLiR4AEEr8FJKuZPn6Nk';
+
+function makeReq(url, methodName, body) {
+ const req = { url, method: methodName, headers: { host: 'x' }, query: {} };
+ if (body !== undefined) {
+ req.headers['content-type'] = 'application/json';
+ req.body = body;
+ }
+ return req;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(b) { this._body = b; },
+ };
+}
+
+async function call(url, methodName, body) {
+ const res = makeRes();
+ await handler(makeReq(url, methodName, body), res);
+ let parsed = null;
+ try { parsed = JSON.parse(res._body); } catch { /* non-JSON body stays null */ }
+ return { res, body: parsed };
+}
+
+function signedIn() {
+ sessionMock.mockResolvedValue({ id: USER_ID });
+}
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ sessionMock.mockReset().mockResolvedValue(null);
+ hasOwnerKeyMock.mockReset().mockReturnValue(true);
+ getSubdomainOwnerMock.mockReset().mockResolvedValue(null);
+ mintSubdomainMock.mockReset().mockResolvedValue({
+ signature: '5xTx',
+ fullName: 'nich.threews.sol',
+ url_record: 'https://three.ws/u/nich',
+ });
+});
+
+describe('POST /api/threews/subdomain', () => {
+ it('401s an anonymous caller before touching the DB or the chain', async () => {
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich' });
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ expect(sqlMock).not.toHaveBeenCalled();
+ expect(mintSubdomainMock).not.toHaveBeenCalled();
+ });
+
+ it('503s with config_missing when the platform owner key is absent', async () => {
+ signedIn();
+ hasOwnerKeyMock.mockReturnValue(false);
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich' });
+ expect(res.statusCode).toBe(503);
+ expect(body.error).toBe('config_missing');
+ expect(mintSubdomainMock).not.toHaveBeenCalled();
+ });
+
+ it('400s a malformed label', async () => {
+ signedIn();
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'not a label!' });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('409s when the account has no username to match the label against', async () => {
+ signedIn();
+ sqlMock.mockResolvedValueOnce([{ id: USER_ID, username: null }]);
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich' });
+ expect(res.statusCode).toBe(409);
+ expect(body.error).toBe('no_username');
+ });
+
+ it('409s when the label does not match the caller username', async () => {
+ signedIn();
+ sqlMock.mockResolvedValueOnce([{ id: USER_ID, username: 'nich' }]);
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'someoneelse' });
+ expect(res.statusCode).toBe(409);
+ expect(body.error).toBe('username_mismatch');
+ expect(mintSubdomainMock).not.toHaveBeenCalled();
+ });
+
+ it('409s when the label is already claimed in our own table', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich' }])
+ .mockResolvedValueOnce([{ id: 'claim-1' }]);
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich' });
+ expect(res.statusCode).toBe(409);
+ expect(body.error).toBe('conflict');
+ expect(getSubdomainOwnerMock).not.toHaveBeenCalled();
+ });
+
+ it('409s when the name is already registered on-chain to someone else', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich' }])
+ .mockResolvedValueOnce([]);
+ getSubdomainOwnerMock.mockResolvedValue(WALLET);
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich' });
+ expect(res.statusCode).toBe(409);
+ expect(body.error).toBe('conflict');
+ expect(mintSubdomainMock).not.toHaveBeenCalled();
+ });
+
+ it('503s (not 500) when the pre-mint on-chain check cannot reach Solana', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich' }])
+ .mockResolvedValueOnce([]);
+ getSubdomainOwnerMock.mockRejectedValue(new Error('fetch failed'));
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich' });
+ expect(res.statusCode).toBe(503);
+ expect(body.error).toBe('upstream_unavailable');
+ expect(body.error_description).toMatch(/retry/i);
+ expect(mintSubdomainMock).not.toHaveBeenCalled();
+ });
+
+ it('400s an owner_wallet that is not a base58 Solana address', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich' }])
+ .mockResolvedValueOnce([]);
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich', owner_wallet: '0xdeadbeef' });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(mintSubdomainMock).not.toHaveBeenCalled();
+ });
+
+ it('403s an owner_wallet that is not linked to the caller account', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich' }])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([]);
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich', owner_wallet: WALLET });
+ expect(res.statusCode).toBe(403);
+ expect(body.error).toBe('forbidden');
+ expect(mintSubdomainMock).not.toHaveBeenCalled();
+ });
+
+ it('409s when no owner_wallet was passed and the account has no agent wallet', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich' }])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([]);
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich' });
+ expect(res.statusCode).toBe(409);
+ expect(body.error).toBe('no_wallet');
+ expect(mintSubdomainMock).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a mint failure with the upstream status instead of a bare 500', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich' }])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([{ sol: WALLET }]);
+ mintSubdomainMock.mockRejectedValue(
+ Object.assign(new Error('insufficient rent'), { status: 502, code: 'upstream_error' }),
+ );
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich' });
+ expect(res.statusCode).toBe(502);
+ expect(body.error).toBe('upstream_error');
+ });
+
+ it('201s with the stored row, showcase URL and explorer link on success', async () => {
+ signedIn();
+ sqlMock
+ .mockResolvedValueOnce([{ id: USER_ID, username: 'nich' }])
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([{ sol: WALLET }])
+ .mockResolvedValueOnce([{
+ id: 'claim-1',
+ label: 'nich',
+ parent: 'threews',
+ owner_wallet: WALLET,
+ url_record: 'https://three.ws/u/nich',
+ signature: '5xTx',
+ created_at: '2026-05-23T00:00:00.000Z',
+ }]);
+ const { res, body } = await call('/api/threews/subdomain', 'POST', { label: 'nich' });
+ expect(res.statusCode).toBe(201);
+ expect(mintSubdomainMock).toHaveBeenCalledWith({ label: 'nich', recipientWallet: WALLET });
+ expect(body.data.full).toBe('nich.threews.sol');
+ expect(body.data.showcase_url).toBe('https://three.ws/u/nich');
+ expect(body.data.explorer).toBe('https://solscan.io/tx/5xTx');
+ });
+});
+
+describe('DELETE /api/threews/subdomain', () => {
+ it('401s an anonymous caller', async () => {
+ const { res, body } = await call('/api/threews/subdomain?label=nich', 'DELETE');
+ expect(res.statusCode).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('400s when no label is supplied', async () => {
+ signedIn();
+ const { res, body } = await call('/api/threews/subdomain', 'DELETE');
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('404s when the caller has no claim on that label', async () => {
+ signedIn();
+ sqlMock.mockResolvedValueOnce([]);
+ const { res, body } = await call('/api/threews/subdomain?label=nich', 'DELETE');
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('200s and says on-chain ownership is untouched when a claim is released', async () => {
+ signedIn();
+ sqlMock.mockResolvedValueOnce([{ id: 'claim-1', label: 'nich', parent: 'threews' }]);
+ const { res, body } = await call('/api/threews/subdomain?label=nich', 'DELETE');
+ expect(res.statusCode).toBe(200);
+ expect(body.data.released.label).toBe('nich');
+ expect(body.data.note).toMatch(/on-chain/i);
+ });
+});
diff --git a/tests/instant-agent.test.js b/tests/instant-agent.test.js
new file mode 100644
index 000000000..47dbdeb8a
--- /dev/null
+++ b/tests/instant-agent.test.js
@@ -0,0 +1,233 @@
+/**
+ * api/instant-agent.js turns one sentence into a finished character: a name, a
+ * handle, a personality, a body from the shipped avatar library, and a signature
+ * move from the shipped clip library. Two halves are covered here.
+ *
+ * 1. The catalogs are claims about real files. BODIES states how many of the 52
+ * canonical joints each GLB resolves and how many of its meshes carry morph
+ * targets; MOVES names clips in public/animations/manifest.json. Both are
+ * re-measured from the assets on disk, so replacing an avatar or renaming a
+ * clip fails here instead of silently shipping a T-posing agent to the first
+ * screen a new visitor sees.
+ * 2. The pure helpers that repair whatever the model returns. Every one of them
+ * must produce a usable value from garbage input, because the page renders
+ * the result directly.
+ */
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import {
+ BODIES,
+ MOVES,
+ MOODS,
+ RESTING_CLIP,
+ safeHandle,
+ pickBody,
+ pickMove,
+ extractJson,
+ buildPersona,
+} from '../api/instant-agent.js';
+import { canonicalizeBoneName, CANONICAL_BONES } from '../src/glb-canonicalize.js';
+
+const root = (p) => resolve(process.cwd(), p);
+
+/** Parse the JSON chunk of a .glb (12-byte header, then the chunk header). */
+function glbJson(path) {
+ const buf = readFileSync(path);
+ expect(buf.subarray(0, 4).toString('ascii')).toBe('glTF');
+ const jsonLength = buf.readUInt32LE(12);
+ return JSON.parse(buf.subarray(20, 20 + jsonLength).toString('utf8'));
+}
+
+/** How many of the 52 canonical joints this file's skins resolve to. */
+function canonicalBoneCount(json) {
+ const nodes = json.nodes || [];
+ const canon = new Set();
+ for (const skin of json.skins || []) {
+ for (const joint of skin.joints || []) {
+ const name = canonicalizeBoneName(nodes[joint]?.name || '');
+ if (name && CANONICAL_BONES.includes(name)) canon.add(name);
+ }
+ }
+ return canon.size;
+}
+
+/** Meshes with at least one morph-target primitive (the ones that can emote). */
+function morphMeshCount(json) {
+ return (json.meshes || []).filter((mesh) =>
+ (mesh.primitives || []).some((p) => Array.isArray(p.targets) && p.targets.length > 0),
+ ).length;
+}
+
+const clipManifest = JSON.parse(readFileSync(root('public/animations/manifest.json'), 'utf8'));
+const clipByName = new Map(clipManifest.map((c) => [c.name, c]));
+
+describe('BODIES is measured against the shipped avatars', () => {
+ it.each(BODIES.map((b) => [b.id, b]))('%s ships, is fully rigged, and matches its counts', (_id, body) => {
+ const json = glbJson(root(`public${body.glb}`));
+ expect(canonicalBoneCount(json)).toBe(body.canonicalBones);
+ expect(body.canonicalBones).toBe(CANONICAL_BONES.length);
+ expect(morphMeshCount(json)).toBe(body.morphMeshes);
+ });
+
+ it('has unique ids and no empty copy', () => {
+ expect(new Set(BODIES.map((b) => b.id)).size).toBe(BODIES.length);
+ for (const body of BODIES) {
+ expect(body.label.length).toBeGreaterThan(0);
+ expect(body.blurb.length).toBeGreaterThan(0);
+ expect(body.traits.length).toBeGreaterThan(0);
+ }
+ });
+});
+
+describe('MOVES names real clips', () => {
+ it.each([...Object.entries(MOVES)])('%s resolves to a manifest clip', (_mood, move) => {
+ const clip = clipByName.get(move.clip);
+ expect(clip, `${move.clip} is not in public/animations/manifest.json`).toBeTruthy();
+ expect(() => readFileSync(root(`public${clip.url}`))).not.toThrow();
+ });
+
+ it('the resting clip every body falls back to is real', () => {
+ expect(clipByName.has(RESTING_CLIP)).toBe(true);
+ });
+
+ it('MOODS is exactly the set the model is told to choose from', () => {
+ expect(MOODS).toEqual(Object.keys(MOVES));
+ });
+});
+
+describe('safeHandle', () => {
+ it('slugifies a display name', () => {
+ expect(safeHandle('Ada Lovelace')).toBe('ada-lovelace');
+ expect(safeHandle(' Café Münz!! ')).toBe('cafe-munz');
+ });
+
+ it('falls back to the name, then to a stable generic', () => {
+ expect(safeHandle('', 'Nova Guide')).toBe('nova-guide');
+ expect(safeHandle('!!', '???')).toBe('new-agent');
+ expect(safeHandle(null, null)).toBe('new-agent');
+ });
+
+ it('refuses reserved handles at both levels', () => {
+ expect(safeHandle('admin', 'Nova')).toBe('nova');
+ expect(safeHandle('admin', 'api')).toBe('new-agent');
+ });
+
+ it('never returns something unusable in a URL', () => {
+ for (const raw of ['../../etc/passwd', '<script>', ' ', 'a', '🙂🙂🙂']) {
+ const handle = safeHandle(raw, 'Fallback Name');
+ expect(handle).toMatch(/^[a-z0-9][a-z0-9-]{1,19}$/);
+ }
+ });
+});
+
+describe('pickBody', () => {
+ it('honours the model hint over incidental words', () => {
+ expect(pickBody('a warm friendly host', 'xbot').id).toBe('xbot');
+ expect(pickBody('anything at all', 'michelle').id).toBe('michelle');
+ });
+
+ it('matches traits on word boundaries, not substrings', () => {
+ expect(pickBody('a robot for tech teams').id).toBe('xbot');
+ // "botany" contains "bot" but must not select the robot shell.
+ expect(pickBody('a botany tutor for gardeners').id).not.toBe('xbot');
+ });
+
+ it('always returns a body, even for an empty idea', () => {
+ expect(BODIES).toContain(pickBody('', ''));
+ expect(BODIES).toContain(pickBody(' '));
+ });
+});
+
+describe('pickMove', () => {
+ it('resolves a known mood and defaults the rest to warm', () => {
+ expect(pickMove('bold')).toBe(MOVES.bold);
+ expect(pickMove('nonsense')).toBe(MOVES.warm);
+ expect(pickMove(undefined)).toBe(MOVES.warm);
+ });
+});
+
+describe('extractJson', () => {
+ it('reads a bare object', () => {
+ expect(extractJson('{"name":"Ada"}')).toEqual({ name: 'Ada' });
+ });
+
+ it('reads through a code fence and surrounding prose', () => {
+ expect(extractJson('Sure!\n```json\n{"name":"Ada"}\n```\nHope that helps.')).toEqual({
+ name: 'Ada',
+ });
+ });
+
+ it('handles nested objects and braces inside strings', () => {
+ expect(extractJson('{"a":{"b":1},"c":"} not the end {"}')).toEqual({
+ a: { b: 1 },
+ c: '} not the end {',
+ });
+ expect(extractJson('{"c":"escaped \\" quote {"}')).toEqual({ c: 'escaped " quote {' });
+ });
+
+ it('returns null for anything unparseable', () => {
+ expect(extractJson('')).toBeNull();
+ expect(extractJson(null)).toBeNull();
+ expect(extractJson('no json here')).toBeNull();
+ expect(extractJson('{"unterminated": ')).toBeNull();
+ expect(extractJson('{not: valid}')).toBeNull();
+ });
+});
+
+describe('buildPersona', () => {
+ const idea = 'a patient museum guide who explains renaissance paintings';
+
+ it('passes a complete completion through, trimmed', () => {
+ const persona = buildPersona(
+ {
+ name: ' Lorenzo ',
+ handle: 'Lorenzo!',
+ tagline: 'Your guide to the Renaissance',
+ personality: 'You are Lorenzo. You explain paintings.',
+ greeting: 'Welcome, traveller.',
+ starters: ['What is this?', 'Who painted it?', 'Why the light?', 'ignored fourth'],
+ mood: 'precise',
+ body: 'studio',
+ },
+ idea,
+ );
+ expect(persona.name).toBe('Lorenzo');
+ expect(persona.handle).toBe('lorenzo');
+ expect(persona.starters).toHaveLength(3);
+ expect(persona.mood).toBe('precise');
+ expect(persona.bodyHint).toBe('studio');
+ });
+
+ it('renders no holes when the model returns nothing usable', () => {
+ for (const parsed of [null, {}, 'not an object', []]) {
+ const persona = buildPersona(parsed, idea);
+ expect(persona.name.length).toBeGreaterThan(0);
+ expect(persona.tagline.length).toBeGreaterThan(0);
+ expect(persona.personality.length).toBeGreaterThan(0);
+ expect(persona.greeting.length).toBeGreaterThan(0);
+ expect(persona.starters).toHaveLength(3);
+ expect(persona.starters.every((s) => s.length > 0)).toBe(true);
+ expect(MOODS).toContain(persona.mood);
+ expect(persona.handle).toMatch(/^[a-z0-9][a-z0-9-]{1,19}$/);
+ }
+ });
+
+ it('clamps every field to its contract length', () => {
+ const long = 'x'.repeat(2000);
+ const persona = buildPersona(
+ { name: long, tagline: long, personality: long, greeting: long, starters: [long] },
+ idea,
+ );
+ expect(persona.name.length).toBeLessThanOrEqual(24);
+ expect(persona.tagline.length).toBeLessThanOrEqual(70);
+ expect(persona.personality.length).toBeLessThanOrEqual(900);
+ expect(persona.greeting.length).toBeLessThanOrEqual(140);
+ for (const starter of persona.starters) expect(starter.length).toBeLessThanOrEqual(60);
+ });
+
+ it('falls back to warm for a mood outside the ladder', () => {
+ expect(buildPersona({ mood: 'furious' }, idea).mood).toBe('warm');
+ });
+});
diff --git a/tests/og-avatar.test.js b/tests/og-avatar.test.js
new file mode 100644
index 000000000..76ba1ef0c
--- /dev/null
+++ b/tests/og-avatar.test.js
@@ -0,0 +1,108 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+
+import { fetchOgImage, MAX_OG_IMAGE_BYTES } from '../api/_lib/og-avatar.js';
+import { parseLimit } from '../api/trending.js';
+
+const realFetch = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = realFetch;
+ vi.restoreAllMocks();
+});
+
+/** A Response whose body streams `bytes` in `chunkSize` pieces, like a real host. */
+function imageResponse(bytes, { ct = 'image/png', contentLength, status = 200, chunkSize = 4096 } = {}) {
+ const headers = new Headers();
+ if (ct) headers.set('content-type', ct);
+ if (contentLength !== null) headers.set('content-length', String(contentLength ?? bytes.length));
+
+ let offset = 0;
+ const body = new ReadableStream({
+ pull(controller) {
+ if (offset >= bytes.length) return controller.close();
+ controller.enqueue(bytes.subarray(offset, offset + chunkSize));
+ offset += chunkSize;
+ },
+ });
+ return { ok: status >= 200 && status < 300, status, headers, body };
+}
+
+function mockFetch(response) {
+ const spy = vi.fn(async () => (typeof response === 'function' ? response() : response));
+ globalThis.fetch = spy;
+ return spy;
+}
+
+describe('og-avatar: fetchOgImage main path', () => {
+ it('returns the inline-ready image for a real portrait response', async () => {
+ const png = Buffer.alloc(2048, 7);
+ mockFetch(imageResponse(png));
+
+ const got = await fetchOgImage('https://cdn.example.test/a.png');
+
+ expect(got).not.toBeNull();
+ expect(got.ct).toBe('image/png');
+ expect(Buffer.from(got.b64, 'base64').equals(png)).toBe(true);
+ });
+
+ it('strips charset parameters off the content type', async () => {
+ mockFetch(imageResponse(Buffer.alloc(16, 1), { ct: 'image/svg+xml; charset=utf-8' }));
+ expect((await fetchOgImage('https://cdn.example.test/a.svg')).ct).toBe('image/svg+xml');
+ });
+});
+
+describe('og-avatar: fetchOgImage failure paths', () => {
+ it('rejects a body that outgrows the cap even when content-length lied', async () => {
+ const huge = Buffer.alloc(MAX_OG_IMAGE_BYTES + 8192, 3);
+ // Host claims a tiny image, then streams a huge one: the stream cap is the
+ // only thing standing between this and an unbounded read.
+ mockFetch(imageResponse(huge, { contentLength: 64 }));
+
+ expect(await fetchOgImage('https://cdn.example.test/huge.png')).toBeNull();
+ });
+
+ it('rejects an oversized image on its declared content-length alone', async () => {
+ const spy = mockFetch(imageResponse(Buffer.alloc(8, 1), { contentLength: MAX_OG_IMAGE_BYTES + 1 }));
+ expect(await fetchOgImage('https://cdn.example.test/big.png')).toBeNull();
+ expect(spy).toHaveBeenCalledOnce();
+ });
+
+ it('rejects a non-image response, so an HTML error page never lands in the card', async () => {
+ mockFetch(imageResponse(Buffer.from('<!doctype html>'), { ct: 'text/html' }));
+ expect(await fetchOgImage('https://cdn.example.test/oops')).toBeNull();
+ });
+
+ it('returns null for a non-ok status', async () => {
+ mockFetch(imageResponse(Buffer.alloc(8), { status: 404 }));
+ expect(await fetchOgImage('https://cdn.example.test/missing.png')).toBeNull();
+ });
+
+ it('swallows a thrown fetch rather than breaking the unfurl', async () => {
+ globalThis.fetch = vi.fn(async () => { throw new Error('ENOTFOUND'); });
+ expect(await fetchOgImage('https://cdn.example.test/dead.png')).toBeNull();
+ });
+
+ it('never fetches a non-http URL', async () => {
+ const spy = mockFetch(imageResponse(Buffer.alloc(8)));
+ for (const bad of [null, undefined, '', 'file:///etc/passwd', 'data:image/png;base64,AA', 42]) {
+ expect(await fetchOgImage(bad)).toBeNull();
+ }
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
+describe('trending: parseLimit', () => {
+ it('clamps a real limit into 1..20', () => {
+ expect(parseLimit('5')).toBe(5);
+ expect(parseLimit('999')).toBe(20);
+ expect(parseLimit('-4')).toBe(1);
+ expect(parseLimit('0')).toBe(1);
+ });
+
+ it('falls back to the default instead of producing "limit NaN"', () => {
+ // The regression: Number('abc') reached Postgres as NaN, both rankings
+ // failed, and the board answered 200 with an empty list.
+ for (const raw of ['abc', '', null, undefined, 'NaN', ' ']) {
+ expect(parseLimit(raw)).toBe(10);
+ }
+ });
+});
diff --git a/tests/share-x-endpoint.test.js b/tests/share-x-endpoint.test.js
new file mode 100644
index 000000000..782ce7aa9
--- /dev/null
+++ b/tests/share-x-endpoint.test.js
@@ -0,0 +1,156 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock the thin glue deps so the test covers the endpoint's OWN logic: the
+// same-site guard, media validation, caption composition and the X error ->
+// HTTP status mapping. The network/DB beneath publishTweet is exercised
+// separately (tests/x-post-impact.test.js) and by the live curl sweep.
+vi.mock('../api/_lib/http.js', () => ({
+ wrap: (fn) => fn,
+ cors: () => false,
+ method: (req, res, allowed) => {
+ if (allowed.includes(req.method)) return true;
+ res._json = { status: 405, body: { error: 'method_not_allowed' } };
+ return false;
+ },
+ json: (res, status, body) => { res._json = { status, body }; return res; },
+ error: (res, status, code, message, extra = {}) => {
+ res._json = { status, body: { error: code, error_description: message, ...extra } };
+ return res;
+ },
+ readBody: (req, limit) => {
+ const buf = req._buffer ?? Buffer.alloc(0);
+ if (buf.length > limit) return Promise.reject(Object.assign(new Error('payload too large'), { status: 413 }));
+ return Promise.resolve(buf);
+ },
+}));
+
+const getSessionUser = vi.fn(async () => ({ id: 'user-1' }));
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUser(...a),
+ isSameSiteOrigin: (req) => req.headers.origin === 'https://three.ws',
+}));
+vi.mock('../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'https://three.ws' } }));
+
+class XPostError extends Error {
+ constructor(code, message, status = 400, extra = {}) {
+ super(message);
+ this.code = code;
+ this.status = status;
+ this.extra = extra;
+ }
+}
+const publishTweet = vi.fn(async () => ({ tweet_id: '1', url: 'https://x.com/walker/status/1' }));
+vi.mock('../api/_lib/x-post.js', () => ({
+ publishTweet: (...a) => publishTweet(...a),
+ XPostError,
+ MAX_TWEET_LEN: 280,
+}));
+
+const handler = (await import('../api/share/x.js')).default;
+
+function makeReq({ method = 'POST', url = '/api/share/x', contentType = 'image/png', body = Buffer.from('png-bytes'), origin = 'https://three.ws' } = {}) {
+ return {
+ method,
+ url,
+ headers: { origin, 'content-type': contentType },
+ _buffer: body,
+ };
+}
+function makeRes() { return { setHeader() {}, end() {}, statusCode: 200 }; }
+
+async function call(reqOverrides) {
+ const req = makeReq(reqOverrides);
+ const res = makeRes();
+ await handler(req, res);
+ return res._json;
+}
+
+describe('POST /api/share/x', () => {
+ beforeEach(() => {
+ publishTweet.mockReset();
+ publishTweet.mockResolvedValue({ tweet_id: '1', url: 'https://x.com/walker/status/1' });
+ getSessionUser.mockReset();
+ getSessionUser.mockResolvedValue({ id: 'user-1' });
+ });
+
+ it('rejects a cross-site POST before touching the session', async () => {
+ const out = await call({ origin: 'https://evil.example' });
+ expect(out.status).toBe(403);
+ expect(out.body.error).toBe('forbidden');
+ expect(getSessionUser).not.toHaveBeenCalled();
+ });
+
+ it('answers 401 with a login_url when no session is present', async () => {
+ getSessionUser.mockResolvedValue(null);
+ const out = await call();
+ expect(out.status).toBe(401);
+ expect(out.body).toMatchObject({ error: 'auth_required', login_url: '/login' });
+ });
+
+ it('rejects an unsupported media type', async () => {
+ const out = await call({ contentType: 'application/json' });
+ expect(out.status).toBe(415);
+ expect(out.body.error).toBe('unsupported_media_type');
+ });
+
+ it('rejects an empty body', async () => {
+ const out = await call({ body: Buffer.alloc(0) });
+ expect(out.status).toBe(400);
+ expect(out.body.error).toBe('empty_body');
+ });
+
+ it('rejects an image over the 5 MB still-image ceiling', async () => {
+ const out = await call({ body: Buffer.alloc(5 * 1024 * 1024 + 1) });
+ expect(out.status).toBe(413);
+ expect(out.body).toMatchObject({ error: 'too_large', error_description: 'image exceeds the 5 MB limit' });
+ });
+
+ it('accepts a video under the 64 MB clip ceiling', async () => {
+ const out = await call({ contentType: 'video/mp4', body: Buffer.alloc(6 * 1024 * 1024) });
+ expect(out.status).toBe(200);
+ expect(publishTweet.mock.calls[0][0].mediaMimeType).toBe('video/mp4');
+ });
+
+ it('composes the default caption with the avatar deep link', async () => {
+ const out = await call({ url: '/api/share/x?avatar=abc123' });
+ expect(out.status).toBe(200);
+ expect(out.body).toMatchObject({ ok: true, tweet_id: '1' });
+ expect(publishTweet.mock.calls[0][0].text).toBe('I walked my avatar around three.ws. Try yours: three.ws/walk?avatar=abc123');
+ });
+
+ it('uses the caller caption when one is supplied, truncated to a tweet', async () => {
+ const long = 'x'.repeat(400);
+ await call({ url: `/api/share/x?text=${long}` });
+ expect(publishTweet.mock.calls[0][0].text).toHaveLength(280);
+ });
+
+ it('maps not_connected to 409 with a connect_url', async () => {
+ publishTweet.mockRejectedValue(new XPostError('not_connected', 'X account not connected', 400));
+ const out = await call();
+ expect(out.status).toBe(409);
+ expect(out.body).toMatchObject({ error: 'not_connected', connect_url: '/api/auth/x/connect' });
+ });
+
+ // An unrefreshable X token is a reconnect, not a three.ws sign-in. Answering
+ // 401 there made the client show "Sign in to three.ws" and link /login to a
+ // user who was already signed in, with no way to reach the X connect flow.
+ it('maps reauth_required to 409 with a connect_url, never 401', async () => {
+ publishTweet.mockRejectedValue(new XPostError('reauth_required', 'refresh_token missing, reconnect X account', 401));
+ const out = await call();
+ expect(out.status).toBe(409);
+ expect(out.body).toMatchObject({ error: 'reauth_required', connect_url: '/api/auth/x/connect' });
+ });
+
+ it('passes other X errors through with their own status and extras', async () => {
+ publishTweet.mockRejectedValue(new XPostError('quota_exceeded', 'free tier limit reached', 402, { upgrade_url: '/pricing' }));
+ const out = await call();
+ expect(out.status).toBe(402);
+ expect(out.body).toMatchObject({ error: 'quota_exceeded', upgrade_url: '/pricing' });
+ expect(out.body.connect_url).toBeUndefined();
+ });
+
+ it('rejects a non-POST method', async () => {
+ const out = await call({ method: 'GET' });
+ expect(out.status).toBe(405);
+ });
+});
diff --git a/tests/social-sentiment-endpoints.test.js b/tests/social-sentiment-endpoints.test.js
new file mode 100644
index 000000000..5c1fdf1c4
--- /dev/null
+++ b/tests/social-sentiment-endpoints.test.js
@@ -0,0 +1,226 @@
+/**
+ * POST /api/social/sentiment and POST /api/social/sentiment-pulse.
+ *
+ * Both are unauthenticated, IP-rate-limited scoring endpoints over the
+ * deterministic lexicon in src/social/sentiment.js. `sentiment` scores texts
+ * the caller already has; `sentiment-pulse` fetches a coin's live pump.fun
+ * callouts first (the commentary feed that replaced the retired
+ * `/replies/:mint` route) and folds in any caller-supplied snippets.
+ *
+ * The property that matters most here: an upstream outage must never render
+ * as a confident neutral reading. With pump.fun down and nothing else to
+ * score, the pulse answers 502 rather than "score 0, 100% neutral", which is
+ * what a caller (and the paid `sentiment_pulse` MCP tool) would otherwise
+ * bank on as real data.
+ *
+ * Rate limiting is stubbed so the suite never needs Redis; pump.fun is
+ * stubbed at the fetch boundary so no test touches the network.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+const rl = { ok: true };
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { mcpIp: vi.fn(async () => ({ success: rl.ok, reset: Date.now() + 60_000 })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const { default: sentimentHandler } = await import('../api/social/sentiment.js');
+const { default: pulseHandler, calloutsToPosts } = await import('../api/social/sentiment-pulse.js');
+
+function makeReq(url, body, { method = 'POST', contentType = 'application/json' } = {}) {
+ return {
+ method,
+ url,
+ headers: { origin: 'https://three.ws', 'content-type': contentType },
+ body,
+ socket: { remoteAddress: '127.0.0.1' },
+ };
+}
+
+function makeRes() {
+ const r = { statusCode: 200, _h: {}, _b: null };
+ r.setHeader = (k, v) => {
+ r._h[k.toLowerCase()] = v;
+ };
+ r.getHeader = (k) => r._h[k.toLowerCase()];
+ r.end = (b) => {
+ r._b = b;
+ };
+ r.json = () => JSON.parse(r._b);
+ return r;
+}
+
+async function call(handler, path, body, opts) {
+ const res = makeRes();
+ await handler(makeReq(path, body, opts), res);
+ return res;
+}
+
+function callout(overrides = {}) {
+ return {
+ calloutId: 'c-1',
+ username: 'trader',
+ createdAt: 1_777_912_958_533,
+ thesis: 'dev is based, bullish',
+ ...overrides,
+ };
+}
+
+function upstream(status, body) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ headers: { get: () => null },
+ json: async () => body,
+ };
+}
+
+beforeEach(() => {
+ rl.ok = true;
+ vi.restoreAllMocks();
+});
+
+describe('POST /api/social/sentiment', () => {
+ it('scores a batch of posts', async () => {
+ const res = await call(sentimentHandler, '/api/social/sentiment', {
+ posts: [
+ { text: 'to the moon, bullish gem' },
+ { text: 'total rug pull scam, rekt' },
+ { text: 'hello there' },
+ ],
+ });
+ expect(res.statusCode).toBe(200);
+ const out = res.json();
+ expect(out.count).toBe(3);
+ expect(out.posPct + out.negPct + out.neuPct).toBe(100);
+ expect(out.examples.pos.length).toBe(1);
+ expect(out.examples.neg.length).toBe(1);
+ });
+
+ it('rejects an empty batch with a 400 validation error', async () => {
+ const res = await call(sentimentHandler, '/api/social/sentiment', { posts: [] });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('validation_error');
+ });
+
+ it('rejects a non-POST method with 405', async () => {
+ const res = await call(sentimentHandler, '/api/social/sentiment', undefined, {
+ method: 'GET',
+ });
+ expect(res.statusCode).toBe(405);
+ });
+});
+
+describe('calloutsToPosts', () => {
+ it('maps thesis, handle and timestamp, newest first, capped at the limit', () => {
+ const posts = calloutsToPosts(
+ [
+ callout({ calloutId: 'old', createdAt: 1_000, thesis: 'early' }),
+ callout({ calloutId: 'new', createdAt: 9_000, thesis: 'latest' }),
+ callout({ calloutId: 'mid', createdAt: 5_000, thesis: 'middle' }),
+ ],
+ 2,
+ );
+ expect(posts.map((p) => p.id)).toEqual(['new', 'mid']);
+ expect(posts[0]).toMatchObject({ text: 'latest', author: 'trader' });
+ expect(posts[0].ts).toBe(new Date(9_000).toISOString());
+ expect(posts[0]).not.toHaveProperty('_at');
+ });
+
+ it('drops rows with no thesis instead of counting them neutral', () => {
+ const posts = calloutsToPosts(
+ [callout({ thesis: ' ' }), callout({ thesis: null }), callout({ thesis: 'real take' })],
+ 10,
+ );
+ expect(posts).toHaveLength(1);
+ expect(posts[0].text).toBe('real take');
+ });
+
+ it('returns an empty list for a non-array body', () => {
+ expect(calloutsToPosts(null, 10)).toEqual([]);
+ expect(calloutsToPosts({ callouts: [] }, 10)).toEqual([]);
+ });
+});
+
+describe('POST /api/social/sentiment-pulse', () => {
+ it('scores live pump.fun callouts', async () => {
+ const fetchMock = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(
+ upstream(200, {
+ callouts: [
+ callout({ calloutId: 'a', thesis: 'moon soon, bullish' }),
+ callout({ calloutId: 'b', createdAt: 1_777_000_000_000, thesis: 'rug pull scam' }),
+ ],
+ }),
+ );
+
+ const res = await call(pulseHandler, '/api/social/sentiment-pulse', { token: MINT, limit: 50 });
+ expect(res.statusCode).toBe(200);
+ const out = res.json();
+ expect(out.ok).toBe(true);
+ expect(out.token).toBe(MINT);
+ expect(out.overall.count).toBe(2);
+ expect(out.sources.pumpfunStatus).toBe('ok');
+ expect(out.sources.pumpfunCount).toBe(2);
+ expect(out.breakdown.pumpfun.count).toBe(2);
+
+ const url = fetchMock.mock.calls[0][0];
+ expect(url).toContain(`/callout/top/${MINT}`);
+ expect(url).toContain('sortBy=TIMESTAMP');
+ });
+
+ it('answers 502 when pump.fun fails and the caller supplied nothing to score', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(upstream(404, null));
+ const res = await call(pulseHandler, '/api/social/sentiment-pulse', { token: MINT });
+ expect(res.statusCode).toBe(502);
+ const out = res.json();
+ expect(out.error).toBe('upstream_unavailable');
+ expect(out.error_description).toContain('404');
+ expect(out.source).toBe('pump.fun');
+ });
+
+ it('still scores caller-supplied texts when pump.fun is down', async () => {
+ vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('socket hang up'));
+ const res = await call(pulseHandler, '/api/social/sentiment-pulse', {
+ token: MINT,
+ extraTexts: ['moon bullish gem', ' ', 'rug pull scam'],
+ });
+ expect(res.statusCode).toBe(200);
+ const out = res.json();
+ expect(out.sources.pumpfunStatus).toBe('unavailable');
+ expect(out.sources.pumpfun).toBe(null);
+ expect(out.sources.extraCount).toBe(2);
+ expect(out.overall.count).toBe(2);
+ expect(out.breakdown.pumpfun.error).toBeTruthy();
+ });
+
+ it('reports a quiet coin as an empty reading, not an outage', async () => {
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(upstream(200, { callouts: [] }));
+ const res = await call(pulseHandler, '/api/social/sentiment-pulse', { token: MINT });
+ expect(res.statusCode).toBe(200);
+ const out = res.json();
+ expect(out.sources.pumpfunStatus).toBe('ok');
+ expect(out.overall.count).toBe(0);
+ });
+
+ it('rejects a token that is not a base58 mint', async () => {
+ const fetchMock = vi.spyOn(globalThis, 'fetch');
+ const res = await call(pulseHandler, '/api/social/sentiment-pulse', { token: 'notamint' });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('validation_error');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a limit above the documented ceiling', async () => {
+ const res = await call(pulseHandler, '/api/social/sentiment-pulse', {
+ token: MINT,
+ limit: 9999,
+ });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('validation_error');
+ });
+});