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(agents): cover the SNS and wallet-guard handlers, and point the airdrop test at the shipped path

nirholas44a3d05c1117
diff --git a/api/agents/solana-airdrop.js b/api/agents/solana-airdrop.js
deleted file mode 100644
index d626377dc..000000000
--- a/api/agents/solana-airdrop.js
+++ /dev/null
@@ -1,16 +0,0 @@
-// POST /api/agents/:id/solana/airdrop — thin delegate.
-//
-// The canonical airdrop implementation lives in solana-wallet.js
-// (handleAirdrop), dispatched from api/agents/[id].js via the `solana`
-// sub-path. This wrapper exists only for direct imports of the standalone
-// module path; it carries no logic of its own so the two paths can never
-// drift apart.
-
-import { wrap } from '../_lib/http.js';
-import solanaWallet from './solana-wallet.js';
-
-export default wrap(async (req, res, id) => {
- const url = new URL(req.url, 'http://x');
- const agentId = id || url.searchParams.get('id') || req.query?.id;
- return solanaWallet(req, res, agentId, 'airdrop');
-});
diff --git a/prompts/swarm-100/api-agents-08.md b/prompts/swarm-100/api-agents-08.md
deleted file mode 100644
index afb586e65..000000000
--- a/prompts/swarm-100/api-agents-08.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# API audit: api/agents batch 08 (10 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/agents/sns.js
-- api/agents/solana-airdrop.js
-- api/agents/solana-guard.js
-- api/agents/solana-intent.js
-- api/agents/solana-trade.js
-- api/agents/solana-wallet.js
-- api/agents/solana/[action].js
-- api/agents/solana/_handlers.js
-- api/agents/suggest-spec.js
-- api/agents/suggest.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-agents-08.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/tests/api/agents-sns.test.js b/tests/api/agents-sns.test.js
new file mode 100644
index 000000000..57abcc2ce
--- /dev/null
+++ b/tests/api/agents-sns.test.js
@@ -0,0 +1,259 @@
+// api/agents/sns.js, the .sol domain surface for an agent identity.
+//
+// Reached only through the dispatcher: /api/agents/:id/sns[/...] ->
+// api/agents/[id].js -> this module. /api/agents/sns is swallowed by the
+// /api/agents/([^/]+) catch-all, so these tests invoke the handler the same way
+// the dispatcher does, with (req, res, id, action).
+//
+// Bonfida is a real upstream HTTP API and the registry read is a real on-chain
+// lookup, so both are stubbed at their module / fetch boundary. Everything else
+// (domain normalization, ownership resolution, meta writes) runs for real.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+import { Keypair } from '@solana/web3.js';
+
+const AGENT_ADDR = Keypair.generate().publicKey.toBase58();
+const LINKED_ADDR = Keypair.generate().publicKey.toBase58();
+
+const authState = { session: null };
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+
+const sqlState = { agent: null, linked: [], writes: [] };
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...vals) => {
+ const q = (typeof strings === 'string' ? strings : strings.join('?')).toLowerCase();
+ if (/update agent_identities/.test(q)) {
+ sqlState.writes.push(JSON.parse(vals[0]));
+ return [];
+ }
+ if (/from user_wallets/.test(q)) return sqlState.linked;
+ if (/from agent_identities/.test(q)) return sqlState.agent ? [sqlState.agent] : [];
+ return [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../../api/_lib/execution-engine.js', () => ({
+ submitProtected: vi.fn(async () => ({ signature: 'SIG'.padEnd(88, 'x') })),
+}));
+
+vi.mock('../../api/_lib/agent-pumpfun.js', () => ({
+ loadAgentForSigning: vi.fn(async () => ({ error: { status: 409, code: 'conflict', msg: 'no keypair' } })),
+ solanaConnection: vi.fn(() => ({})),
+}));
+
+const registryState = { owner: null };
+vi.mock('@bonfida/spl-name-service', () => ({
+ getDomainKeySync: vi.fn(() => ({ pubkey: 'PK' })),
+ NameRegistryState: {
+ retrieve: vi.fn(async () => {
+ if (!registryState.owner) throw new Error('account not found');
+ return { registry: { owner: { toBase58: () => registryState.owner } } };
+ }),
+ },
+ registerDomainNameV2: vi.fn(async () => []),
+}));
+
+const { default: handler } = await import('../../api/agents/sns.js');
+
+const AGENT_ID = '11111111-2222-4333-8444-666666666666';
+
+const fetchState = { byAddress: {}, favByAddress: {}, fail: false };
+beforeEach(() => {
+ authState.session = { id: 'owner-1' };
+ sqlState.agent = { id: AGENT_ID, user_id: 'owner-1', meta: { solana_address: AGENT_ADDR } };
+ sqlState.linked = [];
+ sqlState.writes = [];
+ registryState.owner = null;
+ fetchState.byAddress = {};
+ fetchState.favByAddress = {};
+ fetchState.fail = false;
+
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ if (fetchState.fail) return { ok: false, status: 503, json: async () => ({}) };
+ const u = String(url);
+ const address = u.split('/').pop();
+ if (u.includes('/fav-domains/')) {
+ return { ok: true, status: 200, json: async () => ({ [address]: fetchState.favByAddress[address] ?? null }) };
+ }
+ return { ok: true, status: 200, json: async () => ({ [address]: fetchState.byAddress[address] ?? [] }) };
+ }));
+});
+
+function makeReq(method, { body = null, url = `/api/agents/${AGENT_ID}/sns` } = {}) {
+ const req = Readable.from(body === null ? [] : [Buffer.from(JSON.stringify(body))]);
+ req.method = method;
+ req.url = url;
+ req.headers = { host: 'localhost', 'content-type': 'application/json', origin: 'http://localhost' };
+ return req;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(c) { if (c !== undefined) this.body += c; this.writableEnded = true; },
+ };
+}
+
+async function invoke(method, { action, ...opts } = {}) {
+ const res = makeRes();
+ await handler(makeReq(method, opts), res, AGENT_ID, action);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+describe('GET /api/agents/:id/sns', () => {
+ it('lists the domains the agent wallet owns plus its favorite', async () => {
+ fetchState.byAddress[AGENT_ADDR] = ['nova', 'oracle'];
+ fetchState.favByAddress[AGENT_ADDR] = 'nova';
+
+ const { status, body } = await invoke('GET');
+ expect(status).toBe(200);
+ expect(body.data.address).toBe(AGENT_ADDR);
+ expect(body.data.domains).toEqual(['nova', 'oracle']);
+ expect(body.data.favorite).toBe('nova');
+ expect(body.data.sns_domain).toBeNull();
+ expect(body.data.upstream_ok).toBe(true);
+ expect(body.data.modes).toEqual({ agent_pays: true, user_pays: true });
+ });
+
+ it('degrades to an empty list, flagged, when Bonfida is down', async () => {
+ fetchState.fail = true;
+ const { status, body } = await invoke('GET');
+ expect(status).toBe(200);
+ expect(body.data.upstream_ok).toBe(false);
+ expect(body.data.domains).toEqual([]);
+ });
+
+ it('rejects an unauthenticated caller', async () => {
+ authState.session = null;
+ expect((await invoke('GET')).status).toBe(401);
+ });
+
+ it('rejects a caller who does not own the agent', async () => {
+ sqlState.agent = { ...sqlState.agent, user_id: 'someone-else' };
+ expect((await invoke('GET')).status).toBe(403);
+ });
+
+ it('404s an agent that does not exist', async () => {
+ sqlState.agent = null;
+ expect((await invoke('GET')).status).toBe(404);
+ });
+
+ it('409s an agent with no Solana wallet yet', async () => {
+ sqlState.agent = { ...sqlState.agent, meta: {} };
+ const { status, body } = await invoke('GET');
+ expect(status).toBe(409);
+ expect(body.error_description).toMatch(/provision one first/);
+ });
+});
+
+describe('POST /api/agents/:id/sns (attach)', () => {
+ it('attaches a domain the agent wallet owns', async () => {
+ fetchState.byAddress[AGENT_ADDR] = ['nova'];
+ const { status, body } = await invoke('POST', { body: { domain: 'Nova.sol' } });
+ expect(status).toBe(200);
+ expect(body.data).toMatchObject({ ok: true, sns_domain: 'nova', owner: AGENT_ADDR });
+ expect(sqlState.writes[0].sns_domain).toBe('nova');
+ // Owned by the agent itself, so no separate owner wallet is recorded.
+ expect(sqlState.writes[0].sns_owner_wallet).toBeUndefined();
+ });
+
+ it('accepts a domain owned by a Solana wallet linked to the caller', async () => {
+ sqlState.linked = [{ address: LINKED_ADDR }];
+ fetchState.byAddress[LINKED_ADDR] = ['nova'];
+ const { status, body } = await invoke('POST', { body: { domain: 'nova' } });
+ expect(status).toBe(200);
+ expect(body.data.owner).toBe(LINKED_ADDR);
+ expect(sqlState.writes[0].sns_owner_wallet).toBe(LINKED_ADDR);
+ });
+
+ it('refuses a domain no candidate wallet owns', async () => {
+ fetchState.byAddress[AGENT_ADDR] = ['other'];
+ const { status, body } = await invoke('POST', { body: { domain: 'nova' } });
+ expect(status).toBe(403);
+ expect(body.error_description).toMatch(/not owned/);
+ expect(sqlState.writes).toHaveLength(0);
+ });
+
+ it('rejects a malformed domain', async () => {
+ const { status, body } = await invoke('POST', { body: { domain: 'not a domain!' } });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+});
+
+describe('DELETE /api/agents/:id/sns', () => {
+ it('clears the attached domain and its owner wallet', async () => {
+ sqlState.agent = {
+ ...sqlState.agent,
+ meta: { solana_address: AGENT_ADDR, sns_domain: 'nova', sns_owner_wallet: LINKED_ADDR },
+ };
+ const { status, body } = await invoke('DELETE');
+ expect(status).toBe(200);
+ expect(body.data.sns_domain).toBeNull();
+ expect(sqlState.writes[0].sns_domain).toBeUndefined();
+ expect(sqlState.writes[0].sns_owner_wallet).toBeUndefined();
+ });
+});
+
+describe('GET /api/agents/:id/sns/check', () => {
+ it('reports an unregistered domain as available with its price', async () => {
+ const { status, body } = await invoke('GET', { action: 'check', url: '/api/agents/x/sns/check?domain=nova' });
+ expect(status).toBe(200);
+ expect(body.data).toMatchObject({ domain: 'nova', available: true, owner: null, length: 4 });
+ expect(body.data.price_usdc).toBe(160);
+ });
+
+ it('reports a registered domain as taken', async () => {
+ registryState.owner = LINKED_ADDR;
+ const { status, body } = await invoke('GET', { action: 'check', url: '/api/agents/x/sns/check?domain=nova' });
+ expect(status).toBe(200);
+ expect(body.data.available).toBe(false);
+ expect(body.data.owner).toBe(LINKED_ADDR);
+ });
+
+ it('rejects a check with no domain', async () => {
+ const { status, body } = await invoke('GET', { action: 'check', url: '/api/agents/x/sns/check' });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+});
+
+describe('POST /api/agents/:id/sns/register-prep', () => {
+ it('refuses a wallet that is not linked to the caller', async () => {
+ const { status, body } = await invoke('POST', {
+ action: 'register-prep',
+ url: '/api/agents/x/sns/register-prep',
+ body: { domain: 'nova', wallet_address: LINKED_ADDR },
+ });
+ expect(status).toBe(403);
+ expect(body.error_description).toMatch(/not linked/);
+ });
+
+ it('rejects a missing wallet address', async () => {
+ const { status, body } = await invoke('POST', {
+ action: 'register-prep',
+ url: '/api/agents/x/sns/register-prep',
+ body: { domain: 'nova' },
+ });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/wallet_address/);
+ });
+});
diff --git a/tests/api/solana-airdrop.test.js b/tests/api/solana-airdrop.test.js
index ae9d5490c..1c5ab7196 100644
--- a/tests/api/solana-airdrop.test.js
+++ b/tests/api/solana-airdrop.test.js
@@ -37,7 +37,9 @@ vi.mock('../../api/_lib/agent-pumpfun.js', () => ({
solanaConnection: vi.fn(() => conn),
}));
-const { default: handler } = await import('../../api/agents/solana-airdrop.js');
+// The production path: /api/agents/:id/solana/airdrop is dispatched by
+// api/agents/[id].js into the solana-wallet handler with action='airdrop'.
+const { default: handler } = await import('../../api/agents/solana-wallet.js');
function makeReq() {
const base = Readable.from([]);
@@ -56,7 +58,7 @@ function makeRes() {
async function invoke() {
const req = makeReq();
const res = makeRes();
- await handler(req, res, 'agent-1');
+ await handler(req, res, 'agent-1', 'airdrop');
return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
}
diff --git a/tests/api/solana-guard.test.js b/tests/api/solana-guard.test.js
new file mode 100644
index 000000000..a2d00c801
--- /dev/null
+++ b/tests/api/solana-guard.test.js
@@ -0,0 +1,286 @@
+// api/agents/solana-guard.js, the Self-Defending Wallet control surface.
+//
+// Not routed on its own: /api/agents/solana-guard is swallowed by the
+// /api/agents/([^/]+) catch-all, so the only way in is
+// /api/agents/:id/solana/guard -> api/agents/solana-wallet.js -> handleGuard.
+// These tests drive the handler exactly the way that dispatcher does.
+//
+// The collaborators that touch Postgres and the spend policy (anomaly-events,
+// agent-trade-guards) are mocked. wallet-anomaly is pure and runs for real, so
+// the config defaults, sensitivity presets, and publicConfig projection under
+// test are the shipped ones rather than fixtures.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+import { Keypair, PublicKey } from '@solana/web3.js';
+
+const SAFE_ADDR = Keypair.generate().publicKey.toBase58();
+// A PDA: off-curve, so it cannot sign and must be refused as a sweep target.
+const PDA_ADDR = PublicKey.findProgramAddressSync(
+ [Buffer.from('guard-test')],
+ new PublicKey('11111111111111111111111111111111'),
+)[0].toBase58();
+
+const authState = { session: null };
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+const sqlState = { agent: null, updates: [] };
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings) => {
+ const q = (typeof strings === 'string' ? strings : strings.join('?')).toLowerCase();
+ if (/update agent_anomaly_events/.test(q)) {
+ sqlState.updates.push(q);
+ return [];
+ }
+ if (/from agent_identities/.test(q)) return sqlState.agent ? [sqlState.agent] : [];
+ return [];
+ }),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { walletRead: 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.end(JSON.stringify({ error: 'forbidden', error_description: 'csrf' }));
+ return false;
+ }),
+}));
+
+const guardState = { frozen: false, setCalls: [] };
+vi.mock('../../api/_lib/agent-trade-guards.js', async () => {
+ const real = await vi.importActual('../../api/_lib/agent-trade-guards.js');
+ return {
+ validateSolanaAddress: real.validateSolanaAddress,
+ getSpendLimits: vi.fn(() => ({ frozen: guardState.frozen })),
+ setSpendLimits: vi.fn(async (agentId, userId, patch) => {
+ guardState.setCalls.push({ agentId, userId, patch });
+ guardState.frozen = patch.frozen === true;
+ return { frozen: guardState.frozen };
+ }),
+ };
+});
+
+const eventsState = { events: [], flags: [], event: null, statuses: [], taught: null, saved: null };
+vi.mock('../../api/_lib/anomaly-events.js', () => ({
+ listAnomalyEvents: vi.fn(async () => eventsState.events),
+ listOpenFlags: vi.fn(async () => eventsState.flags),
+ getAnomalyEvent: vi.fn(async () => eventsState.event),
+ setAnomalyStatus: vi.fn(async (eventId, patch) => {
+ eventsState.statuses.push({ eventId, ...patch });
+ }),
+ loadBaselineForDisplay: vi.fn(async () => ({ samples: 12, median_usd: 4.5 })),
+ saveAnomalyConfig: vi.fn(async (agentId, meta, patch) => {
+ eventsState.saved = patch;
+ const { getAnomalyConfig } = await import('../../api/_lib/wallet-anomaly.js');
+ return { ...getAnomalyConfig(meta), ...patch, allow_destinations: patch.allow_destinations ?? [] };
+ }),
+ teachFromApproval: vi.fn(async (agentId, meta, evt) => {
+ eventsState.taught = evt;
+ const { getAnomalyConfig } = await import('../../api/_lib/wallet-anomaly.js');
+ return { ...getAnomalyConfig(meta), allow_destinations: [evt.destination] };
+ }),
+}));
+
+const { default: handleGuard } = await import('../../api/agents/solana-guard.js');
+
+const AGENT_ID = '11111111-2222-4333-8444-555555555555';
+
+function makeReq(method, { body = null, url = '/api/agents/x/solana/guard' } = {}) {
+ const payload = body === null ? [] : [Buffer.from(JSON.stringify(body))];
+ const req = Readable.from(payload);
+ req.method = method;
+ req.url = url;
+ req.headers = { host: 'localhost', 'content-type': 'application/json', origin: 'http://localhost' };
+ return req;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(c) { if (c !== undefined) this.body += c; this.writableEnded = true; },
+ };
+}
+
+async function invoke(method, opts = {}) {
+ const res = makeRes();
+ await handleGuard(makeReq(method, opts), res, AGENT_ID);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+function ownedAgent(meta = {}) {
+ return { id: AGENT_ID, user_id: 'owner-1', meta };
+}
+
+beforeEach(() => {
+ authState.session = { id: 'owner-1' };
+ sqlState.agent = ownedAgent();
+ sqlState.updates = [];
+ csrfState.ok = true;
+ guardState.frozen = false;
+ guardState.setCalls = [];
+ eventsState.events = [];
+ eventsState.flags = [];
+ eventsState.event = null;
+ eventsState.statuses = [];
+ eventsState.taught = null;
+ eventsState.saved = null;
+});
+
+describe('GET /api/agents/:id/solana/guard', () => {
+ it('returns config, presets, baseline, open flags, and the timeline', async () => {
+ guardState.frozen = true;
+ eventsState.flags = [{
+ id: 9n, network: 'mainnet', category: 'withdraw', asset: 'SOL', usd: '120.5',
+ destination: SAFE_ADDR, score: '0.91', decision: 'freeze', critical: true,
+ sensitivity: 'balanced', factors: ['size', 'new_destination'], summary: 'unusually large',
+ status: 'flagged', hour_utc: 3, swept: false, adjudicated_at: null, created_at: '2026-08-01T03:00:00Z',
+ }];
+ eventsState.events = eventsState.flags;
+
+ const { status, body } = await invoke('GET');
+ expect(status).toBe(200);
+ expect(body.data.frozen).toBe(true);
+ expect(body.data.config.sensitivity).toBe('balanced');
+ expect(body.data.config.learned_destinations).toBe(0);
+ expect(body.data.presets.length).toBeGreaterThan(0);
+ expect(body.data.baseline).toEqual({ samples: 12, median_usd: 4.5 });
+ expect(body.data.open_flags[0]).toMatchObject({ id: '9', usd: 120.5, score: 0.91, critical: true });
+ expect(body.data.timeline.items).toHaveLength(1);
+ // One page of results is short of the default limit, so there is no cursor.
+ expect(body.data.timeline.next_cursor).toBeNull();
+ });
+
+ it('rejects an unauthenticated caller', async () => {
+ authState.session = null;
+ expect((await invoke('GET')).status).toBe(401);
+ });
+
+ it('rejects a caller who does not own the agent', async () => {
+ sqlState.agent = { ...ownedAgent(), user_id: 'someone-else' };
+ expect((await invoke('GET')).status).toBe(403);
+ });
+
+ it('404s an agent that does not exist', async () => {
+ sqlState.agent = null;
+ expect((await invoke('GET')).status).toBe(404);
+ });
+});
+
+describe('PUT /api/agents/:id/solana/guard', () => {
+ it('saves sensitivity, enabled, and a safe address', async () => {
+ const { status, body } = await invoke('PUT', {
+ body: { enabled: true, sensitivity: 'strict', safe_address: SAFE_ADDR },
+ });
+ expect(status).toBe(200);
+ expect(eventsState.saved).toEqual({ enabled: true, sensitivity: 'strict', safe_address: SAFE_ADDR });
+ expect(body.data.config.sensitivity).toBe('strict');
+ });
+
+ it('clears everything the guard has learned', async () => {
+ await invoke('PUT', { body: { clear_learned: true } });
+ expect(eventsState.saved).toEqual({ allow_destinations: [], size_ceiling_usd: null, extra_hours: [] });
+ });
+
+ it('rejects an unknown sensitivity', async () => {
+ const { status, body } = await invoke('PUT', { body: { sensitivity: 'paranoid' } });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_sensitivity');
+ });
+
+ it('refuses a PDA as the safe-sweep address', async () => {
+ // Funds swept to an off-curve address can never be moved again.
+ const { status, body } = await invoke('PUT', { body: { safe_address: PDA_ADDR } });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_address');
+ expect(body.error_description).toMatch(/PDA/);
+ });
+
+ it('refuses a malformed safe address', async () => {
+ const { status, body } = await invoke('PUT', { body: { safe_address: 'not-an-address!' } });
+ expect(status).toBe(400);
+ expect(body.error).toBe('invalid_address');
+ });
+
+ it('requires CSRF on a mutation', async () => {
+ csrfState.ok = false;
+ expect((await invoke('PUT', { body: { enabled: false } })).status).toBe(403);
+ });
+});
+
+describe('POST /api/agents/:id/solana/guard (adjudication)', () => {
+ beforeEach(() => {
+ eventsState.event = { id: 7n, destination: SAFE_ADDR, usd: 120.5, hour_utc: 3 };
+ guardState.frozen = true;
+ });
+
+ it('unfreezes and settles every open flag', async () => {
+ const { status, body } = await invoke('POST', { body: { action: 'unfreeze' } });
+ expect(status).toBe(200);
+ expect(body.data).toEqual({ frozen: false, action: 'unfreeze' });
+ expect(guardState.setCalls).toEqual([{ agentId: AGENT_ID, userId: 'owner-1', patch: { frozen: false } }]);
+ expect(sqlState.updates).toHaveLength(1);
+ });
+
+ it('approve teaches the baseline and unfreezes', async () => {
+ const { status, body } = await invoke('POST', { body: { action: 'approve', event_id: 7 } });
+ expect(status).toBe(200);
+ expect(eventsState.taught).toEqual({ destination: SAFE_ADDR, usd: 120.5, hour_utc: 3 });
+ expect(eventsState.statuses).toEqual([{ eventId: '7', status: 'approved', userId: 'owner-1' }]);
+ expect(body.data.frozen).toBe(false);
+ expect(body.data.config.learned_destinations).toBe(1);
+ });
+
+ it('deny records the verdict and leaves the wallet frozen', async () => {
+ const { status, body } = await invoke('POST', { body: { action: 'deny', event_id: 7 } });
+ expect(status).toBe(200);
+ expect(body.data.frozen).toBe(true);
+ expect(guardState.setCalls).toHaveLength(0);
+ expect(eventsState.statuses).toEqual([{ eventId: '7', status: 'denied', userId: 'owner-1' }]);
+ });
+
+ it('mark_swept records the sweep against the flag', async () => {
+ const { status, body } = await invoke('POST', { body: { action: 'mark_swept', event_id: 7 } });
+ expect(status).toBe(200);
+ expect(body.data.swept).toBe(true);
+ expect(eventsState.statuses).toEqual([{ eventId: '7', status: 'denied', userId: 'owner-1', swept: true }]);
+ });
+
+ it('rejects an adjudication with no event id', async () => {
+ const { status, body } = await invoke('POST', { body: { action: 'approve' } });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/event_id/);
+ });
+
+ it('404s an event that belongs to another agent', async () => {
+ eventsState.event = null;
+ expect((await invoke('POST', { body: { action: 'approve', event_id: 7 } })).status).toBe(404);
+ });
+
+ it('rejects an unknown action', async () => {
+ const { status, body } = await invoke('POST', { body: { action: 'thaw', event_id: 7 } });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/approve, deny, mark_swept, or unfreeze/);
+ });
+});
+
+describe('method handling', () => {
+ it('rejects DELETE', async () => {
+ expect((await invoke('DELETE')).status).toBe(405);
+ });
+});