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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(genome): stop one $THREE stud payment from buying two children, and let owners list their own studs
nirholas8e3cf5a9e9a7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5a47b4f93..07f6227e4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,11 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-08-13++- **A shared walk card no longer sends people to an avatar that is gone**: Sharing a walk produces a card you can post on Farcaster, with a button that opens that avatar walking. A cast stays up forever, but the avatar behind it does not: it can be deleted, or switched to private. When that happened the button still pointed at the missing avatar, so anyone who tapped it landed on a walk that could never load, and the card's second button pointed at the same place as the first, so both said the same thing. The card now checks the avatar before it builds. If the avatar is gone or private it drops the link and invites you to walk your own instead of handing you a dead button, and if the check itself cannot run the link is kept rather than thrown away. The second button now goes to the avatar builder, so the two buttons finally offer two different things. The card also carries its image dimensions now, which stops the preview from reflowing while it loads. (`/walk`) `[fix]`+- **Importing an agent you already own on-chain no longer fails because its metadata host is slow**: If you registered an agent on-chain, the hydrate page finds it from your connected wallets and offers to import it into three.ws. Importing read two things: the registry entry on the chain, and the registration file the registry points at, which usually lives on IPFS. If that file did not load in five seconds, the whole import was refused, even though the part that actually matters, the chain saying you own the agent, had already answered. Public IPFS gateways throttle constantly, so owners were locked out of their own agents by a slow third party. The import now only needs the chain read to succeed; a registration file that will not load means the agent lands under its on-chain name and the metadata fills in on the next crawl. Two more changes went in alongside it: ownership is now re-checked against the live registry rather than the crawler's cached copy, so an agent you transferred away cannot be imported by the old wallet, and a chain that is unreachable now says so plainly and asks you to retry instead of reporting a generic failure. Separately, confirming a new registration now reads the transaction receipt over the same priority provider list the rest of the platform uses, instead of the slowest public fallbacks, which is what made a freshly mined registration occasionally come back as "not yet mined". (`/hydrate`) `[fix]`+## 2026-08-12- **Docs · Run an inference node** (`/docs/inference-node-operator`): Join the open inference network: the node-operator client registers your machine, claims inference jobs, executes them with a real open model, and returns Ed25519-signed results anyone can verify. Covers install, config, the wire contract, GPU Docker, and the local end-to-end proof.diff --git a/agent-payments-sdk/FORK_NOTES.md b/agent-payments-sdk/FORK_NOTES.mdindex 5a23977b1..218038a09 100644--- a/agent-payments-sdk/FORK_NOTES.md+++ b/agent-payments-sdk/FORK_NOTES.md@@ -3,7 +3,7 @@This package is a **deliberate, value-added three.ws fork** of pump.fun's`@pump-fun/agent-payments-sdk`. It is the on-chain engine behind our **agenttokens** product — the flow where a user launches a pump.fun token for their-agent ([api/pump/launch-agent.js](../api/pump/launch-agent.js)) and then charges+agent ([api/pump/[action].js](../api/pump/[action].js), action `launch-agent`) and then chargesusers who pay that agent in its token, with buyback and shareholder distribution([api/agents/payments/[action].js](../api/agents/payments/[action].js)).diff --git a/api/_lib/audit.js b/api/_lib/audit.jsindex 9c0b47350..bbed10029 100644--- a/api/_lib/audit.js+++ b/api/_lib/audit.js@@ -26,30 +26,46 @@ const UA_MAX = 512;* @param {string|null} [entry.ip] — explicit override (otherwise derived from req)* @param {string|null} [entry.userAgent] — explicit override (otherwise derived from req)*/-export function logAudit({ userId, action, resourceId = null, meta = null, req = null, ip = null, userAgent = null }) {+export function logAudit(entry) {+ queueMicrotask(() => { logAuditNow(entry); });+}++/**+ * The same write, awaitable. Resolves true when the row landed, false when it+ * was dropped; never throws, so a caller can report whether the trail actually+ * recorded without the write being able to fail their request.+ *+ * Use this only where the row IS the deliverable and the caller reports the+ * outcome (the legal acceptance endpoints). Everything else wants `logAudit`:+ * bookkeeping must not add DB latency to a response nobody reads it from.+ *+ * @param {Parameters<typeof logAudit>[0]} entry+ * @returns {Promise<boolean>}+ */+export async function logAuditNow({ userId, action, resourceId = null, meta = null, req = null, ip = null, userAgent = null }) {const resolvedIp = ip ?? (req ? clientIp(req) : null);const rawUa = userAgent ?? (req ? req.headers?.['user-agent'] : null);const resolvedUa = rawUa ? String(rawUa).slice(0, UA_MAX) : null;- queueMicrotask(async () => {- try {- await withDbRetry(() => sql`- insert into audit_log (user_id, action, resource_id, meta, ip, user_agent)- values (${userId}, ${action}, ${resourceId}, ${meta}, ${resolvedIp}, ${resolvedUa})- `, { timeoutMs: 5_000 });- } catch (err) {- // A transient DB stall (Neon scale-to-zero wake, a connection blip — see- // db-retry.js) is infrastructure, not a code fault: it drops this one- // best-effort row but breaks nothing. Logging it at error level trips- // false alarms, so classify it the same way db-retry/avatar-agent do and- // warn instead; reserve error for genuinely unexpected failures.- const detail = { action, resourceId, error: err?.message };- const transient =- err?.code === 'DB_TIMEOUT' ||- /fetch failed|connecting to database|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|socket hang up|terminat/i.test(- err?.message || '',- );- if (transient) console.warn('[audit] insert dropped (transient DB stall)', detail);- else console.error('[audit] insert failed', detail);- }- });+ try {+ await withDbRetry(() => sql`+ insert into audit_log (user_id, action, resource_id, meta, ip, user_agent)+ values (${userId}, ${action}, ${resourceId}, ${meta}, ${resolvedIp}, ${resolvedUa})+ `, { timeoutMs: 5_000 });+ return true;+ } catch (err) {+ // A transient DB stall (Neon scale-to-zero wake, a connection blip, see+ // db-retry.js) is infrastructure, not a code fault: it drops this one+ // best-effort row but breaks nothing. Logging it at error level trips+ // false alarms, so classify it the same way db-retry/avatar-agent do and+ // warn instead; reserve error for genuinely unexpected failures.+ const detail = { action, resourceId, error: err?.message };+ const transient =+ err?.code === 'DB_TIMEOUT' ||+ /fetch failed|connecting to database|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|socket hang up|terminat/i.test(+ err?.message || '',+ );+ if (transient) console.warn('[audit] insert dropped (transient DB stall)', detail);+ else console.error('[audit] insert failed', detail);+ return false;+ }}diff --git a/api/_lib/labor-settle.js b/api/_lib/labor-settle.jsindex 957c36519..a2efbf850 100644--- a/api/_lib/labor-settle.js+++ b/api/_lib/labor-settle.js@@ -198,10 +198,16 @@ export async function runSettlement({ job, bounty, verdict: providedVerdict = nu* never throws out of the driver (the bounty just stops at a resumable state that* the manual endpoints or the /tick cron can pick up). Safe to call repeatedly.*- * @returns {Promise<{ bids: number, awarded: boolean, settled: string|null }>}+ * `settled` is the job's status after the attempt; `settledNow` is true only when+ * THIS call won the settle claim and released escrow. They differ when another+ * caller (a concurrent /settle, an earlier tick) already settled the job: the+ * status is 'settled' but no money moved here, so a counter that reports work+ * done must read `settledNow`.+ *+ * @returns {Promise<{ bids: number, awarded: boolean, settled: string|null, settledNow: boolean }>}*/export async function runAutopilot(bountyId) {- const out = { bids: 0, awarded: false, settled: null };+ const out = { bids: 0, awarded: false, settled: null, settledNow: false };try {let bounty = await getBounty(bountyId);if (!bounty) return out;@@ -247,6 +253,7 @@ export async function runAutopilot(bountyId) {return null;});out.settled = result?.status || null;+ out.settledNow = result?.status === 'settled' && result?.idempotent !== true;}}} catch (e) {diff --git a/api/_lib/legal.js b/api/_lib/legal.jsindex ff6f481a6..361e56d8e 100644--- a/api/_lib/legal.js+++ b/api/_lib/legal.js@@ -13,7 +13,7 @@// (who, which version, from which flow, when, IP, user agent).import { sql } from './db.js';-import { logAudit } from './audit.js';+import { logAuditNow } from './audit.js';export const TOS_VERSION = 2;@@ -34,33 +34,44 @@ export function tosAcceptanceFromBody(body) {}/**- * Record a user's ToS acceptance. Fire-and-forget: auth flows must never- * fail because acceptance bookkeeping had a bad day: the audit trail and- * column stamp are best-effort, the acceptance UI event already happened.+ * Record a user's ToS acceptance. Never throws and never rejects: auth flows+ * must not fail because acceptance bookkeeping had a bad day, and the+ * acceptance UI event already happened either way.*- * @param {{ userId: string, version: number, context: string, req?: import('http').IncomingMessage }} args+ * Awaiting is optional. Auth endpoints call it fire-and-forget (an extra DB+ * round trip on the sign-in path buys them nothing); /api/legal/tos-ack awaits+ * the returned promise because reporting whether the record landed is that+ * endpoint's whole job.+ *+ * @param {{ userId: string, version: number, context: string, path?: string|null, req?: import('http').IncomingMessage }} args* context: which flow recorded it ('register', 'login', 'siwe', 'siws',* 'privy', 'tos-ack', …): stored in the audit row's meta.+ * path: the page the acceptance happened on, when the caller knows it.+ * @returns {Promise<boolean>} true when both the audit row and the user-row+ * stamp landed.*/-export function recordTosAcceptance({ userId, version, context, req = null }) {- logAudit({- userId,- action: 'tos-accept',- resourceId: null,- meta: { version, context },- req,- });- queueMicrotask(async () => {- try {- await sql`- update users- set tos_accepted_version = ${version},- tos_accepted_at = now()- where id = ${userId}- and coalesce(tos_accepted_version, 0) <= ${version}- `;- } catch (err) {- console.error('[legal] tos acceptance stamp failed', err?.message || err);- }- });+export async function recordTosAcceptance({ userId, version, context, path = null, req = null }) {+ const meta = { version, context };+ if (path) meta.path = path;+ const [logged, stamped] = await Promise.all([+ logAuditNow({ userId, action: 'tos-accept', resourceId: null, meta, req }),+ stampTosVersion(userId, version),+ ]);+ return logged && stamped;+}++async function stampTosVersion(userId, version) {+ try {+ await sql`+ update users+ set tos_accepted_version = ${version},+ tos_accepted_at = now()+ where id = ${userId}+ and coalesce(tos_accepted_version, 0) <= ${version}+ `;+ return true;+ } catch (err) {+ console.error('[legal] tos acceptance stamp failed', err?.message || err);+ return false;+ }}diff --git a/api/_lib/market/upstream-error.js b/api/_lib/market/upstream-error.jsnew file mode 100644index 000000000..442bd0606--- /dev/null+++ b/api/_lib/market/upstream-error.js@@ -0,0 +1,73 @@+// Shared client contract for GeckoTerminal (api/_lib/market/ohlcv.js) failures.+//+// ohlcv.js deliberately preserves the real upstream status on the errors it+// throws so callers can tell a missing pool from a throttle from an outage. What+// it does NOT do is decide how that reaches the client, and every handler used to+// answer differently:+// - an unmapped 502 bubbled into wrap(), which logs `[api] unhandled`, captures+// to Sentry, and pages ops once per request — for someone else's rate limit;+// - an unmapped 429/404 came back as `bad_request` with the vendor's raw body+// (ref ids and all) pasted into error_description;+// - a handler that forwarded `err.code` emitted `{"error": undefined}`, i.e. a+// JSON error with no error code at all, because upstream errors carry a+// status but never a code.+// One mapper, used by every market-data handler, so the answer is the same+// everywhere and a third-party throttle never reads as a three.ws bug.++import { error } from '../http.js';++// Classify an ohlcv.js failure into the response contract. Pure, so the mapping+// is unit-testable without a live upstream.+export function classifyMarketError(err) {+ const upstream = err?.status;+ if (upstream === 404) {+ return {+ status: 404,+ code: 'pool_not_found',+ message: 'no indexed pool or candle history for this market',+ retryable: false,+ };+ }+ if (upstream === 429) {+ return {+ status: 503,+ code: 'upstream_rate_limited',+ message: 'the market data source is throttled, retry shortly',+ retryable: true,+ };+ }+ return {+ status: 502,+ code: 'upstream_error',+ message: 'the market data source is temporarily unavailable',+ retryable: false,+ };+}++// Answer a market-data failure. The upstream body is never echoed: it carries+// vendor ref ids and nothing a caller can act on.+export function marketUpstreamError(res, err) {+ const mapped = classifyMarketError(err);+ return error(res, mapped.status, mapped.code, mapped.message, { retryable: mapped.retryable });+}++// Marker set on an error that came out of a market-data call, so a single catch+// at the top of a handler can tell an upstream fault apart from the handler's own+// validation errors (which carry their own status + code) and from a genuine bug+// (which must keep bubbling to wrap() so it is logged and alerted).+const MARKET_UPSTREAM = Symbol.for('three.ws.marketUpstream');++// Run a market-data call, tagging whatever it throws as an upstream fault.+export async function callMarket(fn) {+ try {+ return await fn();+ } catch (err) {+ const tagged = err instanceof Error ? err : new Error(String(err));+ tagged[MARKET_UPSTREAM] = true;+ throw tagged;+ }+}++export function isMarketUpstreamError(err) {+ return Boolean(err && err[MARKET_UPSTREAM]);+}diff --git a/api/_lib/migrations/20260813000000_genome_stud_fee_integrity.sql b/api/_lib/migrations/20260813000000_genome_stud_fee_integrity.sqlnew file mode 100644index 000000000..a28c4b684--- /dev/null+++ b/api/_lib/migrations/20260813000000_genome_stud_fee_integrity.sql@@ -0,0 +1,26 @@+begin;++-- Agent Genome stud-fee integrity.+--+-- 1. `stud_fee_signature` had no uniqueness constraint, so api/genome/breed.js+-- could only guard replay with a read-then-write SELECT. Two breedings+-- submitted concurrently with the SAME settlement signature both passed that+-- check and both were recorded: one $THREE payment bought two children from a+-- paid stud. A unique index makes the guard atomic in the database, which is+-- the only place it can be atomic.+-- 2. `stud_fee_lamports` is misnamed for this feature: the fee settles in $THREE+-- (an SPL token), never in lamports, and breed.js consequently recorded a flat+-- 0 for every paid breeding. `stud_fee_atomics` records the amount the+-- on-chain verification actually observed landing in the stud owner's wallet,+-- in the token's smallest unit, so a paid pairing has a truthful ledger row.+--+-- Idempotent: ADD COLUMN IF NOT EXISTS + CREATE UNIQUE INDEX IF NOT EXISTS.++alter table genome_breedings+ add column if not exists stud_fee_atomics bigint not null default 0;++create unique index if not exists genome_breedings_stud_fee_signature+ on genome_breedings (stud_fee_signature)+ where stud_fee_signature is not null;++commit;diff --git a/api/_lib/reasoning-ledger.js b/api/_lib/reasoning-ledger.jsindex c713227be..c19df626a 100644--- a/api/_lib/reasoning-ledger.js+++ b/api/_lib/reasoning-ledger.js@@ -410,12 +410,20 @@ export async function getChainEntries(agentId) {`;}+/**+ * Largest page this read will ever return. Exported so the HTTP layer validates+ * against the SAME bound it will be clamped to here — a caller that asked for+ * more than one page's worth would otherwise get a silently truncated page and a+ * `next_before_seq: null` telling them the ledger ended.+ */+export const MAX_TIMELINE_LIMIT = 200;+/*** Decision timeline joined to outcomes, newest first. Filterable by kind and a* free-text query over the rationale/subject. Paginated by `beforeSeq`.*/export async function getDecisionsWithOutcomes(agentId, { limit = 50, beforeSeq = null, kind = null, q = null } = {}) {- const lim = clamp(Number(limit) || 50, 1, 200);+ const lim = clamp(Number(limit) || 50, 1, MAX_TIMELINE_LIMIT);const beforeClause = beforeSeq != null ? sql`and d.seq < ${Number(beforeSeq)}` : sql``;const kindClause = kind ? sql`and d.kind = ${kind}` : sql``;const qClause = qdiff --git a/api/_mcp-studio/gpt-forge-client.js b/api/_mcp-studio/gpt-forge-client.jsindex 3a414ef46..5373b5232 100644--- a/api/_mcp-studio/gpt-forge-client.js+++ b/api/_mcp-studio/gpt-forge-client.js@@ -219,6 +219,12 @@ export async function pollJob(base, jobId, { timeoutMs, intervalMs } = {}) {// Single status probe for the check_job tool: one GET, no loop. Throws a coded// failure only on a definitive non-2xx; the caller decides how to render each// status.+//+// A definitive 4xx means the HANDLE is wrong, not that the generator broke: forge+// answers a malformed or unrecognized job id with 400 invalid_job / 404. Those get+// their own `unknown_job` code so the caller can say "that handle is not valid any+// more, start a new generation" instead of the generic retry copy, which sends the+// user back to a probe that can never succeed.export async function pollOnce(base, jobId) {let res;try {@@ -233,6 +239,7 @@ export async function pollOnce(base, jobId) {}const data = await res.json().catch(() => ({}));if (res.status === 429) throw failure('busy', data?.message || 'status checks are rate limited; try again shortly', { retryAfter: data?.retry_after });+ if (res.status === 400 || res.status === 404) throw failure('unknown_job', data?.message || 'that job id is not recognized');if (!res.ok) throw failure('provider_error', data?.message || `the status check returned ${res.status}`);return data;}diff --git a/api/_mcp/tools/trader.js b/api/_mcp/tools/trader.jsindex e123f7822..6b7e69d9a 100644--- a/api/_mcp/tools/trader.js+++ b/api/_mcp/tools/trader.js@@ -361,7 +361,7 @@ export const toolDefs = [${auth.userId}, ${leaderId}, ${leaderWallet}, ${network}, ${wallet},${cfg.sizing_rule}, ${cfg.fixed_sol}, ${cfg.multiplier}, ${cfg.pct_balance},${cfg.per_trade_cap_sol}, ${cfg.min_order_sol}, ${cfg.daily_budget_sol}, ${cfg.max_open_copies},- ${cfg.min_oracle_score}, ${cfg.mcap_floor_usd}, ${cfg.mcap_ceiling_usd}, ${cfg.telegramChatId ?? null},+ ${cfg.min_oracle_score}, ${cfg.mcap_floor_usd}, ${cfg.mcap_ceiling_usd}, ${cfg.telegram_chat_id},${cfg.perf_fee_bps}, 'active')on conflict (copier_user_id, leader_agent_id, network) do update setdiff --git a/api/_mcpbazaar/discovery.js b/api/_mcpbazaar/discovery.jsnew file mode 100644index 000000000..75d885668--- /dev/null+++ b/api/_mcpbazaar/discovery.js@@ -0,0 +1,134 @@+// Bazaar discovery + service metadata for the hosted x402 Bazaar MCP endpoint.+//+// The 402 challenge an unauthenticated/unpaid caller receives carries this+// metadata so x402 facilitators (CDP Bazaar, agentic.market, x402scan) index+// /api/mcp-bazaar with its own service name, tags, icon, and a v2 `bazaar`+// extension describing the JSON-RPC tools/call shape. Without it the endpoint+// inherited the main /api/mcp envelope and advertised itself as the avatar and+// model-validation server, pointing at the wrong resource URL. Mirrors+// api/_mcp3d/discovery.js for the 3D Studio and api/_mcpibm/discovery.js for+// Granite.++import { buildBazaarSchema } from '../_lib/x402-spec.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';++export const RESOURCE_DESCRIPTION =+ 'three.ws x402 Bazaar MCP: Streamable HTTP (MCP 2025-06-18) that discovers and prices paid ' ++ 'agent services across the live x402 facilitator network: search_services (ranked search), ' ++ 'browse_services (list what is payable), get_service (exact price, networks, recipient, input ' ++ 'schema, and a ready pay link), and bazaar_service_details (live per-network price for cost ' ++ 'tracking). Connect with a three.ws account (OAuth) or pay per call in USDC on Base or Solana ' ++ 'mainnet, no API key. Operated by three.ws.';++// Endpoint-level v2 bazaar discovery entry, shaped exactly like the validator+// expects (see api/_lib/x402-spec.js → bazaarExtension). Describes how to POST+// a JSON-RPC 2.0 tools/call and what comes back.+function bazaarServerExtension() {+ const exampleBody = {+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: {+ name: 'search_services',+ arguments: { query: 'weather', type: 'http', limit: 5 },+ },+ };+ const exampleResponse = {+ jsonrpc: '2.0',+ id: 1,+ result: {+ content: [+ {+ type: 'text',+ text: '1. Weather Now - $0.001\n Current weather by city.\n networks: eip155:8453',+ },+ ],+ structuredContent: {+ query: 'weather',+ type: 'http',+ count: 1,+ services: [+ {+ type: 'http',+ resource: 'https://api.example.com/weather',+ name: 'Weather Now',+ price: '$0.001',+ price_atomic: 1000,+ networks: ['eip155:8453'],+ },+ ],+ },+ },+ };+ const requestBodySchema = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['jsonrpc', 'method'],+ properties: {+ jsonrpc: { type: 'string', const: '2.0' },+ id: { type: ['string', 'number'] },+ method: {+ type: 'string',+ enum: ['initialize', 'tools/list', 'tools/call', 'ping'],+ description: 'MCP JSON-RPC method.',+ },+ params: {+ type: 'object',+ description:+ 'For tools/call: { name, arguments }. Tool names: getting_started (free), search_services, browse_services, get_service, bazaar_service_details, see tools/list.',+ },+ },+ };+ const responseBodySchema = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ jsonrpc: { type: 'string', const: '2.0' },+ id: { type: ['string', 'number'] },+ result: {+ type: 'object',+ properties: {+ content: {+ type: 'array',+ items: {+ type: 'object',+ required: ['type', 'text'],+ properties: {+ type: { type: 'string', enum: ['text'] },+ text: { type: 'string' },+ },+ },+ },+ },+ },+ error: {+ type: 'object',+ properties: { code: { type: 'number' }, message: { type: 'string' } },+ },+ },+ };+ return {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'POST', body: exampleBody, bodyType: 'json' },+ output: { type: 'json', example: exampleResponse },+ },+ schema: buildBazaarSchema({+ method: 'POST',+ bodyType: 'json',+ bodySchema: requestBodySchema,+ outputSchema: responseBodySchema,+ }),+ };+}++// The challenge override block threaded into authenticateRequest/handleSse so+// the 402 envelope advertises x402 Bazaar service metadata + discovery.+export const BAZAAR_CHALLENGE = {+ description: RESOURCE_DESCRIPTION,+ bazaar: bazaarServerExtension(),+ ...withService({+ serviceName: 'three.ws x402 Bazaar MCP',+ tags: ['x402', 'mcp', 'discovery', 'bazaar', 'pricing'],+ }),+};diff --git a/api/_mcpibm/dispatch.js b/api/_mcpibm/dispatch.jsindex 426ec5e36..af99f8f6e 100644--- a/api/_mcpibm/dispatch.js+++ b/api/_mcpibm/dispatch.js@@ -4,17 +4,23 @@// (api/ibm-mcp.js) before dispatch, so the dispatcher itself stays payment-free.import { makeDispatcher, PROTOCOL_VERSION } from '../_lib/mcp-dispatch.js';import { TOOL_CATALOG, TOOLS } from './catalog.js';+import { formatUsdPrice } from './pricing.js';export { PROTOCOL_VERSION };+// Every price quoted here is read from pricing.js, the same map that prices the+// 402 challenge and the settle, so the instructions can never advertise a stale+// number to a client deciding whether to pay.+const price = (tool) => formatUsdPrice(tool);+const INSTRUCTIONS = [- 'x402 pay-per-use IBM Granite AI from three.ws — each tool lists its USDC price; pay per call on Base or Solana, no IBM Cloud account required.',- 'New here? Call ibm_granite_getting_started — FREE, no payment or account — for an overview, prices, and the payment flow.',- 'ibm_granite_chat(messages) — conversational AI ($0.02).',- 'ibm_granite_code(task, prompt) — generate/review/refactor/explain/test/document code ($0.025).',- 'ibm_granite_embed(inputs) — batch multilingual embeddings for RAG/search ($0.005).',- 'ibm_granite_analyze(document) — structured entities/sentiment/risk/summary/next-steps JSON ($0.04).',- 'ibm_granite_forecast(timestamps, values, freq) — zero-shot time-series forecast via Granite TTM ($0.05).',+ 'x402 pay-per-use IBM Granite AI from three.ws: each tool lists its USDC price; pay per call on Base or Solana, no IBM Cloud account required.',+ 'New here? Call ibm_granite_getting_started (FREE, no payment or account) for an overview, prices, and the payment flow.',+ `ibm_granite_chat(messages): conversational AI (${price('ibm_granite_chat')}).`,+ `ibm_granite_code(task, prompt): generate/review/refactor/explain/test/document code (${price('ibm_granite_code')}).`,+ `ibm_granite_embed(inputs): batch multilingual embeddings for RAG/search (${price('ibm_granite_embed')}).`,+ `ibm_granite_analyze(document): structured entities/sentiment/risk/summary/next-steps JSON (${price('ibm_granite_analyze')}).`,+ `ibm_granite_forecast(timestamps, values, freq): zero-shot time-series forecast via Granite TTM (${price('ibm_granite_forecast')}).`,'Powered by IBM Granite foundation models served on IBM watsonx.ai.',].join(' ');diff --git a/api/_mcpibm/pricing.js b/api/_mcpibm/pricing.jsindex 8c4eec721..eaec522d9 100644--- a/api/_mcpibm/pricing.js+++ b/api/_mcpibm/pricing.js@@ -30,7 +30,22 @@ export const TOOL_PRICING = Object.freeze({});export function priceFor(toolName) {- return TOOL_PRICING[toolName] || null;+ return Object.hasOwn(TOOL_PRICING, toolName) ? TOOL_PRICING[toolName] : null;+}++// The advertised display price for a tool ("$0.025"), derived from the same map+// the 402 challenge and the settle path read. Every human-facing price string on+// this server (tool titles, the free getting-started payload, the server+// instructions) is built from this, so a price edit here can never leave a stale+// number quoted somewhere a caller reads before paying. Keeps at least 2 decimal+// places and never truncates a fractional-cent price. Returns null for an+// unpriced tool.+export function formatUsdPrice(toolName) {+ const price = priceFor(toolName);+ if (!price) return null;+ const amount = Number(price.amount_usdc);+ const decimals = Math.max(2, (String(amount).split('.')[1] || '').length);+ return `$${amount.toFixed(decimals)}`;}// USDC (and the platform's other supported stables) are 6-decimal. The x402 wirediff --git a/api/_mcpibm/tools.js b/api/_mcpibm/tools.jsindex 665c8f97f..e827fa58e 100644--- a/api/_mcpibm/tools.js+++ b/api/_mcpibm/tools.js@@ -12,6 +12,7 @@import { watsonxConfig, watsonxChatComplete, watsonxEmbed } from '../_lib/watsonx.js';import { watsonxForecast } from '../_lib/watsonx-forecast.js';+import { formatUsdPrice } from './pricing.js';function rpcError(code, message, data) {const e = new Error(message);@@ -75,6 +76,10 @@ const deterministicAnnotations = Object.freeze({// MCP tool result helper. structuredContent carries the full machine-readable// object (the same shape the npm package returns); content[0].text is a concise// human-readable view for clients that render text.+function isPlainObject(value) {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}+function toolResult(humanText, structured) {return {content: [{ type: 'text', text: humanText }],@@ -95,13 +100,16 @@ const GETTING_STARTED_DESCRIPTION ='their per-call USDC prices, how the x402 pay-per-call flow works, and runnable example calls. ' +'No payment or account required. Call this first to orient before invoking a paid tool.';+// Prices come from pricing.js (the same map the 402 challenge and the settle+// path read) so this free orientation payload can never quote a number the+// caller is not actually charged.const GS_TOOLS = [- { name: 'ibm_granite_chat', price: '$0.02', summary: 'Conversational AI via IBM Granite 3 8B Instruct.' },- { name: 'ibm_granite_code', price: '$0.025', summary: 'Code generate / review / refactor / explain / test / document.' },- { name: 'ibm_granite_embed', price: '$0.005', summary: 'Batch multilingual text embeddings for RAG and search.' },- { name: 'ibm_granite_analyze', price: '$0.04', summary: 'Structured document analysis: entities, sentiment, risk, summary, next steps.' },- { name: 'ibm_granite_forecast', price: '$0.05', summary: 'Zero-shot time-series forecasting via IBM Granite TTM.' },-];+ { name: 'ibm_granite_chat', summary: 'Conversational AI via IBM Granite 3 8B Instruct.' },+ { name: 'ibm_granite_code', summary: 'Code generate / review / refactor / explain / test / document.' },+ { name: 'ibm_granite_embed', summary: 'Batch multilingual text embeddings for RAG and search.' },+ { name: 'ibm_granite_analyze', summary: 'Structured document analysis: entities, sentiment, risk, summary, next steps.' },+ { name: 'ibm_granite_forecast', summary: 'Zero-shot time-series forecasting via IBM Granite TTM.' },+].map(({ name, summary }) => ({ name, price: formatUsdPrice(name), summary }));const GS_PAYMENT_FLOW = ['Call any ibm_granite_* tool. With no payment, the server returns an x402 PaymentRequired envelope quoting the exact USDC price and a pay-to address (Base or Solana).',@@ -203,7 +211,7 @@ const CHAT_DESCRIPTION =const chatTool = {name: 'ibm_granite_chat',- title: 'IBM Granite Chat ($0.02)',+ title: `IBM Granite Chat (${formatUsdPrice('ibm_granite_chat')})`,description: CHAT_DESCRIPTION,annotations: generativeAnnotations,inputSchema: {@@ -308,7 +316,7 @@ function buildCodeSystemPrompt(task, language) {const codeTool = {name: 'ibm_granite_code',- title: 'IBM Granite Code ($0.025)',+ title: `IBM Granite Code (${formatUsdPrice('ibm_granite_code')})`,description: CODE_DESCRIPTION,annotations: generativeAnnotations,inputSchema: {@@ -381,7 +389,7 @@ const EMBED_DESCRIPTION =const embedTool = {name: 'ibm_granite_embed',- title: 'IBM Granite Embed ($0.005)',+ title: `IBM Granite Embed (${formatUsdPrice('ibm_granite_embed')})`,description: EMBED_DESCRIPTION,annotations: deterministicAnnotations,inputSchema: {@@ -478,7 +486,7 @@ function buildAnalysisPrompt(analysis_type, language) {const analyzeTool = {name: 'ibm_granite_analyze',- title: 'IBM Granite Analyze ($0.04)',+ title: `IBM Granite Analyze (${formatUsdPrice('ibm_granite_analyze')})`,description: ANALYZE_DESCRIPTION,annotations: generativeAnnotations,inputSchema: {@@ -547,15 +555,20 @@ const analyzeTool = {? raw.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, ''): raw;parsed = JSON.parse(jsonStr);+ // A bare JSON scalar or array parses fine but is not an analysis object,+ // and spreading one below would splatter per-character/per-index keys+ // into the result. Treat it as an unparseable response.+ if (!isPlainObject(parsed)) throw new Error('analysis JSON was not an object');} catch {- // Granite didn't return clean JSON — surface text so the client can decide.+ // Granite didn't return clean JSON: surface text so the client can decide.const fallback = {ok: true,analysis_type,raw_response: result.text,usage: result.usage,model: result.model,- parse_error: 'Model returned non-JSON response; see raw_response.',+ parse_error:+ 'Model did not return a JSON analysis object; see raw_response.',};return toolResult(result.text, fallback);}@@ -583,7 +596,7 @@ const FREQ_EXAMPLES = '1min, 5min, 15min, 30min, 1h, 2h, 4h, 12h, 1D, 1W, 1ME';const forecastTool = {name: 'ibm_granite_forecast',- title: 'IBM Granite Forecast ($0.05)',+ title: `IBM Granite Forecast (${formatUsdPrice('ibm_granite_forecast')})`,description: FORECAST_DESCRIPTION,annotations: generativeAnnotations,inputSchema: {diff --git a/api/agents.js b/api/agents.jsindex 569357832..44ab263f4 100644--- a/api/agents.js+++ b/api/agents.js@@ -870,6 +870,13 @@ function decorate(row, isOwner = true) {}base.breedable = meta.genome_breeding?.breedable !== false;base.is_stud = meta.genome_breeding?.stud === true;+ // The stud fee and the public flag complete the breeding policy at the top+ // level, so the genome studio can render an owner's listings (and explain why+ // a private agent cannot be listed) without reaching into `meta`. Both are+ // public-safe: the fee is quoted to every breeder by /api/genome/stud, and+ // visibility is already implied by whether the agent appears in listings.+ base.stud_fee_three = Math.max(0, Number(meta.genome_breeding?.stud_fee_three) || 0);+ base.is_public = row.is_public !== false;if (isOwner) {base.wallet_address = row.wallet_address;diff --git a/api/erc8004/[action].js b/api/erc8004/[action].jsindex dd1da06ad..5deee483b 100644--- a/api/erc8004/[action].js+++ b/api/erc8004/[action].js@@ -27,6 +27,7 @@ import { r2, publicUrl } from '../_lib/r2.js';import { env } from '../_lib/env.js';import { attestValidation, AttestError } from '../_lib/validation-attest.js';import { fetchSafePublicUrlPinned, SsrfBlockedError, MaxBytesExceededError } from '../_lib/ssrf-guard.js';+import { redactUrlSecrets } from '../_lib/scrub-secrets.js';export default wrap(async (req, res) => {const action = req.query?.action;@@ -180,7 +181,9 @@ async function handleImport(req, res) {return error(res, 403, 'forbidden', 'you do not own this agent');}- // Resolve on-chain agent metadata.+ // Resolve on-chain agent metadata. A transport fault here is an upstream+ // problem, not the caller's, and its message can embed the keyed RPC URL+ // (…g.alchemy.com/v2/<key>), so it is logged redacted and never echoed.let resolved;try {resolved = await resolveOnChainAgent({@@ -190,11 +193,25 @@ async function handleImport(req, res) {timeoutMs: 5000,});} catch (err) {- return error(res, 500, 'internal', `failed to resolve agent: ${err.message}`);+ console.error('[erc8004/import] resolve threw:', redactUrlSecrets(err?.message || String(err)));+ return error(res, 502, 'resolve_failed', 'could not read this agent from the chain; retry shortly');}- if (resolved.error) {- return error(res, 400, 'bad_request', `failed to resolve agent: ${resolved.error}`);+ // A manifest that will not load is NOT a reason to refuse the import. The+ // registry read already succeeded and ownership is verified below, so the row+ // lands with the on-chain fallback name and the crawler backfills metadata on+ // its next pass. Refusing here meant a throttled ipfs.io gateway locked owners+ // out of their own agents. Only a failed CHAIN read blocks.+ if (resolved.error && !String(resolved.error).startsWith('manifest_fetch:')) {+ console.error('[erc8004/import] resolve failed:', redactUrlSecrets(resolved.error));+ return error(res, 502, 'resolve_failed', 'could not read this agent from the chain; retry shortly');+ }++ // The index row is crawler state and goes stale: an agent transferred since the+ // last crawl would otherwise still import for its former owner. When the live+ // registry answered with an owner, that answer wins over the cached one.+ if (resolved.owner && !userWallets.includes(resolved.owner.toLowerCase())) {+ return error(res, 403, 'forbidden', 'you do not own this agent');}const name = (resolved.name || `Agent #${agentId}`).slice(0, 255);@@ -514,7 +531,7 @@ const MAX_SIZE = 25 * 1024 * 1024; // 25 MBasync function handlePin(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'POST only');+ if (!method(req, res, ['POST'])) return;const session = await getSessionUser(req);if (!session) return error(res, 401, 'unauthorized', 'sign in required');@@ -536,14 +553,22 @@ async function handlePin(req, res) {const web3Token = process.env.WEB3_STORAGE_TOKEN;const nftToken = process.env.NFT_STORAGE_TOKEN;- if (web3Token) {- const result = await uploadToWeb3Storage(web3Token, ext, body, ct);- return json(res, 200, result);- }-- if (nftToken) {- const result = await uploadToNftStorage(nftToken, ext, body, ct);- return json(res, 200, result);+ const pinToIpfs = web3Token+ ? () => uploadToWeb3Storage(web3Token, ext, body, ct)+ : nftToken+ ? () => uploadToNftStorage(nftToken, ext, body, ct)+ : null;++ if (pinToIpfs) {+ // The pinning host is a network boundary: when it rejects the upload the+ // fault is upstream, so the caller gets a 502 it can retry against instead+ // of a generic internal_error that reads as a platform bug.+ try {+ return json(res, 200, await pinToIpfs());+ } catch (err) {+ console.error('[erc8004/pin] ipfs upload failed:', redactUrlSecrets(err?.message || String(err)));+ return error(res, 502, 'pin_failed', 'the IPFS pinning service did not accept the upload');+ }}// Fallback to R2 with warning@@ -572,6 +597,8 @@ function getExt(ct) {return 'json';case 'model/gltf-binary':return 'glb';+ case 'model/gltf+json':+ return 'gltf';case 'image/png':return 'png';case 'image/jpeg':diff --git a/api/erc8004/register-confirm.js b/api/erc8004/register-confirm.jsindex f78bcecfe..927b82a13 100644--- a/api/erc8004/register-confirm.js+++ b/api/erc8004/register-confirm.js@@ -6,6 +6,7 @@ import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/import { parse } from '../_lib/validate.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { CHAIN_BY_ID } from '../_lib/erc8004-chains.js';+import { evmRpcEndpoints } from '../_lib/evm/rpc.js';import { fetchSafePublicUrlPinned, SsrfBlockedError, MaxBytesExceededError } from '../_lib/ssrf-guard.js';const REGISTERED_TOPIC = keccakId('Registered(uint256,string,address)');@@ -14,7 +15,9 @@ const bodySchema = z.object({chainId: z.number().int().positive(),txHash: z.string().regex(/^0x[0-9a-fA-F]{64}$/),agentId: z.union([z.string(), z.number()]).transform(String),- metadataUri: z.string().min(1),+ // Stored verbatim as erc8004_agents_index.agent_uri and fetched by+ // enrichMetadata, so it is bounded here rather than at the DB.+ metadataUri: z.string().min(1).max(2048),ownerAddress: z.string().regex(/^0x[0-9a-fA-F]{40}$/),// Optional: when binding an EXISTING three.ws agent on-chain, the agent's// UUID. After the mint is verified below we write the unified meta.onchain@@ -35,7 +38,7 @@ export default wrap(async (req, res) => {const body = parse(bodySchema, await readJson(req));const chain = CHAIN_BY_ID[body.chainId];if (!chain) return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);- const receipt = await rpcCall(chain.rpcUrls ?? chain.rpcUrl, 'eth_getTransactionReceipt', [body.txHash]);+ const receipt = await rpcCall(body.chainId, 'eth_getTransactionReceipt', [body.txHash]);if (!receipt) return error(res, 422, 'tx_not_mined', 'transaction not yet mined');if (receipt.status === '0x0') return error(res, 422, 'tx_failed', 'transaction reverted');const log = (receipt.logs ?? []).find(@@ -130,8 +133,16 @@ async function bindAgentOnchain({return true;}-async function rpcCall(urls, m, params) {- const urlList = Array.isArray(urls) ? urls : [urls];+/**+ * Read a JSON-RPC method over the chain's canonical failover chain: an operator+ * RPC_URL_<chainId> override, then Alchemy, then the curated public endpoints,+ * with the known-hard-fail keyless hosts sorted last. This used to read+ * `chain.rpcUrls` directly, which is only the KEYLESS TAIL of that chain, so a+ * registration was confirmed against the slowest tier and a tx that was already+ * mined came back as `tx_not_mined` whenever a public node lagged.+ */+async function rpcCall(chainId, m, params) {+ const urlList = evmRpcEndpoints(chainId);let lastErr;for (const url of urlList) {const ac = new AbortController();@@ -153,7 +164,17 @@ async function rpcCall(urls, m, params) {clearTimeout(t);}}- throw lastErr;+ // Every endpoint failed: an infrastructure outage, not a caller mistake. An+ // authored 503 tells the client to retry; letting lastErr bubble produced an+ // opaque `internal_error` that read as a bug in the registration itself. The+ // upstream detail rides on `cause` (logged) and never in the response body,+ // which would otherwise echo a keyed provider URL.+ throw Object.assign(new Error('no RPC endpoint answered for this chain; retry shortly'), {+ status: 503,+ code: 'rpc_unavailable',+ expose: true,+ cause: lastErr,+ });}function resolveGateway(uri) {diff --git a/api/forever/inscribe.js b/api/forever/inscribe.jsindex 7e1e681a9..a4e65188b 100644--- a/api/forever/inscribe.js+++ b/api/forever/inscribe.js@@ -4,21 +4,24 @@// embedded into a Taproot witness on Bitcoin mainnet, where it lives forever.//// Body: { message: string, receiveAddress?: string, feeRate?: number }-// - message: 1–1500 chars of UTF-8 text to inscribe-// - receiveAddress: optional Taproot (bc1p…) address that receives the+// - message: 1 to 1500 chars of UTF-8 text to inscribe+// - receiveAddress: optional Taproot (bc1p...) address that receives the// inscription. If omitted, falls back to the platform vault address// (env.BTC_INSCRIPTION_RECEIVE_ADDRESS).-// - feeRate: optional sats/vB. Defaults to 8 (medium). Range 1–200.+// - feeRate: optional sats/vB. Defaults to 8 (medium). Range 1 to 200.//// Response 200:// { orderId, charge: { address, amount, currency, lightning_invoice? },// receiveAddress, feeRate, sizeBytes, mempoolUrl, ordinalsUrl?, status }//// Errors:-// 400 — invalid message / address / fee rate-// 502 — OrdinalsBot upstream error-// 503 — receive address not configured and none provided+// 400: invalid body / message / address / fee rate+// 401: not signed in and no valid bearer token+// 429: per-IP ceiling, or OrdinalsBot throttling the platform key+// 502: OrdinalsBot upstream error+// 503: receive address not provided and none configured+import { bech32m } from '@scure/base';import { cors, error, json, readJson, rateLimited } from '../_lib/http.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -31,10 +34,42 @@ const MIN_FEE_RATE = 1;const MAX_FEE_RATE = 200;const DEFAULT_FEE_RATE = 8;-// Bitcoin Taproot (P2TR / bc1p…) — the only address class OrdinalsBot will+// Bitcoin Taproot (P2TR / bc1p...) is the only address class OrdinalsBot will// send inscriptions to. Mainnet HRP "bc", witness version 1, bech32m, 62 chars.const TAPROOT_RE = /^bc1p[02-9ac-hj-np-z]{58}$/;+// A P2TR address encodes the witness version plus a 32-byte program, which is+// 1 + ceil(256 / 5) = 53 bech32 words.+const TAPROOT_WORD_COUNT = 53;++/**+ * Full bech32m validation, not just the character shape. A single mistyped+ * character keeps the bc1p... shape and only the checksum catches it, and+ * OrdinalsBot answers a bad address with an opaque proxy error that tells the+ * user nothing. Verifying here turns that into a precise 400 and spares the+ * upstream order-create call entirely.+ */+function hasValidTaprootChecksum(address) {+ try {+ const decoded = bech32m.decode(address, 90);+ return (+ decoded.prefix === 'bc' &&+ decoded.words[0] === 1 &&+ decoded.words.length === TAPROOT_WORD_COUNT+ );+ } catch {+ return false;+ }+}++/** OrdinalsBot reports failures as a string or an array of strings. */+function upstreamMessage(data) {+ const raw = data?.message ?? data?.error;+ if (Array.isArray(raw)) return raw.filter(Boolean).map(String).join('; ');+ if (typeof raw === 'string') return raw;+ return '';+}+function validateMessage(raw) {if (typeof raw !== 'string') {return { error: 'message must be a string' };@@ -53,13 +88,20 @@ function validateMessage(raw) {}function validateAddress(raw) {- if (!raw) return { address: null };+ if (raw === undefined || raw === null || raw === '') return { address: null };if (typeof raw !== 'string') return { error: 'receiveAddress must be a string' };const address = raw.trim();+ if (address === '') return { address: null };if (!TAPROOT_RE.test(address)) {return {error:- 'receiveAddress must be a Bitcoin Taproot address (bc1p…). Ordinals can only be received by Taproot wallets.',+ 'receiveAddress must be a Bitcoin Taproot address (bc1p...). Ordinals can only be received by Taproot wallets.',+ };+ }+ if (!hasValidTaprootChecksum(address)) {+ return {+ error:+ 'receiveAddress failed its bech32m checksum, so it is not a real Taproot address. Copy the bc1p... address again from your wallet.',};}return { address };@@ -118,10 +160,23 @@ async function createOrdinalsBotOrder({ message, receiveAddress, feeRate }) {err.upstream = text.slice(0, 300);throw err;}+ // OrdinalsBot signals failure two different ways: a non-2xx status, and a+ // 200 carrying {status:"error"}. Neither status is usable as our own. It+ // answers a rejected payload with a bare 404 and echoes its own internal+ // axios text, and a key or quota fault would arrive as 401/403. Passing any+ // of those through would tell the caller their request was not found or that+ // THEY are unauthorized, and the 200 case would ship an error envelope under+ // a success status that the client reads as a created order. Every upstream+ // fault is our gateway's fault: 502, except a throttle we can honestly relay.if (!res.ok || data.status === 'error') {- const err = new Error(data.message || data.error || `OrdinalsBot returned ${res.status}`);- err.status = res.status >= 500 ? 502 : res.status || 502;- err.upstream = data;+ const detail = upstreamMessage(data);+ const err = new Error(+ detail+ ? `OrdinalsBot rejected the inscription order: ${detail}`+ : `OrdinalsBot returned ${res.status}`,+ );+ err.status = res.status === 429 ? 429 : 502;+ err.upstream = detail || null;throw err;}return data;@@ -178,6 +233,9 @@ export default async function handler(req, res) {} catch (e) {return error(res, e.status || 400, 'bad_request', e.message || 'invalid request body');}+ if (!body || typeof body !== 'object' || Array.isArray(body)) {+ return error(res, 400, 'bad_request', 'request body must be a JSON object');+ }const msg = validateMessage(body.message);if (msg.error) return error(res, 400, 'invalid_message', msg.error);@@ -188,14 +246,25 @@ export default async function handler(req, res) {const fee = validateFeeRate(body.feeRate);if (fee.error) return error(res, 400, 'invalid_fee_rate', fee.error);- const receiveAddress =- addr.address || process.env.BTC_INSCRIPTION_RECEIVE_ADDRESS || null;+ const vaultAddress = (process.env.BTC_INSCRIPTION_RECEIVE_ADDRESS || '').trim();+ const receiveAddress = addr.address || vaultAddress || null;if (!receiveAddress) {return error(res,503,'no_receive_address',- 'No Taproot receive address provided and BTC_INSCRIPTION_RECEIVE_ADDRESS is not configured. Send your bc1p… address in the request body.',+ 'No Taproot receive address provided and BTC_INSCRIPTION_RECEIVE_ADDRESS is not configured. Send your bc1p... address in the request body.',+ );+ }+ // The vault address comes from config, so it skipped the request validation+ // above. A typo there would mint inscriptions into an unspendable address,+ // so hold it to the same bar and fail loudly instead of silently upstream.+ if (!addr.address && !(TAPROOT_RE.test(receiveAddress) && hasValidTaprootChecksum(receiveAddress))) {+ return error(+ res,+ 503,+ 'invalid_vault_address',+ 'BTC_INSCRIPTION_RECEIVE_ADDRESS is not a valid Bitcoin Taproot address. Send your own bc1p... address in the request body.',);}@@ -207,9 +276,14 @@ export default async function handler(req, res) {feeRate: fee.feeRate,});} catch (e) {- return error(res, e.status || 502, 'inscription_failed', e.message, {- upstream: e.upstream,- });+ const status = e.status === 429 ? 429 : 502;+ return error(+ res,+ status,+ status === 429 ? 'upstream_rate_limited' : 'inscription_failed',+ e.message,+ e.upstream ? { upstream: e.upstream } : {},+ );}const shaped = shapeChargeResponse(order, {diff --git a/api/forever/status.js b/api/forever/status.jsindex 1c69c4cb0..281fbbced 100644--- a/api/forever/status.js+++ b/api/forever/status.js@@ -17,13 +17,33 @@//// state ∈ "waiting-payment" | "payment-received" | "inscribing" |// "inscribed" | "failed"+//+// Errors:+// 400: missing or malformed id+// 404: no OrdinalsBot order exists with that id+// 429: per-IP polling ceiling+// 502: OrdinalsBot upstream error-import { cors, error, json } from '../_lib/http.js';+import { cors, error, json, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';import { getTransactionStatus, getTipHeight, isPlausibleTxid } from '../_lib/esplora.js';const ORDINALSBOT_BASE_URL =process.env.ORDINALSBOT_BASE_URL || 'https://api.ordinalsbot.com';+// Order ids are opaque upstream tokens (uuid or nanoid shaped). Bounding them+// here keeps an arbitrary payload from reaching the metered upstream lookup.+const ORDER_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;++// States that can only be reached after the charge was actually settled.+// "failed" is deliberately absent: an expired or cancelled order is a terminal+// state the user usually reaches by never paying at all.+const PAID_STATES = new Set(['payment-received', 'inscribing', 'inscribed']);++// OrdinalsBot answers an unknown id with HTTP 200 and {status:"error"}, so the+// only signal that an order does not exist is the message text.+const NOT_FOUND_RE = /invalid\s*order\s*id|not\s*found|no\s*such\s*order|missing\s*params/i;+function deriveState(order) {const raw = String(order.status || order.state || '').toLowerCase();if (['completed', 'inscribed', 'sent', 'delivered'].includes(raw)) return 'inscribed';@@ -114,6 +134,14 @@ async function fetchOnchainStatus(txid) {}}+/** OrdinalsBot reports failures as a string or an array of strings. */+function upstreamMessage(data) {+ const raw = data?.message ?? data?.error;+ if (Array.isArray(raw)) return raw.filter(Boolean).map(String).join('; ');+ if (typeof raw === 'string') return raw;+ return '';+}+async function fetchOrdinalsBotOrder(orderId) {const headers = {};if (process.env.ORDINALSBOT_API_KEY) {@@ -131,8 +159,16 @@ async function fetchOrdinalsBotOrder(orderId) {throw err;}if (!res.ok || data.status === 'error') {- const err = new Error(data.message || data.error || `OrdinalsBot returned ${res.status}`);- err.status = res.status === 404 ? 404 : 502;+ const detail = upstreamMessage(data);+ if (res.status === 404 || NOT_FOUND_RE.test(detail)) {+ const err = new Error('no OrdinalsBot order exists with that id');+ err.status = 404;+ throw err;+ }+ const err = new Error(+ detail ? `OrdinalsBot lookup failed: ${detail}` : `OrdinalsBot returned ${res.status}`,+ );+ err.status = res.status === 429 ? 429 : 502;throw err;}return data;@@ -142,15 +178,27 @@ export default async function handler(req, res) {if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;if (req.method !== 'GET') return error(res, 405, 'method_not_allowed', 'GET only');+ // Every call spends a slot of the platform's metered OrdinalsBot budget, and+ // the pay screen polls this endpoint on a timer. The ceiling has to clear a+ // long wait across a couple of tabs while still capping an anonymous script.+ const rl = await limits.inscribeStatusIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+const url = new URL(req.url, 'http://localhost');const orderId = url.searchParams.get('id');if (!orderId) return error(res, 400, 'missing_id', 'query param "id" is required');+ if (!ORDER_ID_RE.test(orderId)) {+ return error(res, 400, 'invalid_id', 'query param "id" is not a valid order id');+ }let order;try {order = await fetchOrdinalsBotOrder(orderId);} catch (e) {- return error(res, e.status || 502, 'status_lookup_failed', e.message);+ const status = e.status || 502;+ const code =+ status === 404 ? 'order_not_found' : status === 429 ? 'upstream_rate_limited' : 'status_lookup_failed';+ return error(res, status, code, e.message);}const state = deriveState(order);@@ -165,7 +213,7 @@ export default async function handler(req, res) {return json(res, 200, {orderId,state,- paid: state !== 'waiting-payment',+ paid: PAID_STATES.has(state),inscribed: state === 'inscribed',charge: chargeAddress? {diff --git a/api/galaxy/flows.js b/api/galaxy/flows.jsindex cd1370c53..b3e157a52 100644--- a/api/galaxy/flows.js+++ b/api/galaxy/flows.js@@ -67,12 +67,15 @@ class FeedDeadline extends Error {}// A valid, empty feed window — the same shape handleFeed returns — so a degraded// response is indistinguishable to the client from a genuinely quiet platform.-function emptyFeed(network, type) {+// `headCursor` echoes a delta poller's own cursor back (exactly as the success+// path does when a poll finds nothing new), so a degraded poll costs the client+// its place in the stream instead of rewinding it.+function emptyFeed(network, type, headCursor = null) {return {flows: [],has_more: false,next_cursor: null,- head_cursor: null,+ head_cursor: headCursor,network,type,summary: {@@ -246,7 +249,11 @@ export default async function handler(req, res) {const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';const typeRaw = url.searchParams.get('type') || 'all';const type = TYPE_KINDS[typeRaw] ? typeRaw : 'all';- const limit = Math.min(MAX_LIMIT, Math.max(1, Number(url.searchParams.get('limit')) || DEFAULT_LIMIT));+ // Floor before clamping: `limit` reaches Postgres as the LIMIT argument, which+ // must be an integer. A fractional `?limit=1.5` sent `LIMIT 2.5` and errored the+ // whole query, degrading a healthy platform to an "honestly empty" window that+ // was neither honest nor empty.+ const limit = Math.min(MAX_LIMIT, Math.max(1, Math.floor(Number(url.searchParams.get('limit'))) || DEFAULT_LIMIT));const cursor = url.searchParams.get('cursor');const since = url.searchParams.get('since');@@ -254,6 +261,18 @@ export default async function handler(req, res) {// timeout or DB failure, fall back to the last-good snapshot for this// view, and only then to an empty (but valid) window — so the galaxy degrades// to last-known or calm-empty instead of surfacing a 504/502 the map can't use.+ //+ // The last-good snapshot belongs to the FIRST-PAGE view alone. It is the only+ // request whose result is a self-contained window a degraded response can+ // honestly stand in for, and the only one keyed unambiguously by+ // (network, type, limit). A delta poll (`since`) or a backfill page (`cursor`)+ // shares that key while returning a completely different slice, so letting+ // either touch it broke the mechanism twice over: the near-empty result of+ // every 6s delta poll overwrote the real window (leaving nothing good to fall+ // back to), and reading it handed a live poller a stale full window whose+ // older head_cursor rewound its position and could replay long-past flows as+ // new light on the map. Scope both the write and the read to the first page.+ const isFirstPage = !cursor && !since;const lastGoodKey = `galaxy:flows:lastgood:${network}:${type}:${limit}`;async function buildWithDeadline() {let timer;@@ -266,7 +285,7 @@ export default async function handler(req, res) {// but at most once per LASTGOOD_REFRESH_MS per view, so the live-feed cache// miss isn't paired with a second large SET on every request.const now = Date.now();- if (now - (_lastGoodWrittenAt.get(lastGoodKey) || 0) >= LASTGOOD_REFRESH_MS) {+ if (isFirstPage && now - (_lastGoodWrittenAt.get(lastGoodKey) || 0) >= LASTGOOD_REFRESH_MS) {_lastGoodWrittenAt.set(lastGoodKey, now);cacheSet(lastGoodKey, body, LASTGOOD_TTL_S).catch(() => {});}@@ -279,7 +298,6 @@ export default async function handler(req, res) {try {// A first page (no cursor/since) is cached briefly to shield the DB from a// herd of pollers. A delta poll (`since`) is never cached — it must be live.- const isFirstPage = !cursor && !since;if (isFirstPage) {const cacheKey = `galaxy:flows:${network}:${type}:${limit}`;let body = await cacheGet(cacheKey);@@ -303,16 +321,18 @@ export default async function handler(req, res) {const dbDown = !timedOut && isDbUnavailableError(e);if (dbDown) console.warn('[api/galaxy/flows] degraded (db unavailable):', e?.message);else console.error('[api/galaxy/flows] failed', timedOut ? 'soft-deadline' : e?.message, timedOut ? '' : e?.stack);- // Degrade gracefully: a delta poll (`since`) returns nothing new rather than- // erroring the live map; any view falls back to its last-good snapshot when- // one exists, else an empty window. All are valid 200s.- const lastGood = await cacheGet(lastGoodKey).catch(() => null);+ // Degrade gracefully: the first page falls back to its last-good snapshot+ // when one exists; a delta poll (`since`) or a backfill page (`cursor`)+ // returns nothing rather than a window that does not answer what was asked,+ // with the poller's own cursor echoed back so it keeps its place. All are+ // valid 200s the map renders calmly.+ const lastGood = isFirstPage ? await cacheGet(lastGoodKey).catch(() => null) : null;if (lastGood) {res.setHeader('cache-control', 'public, max-age=6');res.setHeader('x-galaxy-flows-degraded', timedOut ? 'deadline' : 'error');return json(res, 200, { data: lastGood });}res.setHeader('x-galaxy-flows-degraded', timedOut ? 'deadline-empty' : 'error-empty');- return json(res, 200, { data: emptyFeed(network, type) });+ return json(res, 200, { data: emptyFeed(network, type, decodeCursor(since) ? since : null) });}}diff --git a/api/genome/breed.js b/api/genome/breed.jsindex dc8713cdd..208f501f4 100644--- a/api/genome/breed.js+++ b/api/genome/breed.js@@ -89,9 +89,23 @@ export default wrap(async (req, res) => {if (!eligA.allowed) return error(res, 403, 'parent_ineligible', `parent A: ${eligA.reason}`, { parent: 'a', reason: eligA.reason });if (!eligB.allowed) return error(res, 403, 'parent_ineligible', `parent B: ${eligB.reason}`, { parent: 'b', reason: eligB.reason });+ // Cooldown FIRST, before the fee gate. Both parents must be off cooldown, which+ // keeps deep pedigrees scarce. Checking it after the 402 would have taken a real+ // $THREE settlement for a breeding this request was always going to refuse.+ const now = Date.now();+ const [coolA, coolB] = await Promise.all([cooldownRemainingMs(parentAId, now), cooldownRemainingMs(parentBId, now)]);+ const cool = Math.max(coolA, coolB);+ if (cool > 0) {+ return error(res, 409, 'breeding_cooldown', 'a parent is still on breeding cooldown', {+ cooldown_remaining_ms: cool,+ cooldown_remaining_min: Math.ceil(cool / 60000),+ });+ }+const feeThree = (eligA.fee_three || 0) + (eligB.fee_three || 0);const consentOwner = eligA.cross_owner ? eligA.owner_id : eligB.cross_owner ? eligB.owner_id : null;const studFeeSig = (typeof body.stud_fee_signature === 'string' && body.stud_fee_signature.trim()) || '';+ let studFeeAtomics = '0';// A cross-owner stud with a fee must be paid in $THREE. The caller supplies a// real settlement signature, or we 402 with the exact terms (no breed on credit).if (feeThree > 0) {@@ -129,17 +143,7 @@ export default wrap(async (req, res) => {stud_wallets: studWallets,});}- }-- // Cooldown — both parents must be off cooldown. Keeps deep pedigrees scarce.- const now = Date.now();- const [coolA, coolB] = await Promise.all([cooldownRemainingMs(parentAId, now), cooldownRemainingMs(parentBId, now)]);- const cool = Math.max(coolA, coolB);- if (cool > 0) {- return error(res, 409, 'breeding_cooldown', 'a parent is still on breeding cooldown', {- cooldown_remaining_ms: cool,- cooldown_remaining_min: Math.ceil(cool / 60000),- });+ studFeeAtomics = paid.atomics || '0';}// Derive the child genome — deterministic, re-derivable from (parents, seed).@@ -202,6 +206,7 @@ export default wrap(async (req, res) => {return r;});} catch (e) {+ console.error('[breed] child insert failed', { parents: [rowA.id, rowB.id], error: e?.message });return error(res, 500, 'breed_failed', 'failed to create child agent');}@@ -212,7 +217,11 @@ export default wrap(async (req, res) => {const parentSolanas = [rowA.meta?.solana_address, rowB.meta?.solana_address].filter(Boolean);const parentEvms = [rowA.wallet_address, rowB.wallet_address, rowA.meta?.wallet_address, rowB.meta?.wallet_address].filter(Boolean);if (parentSolanas.includes(wallets.solana) || parentEvms.includes(wallets.evm)) {- return error(res, 500, 'ownership_invariant_violation', 'child wallet collided with a parent — breeding aborted');+ // Retire the row we just inserted. Aborting without it would leave a bred,+ // genome-carrying agent visible in listings and lineage walks that no+ // breeding record ever accounts for.+ await retireChild(child.id, 'ownership_invariant_violation');+ return error(res, 500, 'ownership_invariant_violation', 'child wallet collided with a parent, breeding aborted');}// ── Grant inherited skill licenses on-chain (royalty-provenance recorded) ───@@ -234,23 +243,44 @@ export default wrap(async (req, res) => {// ── Persist the breeding event (the verifiable lineage record) ──────────────const genomeHash = childGenome.genome_hash || hashGenome(childGenome);+ let recorded = null;try {- await sql`+ [recorded] = await sql`insert into genome_breedings (breeding_key, parent_a_agent_id, parent_b_agent_id, child_agent_id,seed, genome, genome_hash, generation, pedigree_tier, bred_by,- stud_fee_lamports, stud_fee_signature, consent_owner, status+ stud_fee_atomics, stud_fee_signature, consent_owner, status) values (${breedingKey}, ${rowA.id}, ${rowB.id}, ${child.id},${seed}, ${JSON.stringify(childGenome)}::jsonb, ${genomeHash},${childGenome.generation}, ${pedigree.tier}, ${auth.userId},- ${0}, ${studFeeSig || null}, ${consentOwner}, 'born'+ ${studFeeAtomics}, ${studFeeSig || null}, ${consentOwner}, 'born')on conflict (breeding_key) do nothing+ returning child_agent_id`;} catch (e) {+ // A unique violation on the settlement signature means a request racing this+ // one already spent the same $THREE payment. The replay SELECT above cannot+ // see an uncommitted sibling; the index can, and it is the only place this+ // can be decided atomically. Retire our child rather than let one payment+ // buy two.+ if (e?.code === '23505' && /stud_fee_signature/.test(String(e?.constraint || e?.message || ''))) {+ await retireChild(child.id, 'stud_fee_replayed');+ return error(res, 409, 'stud_fee_replayed', 'that stud_fee_signature was already used to pay for another breeding');+ }console.error('[breed] lineage record failed', { child: child.id, error: e?.message });}+ // No returned row means the breeding key conflicted: a concurrent request (a+ // double-submitted preview) recorded this exact pairing first. The header+ // promises no twins, so retire ours and hand back the child that won.+ if (recorded === undefined) {+ await retireChild(child.id, 'breeding_key_race');+ const [winner] = await sql`+ select child_agent_id from genome_breedings where breeding_key = ${breedingKey} limit 1+ `;+ return json(res, 200, { child: await loadChildSummary(winner?.child_agent_id || child.id), deduped: true });+ }dispatchWebhooks({userId: auth.userId,@@ -400,6 +430,22 @@ async function grantInheritedSkills({ skills, childGenome, childWallet, parentA,return grants;}+// Withdraw a child that was inserted but must not exist: a wallet-collision abort,+// or a lost race for the breeding key. Soft-delete keeps the row for forensics+// while removing it from every listing, lineage walk, and cooldown calculation.+async function retireChild(childAgentId, reason) {+ try {+ await sql`+ update agent_identities+ set deleted_at = now(), updated_at = now(),+ meta = jsonb_set(coalesce(meta, '{}'::jsonb), '{bred_from,retired}', ${JSON.stringify(reason)}::jsonb, true)+ where id = ${childAgentId} and deleted_at is null+ `;+ } catch (e) {+ console.error('[breed] child retire failed', { child: childAgentId, reason, error: e?.message });+ }+}+async function loadChildSummary(childAgentId) {const [r] = await sql`select id, name, avatar_id, meta from agent_identities where id = ${childAgentId} limit 1diff --git a/api/genome/edges.js b/api/genome/edges.jsindex 00ed69a03..7613a1720 100644--- a/api/genome/edges.js+++ b/api/genome/edges.js@@ -12,11 +12,16 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 2000, 1), 5000);+ // Inner-joined to the three live agents so a deleted node never leaves a lineage+ // line hanging off the star map to a star that is no longer drawn.const rows = await sql`- select parent_a_agent_id, parent_b_agent_id, child_agent_id, generation, pedigree_tier- from genome_breedings- where status = 'born' and child_agent_id is not null- order by created_at desc+ select b.parent_a_agent_id, b.parent_b_agent_id, b.child_agent_id, b.generation, b.pedigree_tier+ from genome_breedings b+ join agent_identities pa on pa.id = b.parent_a_agent_id and pa.deleted_at is null+ join agent_identities pb on pb.id = b.parent_b_agent_id and pb.deleted_at is null+ join agent_identities c on c.id = b.child_agent_id and c.deleted_at is null+ where b.status = 'born'+ order by b.created_at desclimit ${limit}`;const edges = rows.map((r) => ({diff --git a/api/genome/lineage.js b/api/genome/lineage.jsindex 0d67d2fc5..dcee2bad5 100644--- a/api/genome/lineage.js+++ b/api/genome/lineage.js@@ -26,7 +26,7 @@ export default wrap(async (req, res) => {const node = await loadNode(agentId);if (!node) return error(res, 404, 'not_found', 'agent not found');- if (url.searchParams.get('verify')) {+ if (isTruthy(url.searchParams.get('verify'))) {return json(res, 200, await verifyNode(agentId), { 'cache-control': 'public, s-maxage=30' });}@@ -38,10 +38,6 @@ export default wrap(async (req, res) => {where b.child_agent_id = ${agentId} and b.status = 'born'order by b.created_at asc limit 1`;- const parents = birth- ? await Promise.all([loadNode(birth.parent_a_agent_id), loadNode(birth.parent_b_agent_id)])- : [];-// Children (every breed this agent was a parent of).const childRows = await sql`select b.child_agent_id, b.generation, b.pedigree_tier, b.created_at,@@ -51,13 +47,20 @@ export default wrap(async (req, res) => {and b.status = 'born' and b.child_agent_id is not nullorder by b.created_at desc limit 100`;- const children = await Promise.all(- childRows.map(async (r) => ({- ...(await loadNode(r.child_agent_id)),- co_parent: await loadNode(r.co_parent),- bred_at: r.created_at,- })),- );++ // One lookup for the parents plus every child and co-parent. Loading them one+ // id at a time issued up to 202 round trips for a well-bred agent.+ const nodes = await loadNodes([+ birth?.parent_a_agent_id,+ birth?.parent_b_agent_id,+ ...childRows.flatMap((r) => [r.child_agent_id, r.co_parent]),+ ]);+ const parents = birth ? [nodes.get(birth.parent_a_agent_id), nodes.get(birth.parent_b_agent_id)] : [];+ const children = childRows.map((r) => ({+ ...nodes.get(r.child_agent_id),+ co_parent: nodes.get(r.co_parent) || null,+ bred_at: r.created_at,+ }));// Ancestors — walk up the pedigree (bounded), so a profile can render depth.const ancestors = await walkAncestors(agentId);@@ -125,16 +128,23 @@ async function walkAncestors(agentId) {where child_agent_id = any(${frontier}) and status = 'born'`;const next = [];+ const owner = new Map();for (const r of rows) {for (const pid of [r.parent_a_agent_id, r.parent_b_agent_id]) {if (pid && !seen.has(pid)) {seen.add(pid);next.push(pid);- const n = await loadNode(pid);- if (n) out.push({ ...n, depth, of: r.child_agent_id });+ owner.set(pid, r.child_agent_id);}}}+ // One lookup per generation rather than one per ancestor: a full 8-deep+ // pedigree fans out to 255 forebears.+ const nodes = await loadNodes(next);+ for (const pid of next) {+ const n = nodes.get(pid);+ if (n) out.push({ ...n, depth, of: owner.get(pid) });+ }frontier = next;}return out;@@ -143,24 +153,42 @@ async function walkAncestors(agentId) {// One node of the tree — public-safe. Private agents reveal only that they exist.async function loadNode(agentId) {if (!agentId) return null;- const [r] = await sql`+ return (await loadNodes([agentId])).get(agentId) || null;+}++// Batch form of loadNode: ids in, Map(id → node) out. Missing/deleted ids are+// simply absent from the map.+async function loadNodes(agentIds) {+ const ids = [...new Set(agentIds.filter(Boolean))];+ if (!ids.length) return new Map();+ const rows = await sql`select i.id, i.name, i.is_public, i.user_id, i.avatar_id, i.meta,a.thumbnail_key as avatar_thumbnail_keyfrom agent_identities ileft join avatars a on a.id = i.avatar_id and a.deleted_at is null- where i.id = ${agentId} and i.deleted_at is null- limit 1+ where i.id = any(${ids}) and i.deleted_at is null`;- if (!r) return null;- const genome = r.meta?.genome ? normalizeGenome(r.meta.genome) : null;- const pedigree = genome ? pedigreeScore(genome) : { tier: 'common', generation: 0, score: 0 };- return {- id: r.id,- name: r.is_public ? r.name : 'Private agent',- is_public: !!r.is_public,- avatar_id: r.avatar_id,- generation: genome?.generation ?? 0,- pedigree,- bred: !!r.meta?.bred_from,- };+ const out = new Map();+ for (const r of rows) {+ const genome = r.meta?.genome ? normalizeGenome(r.meta.genome) : null;+ const pedigree = genome ? pedigreeScore(genome) : { tier: 'common', generation: 0, score: 0 };+ out.set(r.id, {+ id: r.id,+ name: r.is_public ? r.name : 'Private agent',+ is_public: !!r.is_public,+ avatar_id: r.avatar_id,+ generation: genome?.generation ?? 0,+ pedigree,+ bred: !!r.meta?.bred_from,+ });+ }+ return out;+}++// `?verify=1` verifies; `?verify=0` and `?verify=false` do not. Any non-empty+// value used to pass, so a client sending an explicit "off" got verification.+function isTruthy(raw) {+ if (raw === null) return false;+ const v = String(raw).trim().toLowerCase();+ return v !== '' && v !== '0' && v !== 'false' && v !== 'no';}diff --git a/api/genome/preview.js b/api/genome/preview.jsindex 0c9ad11f2..d0700d294 100644--- a/api/genome/preview.js+++ b/api/genome/preview.js@@ -49,7 +49,9 @@ export default wrap(async (req, res) => {if (!eligB.allowed) return error(res, 403, 'parent_ineligible', `parent B: ${eligB.reason}`, { parent: 'b', reason: eligB.reason });const seed = typeof body.seed === 'string' && body.seed ? body.seed.slice(0, 64) : makeSeed();- const childName = (typeof body.name === 'string' && body.name.trim()) || `${rowA.name} × ${rowB.name}`;+ // Same 80-char ceiling breed.js applies, so the previewed name is exactly the+ // name the committed child will carry.+ const childName = (typeof body.name === 'string' && body.name.trim().slice(0, 80)) || `${rowA.name} × ${rowB.name}`.slice(0, 80);const child = deriveGenome({ parentA: agentGenome(rowA), parentB: agentGenome(rowB), seed });const feeThree = (eligA.fee_three || 0) + (eligB.fee_three || 0);diff --git a/api/genome/stud.js b/api/genome/stud.jsindex c95cd7d37..145a3deb9 100644--- a/api/genome/stud.js+++ b/api/genome/stud.js@@ -10,9 +10,13 @@ import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../import { requireCsrf } from '../_lib/csrf.js';import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';import { isUuid } from '../_lib/validate.js';+import { limits } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';+import { breedingPolicy } from '../_lib/genome-agent.js';import { pedigreeScore, normalizeGenome, genomeFromAgent } from '../_lib/genome.js';+const MAX_STUD_FEE_THREE = 1_000_000;+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET', 'POST'])) return;@@ -28,22 +32,50 @@ export default wrap(async (req, res) => {const agentId = String(body.agent_id || body.agentId || '').trim();if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id is required');+ const rl = await limits.genomeStudWrite(auth.userId);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many stud listing updates, slow down');+const [row] = await sql`select id, user_id, meta from agent_identities where id = ${agentId} and deleted_at is null limit 1`;if (!row) return error(res, 404, 'not_found', 'agent not found');if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'you do not own this agent');- const stud = body.stud === true;- const fee = Math.max(0, Math.min(1_000_000, Number(body.stud_fee_three) || 0));- const breedable = body.breedable !== false;- const meta = { ...(row.meta || {}) };- meta.genome_breeding = { ...(meta.genome_breeding || {}), breedable, stud, stud_fee_three: fee };+ // PATCH semantics, not PUT: an omitted field keeps its stored value. A whole-+ // object read-modify-write meant "set my fee to 40" (a body carrying only+ // stud_fee_three) silently unlisted the agent and re-enabled breeding, because+ // the absent `stud` and `breedable` keys fell back to their bare defaults.+ const current = breedingPolicy(row);+ const policy = {+ breedable: typeof body.breedable === 'boolean' ? body.breedable : current.breedable,+ stud: typeof body.stud === 'boolean' ? body.stud : current.stud,+ stud_fee_three: has(body, 'stud_fee_three') ? clampFee(body.stud_fee_three) : current.stud_fee_three,+ };- await sql`update agent_identities set meta = ${JSON.stringify(meta)}::jsonb, updated_at = now() where id = ${agentId}`;- return json(res, 200, { agent_id: agentId, genome_breeding: meta.genome_breeding });+ // Write only the genome_breeding subtree. Replacing the whole `meta` document+ // would clobber any key a concurrent write (wallet provisioning, persona save)+ // landed between our SELECT and our UPDATE.+ await sql`+ update agent_identities+ set meta = jsonb_set(coalesce(meta, '{}'::jsonb), '{genome_breeding}', ${JSON.stringify(policy)}::jsonb, true),+ updated_at = now()+ where id = ${agentId} and user_id = ${auth.userId}+ `;+ return json(res, 200, { agent_id: agentId, genome_breeding: policy });});+function has(obj, key) {+ return Object.prototype.hasOwnProperty.call(obj, key);+}++// A fee is $THREE, so it is non-negative, finite, and bounded. A junk value+// (null, a string, NaN) reads as "no fee" rather than failing the whole update.+function clampFee(raw) {+ const n = Number(raw);+ if (!Number.isFinite(n)) return 0;+ return Math.max(0, Math.min(MAX_STUD_FEE_THREE, n));+}+async function listStuds(req, res) {const url = new URL(req.url, 'http://x');const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 24, 1), 60);diff --git a/api/guardian/assess.js b/api/guardian/assess.jsindex 25c4b745a..83c8cf0b9 100644--- a/api/guardian/assess.js+++ b/api/guardian/assess.js@@ -1,9 +1,9 @@-// POST /api/guardian/assess — IBM Granite Guardian governance for AI agents.+// POST /api/guardian/assess: IBM Granite Guardian governance for AI agents.//// The watsonx "Trust Layer": classify a message (or a proposed autonomous action)// against IBM's Granite Guardian risk model and return a structured verdict plus// a tamper-evident, hash-chained audit record. This is what lets a three.ws-// avatar — which thinks on Granite and holds its own Solana wallet — be GOVERNED+// avatar (which thinks on Granite and holds its own Solana wallet) be GOVERNED// by Granite before it acts. Same IBM Cloud key, same watsonx.ai REST surface as// the Granite brain (see api/_lib/granite-guardian.js).//@@ -36,17 +36,18 @@ import {const MAX_TEXT_LEN = 4000;const MAX_TURNS = 20;-// Default risk panel for the standalone assess flow — the user-facing harms a+// Default risk panel for the standalone assess flow: the user-facing harms a// governance dashboard wants on screen. All are scorable from a single message.const SHOWCASE_RISKS = ['harm', 'jailbreak', 'violence', 'social_bias', 'profanity', 'sexual_content', 'unethical_behavior'];-function bad(res, msg) {- return error(res, 400, 'bad_request', msg);+function bad(res, msg, status = 400) {+ return error(res, status, 'bad_request', msg);}// Normalize the assessed input into a {messages, summary} pair. `summary` is the// human-readable content the audit record commits to (hashed, never stored raw).function parseInput(body) {+ if (!body || typeof body !== 'object') throw new Error('body must be a JSON object');if (typeof body.text === 'string') {const t = body.text.trim();if (!t) throw new Error('text must not be empty');@@ -55,7 +56,7 @@ function parseInput(body) {}if (Array.isArray(body.messages)) {if (!body.messages.length || body.messages.length > MAX_TURNS) {- throw new Error(`messages must hold 1–${MAX_TURNS} turns`);+ throw new Error(`messages must hold 1 to ${MAX_TURNS} turns`);}const input = [];for (const m of body.messages) {@@ -97,23 +98,23 @@ export default wrap(async function handler(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;- // Per-IP burst control + a global hourly ceiling that caps watsonx spend- // regardless of how many distinct clients call in.+ // Per-IP burst control, charged on every request so a single client cannot+ // hammer the endpoint. The global watsonx spend ceiling is charged later, on+ // the path that actually bills inference.const ip = clientIp(req);const perIp = await limits.guardianIp(ip);if (!perIp.success) {- return rateLimited(res, perIp, 'too many governance requests — slow down');- }- const globalLimit = await limits.guardianGlobal();- if (!globalLimit.success) {- return rateLimited(res, globalLimit, 'governance capacity reached — try again shortly');+ return rateLimited(res, perIp, 'too many governance requests, slow down');}let body;try {+ // readJson tags its own status (415 wrong content-type, 413 oversized).+ // Collapsing those into 400 tells the caller "your JSON is malformed"+ // when the real fix is a header or a smaller body.body = await readJson(req, 100_000);} catch (e) {- return bad(res, e.message || 'invalid JSON body');+ return bad(res, e.message || 'invalid JSON body', e.status || 400);}let parsed;@@ -137,6 +138,16 @@ export default wrap(async function handler(req, res) {);}+ // Global hourly ceiling: a hard cost cap on watsonx inference, independent of+ // how many distinct clients call in. Charged here, after validation and the+ // config gate, because those paths never reach watsonx. Charging it up front+ // let a single client sending malformed bodies drain the platform-wide+ // governance quota and 429 everyone else for the rest of the hour.+ const globalLimit = await limits.guardianGlobal();+ if (!globalLimit.success) {+ return rateLimited(res, globalLimit, 'governance capacity reached, try again shortly');+ }+const started = Date.now();let verdicts;let decision;@@ -154,7 +165,7 @@ export default wrap(async function handler(req, res) {decision = decide(verdicts);}} catch (e) {- // A real upstream failure (IAM, region, model) — surface it, don't invent.+ // A real upstream failure (IAM, region, model). Surface it, never invent.return error(res, 502, 'guardian_failed', `Granite Guardian assessment failed: ${e.message}`);}diff --git a/api/ibm/attest.js b/api/ibm/attest.jsindex 08ead4a76..fd4f9c445 100644--- a/api/ibm/attest.js+++ b/api/ibm/attest.js@@ -26,13 +26,13 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';import { watsonxForecast, forecastModelFor } from '../_lib/watsonx-forecast.js';+import { guardianConfig, assessRisk } from '../_lib/granite-guardian.js';import { fetchOhlcv, topPoolForToken, trendingPools } from '../_lib/market/ohlcv.js';--// Granite Guardian model — IBM's open safety classifier. Run inline via the-// stable chat endpoint (system message names the risk, the model answers-// Yes/No) so this feature is self-contained and does not couple to the-// repo's churning guardian helper module.-const GUARDIAN_MODEL = process.env.WATSONX_GUARDIAN_MODEL?.trim() || 'ibm/granite-guardian-3-8b';+import {+ callMarket,+ isMarketUpstreamError,+ marketUpstreamError,+} from '../_lib/market/upstream-error.js';import {avatarWalletConfig,loadAvatarKeypair,@@ -147,30 +147,6 @@ async function narrate(cfg, { name, symbol, currentPrice, stats }) {return { text: (text || '').trim(), model };}-// Granite Guardian risk classification. Drives the Guardian model through the-// standard chat endpoint: the system turn states the risk name, the user turn-// is the text to screen, and the model replies "Yes" (risk present) or "No".-async function graniteGuardian(cfg, text) {- const { text: out, model } = await watsonxChatComplete(cfg, {- model: GUARDIAN_MODEL,- messages: [- { role: 'system', content: 'harm' },- { role: 'user', content: text },- ],- maxTokens: 16,- temperature: 0,- });- const verdict = (out || '').trim().toLowerCase();- const flagged = verdict.startsWith('yes');- return {- flagged,- risk: 'harm',- label: flagged ? 'Harm' : 'Safe',- verdict: flagged ? 'Yes' : 'No',- model: model || GUARDIAN_MODEL,- };-}-// Build the on-chain memo for a claim — kept compact (the SPL-memo write is// truncated at 180 bytes by the wallet layer; we stay well under).function memoFor({ symbol, stats, governance, digest, tsModel }) {@@ -194,7 +170,7 @@ async function loadMarket(params) {if (!pool && token) {if (!isBase58(token))throw { status: 400, code: 'bad_token', message: 'token must be a base58 mint' };- pool = await topPoolForToken(token, network);+ pool = await callMarket(() => topPoolForToken(token, network));}if (!pool || !isBase58(pool)) {throw {@@ -207,13 +183,9 @@ async function loadMarket(params) {? params.timeframe: 'hour';const aggregate = Math.max(1, Math.min(60, parseInt(params.aggregate || '1', 10) || 1));- const { candles, base, quote, freq } = await fetchOhlcv({- pool,- network,- timeframe,- aggregate,- limit: 1000,- });+ const { candles, base, quote, freq } = await callMarket(() =>+ fetchOhlcv({ pool, network, timeframe, aggregate, limit: 1000 }),+ );if (candles.length < 64)throw {status: 422,@@ -297,12 +269,18 @@ async function runGranite(out, market, attesterAddress) {});narration = { text: n.text, model: n.model };try {- const g = await graniteGuardian(cfg, n.text);+ // The canonical Granite Guardian client: real safety-agent framing for the+ // named risk, plus a probability read back from logprobs. This verdict is+ // what vetoes an on-chain write, so it runs the same classifier the rest+ // of the platform is governed by rather than a bespoke prompt that hands+ // the model the bare word "harm" as its system turn.+ const g = await assessRisk(guardianConfig(), { risk: 'harm', input: n.text });governance = {passed: !g.flagged,risk: g.risk,label: g.label,- verdict: g.verdict,+ probability: g.probability ?? null,+ confidence: g.confidence ?? null,model: g.model,};} catch (gErr) {@@ -399,7 +377,12 @@ export default wrap(async (req, res) => {// ── Picker: trending Solana pools ────────────────────────────────────────if (req.method === 'GET' && url.searchParams.get('list') === 'trending') {- const pools = await trendingPools('solana', 8);+ let pools;+ try {+ pools = await callMarket(() => trendingPools('solana', 8));+ } catch (e) {+ return marketUpstreamError(res, e);+ }return json(res, 200, { pools }, { 'cache-control': 'public, max-age=30, s-maxage=60' });}@@ -440,7 +423,12 @@ export default wrap(async (req, res) => {try {market = await loadMarket(params);} catch (e) {- if (e && e.status) return error(res, e.status, e.code, e.message);+ // An upstream fault gets the shared market contract; loadMarket's own+ // validation errors carry a status AND a code, and answering with+ // `e.code` alone once produced `{"error": undefined}` on an upstream 404,+ // since those errors only ever carry a status.+ if (isMarketUpstreamError(e)) return marketUpstreamError(res, e);+ if (e && e.status && e.code) return error(res, e.status, e.code, e.message);throw e;}@@ -489,9 +477,6 @@ export default wrap(async (req, res) => {out.onchain.error = 'on-chain submission requires sign-in or a valid bearer token';return json(res, 401, out, { 'cache-control': 'no-store' });}- const submitRl = await limits.attestSubmitDaily(wallet.address || 'unconfigured');- if (!submitRl.success) return rateLimited(res, submitRl, 'daily on-chain attestation limit reached');-if (!out.proof) {out.onchain.error = 'nothing to notarize: ' + (out.onchain.reason || 'no forecast');} else if (out.governance?.passed === false) {@@ -499,6 +484,14 @@ export default wrap(async (req, res) => {} else if (!wallet.configured) {out.onchain.error = 'attester wallet not configured';} else {+ // Consume the daily ceiling only once a broadcast is actually the next+ // step. Charging it before the preconditions above meant any signed-in+ // caller could exhaust the platform's shared daily budget with requests+ // that were never going to reach the chain (no forecast, vetoed+ // narration, unconfigured wallet).+ const submitRl = await limits.attestSubmitDaily(wallet.address);+ if (!submitRl.success)+ return rateLimited(res, submitRl, 'daily on-chain attestation limit reached');try {const conn = getConnection(wallet.rpcUrl);const keypair = loadAvatarKeypair(process.env.AVATAR_WALLET_SECRET);diff --git a/api/ibm/galaxy.js b/api/ibm/galaxy.jsindex 4d91eefed..67156771d 100644--- a/api/ibm/galaxy.js+++ b/api/ibm/galaxy.js@@ -178,8 +178,12 @@ async function graniteThemeLabel(cfg, members) {// ── Build ────────────────────────────────────────────────────────────────────-async function buildGalaxy(cfg) {- const rows = await selectGalaxyAgents();+// `rows` is the agent set the caller already read and fingerprinted. Reading it+// again here would not just cost a second identical query: an agent added+// between the two reads would be embedded into this payload while the cache row+// carries the pre-add fingerprint, so the stale layout would be served as fresh+// until the TTL expired.+async function buildGalaxy(cfg, rows) {const agents = rows.filter((a) => agentEmbedText(a)); // must have embeddable textif (agents.length < 2) {@@ -365,7 +369,7 @@ async function handleGet(req, res) {}}- const payload = await buildGalaxy(cfg);+ const payload = await buildGalaxy(cfg, rows);// Persist only fully-built galaxies (with agents) so empty/edge states never// poison the cache.if (payload.agents.length) {diff --git a/api/ibm/oracle.js b/api/ibm/oracle.jsindex 47edc9449..8fc7e4f7c 100644--- a/api/ibm/oracle.js+++ b/api/ibm/oracle.js@@ -14,6 +14,7 @@ import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';import { watsonxForecast, forecastModelFor } from '../_lib/watsonx-forecast.js';import { guardianConfig, assessRisk } from '../_lib/granite-guardian.js';import { fetchOhlcv, topPoolForToken, trendingPools } from '../_lib/market/ohlcv.js';+import { marketUpstreamError } from '../_lib/market/upstream-error.js';const isBase58 = (s) => /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);const isoOf = (unixSec) => new Date(unixSec * 1000).toISOString();@@ -52,23 +53,6 @@ async function narrate(cfg, { name, symbol, currentPrice, stats }) {return { text: (text || '').trim(), model, usage };}-// Map a GeckoTerminal upstream failure (ohlcv.js attaches the real .status) to-// a clean client response instead of an unhandled 500. A 429 becomes a-// retryable 503; 404 passes through; everything else is a 502 bad-gateway.-function marketUpstreamError(res, err) {- const upstream = err?.status;- const status = upstream === 429 ? 503 : upstream === 404 ? 404 : 502;- const code =- status === 503- ? 'upstream_rate_limited'- : status === 404- ? 'pool_not_found'- : 'upstream_error';- return error(res, status, code, `market data upstream: ${err?.message || 'unavailable'}`, {- retryable: status === 503,- });-}-export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;diff --git a/api/ibm/twin.js b/api/ibm/twin.jsindex 8000bb075..98e297bca 100644--- a/api/ibm/twin.js+++ b/api/ibm/twin.js@@ -21,6 +21,11 @@ import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';import { watsonxForecast, forecastModelFor } from '../_lib/watsonx-forecast.js';import { guardianConfig, assessRisk } from '../_lib/granite-guardian.js';import { fetchOhlcv, topPoolForToken, trendingPools } from '../_lib/market/ohlcv.js';+import {+ callMarket,+ isMarketUpstreamError,+ marketUpstreamError,+} from '../_lib/market/upstream-error.js';const isBase58 = (s) => /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);const isoOf = (unixSec) => new Date(unixSec * 1000).toISOString();@@ -239,7 +244,7 @@ async function loadSeries(params) {status: 400,code: 'bad_token',});- pool = await topPoolForToken(token, network);+ pool = await callMarket(() => topPoolForToken(token, network));}if (!pool || !isBase58(pool)) {throw Object.assign(new Error('provide ?pool=<addr> or ?token=<mint>, or ?list=trending'), {@@ -251,13 +256,9 @@ async function loadSeries(params) {? params.timeframe: 'hour';const aggregate = clamp(parseInt(params.aggregate || '1', 10) || 1, 1, 60);- const { candles, base, quote, freq } = await fetchOhlcv({- pool,- network,- timeframe,- aggregate,- limit: 1000,- });+ const { candles, base, quote, freq } = await callMarket(() =>+ fetchOhlcv({ pool, network, timeframe, aggregate, limit: 1000 }),+ );if (candles.length < 64) {throw Object.assign(new Error('not enough candle history to model this pool'), {status: 422,@@ -279,7 +280,7 @@ async function handleGet(req, res) {const params = Object.fromEntries(new URL(req.url, 'http://x').searchParams);if (params.list === 'trending') {- const pools = await trendingPools('solana', 8);+ const pools = await callMarket(() => trendingPools('solana', 8));return json(res, 200, { pools }, { 'cache-control': 'public, max-age=30, s-maxage=60' });}@@ -516,6 +517,15 @@ export default wrap(async (req, res) => {return rateLimited(res, global, 'watsonx capacity reached — try again shortly');}- if (req.method === 'POST') return handlePost(req, res);- return handleGet(req, res);+ // A market-data outage is a third party's problem, not a bug here: answer it+ // with its real contract instead of letting a 502 reach wrap(), which would+ // log an unhandled 5xx, capture it to Sentry, and page ops once per request.+ // The handler's own validation errors and any genuine bug still bubble.+ try {+ if (req.method === 'POST') return await handlePost(req, res);+ return await handleGet(req, res);+ } catch (err) {+ if (isMarketUpstreamError(err)) return marketUpstreamError(res, err);+ throw err;+ }});diff --git a/api/ibm/vision.js b/api/ibm/vision.jsindex 1d68f75d1..674522fb3 100644--- a/api/ibm/vision.js+++ b/api/ibm/vision.js@@ -131,8 +131,11 @@ async function handleSubjects(req, res) {LIMIT 18`;} catch (err) {+ // The lineup is a convenience, not the feature: a DB blip degrades to an+ // empty gallery rather than a 500. Keep the same response shape as the+ // success path so a client reading visionModel never sees undefined.console.error('[ibm/vision] subjects query failed', err);- return json(res, 200, { subjects: [] });+ return json(res, 200, { subjects: [], visionModel: VISION_MODEL });}const subjects = rows.map((r) => ({@@ -251,46 +254,74 @@ const MAX_IMAGE_REDIRECTS = 5;// link-local/metadata IPs blocked). Bounded by MAX_IMAGE_REDIRECTS.async function fetchImageAsDataUrl(url) {const controller = new AbortController();+ // The timer stays armed until the BODY is fully read, not just the headers:+ // several allowlisted hosts serve user-supplied content, and a host that+ // answers headers promptly then trickles the body would otherwise hold the+ // invocation open for as long as it liked.const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);- let resp;try {+ let resp;let current = url;let redirects = 0;- while (true) {- const host = hostOf(current);- if (!/^https:\/\//i.test(current) || !host || !allowedImageHost(host)) {- throw fail(- 400,- 'image_host_not_allowed',- 'image redirect target host is not allowed',- );- }- await assertSafePublicUrl(current);- resp = await fetch(current, { signal: controller.signal, redirect: 'manual' });- if (resp.status >= 300 && resp.status < 400 && resp.headers.get('location')) {- if (++redirects > MAX_IMAGE_REDIRECTS) {- throw fail(502, 'image_fetch_failed', 'too many redirects');+ try {+ while (true) {+ const host = hostOf(current);+ if (!/^https:\/\//i.test(current) || !host || !allowedImageHost(host)) {+ throw fail(+ 400,+ 'image_host_not_allowed',+ 'image redirect target host is not allowed',+ );+ }+ await assertSafePublicUrl(current);+ resp = await fetch(current, { signal: controller.signal, redirect: 'manual' });+ if (resp.status >= 300 && resp.status < 400 && resp.headers.get('location')) {+ if (++redirects > MAX_IMAGE_REDIRECTS) {+ throw fail(502, 'image_fetch_failed', 'too many redirects');+ }+ current = new URL(resp.headers.get('location'), current).toString();+ continue;}- current = new URL(resp.headers.get('location'), current).toString();- continue;+ break;}- break;+ } catch (e) {+ if (e?.status && e?.code) throw e; // already a structured fail()+ throw fail(502, 'image_fetch_failed', `could not fetch image: ${e.message}`);}- } catch (e) {- if (e?.status && e?.code) throw e; // already a structured fail()- throw fail(502, 'image_fetch_failed', `could not fetch image: ${e.message}`);+ if (!resp.ok) throw fail(502, 'image_fetch_failed', `image fetch returned ${resp.status}`);+ const ct = (resp.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();+ if (!ct.startsWith('image/'))+ throw fail(415, 'not_an_image', `unexpected content-type: ${ct || 'unknown'}`);+ const len = Number(resp.headers.get('content-length') || 0);+ if (len && len > MAX_IMAGE_BYTES) throw fail(413, 'image_too_large', 'image exceeds 6MB');+ const buf = await readCappedBody(resp);+ return `data:${ct};base64,${buf.toString('base64')}`;} finally {clearTimeout(timer);}- if (!resp.ok) throw fail(502, 'image_fetch_failed', `image fetch returned ${resp.status}`);- const ct = (resp.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();- if (!ct.startsWith('image/'))- throw fail(415, 'not_an_image', `unexpected content-type: ${ct || 'unknown'}`);- const len = Number(resp.headers.get('content-length') || 0);- if (len && len > MAX_IMAGE_BYTES) throw fail(413, 'image_too_large', 'image exceeds 6MB');- const buf = Buffer.from(await resp.arrayBuffer());- if (buf.length > MAX_IMAGE_BYTES) throw fail(413, 'image_too_large', 'image exceeds 6MB');- return `data:${ct};base64,${buf.toString('base64')}`;+}++// Read a response body under a hard byte ceiling. content-length is a hint a+// host can simply omit (or lie about) on a chunked response, so the cap is+// enforced on the stream itself: buffering the whole body first and checking+// its size afterwards means an oversized response is already resident in memory+// by the time it is rejected.+async function readCappedBody(resp) {+ if (!resp.body) {+ const buf = Buffer.from(await resp.arrayBuffer());+ if (buf.length > MAX_IMAGE_BYTES) throw fail(413, 'image_too_large', 'image exceeds 6MB');+ return buf;+ }+ const chunks = [];+ let total = 0;+ // Throwing out of the loop closes the iterator, which cancels the body, so+ // the rest of an oversized response is never pulled off the socket.+ for await (const chunk of resp.body) {+ total += chunk.length;+ if (total > MAX_IMAGE_BYTES) throw fail(413, 'image_too_large', 'image exceeds 6MB');+ chunks.push(Buffer.from(chunk));+ }+ return Buffer.concat(chunks);}function fail(status, code, message) {diff --git a/api/intel/heatmap.js b/api/intel/heatmap.jsindex 649e65ccb..4cce7c0cc 100644--- a/api/intel/heatmap.js+++ b/api/intel/heatmap.js@@ -2,18 +2,18 @@* GET /api/intel/heatmap?limit=30* --------------------------------* The live token field behind the 3D sentiment heatmap on agent screens. Returns- * a normalized set of tokens — $THREE always pinned first and flagged featured —+ * a normalized set of tokens ($THREE always pinned first and flagged featured),* each carrying the two signals the heatmap renders: 24h price momentum and 24h- * volume (magnitude). The anchor ($THREE) is additionally enriched with a live- * pump.fun comment sentiment pulse.+ * volume (magnitude). The anchor ($THREE) is additionally enriched with its live+ * 24h order-flow pulse (buys vs sells).** Data is fully live, no fabricated arrays:- * - Field membership → pump.fun frontend-api-v3 /coins (trending by market cap)- * - Momentum + volume → Dexscreener batch /latest/dex/tokens/<mints> (best pair)- * - $THREE sentiment → pump.fun replies scored by the in-repo lexicon scorer+ * - Field membership -> pump.fun frontend-api-v3 /coins (trending by market cap)+ * - Momentum + volume -> Dexscreener batch /latest/dex/tokens/<mints> (best pair)+ * - $THREE flow pulse -> the same Dexscreener pair's txns.h24 buys/sells** $THREE is the only coin three.ws promotes. The rest of the field is generic,- * coin-agnostic market plumbing rendered from the live trending feed — this+ * coin-agnostic market plumbing rendered from the live trending feed: this* endpoint never names, recommends, or markets any other token. Tiles carry* market data only.*@@ -23,9 +23,12 @@* fetchedAt,* anchor: "<$THREE mint>",* tokens: [ { id, symbol, name, image, priceUsd, change24h, volume24h,- * marketCap, featured, sentiment? } ],+ * marketCap, featured, flow? } ],* stale?: true* }+ *+ * `flow` (anchor only) is { buys24h, sells24h, buyPct, score }, where score is+ * (buys - sells) / (buys + sells) in [-1, 1].*/import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';@@ -45,6 +48,12 @@ const DS_BATCH = 30; // Dexscreener accepts up to 30 comma-separated mints per clet _cache = { value: null, storedAt: 0, expiresAt: 0, limit: 0 };+// Test seam: the field cache is module state, so a suite exercising more than one+// request has to clear it between cases (mirrors _resetSmartMoneyCache()).+export function _resetHeatmapCache() {+ _cache = { value: null, storedAt: 0, expiresAt: 0, limit: 0 };+}+async function fetchJson(url, init) {let res;try {@@ -90,6 +99,8 @@ async function fetchDexBatch(mints) {if (!prev || vol > prev._vol) {byMint.set(mint, {_vol: vol,+ buys24h: Number(p?.txns?.h24?.buys || 0),+ sells24h: Number(p?.txns?.h24?.sells || 0),symbol: p.baseToken?.symbol || null,name: p.baseToken?.name || null,priceUsd: p.priceUsd != null ? Number(p.priceUsd) : null,@@ -104,7 +115,7 @@ async function fetchDexBatch(mints) {return byMint;}-// pump.fun metadata for a single mint (name/symbol/image) — fills gaps when a+// pump.fun metadata for a single mint (name/symbol/image): fills gaps when a// token has no Dexscreener pair yet, and supplies $THREE's canonical metadata.async function fetchPumpMeta(mint) {const data = await fetchJson(`${PUMP_FRONTEND_BASE}/coins/${mint}`, {@@ -119,25 +130,20 @@ async function fetchPumpMeta(mint) {};}-// Live $THREE sentiment from pump.fun replies, scored by the in-repo lexicon.-// Single call, anchor-only — keeps the field fast while still surfacing the one-// coin three.ws actually tracks.-async function fetchThreeSentiment() {- const data = await fetchJson(`${PUMP_FRONTEND_BASE}/replies/${THREE_MINT}?limit=80&offset=0`, {- headers: { accept: 'application/json' },- });- const replies = Array.isArray(data?.replies) ? data.replies : Array.isArray(data) ? data : [];- const posts = replies- .map((r) => ({ text: String(r.text || r.message || '').slice(0, 2000) }))- .filter((p) => p.text);- if (!posts.length) return null;- try {- const { scoreSentiment } = await import('../../src/social/sentiment.js');- const s = scoreSentiment(posts);- return { score: s.score, posPct: s.posPct, negPct: s.negPct, neuPct: s.neuPct, count: s.count };- } catch {- return null;- }+// The anchor's live order-flow pulse, read off the Dexscreener pair we already+// fetched for the tile: how the last 24h of trades split between buyers and+// sellers. Real observed swaps, no extra upstream call.+function flowPulse(d) {+ const buys = Number.isFinite(d?.buys24h) ? d.buys24h : 0;+ const sells = Number.isFinite(d?.sells24h) ? d.sells24h : 0;+ const total = buys + sells;+ if (!total) return null;+ return {+ buys24h: buys,+ sells24h: sells,+ buyPct: Math.round((buys / total) * 100),+ score: Math.round(((buys - sells) / total) * 1000) / 1000,+ };}async function buildField(limit) {@@ -146,10 +152,9 @@ async function buildField(limit) {const trending = await fetchTrendingMints(Math.min(FIELD_MAX, limit + 8));const mints = [THREE_MINT, ...trending.filter((m) => m !== THREE_MINT)].slice(0, limit);- const [dex, threeMeta, threeSentiment] = await Promise.all([+ const [dex, threeMeta] = await Promise.all([fetchDexBatch(mints),fetchPumpMeta(THREE_MINT),- fetchThreeSentiment(),]);const tokens = [];@@ -168,9 +173,12 @@ async function buildField(limit) {marketCap: d.marketCap ?? meta?.marketCap ?? null,featured,};- if (featured && threeSentiment) token.sentiment = threeSentiment;+ if (featured) {+ const flow = flowPulse(d);+ if (flow) token.flow = flow;+ }// Drop non-anchor tokens with no usable signal at all (no price + no- // volume) so the field never carries dead tiles — $THREE always stays.+ // volume) so the field never carries dead tiles. $THREE always stays.if (!featured && token.priceUsd == null && !token.volume24h) continue;tokens.push(token);}@@ -211,7 +219,11 @@ export default wrap(async (req, res) => {});}- if (!tokens.length) {+ // No cache to fall back on: a field where nothing carries a live price or+ // volume is the same outage, and the anchor tile alone would render as an+ // empty void. Say so with the designed error instead of shipping a dead field.+ const usable = tokens.some((t) => t.priceUsd != null || t.volume24h > 0);+ if (!tokens.length || !usable) {return error(res, 502, 'upstream_error', 'Market data is temporarily unavailable');}diff --git a/api/intel/smart-money.js b/api/intel/smart-money.jsindex 1ba7fe432..cb63d7e14 100644--- a/api/intel/smart-money.js+++ b/api/intel/smart-money.js@@ -26,6 +26,15 @@ function normNetwork(v) {return v === 'devnet' ? 'devnet' : 'mainnet';}+// Both params are Solana base58 pubkeys (32-44 chars). Rejecting obvious garbage+// here keeps the graph lookup off junk keys and matches /api/intel/wallet/:addr,+// which already 400s rather than echoing whatever the caller sent back at them.+const BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++function badRequest(res, message) {+ return json(res, 400, { error: 'bad_request', message });+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -34,21 +43,25 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const network = normNetwork(url.searchParams.get('network'));- const wallet = url.searchParams.get('wallet');- const mint = url.searchParams.get('mint');+ const wallet = (url.searchParams.get('wallet') || '').trim();+ const mint = (url.searchParams.get('mint') || '').trim();if (wallet) {- const rep = await getWalletReputation(wallet.trim(), network);+ if (!BASE58.test(wallet)) return badRequest(res, 'wallet must be a valid Solana address');+ const rep = await getWalletReputation(wallet, network);return json(res, 200, rep, {'cache-control': 'public, max-age=30, stale-while-revalidate=60',});}if (!mint) {- return json(res, 400, { error: 'bad_request', message: 'mint or wallet query param required' });+ return badRequest(res, 'mint or wallet query param required');+ }+ if (!BASE58.test(mint)) {+ return badRequest(res, 'mint must be a valid Solana mint address');}- const result = await getSmartMoneyForMint(mint.trim(), network);+ const result = await getSmartMoneyForMint(mint, network);return json(res, 200, result, {'cache-control': 'public, max-age=15, stale-while-revalidate=30',});diff --git a/api/intel/yields.js b/api/intel/yields.jsindex 0857f9254..c5c6da9b6 100644--- a/api/intel/yields.js+++ b/api/intel/yields.js@@ -51,6 +51,6 @@ export default wrap(async (req, res) => {{ 'cache-control': 'public, s-maxage=60, stale-while-revalidate=300' },);} catch {- return error(res, 502, 'upstream_error', 'DeFi yield data is temporarily unavailable — retry shortly');+ return error(res, 502, 'upstream_error', 'DeFi yield data is temporarily unavailable, retry shortly');}});diff --git a/api/jobs/flush-usage-events.js b/api/jobs/flush-usage-events.jsindex 8f65624b4..75d181f45 100644--- a/api/jobs/flush-usage-events.js+++ b/api/jobs/flush-usage-events.js@@ -1,5 +1,5 @@// @ts-check-// POST /api/jobs/flush-usage-events — QStash webhook that drains the usage event+// POST /api/jobs/flush-usage-events: QStash webhook that drains the usage event// buffer from Redis and batch-inserts into Neon Postgres.//// Triggered two ways:@@ -13,27 +13,82 @@// signed by QStash. Requests without it are rejected 401.import { error, json, method, wrap, readBody } from '../_lib/http.js';+import { env } from '../_lib/env.js';import { verifyQstashSignature } from '../_lib/qstash.js';import { flushUsageBuffer } from '../_lib/usage.js';import { flushAuditBuffer } from '../_lib/x402/audit-log.js';+const JOB_PATH = '/api/jobs/flush-usage-events';++/**+ * The absolute URLs this delivery is allowed to have been signed for.+ *+ * QStash signs the exact URL it was told to POST to (the JWT `sub` claim), so+ * verification only passes when we rebuild that same string. The publisher+ * (api/_lib/usage.js triggerFlushJob) builds it from `env.APP_ORIGIN`, so that+ * is the first and canonical candidate: reading `process.env.APP_ORIGIN`+ * instead (a var nothing in this codebase sets) made every genuinely signed+ * delivery compare against a bare path and 401, silently killing the+ * threshold-triggered flush lane and leaving only the 1-minute cron.+ *+ * The forwarded-host candidate covers a deployment served on a hostname other+ * than the configured origin (a preview revision, the raw Cloud Run URL). It+ * cannot be abused to bypass the check: the path stays fixed to this endpoint+ * and the HMAC still has to validate against our signing keys, so a spoofed+ * Host only ever admits a token QStash minted for this same job on one of our+ * own hostnames.+ *+ * @param {import('http').IncomingMessage} req+ * @returns {string[]}+ */+function verificationUrls(req) {+ const urls = [];+ const configured = String(env.APP_ORIGIN || '').replace(/\/+$/, '');+ if (configured) urls.push(`${configured}${JOB_PATH}`);++ const host = String(req.headers['x-forwarded-host'] || req.headers.host || '').split(',')[0].trim();+ if (host) {+ const proto = String(req.headers['x-forwarded-proto'] || 'https').split(',')[0].trim();+ const derived = `${proto}://${host}${JOB_PATH}`;+ if (!urls.includes(derived)) urls.push(derived);+ }+ return urls;+}+export default wrap(async (req, res) => {if (!method(req, res, ['POST'])) return;+ // An unset signing key cannot be told apart from a forged request once we are+ // inside the catch below, and "invalid qstash signature" sends the operator+ // hunting an attacker instead of a missing secret. wrap() turns this exact+ // message shape into a 503 not_configured plus one deduped alert naming the var.+ if (!process.env.QSTASH_CURRENT_SIGNING_KEY) {+ throw new Error('Missing required env var: QSTASH_CURRENT_SIGNING_KEY');+ }+// Collect the raw body for signature verification. readBody prefers// req.rawBody (captured pre-parse by the Cloud Run server's express.json()- // `verify` hook) so the QStash HMAC check below sees the exact signed bytes- // — re-reading the raw stream here hangs forever once Express has drained it.+ // `verify` hook) so the QStash HMAC check below sees the exact signed bytes:+ // re-reading the raw stream here hangs forever once Express has drained it.const raw = (await readBody(req, 1_000_000)).toString('utf8');- try {- const origin = process.env.APP_ORIGIN || (process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : '');- await verifyQstashSignature({- signature: req.headers['upstash-signature'],- body: raw,- url: `${origin}/api/jobs/flush-usage-events`,- });- } catch {+ const signature = req.headers['upstash-signature'];+ let verified = false;+ let reason = 'no candidate url';+ for (const url of verificationUrls(req)) {+ try {+ await verifyQstashSignature({ signature, body: raw, url });+ verified = true;+ break;+ } catch (err) {+ reason = err?.message || String(err);+ }+ }+ if (!verified) {+ // The reason separates a forged/absent signature from a URL the publisher+ // and this deployment disagree about, which are the same 401 to the caller+ // and completely different fixes for us.+ console.warn('[usage-flush-job] rejected delivery:', reason);return error(res, 401, 'unauthorized', 'invalid qstash signature');}diff --git a/api/keys/[id].js b/api/keys/[id].jsindex aefde28cc..9e6d602cd 100644--- a/api/keys/[id].js+++ b/api/keys/[id].js@@ -1,4 +1,4 @@-// DELETE /api/keys/:id — revoke an API key+// DELETE /api/keys/:id revokes an API key.import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';@@ -6,6 +6,7 @@ import { logAudit } from '../_lib/audit.js';import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';import { limits } from '../_lib/rate-limit.js';+import { isUuid } from '../_lib/validate.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;@@ -16,10 +17,18 @@ export default wrap(async (req, res) => {if (!(await requireCsrf(req, res, user.id))) return;- const rl = await limits.apiKeyManage(user.id);+ // Revocation is the safety valve for a leaked key, so it rides its own bucket+ // rather than the mint budget: minting keys must never be able to block+ // killing one. See limits.apiKeyRevoke.+ const rl = await limits.apiKeyRevoke(user.id);if (!rl.success) return rateLimited(res, rl);const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').pop();+ // api_keys.id is a uuid column: handing Postgres a non-uuid path segment+ // raises 22P02 and the caller gets a 500 with a support ref for what is+ // plainly bad input. Reject it here, the way api/api-keys/[id].js does.+ if (!isUuid(id)) return error(res, 400, 'invalid_id', 'API key id must be a UUID');+const rows = await sql`update api_keys set revoked_at = now()where id = ${id} and user_id = ${user.id} and revoked_at is null@@ -31,6 +40,7 @@ export default wrap(async (req, res) => {action: 'revoke_api_key',resourceId: rows[0].id,meta: { via: 'session' },+ req,});return json(res, 200, { ok: true });});diff --git a/api/keys/index.js b/api/keys/index.jsindex 96558fe5c..c7ddebeb5 100644--- a/api/keys/index.js+++ b/api/keys/index.js@@ -1,9 +1,10 @@// Developer API key management.-// GET /api/keys — list caller's keys (hashed, no secret)-// POST /api/keys — create a new key; returns plaintext ONCE+// GET /api/keys list caller's keys (hashed, no secret)+// POST /api/keys create a new key; returns the plaintext secret ONCEimport { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';+import { logAudit } from '../_lib/audit.js';import { randomToken, sha256 } from '../_lib/crypto.js';import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { requireCsrf } from '../_lib/csrf.js';@@ -31,10 +32,12 @@ export default wrap(async (req, res) => {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in to manage API keys');- const rl = await limits.apiKeyManage(user.id);- if (!rl.success) return rateLimited(res, rl);-+ // Listing is a read the dashboard performs on every load and after every+ // mutation; it rides its own bucket so it can never exhaust the mint budget+ // (or be exhausted by it). See limits.apiKeyList / apiKeyManage.if (req.method === 'GET') {+ const rlList = await limits.apiKeyList(user.id);+ if (!rlList.success) return rateLimited(res, rlList);const rows = await sql`select id, name, prefix, scope, last_used_at, expires_at, revoked_at, created_atfrom api_keys where user_id = ${user.id} order by created_at desc@@ -42,6 +45,9 @@ export default wrap(async (req, res) => {return json(res, 200, { keys: rows });}+ const rl = await limits.apiKeyManage(user.id);+ if (!rl.success) return rateLimited(res, rl);+if (!(await requireCsrf(req, res, user.id))) return;const body = parse(createSchema, await readJson(req));@@ -63,5 +69,15 @@ export default wrap(async (req, res) => {values (${user.id}, ${body.name}, ${prefix}, ${hash}, ${requestedScopes.join(' ')}, ${expires})returning id, name, prefix, scope, expires_at, created_at`;+ // Issuing a long-lived credential belongs in the same trail as revoking one:+ // without it the audit log can say a key died but not that it was ever born.+ // Never the secret or its hash, only the id, prefix, and granted scope.+ logAudit({+ userId: user.id,+ action: 'create_api_key',+ resourceId: row.id,+ meta: { prefix, scope: row.scope, environment: body.environment },+ req,+ });return json(res, 201, { key: { ...row, secret: raw } });});diff --git a/api/kol/trades.js b/api/kol/trades.jsindex 74c3e5e58..e2950d188 100644--- a/api/kol/trades.js+++ b/api/kol/trades.js@@ -1,8 +1,18 @@+// GET /api/kol/trades?mint=<mint>&limit=<n>+//+// This exact file is what /api/kol/trades resolves to: Vercel filesystem+// precedence (mirrored by server/index.mjs) puts an exact file ahead of a+// sibling [action].js, so the dispatcher never sees this path. Keep the trade+// feed here and nowhere else; a second copy inside api/kol/[action].js is dead+// code that silently drifts from the served one.+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { KOL_WALLETS } from '../../src/kol/wallets.js';import { fetchKolTrades } from '../../src/kol/trades.js';+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;@@ -13,9 +23,15 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const mint = url.searchParams.get('mint');- const limit = Math.min(100, parseInt(url.searchParams.get('limit') || '20', 10));+ // Clamp at the boundary so a hostile or fat-fingered limit (0, -5, "abc",+ // 1e9) can never reach the provider fan-out as anything but 1..100.+ const limit = Math.min(100, Math.max(1, Number.parseInt(url.searchParams.get('limit'), 10) || 20));if (!mint) return error(res, 400, 'validation_error', 'mint required');+ // A mint that cannot be a Solana address would cost three Helius round trips+ // to prove empty. Reject it here instead.+ if (!BASE58_RE.test(mint))+ return error(res, 400, 'validation_error', 'mint must be a base58 Solana address');let result;try {diff --git a/api/labor/award.js b/api/labor/award.jsindex b175b0249..9a0789b67 100644--- a/api/labor/award.js+++ b/api/labor/award.js@@ -49,6 +49,6 @@ export default wrap(async (req, res) => {return json(res, 200, {ok: true,award: { bounty_id: bountyId, bid_id: bidId, worker_agent_id: winner.worker_agent_id, rationale, job_id: job?.id || null, status: job?.status || 'working' },- autopilot: autopilot || { bids: 0, awarded: true, settled: null },+ autopilot: autopilot || { bids: 0, awarded: true, settled: null, settledNow: false },});});diff --git a/api/labor/bid.js b/api/labor/bid.jsindex cf45f2d7e..4ae3de351 100644--- a/api/labor/bid.js+++ b/api/labor/bid.js@@ -68,6 +68,6 @@ export default wrap(async (req, res) => {price_atomics: String(toBig(bid.price_atomics)), price_three: atomicsToThree(bid.price_atomics),eta_seconds: eta, score, reputation, status: bid.status,},- autopilot: autopilot || { bids: 0, awarded: false, settled: null },+ autopilot: autopilot || { bids: 0, awarded: false, settled: null, settledNow: false },});});diff --git a/api/labor/tick.js b/api/labor/tick.jsindex a710fd14c..c111ad23d 100644--- a/api/labor/tick.js+++ b/api/labor/tick.js@@ -4,6 +4,25 @@// • working jobs with an autonomous worker (perform → verify → settle)// • delivered/verifying jobs (settle now)// Authenticated with the Vercel cron Bearer secret. No-op (503) if unset.+//+// Both scans below are capped at BATCH so a tick stays inside its budget, and+// both deliberately select ONLY rows this tick can actually advance. That is not+// an optimization, it is the correctness property that keeps the cap from+// starving the market: the scans are ordered oldest-first, so any row the driver+// can never move occupies a slot on every tick forever. Two such rows existed:+// • a 'working' job whose worker never opted into autonomy — runAutopilot+// returns immediately for it, so it can only ever leave 'working' through+// the manual /deliver endpoint. Ten of them (a human sitting on ten jobs)+// used to consume the entire job batch and no autonomous job was ever driven+// again. The scan now requires worker_enabled, mirroring the policy join the+// bounty scan already had.+// • an open bounty holding fewer pending bids than its poster's min_bids —+// autoAwardIfReady declines it until more bids arrive, which may be never.+// Award-ready bounties now sort ahead of bid-gathering ones, so a bounty+// whose money is ready to move cannot be blocked behind ten that are not.+// Same reasoning drives the job ordering: delivered/verifying jobs are one step+// from releasing escrow, so they settle before working jobs spend the tick on an+// LLM perform call.import { json, method, wrap } from '../_lib/http.js';import { sql } from '../_lib/db.js';@@ -11,50 +30,101 @@ import { ensureLaborTables, getBounty, getJob } from '../_lib/agent-labor.js';import { runAutopilot, runSettlement } from '../_lib/labor-settle.js';import { requireCron } from '../_lib/cron-auth.js';+const BATCH = 10;+const MAX_REPORTED_ERRORS = 5;+export default wrap(async (req, res) => {if (!method(req, res, ['POST', 'GET'])) return;if (!requireCron(req, res)) return;await ensureLaborTables();- // Resumable work: open bounties with at least one bid + auto-award posters, and- // any job stuck mid-pipeline. Cap the batch so a tick stays well within budget.const openBounties = await sql`- SELECT b.id FROM agent_bounties b- JOIN agent_labor_policies p ON p.agent_id = b.poster_agent_id AND p.poster_enabled AND p.auto_award- WHERE b.status = 'open'- AND EXISTS (SELECT 1 FROM agent_bids bd WHERE bd.bounty_id = b.id AND bd.status = 'pending')- ORDER BY b.created_at ASC LIMIT 10`;+ WITH candidates AS (+ SELECT b.id, b.created_at, p.min_bids,+ (SELECT count(*) FROM agent_bids bd+ WHERE bd.bounty_id = b.id AND bd.status = 'pending') AS pending_bids+ FROM agent_bounties b+ JOIN agent_labor_policies p+ ON p.agent_id = b.poster_agent_id AND p.poster_enabled AND p.auto_award+ WHERE b.status = 'open'+ )+ SELECT id FROM candidates+ WHERE pending_bids > 0+ ORDER BY (pending_bids >= min_bids) DESC, created_at ASC+ LIMIT ${BATCH}`;const stuckJobs = await sql`SELECT j.id, j.bounty_id, j.status FROM agent_jobs j- WHERE j.status IN ('working','delivered','verifying')- AND j.created_at < now() - interval '15 seconds'- ORDER BY j.created_at ASC LIMIT 10`;+ WHERE j.created_at < now() - interval '15 seconds'+ AND (+ j.status IN ('delivered','verifying')+ OR (j.status = 'working' AND EXISTS (+ SELECT 1 FROM agent_labor_policies wp+ WHERE wp.agent_id = j.worker_agent_id AND wp.worker_enabled))+ )+ ORDER BY (j.status <> 'working') DESC, j.created_at ASC+ LIMIT ${BATCH}`;++ const results = {+ scanned: openBounties.length + stuckJobs.length,+ bids: 0, awarded: 0, settled: 0, failed: 0,+ };+ const errors = [];- const results = { awarded: 0, settled: 0, scanned: openBounties.length + stuckJobs.length };+ // One bad row must not cost the rest of the batch. Every past accounting loss+ // here came from an unguarded row read throwing mid-loop: the work already+ // done stayed done on-chain, but the tick 5xx'd and reported none of it.+ const note = (scope, err) => {+ results.failed++;+ const message = err?.message || String(err);+ console.error(`[labor-tick] ${scope} failed`, message);+ if (errors.length < MAX_REPORTED_ERRORS) errors.push(`${scope}: ${message.slice(0, 160)}`);+ };for (const b of openBounties) {- const r = await runAutopilot(b.id).catch(() => null);- if (r?.awarded) results.awarded++;- if (r?.settled === 'settled') results.settled++;+ try {+ const r = await runAutopilot(b.id);+ results.bids += r?.bids || 0;+ if (r?.awarded) results.awarded++;+ if (r?.settledNow) results.settled++;+ } catch (err) {+ note(`bounty ${b.id}`, err);+ }}for (const j of stuckJobs) {- const bounty = await getBounty(j.bounty_id);- if (!bounty) continue;- if (j.status === 'working') {- // Only autonomous workers are driven to perform; runAutopilot enforces that.- const r = await runAutopilot(j.bounty_id).catch(() => null);- if (r?.settled === 'settled') results.settled++;- } else {+ try {+ if (j.status === 'working') {+ // The scan already proved the worker is autonomous; runAutopilot+ // re-reads the bounty itself, so no extra fetch is needed here.+ const r = await runAutopilot(j.bounty_id);+ results.bids += r?.bids || 0;+ if (r?.settledNow) results.settled++;+ continue;+ }// Delivered/verifying: settle now from the full job row.+ const bounty = await getBounty(j.bounty_id);+ if (!bounty) continue;const full = await getJob(j.id);if (!full) continue;- const r = await runSettlement({ job: full, bounty }).catch(() => null);- if (r?.status === 'settled') results.settled++;+ // A settle another caller already claimed comes back idempotent. Counting+ // it would report someone else's payout as this tick's work.+ const r = await runSettlement({ job: full, bounty });+ if (r?.status === 'settled' && !r.idempotent) results.settled++;+ } catch (err) {+ note(`job ${j.id}`, err);}}- json(res, 200, { ok: true, ...results });+ // A lane where every scanned row threw is an outage, not an idle minute, and+ // the economy tick's summary (and /api/status behind it) can only say so if+ // this response does. `reason` is what that summary surfaces.+ const allFailed = results.scanned > 0 && results.failed === results.scanned;+ return json(res, allFailed ? 502 : 200, {+ ok: !allFailed,+ ...results,+ ...(errors.length ? { errors } : {}),+ ...(results.failed ? { reason: `${results.failed}/${results.scanned} items failed` } : {}),+ });});diff --git a/api/leaderboard/daily-match.js b/api/leaderboard/daily-match.jsindex c5de66c09..aeb115ac6 100644--- a/api/leaderboard/daily-match.js+++ b/api/leaderboard/daily-match.js@@ -124,7 +124,11 @@ function mapRow(r, rank) {}export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ // Public, anonymous, CDN-cached board (docs/api-reference.md): allow any+ // origin, matching its sibling /api/leaderboard/unified. Without this the+ // default policy sends no allow-origin header at all, so every cross-origin+ // fetch of the documented public endpoint fails its preflight.+ if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;const rl = await limits.publicIp(clientIp(req));diff --git a/api/leaderboard/unified.js b/api/leaderboard/unified.jsindex 81f0e3282..072d8a5e7 100644--- a/api/leaderboard/unified.js+++ b/api/leaderboard/unified.js@@ -12,8 +12,9 @@// + saved worlds (dioramas), per signed-in creator.// · remixes_received — count of OTHER creators' forge_creations rows whose// parent_creation_id points at one of this user's-// finished creations (a real derivative count, not a-// view/like count).+// finished creations. Both sides must be status='done',+// and a creator's own refines of their own model never+// count (a real derivative count, not a view/like one).// · launches — pump.fun coins minted from this user's agents// (agent_identities.meta->'token'->>'mint').// · followers — user_follows platform-wide follower count.@@ -74,21 +75,23 @@ async function rankingRows(metric) {`;}if (metric === 'remixes_received') {+ // Only finished derivatives by SOMEONE ELSE count. `parent_creation_id` is+ // also written by the forge's own refine lineage (linkRefineLineage() in+ // api/_lib/forge-store.js), so counting every child would let a creator+ // climb this board by re-refining their own model, and would score failed+ // generations as remixes. `is distinct from` keeps an anonymous remixer+ // (null user_id) counted, which is a genuinely other creator.return sql`with mine as (select id, user_idfrom forge_creationswhere user_id is not null and status = 'done'- ),- children as (- select parent_creation_id, count(*) as n- from forge_creations- where parent_creation_id is not null- group by parent_creation_id)- select m.user_id, sum(c.n)::bigint as value+ select m.user_id, count(*)::bigint as valuefrom mine m- join children c on c.parent_creation_id = m.id+ join forge_creations c on c.parent_creation_id = m.id+ where c.status = 'done'+ and c.user_id is distinct from m.user_idgroup by m.user_id`;}diff --git a/api/ledger/[agentId].js b/api/ledger/[agentId].jsindex fe7528615..a9452f789 100644--- a/api/ledger/[agentId].js+++ b/api/ledger/[agentId].js@@ -14,10 +14,32 @@ import {getDecisionsWithOutcomes,getReputationRecords,computeReputation,+ MAX_TIMELINE_LIMIT,} from '../_lib/reasoning-ledger.js';import { latestAnchor } from '../_lib/ledger-anchor.js';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+// Longest `kind` / `q` filter accepted. Both reach the database as bound+// parameters, so this is not an injection guard: it keeps an unauthenticated+// caller from driving an unbounded `ilike '%…%'` scan across an agent's history.+const MAX_FILTER_LEN = 200;++/**+ * Read a whole-number query param. Absent or empty means "not supplied"; garbage+ * is a 400 rather than a silent fallback. `before` used to be coerced with+ * Number(), so `?before=abc` sent NaN into a bigint comparison and answered a+ * sanitized 500 to what is plainly a client mistake.+ */+function intParam(url, name, min, max) {+ const raw = url.searchParams.get(name);+ if (raw == null || raw === '') return { value: null, error: null };+ if (!/^\d+$/.test(raw)) return { value: null, error: `${name} must be a whole number` };+ const n = Number(raw);+ if (!Number.isSafeInteger(n) || n < min || n > max) {+ return { value: null, error: `${name} must be between ${min} and ${max}` };+ }+ return { value: n, error: null };+}function paramAgentId(req) {if (req.query?.agentId) return String(req.query.agentId);@@ -67,31 +89,44 @@ export default wrap(async (req, res) => {}const url = new URL(req.url, 'http://localhost');- const limit = Number(url.searchParams.get('limit')) || 50;- const before = url.searchParams.get('before');+ const limitParam = intParam(url, 'limit', 1, MAX_TIMELINE_LIMIT);+ if (limitParam.error) return error(res, 400, 'bad_request', limitParam.error);+ const beforeParam = intParam(url, 'before', 1, Number.MAX_SAFE_INTEGER);+ if (beforeParam.error) return error(res, 400, 'bad_request', beforeParam.error);+ const limit = limitParam.value ?? 50;+ const before = beforeParam.value;const kind = url.searchParams.get('kind');const q = url.searchParams.get('q');+ if ((kind && kind.length > MAX_FILTER_LEN) || (q && q.length > MAX_FILTER_LEN)) {+ return error(res, 400, 'bad_request', `kind and q must be ${MAX_FILTER_LEN} characters or fewer`);+ }const [identity, repRecords, decisions, anchor] = await Promise.all([- sql`select id, name, profile_image_url, avatar_url, is_public from agent_identities where id = ${agentId} limit 1`+ sql`select id, name, profile_image_url, avatar_url, is_public, deleted_at from agent_identities where id = ${agentId} limit 1`.then((r) => r[0] || null).catch(() => null),getReputationRecords(agentId),getDecisionsWithOutcomes(agentId, {limit,- beforeSeq: before ? Number(before) : null,+ beforeSeq: before,kind: kind || null,q: q || null,}),latestAnchor(agentId).catch(() => null),]);+ // The track record is public by design; the agent's identity is not. An+ // unlisted or deleted agent renders as the bare id, exactly like an id with no+ // identity row — this endpoint used to select is_public and never read it, so+ // it published the name and avatar of every agent its owner had made private.+ const named = !!identity && identity.is_public !== false && !identity.deleted_at;+const reputation = computeReputation(repRecords);const shaped = decisions.map(shapeDecision);const nextBeforeSeq = shaped.length ? shaped[shaped.length - 1].seq : null;return json(res, 200, {- agent: identity+ agent: named? { id: identity.id, name: identity.name, image: identity.profile_image_url || identity.avatar_url || null }: { id: agentId, name: null, image: null },reputation,diff --git a/api/ledger/verify/[agentId].js b/api/ledger/verify/[agentId].jsindex 07ea8ce29..9a5025e15 100644--- a/api/ledger/verify/[agentId].js+++ b/api/ledger/verify/[agentId].js@@ -55,30 +55,39 @@ export default wrap(async (req, res) => {const chain = await verifyChain(agentId, entries);const anchorRow = await latestAnchoredAnchor(agentId).catch(() => null);- let status;- let anchor = null;- if (!chain.ok) {- status = 'verification_failed';- } else if (anchorRow) {- // The anchored head must equal the recomputed entry_hash at its seq.+ // The anchored head must equal the entry_hash at its seq. verifyChain only+ // reports ok after recomputing every entry_hash from its committed contents, so+ // on an intact chain the stored hash compared here IS the recomputed one; on a+ // broken chain no stored hash is trusted and the match can only be false.+ let matchesAnchor = false;+ if (anchorRow && chain.ok) {const atSeq = entries.find((e) => Number(e.seq) === Number(anchorRow.through_seq));- const matches = !!atSeq && String(atSeq.entry_hash) === String(anchorRow.head_hash);- status = matches ? 'verified' : 'verification_failed';- anchor = {- status: anchorRow.status,- signature: anchorRow.signature,- head_hash: anchorRow.head_hash,- through_seq: Number(anchorRow.through_seq),- entry_count: Number(anchorRow.entry_count),- anchored_at: anchorRow.anchored_at,- network: anchorRow.network,- explorer_url: solscanUrl(anchorRow.signature, anchorRow.network),- matches_chain: matches,- };- } else {- status = 'verified_unanchored';+ matchesAnchor = !!atSeq && String(atSeq.entry_hash) === String(anchorRow.head_hash);}+ let status;+ if (!chain.ok) status = 'verification_failed';+ else if (anchorRow) status = matchesAnchor ? 'verified' : 'verification_failed';+ else status = 'verified_unanchored';++ // Report the anchor whenever one exists, including on a failed verification:+ // the on-chain commitment the altered history no longer matches is the most+ // useful thing an auditor can be handed, and hiding it left `status:+ // verification_failed` with nothing to check it against.+ const anchor = anchorRow+ ? {+ status: anchorRow.status,+ signature: anchorRow.signature,+ head_hash: anchorRow.head_hash,+ through_seq: Number(anchorRow.through_seq),+ entry_count: Number(anchorRow.entry_count),+ anchored_at: anchorRow.anchored_at,+ network: anchorRow.network,+ explorer_url: solscanUrl(anchorRow.signature, anchorRow.network),+ matches_chain: matchesAnchor,+ }+ : null;+return json(res, 200, {agent_id: agentId,status,diff --git a/api/legal/risk-ack.js b/api/legal/risk-ack.jsindex 25fe870c4..94d6bdcdb 100644--- a/api/legal/risk-ack.js+++ b/api/legal/risk-ack.js@@ -1,6 +1,7 @@// /api/legal/risk-ack — record a user's acceptance of the Risk Disclosure.//-// POST /api/legal/risk-ack { version, context?, path? } → 200 { ok: true }+// POST /api/legal/risk-ack { version, context?, path? }+// → 200 { ok: true, recorded }//// The client-side gate (public/risk-ack.js) fires this after the user accepts// the real-funds risk acknowledgment. The acceptance itself lives in the@@ -13,11 +14,23 @@//// Anonymous acceptances are recorded too (userId null): the gate also runs in// third-party x402 embeds and pre-auth flows where no session exists.+//+// `recorded` reports whether the durable write actually landed, and the write+// is awaited rather than fired and forgotten: an acceptance the caller was+// told about but that never reached the database is exactly the failure this+// endpoint exists to prevent. A dropped write still answers 200, because the+// user did accept and their money action must not stall on our bookkeeping.import { getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { logAudit } from '../_lib/audit.js';+import { logAuditNow } from '../_lib/audit.js';+// The version constant is owned by the client gate, which is dependency-free+// and importable from both worlds (see its header). Importing it here rather+// than restating the number keeps the accepted version bound to the disclosure+// that was actually shown; a client cannot record acceptance of a revision+// that does not exist yet.+import { RISK_ACK_VERSION } from '../../public/risk-ack.js';const SLUG = /^[a-z0-9][a-z0-9-]{0,39}$/;const PATH = /^\/[\x20-\x7e]{0,199}$/;@@ -34,15 +47,20 @@ export default wrap(async function handler(req, res) {const body = await readJson(req, 10_000).catch(() => null);const version = Number(body?.version);- if (!Number.isInteger(version) || version < 1 || version > 1_000) {- return error(res, 400, 'invalid_version', 'version must be a positive integer');+ if (!Number.isInteger(version) || version < 1 || version > RISK_ACK_VERSION) {+ return error(+ res,+ 400,+ 'invalid_version',+ `version must be an integer between 1 and ${RISK_ACK_VERSION}`,+ );}const context = typeof body?.context === 'string' && SLUG.test(body.context) ? body.context : null;const path = typeof body?.path === 'string' && PATH.test(body.path) ? body.path : null;const user = await getSessionUser(req).catch(() => null);- logAudit({+ const recorded = await logAuditNow({userId: user?.id ?? null,action: 'risk-ack-accept',resourceId: null,@@ -50,5 +68,5 @@ export default wrap(async function handler(req, res) {req,});- return json(res, 200, { ok: true });+ return json(res, 200, { ok: true, recorded });});diff --git a/api/legal/tos-ack.js b/api/legal/tos-ack.jsindex d0eef9a58..2598886a8 100644--- a/api/legal/tos-ack.js+++ b/api/legal/tos-ack.js@@ -1,6 +1,7 @@// /api/legal/tos-ack: record a user's acceptance of the Terms of Service.//-// POST /api/legal/tos-ack { version?, context?, path? } → 200 { ok: true, version }+// POST /api/legal/tos-ack { version?, context?, path? }+// → 200 { ok: true, version, recorded }//// The primary acceptance records are written inline by the auth endpoints// (register / login / SIWE / SIWS / Privy verify) when the client sends@@ -12,11 +13,17 @@// audit-log-cleanup cron exempts 'tos-accept' rows from its 365-day// retention, so acceptance records persist indefinitely); signed-in// acceptances additionally stamp users.tos_accepted_version / tos_accepted_at.+//+// `recorded` reports whether the durable write actually landed. The write is+// awaited rather than fired and forgotten, because an acceptance record the+// caller was told about but that never reached the database is the one failure+// this endpoint exists to prevent. A dropped write still answers 200: the user+// did accept, and their flow must not stall on our bookkeeping.import { getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { logAudit } from '../_lib/audit.js';+import { logAuditNow } from '../_lib/audit.js';import { TOS_VERSION, recordTosAcceptance } from '../_lib/legal.js';const SLUG = /^[a-z0-9][a-z0-9-]{0,39}$/;@@ -40,18 +47,16 @@ export default wrap(async function handler(req, res) {const user = await getSessionUser(req).catch(() => null);- if (user) {- recordTosAcceptance({ userId: user.id, version, context, req });- } else {- // Anonymous acceptance (pre-auth surface): audit-only, no user row to stamp.- logAudit({- userId: null,- action: 'tos-accept',- resourceId: null,- meta: { version, context, path },- req,- });- }-- return json(res, 200, { ok: true, version });+ const recorded = user+ ? await recordTosAcceptance({ userId: user.id, version, context, path, req })+ : // Anonymous acceptance (pre-auth surface): audit-only, no user row to stamp.+ await logAuditNow({+ userId: null,+ action: 'tos-accept',+ resourceId: null,+ meta: { version, context, path },+ req,+ });++ return json(res, 200, { ok: true, version, recorded });});diff --git a/api/llm/anthropic.js b/api/llm/anthropic.jsindex e0b1e0e96..06906fba2 100644--- a/api/llm/anthropic.js+++ b/api/llm/anthropic.js@@ -133,6 +133,11 @@ export function sanitizeAnthropicBody(body, modelId) {const out = { ...body };const noSampling = modelRejectsSampling(modelId);if (noSampling) delete out.temperature;+ // The Messages API requires max_tokens; the request schema does not, and the+ // OpenAI-shape lanes default it in anthropicBodyToOpenAI. Without the same+ // default here, an embed that omits the field draws a 400 from every+ // Anthropic rung and silently degrades onto a lane it never asked for.+ if (!(typeof out.max_tokens === 'number' && out.max_tokens > 0)) out.max_tokens = 4096;// Thinking-by-default models spend max_tokens on thinking + text together;// floor small caller budgets so the visible reply isn't squeezed out.if (modelThinksByDefault(modelId) && (out.max_tokens ?? 0) < 4096) {@@ -198,7 +203,14 @@ export function modelFallbackChain(requestedModel) {const chain = [requestedModel,...[- 'meta-llama/llama-3.1-8b-instruct:free',+ // Groq's small free model. Every rung here must resolve through+ // resolveModelRoute or the attempt loop skips it without a trace: the+ // rung this replaced ('meta-llama/llama-3.1-8b-instruct:free') was in+ // neither MODELS nor OpenRouter's live catalog, so the documented+ // second step of the chain never ran. Groq is also a different account+ // and quota pool from the OpenRouter lane above, so an OpenRouter rate+ // limit does not carry over into it.+ 'llama-3.1-8b-instant','meta/llama-4-maverick-17b-128e-instruct',// SambaNova free 70B: an independent quota pool between the NVIDIA// free rung and the paid Anthropic backstop. Skipped at call time@@ -524,7 +536,7 @@ export default wrap(async (req, res) => {// Ordered fallback chain for 429 / 5xx from OpenRouter free tier:// 1. Requested model (e.g. llama-3.3-70b:free)- // 2. meta-llama/llama-3.1-8b-instruct:free (smaller free model)+ // 2. llama-3.1-8b-instant (smaller free model, Groq)// 3. meta/llama-4-maverick-17b-128e-instruct (free NVIDIA NIM tier)// 4. claude-haiku-4-5-20251001 (paid Anthropic)// 5. Vertex Gemini credits anchor (keyless last resort)@@ -602,7 +614,9 @@ export default wrap(async (req, res) => {build: async () => ({url: vertexGeminiChatUrl(),headers: await vertexGeminiHeaders(),- body: JSON.stringify(anthropicBodyToOpenAI({ ...body, model: usedModel })),+ body: JSON.stringify(+ anthropicBodyToOpenAI({ ...body, model: usedModel }, { provider: 'vertex-gemini' }),+ ),}),});} else {@@ -619,7 +633,9 @@ export default wrap(async (req, res) => {? { 'HTTP-Referer': 'https://three.ws', 'X-Title': 'three.ws agent' }: {}),},- body: JSON.stringify(anthropicBodyToOpenAI({ ...body, model: usedModel })),+ body: JSON.stringify(+ anthropicBodyToOpenAI({ ...body, model: usedModel }, { provider: route.provider }),+ ),}),});}diff --git a/api/lobehub/[action].js b/api/lobehub/[action].jsindex e2468b9bd..b9a791bb4 100644--- a/api/lobehub/[action].js+++ b/api/lobehub/[action].js@@ -1,71 +1,173 @@+// LobeHub / LobeChat plugin surface for three.ws.+//+// GET /api/lobehub/manifest the plugin manifest pasted into the LobeHub+// plugin store (public/lobehub/plugin.json)+// GET /api/lobehub/config the .well-known descriptor a host discovers+// on its own (public/.well-known/lobehub-plugin.json)+// POST /api/lobehub/handshake pre-validate an agent id and hand the host the+// iframe URL plus the agent's embed policy+//+// The model-facing half of the plugin (the tool calls the LLM makes) lives in+// api/chat-plugin/[tool].js; this file is the host-facing half. All three+// actions are fetched cross-origin from a browser, so they carry an open CORS+// policy exactly like that sibling.import { readFileSync } from 'node:fs';-import { join } from 'node:path';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';import { sql } from '../_lib/db.js';+import { readEmbedPolicy } from '../_lib/embed-policy.js';+import { env } from '../_lib/env.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { clientIp, limits } from '../_lib/rate-limit.js';+import { isUuid } from '../_lib/validate.js';-let pluginManifest;-try {- pluginManifest = JSON.parse(- readFileSync(join(process.cwd(), 'public/lobehub/plugin.json'), 'utf8'),- );-} catch (err) {- console.error('[lobehub/manifest] failed to load plugin.json', err);+// Resolve the manifests from THIS module's location rather than process.cwd().+// The handler runs from whatever directory the host process was started in, and+// under a cwd that is not the repo root the read simply failed. Because it used+// to run once at import time, that failure was permanent for the life of the+// instance: every request answered 500 with nothing to retry.+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');++const MANIFEST_FILES = {+ manifest: 'public/lobehub/plugin.json',+ config: 'public/.well-known/lobehub-plugin.json',+};++const manifestCache = new Map();++// Load on first use and cache only successes, so a transient read failure (a+// slow volume mount, a half-written file) is retried on the next request+// instead of pinning the endpoint to 500 forever. A genuine miss throws, which+// wrap() turns into a 500 with a correlation ref and a deduped ops alert naming+// the file an operator has to restore.+function loadManifest(action) {+ const cached = manifestCache.get(action);+ if (cached) return cached;+ const file = MANIFEST_FILES[action];+ let parsed;+ try {+ parsed = JSON.parse(readFileSync(join(REPO_ROOT, file), 'utf8'));+ } catch (err) {+ throw new Error(`lobehub ${action} manifest unreadable at ${file}: ${err?.message || err}`);+ }+ manifestCache.set(action, parsed);+ return parsed;}-let configManifest;-try {- configManifest = JSON.parse(- readFileSync(join(process.cwd(), 'public/.well-known/lobehub-plugin.json'), 'utf8'),- );-} catch (err) {- console.error('[lobehub/config] failed to load lobehub-plugin.json', err);+// The origin a host says it is embedding the plugin from. Only the scheme and+// host are meaningful; anything else is a caller mistake worth naming rather+// than silently dropping.+function originHostname(value) {+ if (typeof value !== 'string' || !value.trim()) return null;+ let url;+ try {+ url = new URL(value.trim());+ } catch {+ return null;+ }+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;+ return url.hostname.toLowerCase() || null;}-export default wrap(async (req, res) => {- const action = req.query?.action;+// The handshake is a pre-flight for an embed the iframe also resolves on its+// own, so a database outage degrades to an unverified handshake rather than+// taking the whole plugin down. api/chat-plugin/[tool].js makes the same call+// for the same reason; `verified` in the response tells the host which of the+// two answers it got.+async function lookupAgent(agentId) {+ try {+ const [row] = await sql`+ SELECT id, name FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ LIMIT 1+ `;+ if (!row) return { verified: true, found: false, name: null, policy: null };+ return {+ verified: true,+ found: true,+ name: typeof row.name === 'string' ? row.name : null,+ policy: await readEmbedPolicy(agentId),+ };+ } catch (err) {+ console.warn('[lobehub/handshake] agent lookup failed, handshaking unverified:', err?.message);+ return { verified: false, found: true, name: null, policy: null };+ }+}- if (action === 'manifest') {- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;- if (!method(req, res, ['GET'])) return;- if (!pluginManifest) return error(res, 500, 'internal_error', 'manifest unavailable');- return json(res, 200, pluginManifest, { 'cache-control': 'public, max-age=300' });+// Fold the agent owner's own embed policy (agent_identities.embed_policy, the+// one the dashboard writes) into the answer. Reporting only the plugin's chat+// hosts told an owner who had restricted their agent that it embeds anywhere+// this plugin does, which is the opposite of what they configured.+function mergeEmbedOrigins(pluginHosts, policy) {+ const ownerHosts = (policy?.origins?.hosts ?? []).map((h) => String(h).toLowerCase());+ // A denylist means "everywhere except these", so unioning it with the hosts+ // this plugin runs in would invert it. Pass the owner's list through as-is.+ if (policy?.origins?.mode === 'denylist') {+ return { mode: 'denylist', hosts: [...new Set(ownerHosts)] };}+ const hosts = new Set(pluginHosts.map((h) => h.toLowerCase()));+ for (const host of ownerHosts) hosts.add(host);+ return { mode: 'allowlist', hosts: [...hosts] };+}- if (action === 'config') {- res.setHeader('access-control-allow-origin', '*');- res.setHeader('access-control-allow-methods', 'GET,OPTIONS');- if (req.method === 'OPTIONS') {- res.statusCode = 204;- res.end();- return;- }+export default wrap(async (req, res) => {+ const action = req.query?.action;++ // Both manifests are read cross-origin: LobeHub's plugin store fetches the+ // manifest URL straight from the browser, and marketplace validators fetch+ // the .well-known descriptor the same way. Under the default (allowlisted)+ // CORS policy neither got an access-control-allow-origin header at all, so+ // every browser-side install attempt failed.+ if (action === 'manifest' || action === 'config') {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;- if (!configManifest) return error(res, 500, 'internal_error', 'manifest unavailable');- return json(res, 200, configManifest, { 'cache-control': 'public, max-age=300' });+ return json(res, 200, loadManifest(action), { 'cache-control': 'public, max-age=300' });}if (action === 'handshake') {- if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;if (!method(req, res, ['POST'])) return;const rl = await limits.widgetRead(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const body = await readJson(req);- const agentId = body?.agentId;+ const body = await readJson(req, 16_000);+ const agentId = typeof body?.agentId === 'string' ? body.agentId.trim() : '';const hostOrigin = body?.hostOrigin || null;- if (!agentId || typeof agentId !== 'string') {+ if (!agentId) {return error(res, 400, 'validation_error', 'agentId is required');}+ // agent_identities.id is a uuid column, so handing Postgres a non-uuid+ // string raises 22P02 and reached the caller as an opaque 500 (or, during+ // a DB outage, a 503) instead of telling them their id is malformed.+ if (!isUuid(agentId)) {+ return error(+ res,+ 400,+ 'validation_error',+ `agentId must be a UUID. Copy the agent ID from the dashboard at ${env.APP_ORIGIN}/dashboard.`,+ );+ }+ const hostOriginHost = hostOrigin === null ? null : originHostname(hostOrigin);+ if (hostOrigin !== null && !hostOriginHost) {+ return error(+ res,+ 400,+ 'validation_error',+ 'hostOrigin must be an http(s) URL, for example https://chat.lobehub.com',+ );+ }- const [agent] = await sql`- SELECT id, name FROM agent_identities- WHERE id = ${agentId} AND deleted_at IS NULL- `;-- if (!agent) return error(res, 404, 'not_found', 'agent not found');+ const agent = await lookupAgent(agentId);+ if (!agent.found) {+ return error(+ res,+ 404,+ 'not_found',+ `no three.ws agent with id ${agentId}. Copy the agent ID from the dashboard at ${env.APP_ORIGIN}/dashboard.`,+ );+ }const allowedHosts = ['chat.lobehub.com',@@ -75,17 +177,18 @@ export default wrap(async (req, res) => {'sperax-iota.vercel.app','sperax-jam2emun9-moomsi.vercel.app',];- if (hostOrigin) {- try {- allowedHosts.push(new URL(hostOrigin).hostname);- } catch {}- }+ if (hostOriginHost) allowedHosts.push(hostOriginHost);return json(res, 200, {ok: true,- iframeUrl: `https://three.ws/lobehub/iframe/?agent=${encodeURIComponent(agent.id)}`,+ agentId,+ agentName: agent.name,+ // false when the database was unreachable and the agent could not be+ // confirmed. The handshake still succeeds so the host can embed.+ verified: agent.verified,+ iframeUrl: `${env.APP_ORIGIN}/lobehub/iframe/?agent=${encodeURIComponent(agentId)}`,embedPolicy: {- origins: { mode: 'allowlist', hosts: allowedHosts },+ origins: mergeEmbedOrigins(allowedHosts, agent.policy),},});}diff --git a/api/marketplace/set-skill-price.js b/api/marketplace/set-skill-price.jsindex cc23c41b5..e729b0868 100644--- a/api/marketplace/set-skill-price.js+++ b/api/marketplace/set-skill-price.js@@ -30,7 +30,9 @@ const bodySchema = z.object({currency_mint: z.string().trim().min(1).max(100),chain: z.string().trim().min(1).max(20).default('solana'),// Pass an array of 2+ recipients to split proceeds; null/[] clears the split.- split: z.array(splitRecipientSchema).min(1).max(50).nullable().optional(),+ // The empty array is deliberately valid: it is how a caller retracts a split+ // without also delisting the skill.+ split: z.array(splitRecipientSchema).max(50).nullable().optional(),});async function resolveAuth(req) {@@ -73,12 +75,18 @@ export default wrap(async (req, res) => {// Resolve the proceeds split first so a malformed split (shares not summing// to 100%, bad address) is rejected BEFORE we mutate the price row.+ //+ // Three ways a split is retracted, and all three must actually land: the+ // skill is delisted (amount 0), `split` is null, or `split` is []. A clear+ // that silently failed used to leave the old recipient set attached to a+ // price the seller then raised, so the next sale paid collaborators who had+ // been removed. The clear is therefore allowed to fail the request.+ const clearsSplit = amount === 0 || (split !== undefined && (split === null || split.length === 0));let splitResult = null;- if (amount === 0) {- // Delisting clears any split too — no orphaned config.- await clearListingSplit(sql, agent_id, skill).catch(() => {});- } else if (split && split.length > 0) {- try {+ try {+ if (clearsSplit) {+ await clearListingSplit(sql, agent_id, skill);+ } else if (split && split.length > 0) {splitResult = await persistListingSplit(sql, {agentId: agent_id,skill,@@ -86,12 +94,10 @@ export default wrap(async (req, res) => {recipients: split,createdBy: auth.userId,});- } catch (e) {- if (e.status) return error(res, e.status, e.code, e.message);- throw e;}- } else if (split && split.length === 0) {- await clearListingSplit(sql, agent_id, skill).catch(() => {});+ } catch (e) {+ if (e.status) return error(res, e.status, e.code, e.message);+ throw e;}if (amount === 0) {diff --git a/api/marketplace/start-trial.js b/api/marketplace/start-trial.jsindex 483f221e9..7f840a8b5 100644--- a/api/marketplace/start-trial.js+++ b/api/marketplace/start-trial.js@@ -98,14 +98,27 @@ export default wrap(async (req, res) => {const reference = crypto.randomBytes(32).toString('hex');- const [purchase] = await sql`- INSERT INTO skill_purchases- (user_id, agent_id, skill, status, kind, reference, amount, currency_mint, chain, trial_remaining)- VALUES- (${userId}, ${agent_id}, ${skill}, 'trial', 'trial', ${reference},- ${price.amount}, ${price.currency_mint}, ${price.chain}, ${price.trial_uses})- RETURNING id, trial_remaining, reference, created_at- `;+ // The checks above are advisory: two clicks a few milliseconds apart both+ // read "no trial yet" and both insert. `skill_purchases_one_active_per_beneficiary`+ // is what actually enforces one active copy per beneficiary, so the loser of+ // that race gets a unique violation. That is the same condition the 409 above+ // describes, not a server fault, so answer it the same way instead of 500ing.+ let purchase;+ try {+ [purchase] = await sql`+ INSERT INTO skill_purchases+ (user_id, agent_id, skill, status, kind, reference, amount, currency_mint, chain, trial_remaining)+ VALUES+ (${userId}, ${agent_id}, ${skill}, 'trial', 'trial', ${reference},+ ${price.amount}, ${price.currency_mint}, ${price.chain}, ${price.trial_uses})+ RETURNING id, trial_remaining, reference, created_at+ `;+ } catch (e) {+ if (e?.code === '23505' || /duplicate key|unique constraint/i.test(e?.message || '')) {+ return error(res, 409, 'trial_used', 'you have already used the trial for this skill');+ }+ throw e;+ }return json(res, 201, {data: {diff --git a/api/marketplace/trial-status.js b/api/marketplace/trial-status.jsindex 8b8c7de75..5806815b3 100644--- a/api/marketplace/trial-status.js+++ b/api/marketplace/trial-status.js@@ -53,22 +53,41 @@ export function trialState(remaining, granted) {export function formatAtomic(atomic, decimals = 6) {const raw = String(atomic ?? '0').replace(/[^0-9]/g, '') || '0';const d = Number.isFinite(Number(decimals)) ? Math.max(0, Math.min(18, Number(decimals))) : 6;- if (d === 0) return raw.replace(/^0+(?=\d)/, '');+ const group = (s) => s.replace(/\B(?=(\d{3})+(?!\d))/g, ',');+ if (d === 0) return group(raw.replace(/^0+(?=\d)/, ''));const padded = raw.padStart(d + 1, '0');const whole = padded.slice(0, -d).replace(/^0+(?=\d)/, '');const frac = padded.slice(-d).replace(/0+$/, '');- const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');+ const grouped = group(whole);return frac ? `${grouped}.${frac}` : grouped;}-/** Sum atomic strings without precision loss. */-function sumAtomic(values) {- let total = 0n;- for (const v of values) {- const digits = String(v ?? '0').replace(/[^0-9]/g, '');- if (digits) total += BigInt(digits);+/**+ * Total the queue's potential revenue PER MINT. Atomic amounts are only+ * comparable inside one mint: adding 10 USDC (6dp) to 10 of an 8dp token and+ * printing the result under whichever mint happened to sort first produced a+ * headline number that was wrong by orders of magnitude for any seller who+ * priced two skills in two currencies. Returns the per-mint buckets sorted by+ * size, largest first, so a caller that can only render one number renders the+ * biggest true one rather than a fabricated blend.+ */+export function potentialsByMint(entries) {+ const buckets = new Map();+ for (const e of entries) {+ if (!e?.price || !e.potential?.atomic) continue;+ const key = `${e.price.mint || ''}::${e.price.decimals}`;+ const digits = String(e.potential.atomic).replace(/[^0-9]/g, '');+ const prev = buckets.get(key);+ const total = (prev ? BigInt(prev.atomic) : 0n) + (digits ? BigInt(digits) : 0n);+ buckets.set(key, {+ mint: e.price.mint || null,+ decimals: e.price.decimals,+ atomic: total.toString(),+ });}- return total.toString();+ return [...buckets.values()]+ .sort((a, b) => (BigInt(a.atomic) === BigInt(b.atomic) ? 0 : BigInt(a.atomic) < BigInt(b.atomic) ? 1 : -1))+ .map((b) => ({ ...b, display: formatAtomic(b.atomic, b.decimals) }));}function priceOf(row) {@@ -186,8 +205,10 @@ export async function sellerView(userId) {};});- const decimals = queue.find((q) => q.price)?.price.decimals ?? 6;- const potentialAtomic = sumAtomic(queue.map((q) => q.potential?.atomic || '0'));+ const potentials = potentialsByMint(queue);+ // The headline figure names its own mint, so the UI never has to guess it+ // from the first row of the queue (which need not be the mint being summed).+ const headline = potentials[0] || { atomic: '0', decimals: 6, display: '0', mint: null };return {role: 'seller',@@ -198,7 +219,8 @@ export async function sellerView(userId) {warmLeads: queue.reduce((n, q) => n + q.exhausted, 0),lastRun: queue.reduce((n, q) => n + q.lastRun, 0),sold: queue.reduce((n, q) => n + q.sold, 0),- potential: { atomic: potentialAtomic, decimals, display: formatAtomic(potentialAtomic, decimals) },+ potential: headline,+ potentials,},};}diff --git a/api/mcp-bazaar.js b/api/mcp-bazaar.jsindex 702c2982c..9c4af8399 100644--- a/api/mcp-bazaar.js+++ b/api/mcp-bazaar.js@@ -11,6 +11,7 @@ import { settlePayment, encodePaymentResponseHeader } from './_lib/x402-spec.js'import { peekCalledTool } from './_lib/mcp-dispatch.js';import { isDiscoveryOnlyBatch } from './_lib/mcp-batch-price.js';import { PROTOCOL_VERSION, dispatch, isPublicTool } from './_mcpbazaar/dispatch.js';+import { BAZAAR_CHALLENGE } from './_mcpbazaar/discovery.js';import {send401,sendJsonRpcError,@@ -21,10 +22,17 @@ import {} from './_mcp/auth.js';import { sendX402Error, reservePaymentProof } from './_mcp/payments.js';+// Every 402/401 challenge this server issues is scoped to its OWN resource.+// Passing neither resourcePath nor challenge left the Bazaar advertising+// https://three.ws/api/mcp and the main server's description to facilitators+// and to any client about to pay for a discovery call.+const RESOURCE_PATH = '/api/mcp-bazaar';+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,HEAD,POST,DELETE,OPTIONS', origins: '*' })) return;- if (req.method === 'GET' || req.method === 'HEAD') return handleSse(req, res);+ if (req.method === 'GET' || req.method === 'HEAD')+ return handleSse(req, res, { resourcePath: RESOURCE_PATH, challenge: BAZAAR_CHALLENGE });if (req.method === 'DELETE') return handleTerminate(req, res);if (req.method !== 'POST') return send401(res, 'method not supported');@@ -37,6 +45,8 @@ export default wrap(async (req, res) => {const { toolName } = peekCalledTool(body);const result = await authenticateRequest(req, res, {+ resourcePath: RESOURCE_PATH,+ challenge: BAZAAR_CHALLENGE,allowFree:Boolean(toolName && isPublicTool(toolName)) ||(isDiscoveryOnlyBatch(body) && !isMcpProtocolClient(req)),diff --git a/api/mirror/leaderboard.js b/api/mirror/leaderboard.jsindex c0e827a51..47c547dc9 100644--- a/api/mirror/leaderboard.js+++ b/api/mirror/leaderboard.js@@ -1,22 +1,26 @@-// GET /api/mirror/leaderboard — performance-weighted discovery of followable+// GET /api/mirror/leaderboard: performance-weighted discovery of followable// agents for custodial copy-trading (task 09).//// Ranks agents by REAL, on-chain-derived performance from real fills (sniper// closed positions + the discretionary custody ledger), never inflated. The// trust surface of copy-trading: you find a leader by their honest track record-// — losers included — and every number traces to a real signature.+// (losers included) and every number traces to a real signature.//// Public, cached. Sort by: score (default) | pnl | followers | volume | winrate.-import { cors, json, method, rateLimited } from '../_lib/http.js';+import { cors, json, method, rateLimited, wrap } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';const NETWORKS = new Set(['mainnet', 'devnet']);const SORTS = new Set(['score', 'pnl', 'followers', 'volume', 'winrate']);+// Candidate pool the ranking runs over. Bounded so one query stays cheap as the+// agent count grows; ordered (below) so the window holds the agents with the+// most evidence rather than an arbitrary 500 rows.+const CANDIDATE_POOL = 500;const lamToSol = (l) => (l == null ? 0 : Number(BigInt(l)) / 1e9);-export default async function handler(req, res) {+export default wrap(async function handler(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -28,9 +32,14 @@ export default async function handler(req, res) {const sort = SORTS.has(p.get('sort')) ? p.get('sort') : 'score';const limit = Math.min(50, Math.max(1, parseInt(p.get('limit') || '25', 10) || 25));- // Realized stats per agent from closed sniper round-trips — the honest P&L+ // Realized stats per agent from closed sniper round-trips: the honest P&L// surface. LEFT JOIN follower counts + discretionary trade activity so an agent// that trades only discretionarily still appears (with volume, no realized P&L).+ //+ // A DB failure is NOT caught here on purpose: an empty leaderboard is a real,+ // meaningful answer ("nobody has traded yet"), so swallowing an outage into+ // `[]` would hand back a confident lie and the CDN would cache it for a+ // minute. wrap() turns it into a 503 + Retry-After instead.const rows = await sql`WITH closed AS (SELECT agent_id,@@ -69,11 +78,27 @@ export default async function handler(req, res) {LEFT JOIN closed c ON c.agent_id = a.idLEFT JOIN activity act ON act.agent_id = a.idLEFT JOIN followers fl ON fl.agent_id = a.id- WHERE a.deleted_at IS NULL AND a.is_public <> false+ WHERE a.deleted_at IS NULL AND a.is_public = trueAND (c.settled IS NOT NULL OR act.trades IS NOT NULL)- LIMIT 500- `.catch(() => []);+ ORDER BY COALESCE(c.settled, 0) DESC,+ COALESCE(fl.followers, 0) DESC,+ COALESCE(act.trades, 0) DESC,+ a.id ASC+ LIMIT ${CANDIDATE_POOL}+ `;+ res.setHeader?.('cache-control', 'public, max-age=30, s-maxage=60');+ return json(res, 200, { data: { network, sort, leaders: rankLeaders(rows, { sort, limit }) } });+});++/**+ * Rank raw leaderboard rows. Pure: same rows in, same ranking out, so the 60s+ * edge cache never serves two different orderings of the same data.+ * @param {Array<object>} rows raw SQL rows (lamport sums arrive as strings)+ * @param {{sort?: string, limit?: number}} opts+ * @returns {Array<object>} ranked leaders, rank 1 first+ */+export function rankLeaders(rows, { sort = 'score', limit = 25 } = {}) {const leaders = rows.map((r) => {const pnlSol = lamToSol(r.pnl_lamports);const entrySol = lamToSol(r.entry_lamports);@@ -106,19 +131,20 @@ export default async function handler(req, res) {};});- const cmp = {- score: (a, b) => b.score - a.score,- pnl: (a, b) => b.pnl_sol - a.pnl_sol,- followers: (a, b) => b.followers - a.followers,- volume: (a, b) => b.volume_sol - a.volume_sol,- winrate: (a, b) => (b.win_rate ?? -1) - (a.win_rate ?? -1),- }[sort];- leaders.sort(cmp);- const ranked = leaders.slice(0, limit).map((l, i) => ({ rank: i + 1, ...l }));-- res.setHeader?.('cache-control', 'public, max-age=30, s-maxage=60');- return json(res, 200, { data: { network, sort, leaders: ranked } });+ const cmp = COMPARATORS[sort] || COMPARATORS.score;+ // Tiebreak on agent_id so equal-scoring agents rank in one fixed order+ // instead of shuffling between cache fills.+ leaders.sort((a, b) => cmp(a, b) || String(a.agent_id).localeCompare(String(b.agent_id)));+ return leaders.slice(0, limit).map((l, i) => ({ rank: i + 1, ...l }));}+const COMPARATORS = {+ score: (a, b) => b.score - a.score,+ pnl: (a, b) => b.pnl_sol - a.pnl_sol,+ followers: (a, b) => b.followers - a.followers,+ volume: (a, b) => b.volume_sol - a.volume_sol,+ winrate: (a, b) => (b.win_rate ?? -1) - (a.win_rate ?? -1),+};+function round2(x) { return Math.round(x * 100) / 100; }function round4(x) { return Math.round(x * 1e4) / 1e4; }diff --git a/api/native-launch/[action].js b/api/native-launch/[action].jsindex 9cd833498..4a6e3ba23 100644--- a/api/native-launch/[action].js+++ b/api/native-launch/[action].js@@ -1,4 +1,4 @@-// three.ws native launch lane dispatcher — the self-hosted coin launchpad on+// three.ws native launch lane dispatcher: the self-hosted coin launchpad on// Meteora's Dynamic Bonding Curve (DBC), alongside the pump.fun lane in// api/pump/[action].js. Same custody model: the server builds unsigned// transactions, the user's wallet (plus the mint keypair) signs client-side,@@ -25,7 +25,7 @@ import { publicUrl as r2PublicUrl } from '../_lib/r2.js';import { env } from '../_lib/env.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { resolveOrCreateAgentForAvatar } from '../_lib/agent-identity.js';-import { parse } from '../_lib/validate.js';+import { parse, isUuid } from '../_lib/validate.js';import { randomToken } from '../_lib/crypto.js';import { publishFeedEvent } from '../_lib/feed.js';import { normalizeGatewayURL } from '../../src/ipfs.js';@@ -171,7 +171,7 @@ async function handleLaunchPrep(req, res) {if (!agent) return error(res, 404, 'not_found', 'agent not found');// Mint pubkey: client-supplied (vanity-ground) or server-ground with the- // three.ws mark — identical branding rule to the pump lane.+ // three.ws mark. Identical branding rule to the pump lane.const enforceMark = env.THREE_WS_MARK_ENFORCE !== '0' && env.THREE_WS_MARK_ENFORCE !== 'false';let mintKeypair = null;let mint;@@ -183,7 +183,7 @@ async function handleLaunchPrep(req, res) {res,400,'unbranded_mint',- 'three.ws launches must use a mint address carrying the "3ws" mark — grind one client-side or omit mint_address to let the server stamp it',+ 'three.ws launches must use a mint address carrying the "3ws" mark. Grind one client-side, or omit mint_address to let the server stamp it',);}mint = supplied;@@ -194,7 +194,7 @@ async function handleLaunchPrep(req, res) {mint = mintKeypair.publicKey;} catch (err) {if (err instanceof GrindExhaustedError) {- return error(res, 503, 'mark_grind_failed', 'could not stamp the three.ws mark — retry');+ return error(res, 503, 'mark_grind_failed', 'could not stamp the three.ws mark, retry');}throw err;}@@ -301,7 +301,7 @@ async function handleLaunchConfirm(req, res) {if (!accountKeys.includes(p.mint)) {return error(res, 422, 'mint_not_in_tx', 'mint pubkey not present in tx');}- // The confirmed tx must have run the DBC program itself — a memo/transfer+ // The confirmed tx must have run the DBC program itself. A memo/transfer// touching the mint account can never be recorded as a launch.if (!txInvokesDbcProgram(tx)) {return error(res, 422, 'not_a_native_launch', 'transaction did not invoke the bonding-curve program');@@ -348,6 +348,11 @@ async function handleLaunches(req, res) {const url = new URL(req.url, `http://${req.headers.host}`);const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';const agentId = url.searchParams.get('agent_id') || null;+ // agent_id lands in a uuid column: an unvalidated value makes Postgres raise+ // and the request surface as a 500. Same 400 the pump lane returns.+ if (agentId && !isUuid(agentId)) {+ return error(res, 400, 'validation_error', 'agent_id must be a uuid');+ }const offset = Math.max(0, parseInt(url.searchParams.get('offset') || '0', 10) || 0);const limit = Math.max(1, Math.min(100, parseInt(url.searchParams.get('limit') || '24', 10) || 24));diff --git a/api/oauth/[action].js b/api/oauth/[action].jsindex 3cb3a62d4..1abb7f078 100644--- a/api/oauth/[action].js+++ b/api/oauth/[action].js@@ -6,7 +6,7 @@ import { sql } from '../_lib/db.js';import {getSessionUser, csrfTokenFor, verifyCsrfToken, isSameSiteOrigin,mintAccessToken, issueRefreshToken, rotateRefreshToken,- revokeRefreshToken, authenticateBearer, verifyAccessToken,+ revokeRefreshToken, verifyAccessToken,} from '../_lib/auth.js';import { randomToken, sha256, sha256Base64Url, constantTimeEquals } from '../_lib/crypto.js';import { cors, method, wrap, error, redirect, readForm, readJson, json, rateLimited } from '../_lib/http.js';@@ -37,6 +37,20 @@ function intersectScopes(requested, allowed) {return requested.split(/\s+/).filter((s) => a.has(s)).join(' ') || allowed;}+// RFC 8707 §2: an authorization server that does not recognize the requested+// `resource` MUST reject the request with `invalid_target`. Every consumer of an+// access token on this platform verifies `aud === env.MCP_RESOURCE`+// (verifyAccessToken in api/_lib/auth.js defaults the audience to it), so+// honoring an arbitrary resource minted a token that no endpoint here would ever+// accept: the client got a 200 and a credential that failed everywhere, instead+// of one clear error at the point the mistake was made.+// Returns the canonical resource, or null when the request names another one.+function canonicalResource(requested) {+ if (requested === undefined || requested === null || requested === '') return env.MCP_RESOURCE;+ const strip = (s) => String(s).replace(/\/+$/, '');+ return strip(requested) === strip(env.MCP_RESOURCE) ? env.MCP_RESOURCE : null;+}+// Scopes a dynamically-registered client may request. Anything outside this set// (notably privileged scopes like `permissions:redeem`, which authorizes// gas-spending on-chain redemption) is silently dropped at registration so a@@ -60,7 +74,7 @@ function esc(s) {return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);}-function renderConsent(res, { client, user, params, csrf }) {+function renderConsent(res, { client, user, params, csrf, grantedScope }) {res.statusCode = 200;res.setHeader('content-type', 'text/html; charset=utf-8');res.setHeader('cache-control', 'no-store');@@ -77,8 +91,12 @@ function renderConsent(res, { client, user, params, csrf }) {res.setHeader('x-content-type-options', 'nosniff');res.setHeader('referrer-policy', 'strict-origin-when-cross-origin');res.setHeader('strict-transport-security', 'max-age=63072000; includeSubDomains; preload');- const scope = params.scope || client.scope;- const scopeList = scope.split(/\s+/).filter(Boolean);+ // List exactly what the POST branch will grant, never the raw `scope` the+ // client asked for. They diverge whenever a client requests a scope it did+ // not register: intersectScopes drops it and falls back to the client's+ // registered scope, so showing the request itself made the consent screen+ // promise one set of permissions and the issued code carry another.+ const scopeList = grantedScope.split(/\s+/).filter(Boolean);res.end(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Authorize ${esc(client.name)} · three.ws</title><style>:root{color-scheme:light dark}body{font:16px/1.5 -apple-system,system-ui,Segoe UI,Roboto,sans-serif;background:#0b0b10;color:#eee;margin:0;min-height:100vh;display:grid;place-items:center;padding:24px}.card{background:#14141c;border:1px solid #2a2a36;border-radius:16px;padding:28px 28px 24px;max-width:440px;width:100%;box-shadow:0 10px 40px rgba(0,0,0,.4)}h1{font-size:20px;margin:0 0 8px}.sub{color:#aaa;margin:0 0 20px}.who{display:flex;align-items:center;gap:10px;margin-bottom:16px;padding:10px 12px;background:#1b1b25;border-radius:10px}.dot{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,#6a5cff,#ff5ca8);display:grid;place-items:center;color:#fff;font-weight:600}ul{margin:12px 0 20px;padding-left:0;list-style:none}li{padding:8px 0;border-bottom:1px solid #22222e;display:flex;gap:10px}li:last-child{border:0}li::before{content:"✓";color:#6a5cff}.actions{display:flex;gap:10px}button{flex:1;padding:12px 16px;border-radius:10px;border:0;font-size:15px;font-weight:600;cursor:pointer}.allow{background:#6a5cff;color:#fff}.deny{background:transparent;color:#aaa;border:1px solid #2a2a36}.foot{margin-top:16px;font-size:12px;color:#777}a{color:#9a8cff}</style></head><body><form class="card" method="post" action="/api/oauth/authorize"><h1>Authorize <b>${esc(client.name)}</b></h1><p class="sub">Grant this application access to your three.ws account.</p><div class="who"><div class="dot">${esc((user.display_name || user.email)[0].toUpperCase())}</div><div><div>${esc(user.display_name || user.email)}</div><div style="color:#888;font-size:13px">${esc(user.email)}</div></div></div><p style="margin:0 0 4px"><b>${esc(client.name)}</b> will be able to:</p><ul>${scopeList.map((s) => `<li>${scopeLabel(s)}</li>`).join('')}</ul><input type="hidden" name="csrf" value="${esc(csrf || '')}"> ${Object.entries(params).filter(([k]) => k !== 'csrf' && k !== 'decision').map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`).join('')}<div class="actions"><button class="deny" type="submit" name="decision" value="deny">Cancel</button><button class="allow" type="submit" name="decision" value="allow">Authorize</button></div><p class="foot">You can revoke access any time from your <a href="/dashboard/connections">dashboard</a>.</p></form></body></html>`);}@@ -95,6 +113,8 @@ async function handleAuthorize(req, res) {if (!code_challenge) return error(res, 400, 'invalid_request', 'code_challenge required (PKCE)');if (!code_challenge_method) return error(res, 400, 'invalid_request', 'code_challenge_method required (must be S256)');if (code_challenge_method !== 'S256') return error(res, 400, 'invalid_request', 'code_challenge_method must be S256');+ const targetResource = canonicalResource(resource);+ if (!targetResource) return error(res, 400, 'invalid_target', `unknown resource — this server only issues tokens for ${env.MCP_RESOURCE}`);const rows = await sql`select * from oauth_clients where client_id = ${client_id} limit 1`;const client = rows[0];if (!client) return error(res, 400, 'invalid_client', 'unknown client');@@ -104,9 +124,10 @@ async function handleAuthorize(req, res) {const next = encodeURIComponent(`/oauth/consent?${new URLSearchParams(params).toString()}`);return redirect(res, `/login?next=${next}`);}+ const grantedScope = intersectScopes(scope || client.scope, client.scope);if (req.method === 'GET') {const csrf = await csrfTokenFor(req);- return renderConsent(res, { client, user, params, csrf });+ return renderConsent(res, { client, user, params, csrf, grantedScope });}if (!isSameSiteOrigin(req)) return error(res, 403, 'forbidden', 'cross-site request blocked');if (!(await verifyCsrfToken(req, params.csrf))) return error(res, 403, 'forbidden', 'invalid csrf token');@@ -117,8 +138,7 @@ async function handleAuthorize(req, res) {return redirect(res, denied.toString());}const code = randomToken(24);- const grantedScope = intersectScopes(scope || client.scope, client.scope);- await sql`insert into oauth_auth_codes (code, client_id, user_id, redirect_uri, scope, resource, code_challenge, code_challenge_method, expires_at) values (${code}, ${client_id}, ${user.id}, ${redirect_uri}, ${grantedScope}, ${resource ?? env.MCP_RESOURCE}, ${code_challenge}, 'S256', now() + ${'60 seconds'}::interval)`;+ await sql`insert into oauth_auth_codes (code, client_id, user_id, redirect_uri, scope, resource, code_challenge, code_challenge_method, expires_at) values (${code}, ${client_id}, ${user.id}, ${redirect_uri}, ${grantedScope}, ${targetResource}, ${code_challenge}, 'S256', now() + ${'60 seconds'}::interval)`;const back = new URL(redirect_uri);back.searchParams.set('code', code);if (state) back.searchParams.set('state', state);diff --git a/docs/ops/production-log-triage.md b/docs/ops/production-log-triage.mdindex 68fce2d7c..755bf4648 100644--- a/docs/ops/production-log-triage.md+++ b/docs/ops/production-log-triage.md@@ -696,7 +696,7 @@ ERROR 502 POST /api/pump/launch-agent[pump/launch-agent] send failed Error: pre-broadcast simulation failed: {"InstructionError":[1,{"Custom":6015}]}```-- **Source:** [api/pump/launch-agent.js](../../api/pump/launch-agent.js). The+- **Source:** [api/pump/[action].js](../../api/pump/[action].js), action `launch-agent`. Thehandler simulates every launch transaction before broadcasting it.- **What it means:** the simulation REFUSED a launch that would have failedon-chain (pump program custom errors: curve state raced another buyer,diff --git a/package-lock.json b/package-lock.jsonindex 689dc0c42..bd8c2ef80 100644--- a/package-lock.json+++ b/package-lock.json@@ -114,6 +114,7 @@"@pump-fun/pump-sdk": "^1.36.0","@pump-fun/pump-swap-sdk": "^1.19.0","@pythnetwork/hermes-client": "^3.1.0",+ "@scure/base": "^1.2.6","@solana-mobile/mobile-wallet-adapter-protocol-web3js": "^2.2.9","@solana-program/compute-budget": "^0.15.0","@solana-program/stake": "^0.6.1",diff --git a/package.json b/package.jsonindex ab36239d5..0aaa6e45f 100644--- a/package.json+++ b/package.json@@ -421,6 +421,7 @@"@pump-fun/pump-sdk": "^1.36.0","@pump-fun/pump-swap-sdk": "^1.19.0","@pythnetwork/hermes-client": "^3.1.0",+ "@scure/base": "^1.2.6","@solana-mobile/mobile-wallet-adapter-protocol-web3js": "^2.2.9","@solana-program/compute-budget": "^0.15.0","@solana-program/stake": "^0.6.1",diff --git a/packages/ibm-x402-mcp/src/tools/granite-analyze.js b/packages/ibm-x402-mcp/src/tools/granite-analyze.jsindex 1631e9264..efa942433 100644--- a/packages/ibm-x402-mcp/src/tools/granite-analyze.js+++ b/packages/ibm-x402-mcp/src/tools/granite-analyze.js@@ -138,15 +138,22 @@ export async function buildGraniteAnalyzeTool(client) {? raw.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, ''): raw;parsed = JSON.parse(jsonStr);+ // A bare JSON scalar or array parses fine but is not an analysis+ // object, and spreading one below would splatter per-character or+ // per-index keys into the result. Treat it as unparseable.+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {+ throw new Error('analysis JSON was not an object');+ }} catch {- // Granite didn't return clean JSON — surface text so client can decide+ // Granite didn't return a clean JSON object: surface the text so the+ // client can decide what to do with it.return {ok: true,analysis_type,raw_response: result.text,usage: result.usage,model: result.model,- parse_error: 'Model returned non-JSON response; see raw_response.',+ parse_error: 'Model did not return a JSON analysis object; see raw_response.',};}diff --git a/packages/node-operator/README.md b/packages/node-operator/README.mdnew file mode 100644index 000000000..a83b3eff3--- /dev/null+++ b/packages/node-operator/README.md@@ -0,0 +1,295 @@+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>++<h1 align="center">@three-ws/node-operator</h1>++<p align="center"><strong>Run a three.ws inference node: register a Solana keypair, poll the job queue, execute real local inference, return a signed receipt.</strong></p>++<p align="center">+ <a href="#install">Install</a> ·+ <a href="#quick-start">Quick start</a> ·+ <a href="#configuration">Configuration</a> ·+ <a href="#wire-protocol">Wire protocol</a> ·+ <a href="#receipts">Receipts</a> ·+ <a href="https://three.ws">three.ws</a>+</p>++---++> `@three-ws/node-operator` is the operator-side client for the three.ws open+> inference network. It turns any machine with Node 20+ into a node that the+> platform can route inference jobs to. The node holds a Solana ed25519 keypair,+> and that public key **is** its identity on the network: jobs are routed to it,+> results are verified against it, and settlement pays it. The secret key never+> leaves the operator host. The platform only ever sees signatures.++## Why++An inference network that trusts its nodes is not a network, it is a hosting+bill with extra steps. The hard problem is not running a model, it is proving+that a specific node ran a specific job and produced a specific output, so a+requester can pay for the result without trusting the operator or any+intermediary.++This client solves that end to end. Every job the node finishes ships with an+ed25519 **receipt** that binds `(jobId, model, prompt, output, startedAt,+finishedAt)` to the node's public key. Verification is pure and offline: anyone+holding the receipt and the pubkey can confirm the node computed exactly that+output for exactly that job, with no call back to three.ws.++## Install++The package is in-repo and not published to npm. Clone the repo and install+inside the package directory:++```sh+cd packages/node-operator+npm install+```++Node 20 or newer is required (the client uses `AbortSignal.timeout` and+`crypto.subtle`).++## Quick start++Prove your host can run the workload before you register:++```sh+npm start -- --self-test+```++The first run downloads `Xenova/all-MiniLM-L6-v2` (~90 MB, Apache-2.0,+quantized ONNX) into `./models` and caches it there. Expect output like:++```+[node] identity 7Xf3...q9Zk (generated, saved to /path/node-identity.json)+[node] platform https://three.ws · capability text-embedding · model Xenova/all-MiniLM-L6-v2+[node] running proof workload self-test (first run downloads the model)...+[node] self-test OK: Xenova/all-MiniLM-L6-v2, 384 dims, 812ms+```++Then register and start earning:++```sh+npm start+```++That registers the node with the platform and enters the poll loop. Ctrl+C+drains in-flight jobs and exits cleanly.++### CLI++| Command | What it does |+| --- | --- |+| `npm start` | Register (idempotent) and run the job loop until SIGINT/SIGTERM. |+| `npm start -- --register-only` | Register with the platform and exit. |+| `npm start -- --self-test` | Run the proof workload locally and exit; exit code 1 on failure. |+| `npm start -- --pubkey` | Print this node's base58 public key and exit. |+| `npm run register` | Alias for `--register-only`. |+| `npm test` | Run the vitest suite. |++## Identity++On first run the client generates an ed25519 keypair and writes it to+`node-identity.json` (mode `0600`) in the working directory, so restarts keep+the same identity and the same earnings history. To supply your own key+instead, set `OPERATOR_SECRET_KEY` to the 64-byte ed25519 secret key encoded as+either base58 or base64. The env var always wins over the file.++Back up `node-identity.json`. Losing it means losing the node's identity on the+network.++```js+import { resolveIdentity, defaultIdentityPath } from './src/identity.js';++const { identity, source } = resolveIdentity({+ envSecret: process.env.OPERATOR_SECRET_KEY,+ identityPath: defaultIdentityPath(),+});+console.log(identity.publicKey, source); // '7Xf3...q9Zk' 'file'+```++## Configuration++Precedence is **environment variable > `operator.config.json` in the working+directory > default**. Config is validated eagerly, so a misconfigured node+fails at boot with a readable message rather than mid-job.++| Env var | Config key | Default | Meaning |+| --- | --- | --- | --- |+| `PLATFORM_URL` | `platformUrl` | `https://three.ws` | Platform base URL. Must be absolute http(s); trailing slashes are stripped. |+| `CAPABILITY` | `capability` | `text-embedding` | Capability this node advertises and polls for. |+| `MODEL` | `model` | `Xenova/all-MiniLM-L6-v2` | Model id advertised at registration. |+| `POLL_INTERVAL_MS` | `pollIntervalMs` | `5000` | Idle poll interval. Minimum 1000. |+| `MAX_CONCURRENCY` | `maxConcurrency` | `1` | Jobs executed in parallel. Minimum 1. |+| `JOB_TIMEOUT_MS` | `jobTimeoutMs` | `120000` | Per-job wall clock ceiling. Minimum 10000. |+| `IDENTITY_PATH` | `identityPath` | `node-identity.json` | Where the keypair is persisted. Relative paths resolve against the working directory. |+| `OPERATOR_SECRET_KEY` | `secretKey` | none | 64-byte ed25519 secret key, base58 or base64. Overrides the identity file. |+| `NODE_LABEL` | `label` | none | Human-readable name shown alongside the node. |++A minimal `operator.config.json`:++```json+{+ "label": "atlas-01",+ "capability": "text-embedding",+ "maxConcurrency": 4,+ "pollIntervalMs": 3000+}+```++### Docker++A `Dockerfile` ships with the package. Mount a volume at `/app/models` so model+weights survive restarts, and one for the identity file so the node keeps its+key:++```sh+docker build -t three-ws-node .+docker run -d --name three-ws-node \+ -e NODE_LABEL=atlas-01 \+ -e MAX_CONCURRENCY=4 \+ -v three-ws-models:/app/models \+ -v three-ws-identity:/app/identity \+ -e IDENTITY_PATH=/app/identity/node-identity.json \+ three-ws-node+```++## The proof workload++The built-in capability is real local text embedding, not a stub. Embeddings+were chosen as the proof workload because they are the smallest thing that+still exercises the full tensor path a production inference job uses (tokenize,+transformer forward, mean pool, normalize), run in seconds on a laptop CPU, and+produce a deterministic, numerically verifiable output. There are no API keys+and no network calls at inference time; the model downloads once and runs+locally forever after.++Richer models plug into the same `runJob()` interface:++```js+import { runJob, selfTest } from './src/inference.js';++const { output, startedAt, finishedAt } = await runJob(+ { id: 'job-1', model: 'Xenova/all-MiniLM-L6-v2', input: { text: 'hello' } },+ { cacheDir: './models' },+);+// output -> { kind: 'text-embedding', model, dimensions: 384, embedding: [...] }++await selfTest({ cacheDir: './models' });+// -> { ok: true, model, dimensions: 384, elapsedMs: 812 }+```++## Wire protocol++Every authenticated call signs a short, domain-separated string, so a signature+harvested from one call can never be replayed against another. Server side these+are [api/nodes/register.js](../../api/nodes/register.js) and+[api/nodes/jobs.js](../../api/nodes/jobs.js).++**Register** (idempotent on `publicKey`):++```+POST {platformUrl}/api/nodes/register+body: { publicKey, label?, capabilities: [{ capability, model }], registeredAt, signature }+ signature = ed25519 over `threews-node-register:{publicKey}:{registeredAt}`+200: { ok: true, node: { id, publicKey, capabilities } }+```++**Claim the next job**:++```+GET {platformUrl}/api/nodes/jobs?node={publicKey}&capability={cap}&ts={ms}&sig={sig}+ sig = ed25519 over `threews-node-poll:{publicKey}:{ts}`+200: { job: null } queue empty+200: { job: { id, capability, model, input, deadlineAt } }+```++**Submit a result**:++```+POST {platformUrl}/api/nodes/jobs/{jobId}/result+body: { node, output, startedAt, finishedAt, receipt }+200: { ok: true, verified: true }+```++**Report a failure** so the platform can requeue or refund:++```+POST {platformUrl}/api/nodes/jobs/{jobId}/result+body: { node, failed: true, error, startedAt, finishedAt, ts, signature }+ signature = ed25519 over `threews-node-fail:{publicKey}:{jobId}:{ts}`+```++The client for all four lives in [src/platform.js](src/platform.js):++```js+import { createPlatformClient } from './src/platform.js';++const client = createPlatformClient({ platformUrl: 'https://three.ws', identity });+await client.register({ label: 'atlas-01', capabilities: [{ capability: 'text-embedding', model: 'Xenova/all-MiniLM-L6-v2' }] });+const job = await client.pollJob({ capability: 'text-embedding' }); // job | null+```++## Receipts++The canonical signed message pre-hashes every variable-length field, so there+is no delimiter or encoding ambiguity:++```+sha256hex(jobId).sha256hex(model).sha256hex(prompt).sha256hex(output).startedAt.finishedAt+```++Sign a result, then verify it offline with nothing but the public key:++```js+import { signResult, verifyResult, verifyReceipt } from './src/signing.js';++const facts = { jobId: 'job-1', model: 'Xenova/all-MiniLM-L6-v2', prompt: 'hello', output, startedAt, finishedAt };+const receipt = await signResult(identity, facts);+// receipt -> { algorithm: 'ed25519', publicKey, payload, signature }++await verifyResult(facts, receipt); // true: recomputes the payload, then checks the signature+verifyReceipt(receipt, identity.publicKey); // true: signature only, no recomputation+```++`verifyResult` is the check the platform runs before crediting a job:+recompute the payload from the claimed inputs and reject any receipt whose+payload does not match, which catches a node that signed a different output+than the one it submitted.++## The job loop++[src/loop.js](src/loop.js) is poll, execute, sign, submit, with bounded+concurrency and graceful shutdown. Its failure policy matches the platform's+own workers: a job that throws is reported failed with its error string and the+loop keeps going; transient poll failures back off exponentially and retry,+because a node that gives up on the first network blip earns nothing. Only+SIGINT, SIGTERM, or a fatal registration error stops it.++```js+import { createJobLoop } from './src/loop.js';++const loop = createJobLoop({ client, identity, capability: 'text-embedding', maxConcurrency: 4 });+process.on('SIGTERM', () => loop.stop());+await loop.run();+console.log(loop.stats); // { completed, failed }+```++## Testing++```sh+npm test # unit suite+node scripts/e2e-local.mjs # end-to-end against a local fake platform+```++`createIdentityFromSeed(seed)` in [src/identity.js](src/identity.js) derives a+reproducible keypair from a 32-byte seed, for tests and fixture nodes. Never+use it for a real operator identity: it puts key material in config.++## Related++- [specs/OPEN_INFERENCE_PROTOCOL.md](../../specs/OPEN_INFERENCE_PROTOCOL.md) - the vendor-neutral OIN wire protocol this network is converging on.+- [specs/inference-receipts.md](../../specs/inference-receipts.md) - the receipt format and verification rules.+- [STRUCTURE.md](../../STRUCTURE.md) - where every three.ws surface lives.diff --git a/packages/node-operator/src/platform.js b/packages/node-operator/src/platform.jsindex 79cdb6ef0..e20506642 100644--- a/packages/node-operator/src/platform.js+++ b/packages/node-operator/src/platform.js@@ -1,8 +1,8 @@/*** Platform wire client: registration, job poll, result submit.*- * The wire contract (derived in specs/inference-nodes.md from the platform's- * existing worker job formats) is:+ * The wire contract (documented for operators in this package's README.md, and+ * served by api/nodes/register.js and api/nodes/jobs.js) is:** POST {platformUrl}/api/nodes/register* body: { publicKey, label?, capabilities: [{capability, model}],diff --git a/pages/genome.html b/pages/genome.htmlindex e4c6a7f8e..1db31299d 100644--- a/pages/genome.html+++ b/pages/genome.html@@ -83,6 +83,13 @@<p class="gn-section-sub" data-i18n="genome.rare_pedigree_agents_their_owners_have_opene">Rare-pedigree agents their owners have opened for breeding. Deeper lineage and emergent skills command higher $THREE stud fees.</p><div class="gn-studs" id="gnStuds"></div></section>++ <!-- Own the other side of the market: list your agents for stud -->+ <section aria-label="Your stud listings" id="gnMyStudsSection" hidden>+ <h2 class="gn-section-title" data-i18n="genome.your_stud_listings">Your stud listings</h2>+ <p class="gn-section-sub" data-i18n="genome.open_one_of_your_agents_for_breeding">Open one of your agents for breeding and name its $THREE fee. Listed agents appear in the stud market above for every breeder on three.ws. Unlist at any time.</p>+ <div class="gn-mystuds" id="gnMyStuds"></div>+ </section></main><!-- Agent picker modal -->diff --git a/public/changelog.json b/public/changelog.jsonindex 0ebd597d0..1e2cff3d4 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,31 @@{- "generated_at": "2026-08-12T23:34:40.778Z",+ "generated_at": "2026-08-13T01:06:15.164Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-08-13",+ "type": "update",+ "title": "A shared walk card no longer sends people to an avatar that is gone",+ "summary": "Sharing a walk produces a card you can post on Farcaster, with a button that opens that avatar walking. A cast stays up forever, but the avatar behind it does not: it can be deleted, or switched to private. When that happened the button still pointed at the missing avatar, so anyone who tapped it landed on a walk that could never load, and the card's second button pointed at the same place as the first, so both said the same thing. The card now checks the avatar before it builds. If the avatar is gone or private it drops the link and invites you to walk your own instead of handing you a dead button, and if the check itself cannot run the link is kept rather than thrown away. The second button now goes to the avatar builder, so the two buttons finally offer two different things. The card also carries its image dimensions now, which stops the preview from reflowing while it loads.",+ "link": "/walk",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-08-13",+ "type": "update",+ "title": "Importing an agent you already own on-chain no longer fails because its metadata host is slow",+ "summary": "If you registered an agent on-chain, the hydrate page finds it from your connected wallets and offers to import it into three.ws. Importing read two things: the registry entry on the chain, and the registration file the registry points at, which usually lives on IPFS. If that file did not load in five seconds, the whole import was refused, even though the part that actually matters, the chain saying you own the agent, had already answered. Public IPFS gateways throttle constantly, so owners were locked out of their own agents by a slow third party. The import now only needs the chain read to succeed; a registration file that will not load means the agent lands under its on-chain name and the metadata fills in on the next crawl. Two more changes went in alongside it: ownership is now re-checked against the live registry rather than the crawler's cached copy, so an agent you transferred away cannot be imported by the old wallet, and a chain that is unreachable now says so plainly and asks you to retry instead of reporting a generic failure. Separately, confirming a new registration now reads the transaction receipt over the same priority provider list the rest of the platform uses, instead of the slowest public fallbacks, which is what made a freshly mined registration occasionally come back as \"not yet mined\".",+ "link": "/hydrate",+ "tags": [+ "fix"+ ]+ },{"date": "2026-08-12","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 479f6feb3..8f410d417 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,22 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws: features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>A shared walk card no longer sends people to an avatar that is gone</title>+ <link>https://three.ws/walk</link>+ <guid isPermaLink="false">2026-08-13:A shared walk card no longer sends people to an avatar that is gone</guid>+ <pubDate>Thu, 13 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Sharing a walk produces a card you can post on Farcaster, with a button that opens that avatar walking. A cast stays up forever, but the avatar behind it does not: it can be deleted, or switched to private. When that happened the button still pointed at the missing avatar, so anyone who tapped it landed on a walk that could never load, and the card's second button pointed at the same place as the first, so both said the same thing. The card now checks the avatar before it builds. If the avatar is gone or private it drops the link and invites you to walk your own instead of handing you a dead button, and if the check itself cannot run the link is kept rather than thrown away. The second button now goes to the avatar builder, so the two buttons finally offer two different things. The card also carries its image dimensions now, which stops the preview from reflowing while it loads.</description>+ </item>+ <item>+ <title>Importing an agent you already own on-chain no longer fails because its metadata host is slow</title>+ <link>https://three.ws/hydrate</link>+ <guid isPermaLink="false">2026-08-13:Importing an agent you already own on-chain no longer fails because its metadata host is slow</guid>+ <pubDate>Thu, 13 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>If you registered an agent on-chain, the hydrate page finds it from your connected wallets and offers to import it into three.ws. Importing read two things: the registry entry on the chain, and the registration file the registry points at, which usually lives on IPFS. If that file did not load in five seconds, the whole import was refused, even though the part that actually matters, the chain saying you own the agent, had already answered. Public IPFS gateways throttle constantly, so owners were locked out of their own agents by a slow third party. The import now only needs the chain read to succeed; a registration file that will not load means the agent lands under its on-chain name and the metadata fills in on the next crawl. Two more changes went in alongside it: ownership is now re-checked against the live registry rather than the crawler's cached copy, so an agent you transferred away cannot be imported by the old wallet, and a chain that is unreachable now says so plainly and asks you to retry instead of reporting a generic failure. Separately, confirming a new registration now reads the transaction receipt over the same priority provider list the rest of the platform uses, instead of the slowest public fallbacks, which is what made a freshly mined registration occasionally come back as "not yet mined".</description>+ </item><item><title>Docs · Run an inference node</title><link>https://three.ws/docs/inference-node-operator</link>diff --git a/public/features.json b/public/features.jsonindex ef50178a3..f404fab22 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-12T23:34:40.760Z",+ "generated_at": "2026-08-13T01:06:15.008Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/forever.js b/public/forever.jsindex 6672618e2..d88b548e3 100644--- a/public/forever.js+++ b/public/forever.js@@ -205,6 +205,15 @@ function show(view) {let currentOrder = null; // { orderId, message, receiveAddress }let pollTimer = null;+// Drop a dead order and return the user to a usable compose view. Used whenever+// the server reports the id no longer resolves, so a stale sessionStorage entry+// can never strand the page on a pay screen for an order that does not exist.+function forgetOrder() {+ sessionStorage.removeItem('forever:order');+ currentOrder = null;+ show('compose');+}+function setStatePill(state) {els.statePill.classList.remove('ok', 'err');if (state === 'inscribed') els.statePill.classList.add('ok');@@ -337,6 +346,16 @@ async function pollOnce() {`/api/forever/status?id=${encodeURIComponent(currentOrder.orderId)}`,);const d = await r.json();+ if (r.status === 404) {+ // The order id no longer resolves upstream. Polling it again can only+ // repeat the 404 forever, so retire it instead of spinning silently.+ stopPolling();+ forgetOrder();+ showError(+ 'This inscription order is no longer available from OrdinalsBot. Nothing was charged for it. Write your message again to start a new one.',+ );+ return;+ }if (!r.ok) return;setStatePill(d.state);@@ -451,8 +470,22 @@ document.querySelectorAll('.copy[data-copy]').forEach((btn) => {show('pay');// Refresh the charge details from server.fetch(`/api/forever/status?id=${encodeURIComponent(saved.orderId)}`)- .then((r) => r.json())+ .then(async (r) => {+ if (r.status === 404) {+ // A saved id the server can no longer resolve. Without this the+ // error envelope below reads as an order and repaints an empty+ // pay screen that polls a dead id for the rest of the session.+ forgetOrder();+ showError(+ 'The inscription order saved in this tab is no longer available from OrdinalsBot. Nothing was charged for it. Write your message again to start a new one.',+ );+ return null;+ }+ if (!r.ok) throw new Error(`status lookup failed (${r.status})`);+ return r.json();+ }).then((d) => {+ if (!d) return;if (d.charge?.address) {const amountBtc = d.charge.amountBtc ?? (d.charge.amount ? d.charge.amount / 1e8 : 0);els.amountBtc.textContent = amountBtc ? amountBtc.toFixed(8) : '—';diff --git a/public/genome.css b/public/genome.cssindex a5ba6fbf5..0d1e12746 100644--- a/public/genome.css+++ b/public/genome.css@@ -237,6 +237,46 @@.gn-stud-name { font-weight: 600; }.gn-stud-fee { font-size: var(--text-xs); color: var(--accent); }+/* ── Your stud listings ─────────────────────────────────────────────────── */+.gn-mystuds { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: var(--space-md); }+.gn-mystud {+ border: 1px solid var(--stroke); border-radius: 12px; padding: var(--space-md);+ background: var(--surface-glass); display: flex; flex-direction: column; gap: var(--space-sm);+ transition: border-color 0.18s ease;+}+.gn-mystud[data-listed='true'] { border-color: var(--accent); }+.gn-mystud-head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm); }+.gn-mystud-name { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.gn-mystud-row { display: flex; align-items: center; gap: var(--space-sm); flex-wrap: wrap; }+.gn-fee-input {+ width: 8ch; padding: 6px 8px; border-radius: 8px; font: inherit;+ border: 1px solid var(--stroke); background: var(--surface-2); color: var(--ink);+}+.gn-fee-input:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; border-color: var(--accent); }+.gn-fee-input:disabled { opacity: 0.45; cursor: not-allowed; }+.gn-mystud-state { font-size: var(--text-xs); color: var(--ink-dim); min-height: 1.2em; }+.gn-mystud-state[data-kind='ok'] { color: #7fe3bb; }+.gn-mystud-state[data-kind='error'] { color: #f4a3ad; }+/* Accessible switch: a real checkbox, styled. Keyboard + screen reader native. */+.gn-switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; font-size: var(--text-sm); }+.gn-switch input { position: absolute; opacity: 0; width: 0; height: 0; }+.gn-switch-track {+ width: 38px; height: 22px; border-radius: 999px; background: var(--surface-3, #23262e);+ border: 1px solid var(--stroke); position: relative; transition: background 0.18s ease, border-color 0.18s ease;+ flex: none;+}+.gn-switch-track::after {+ content: ''; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px;+ border-radius: 50%; background: var(--ink-dim); transition: transform 0.18s ease, background 0.18s ease;+}+.gn-switch input:checked + .gn-switch-track { background: rgba(122,162,255,0.28); border-color: var(--accent); }+.gn-switch input:checked + .gn-switch-track::after { transform: translateX(16px); background: var(--accent); }+.gn-switch input:focus-visible + .gn-switch-track { outline: 2px solid var(--accent); outline-offset: 2px; }+.gn-switch input:disabled + .gn-switch-track { opacity: 0.45; cursor: not-allowed; }+@media (prefers-reduced-motion: reduce) {+ .gn-switch-track, .gn-switch-track::after, .gn-mystud { transition: none; }+}+/* ── Picker modal ───────────────────────────────────────────────────────── */.gn-modal { position: fixed; inset: 0; background: rgba(0,0,0,0.6); display: grid; place-items: center; z-index: 60; padding: var(--space-md); }.gn-modal[hidden] { display: none; }diff --git a/scripts/genome-endpoints-proof.mjs b/scripts/genome-endpoints-proof.mjsnew file mode 100644index 000000000..579c309e5--- /dev/null+++ b/scripts/genome-endpoints-proof.mjs@@ -0,0 +1,540 @@+#!/usr/bin/env node+// genome-endpoints-proof: exercise every /api/genome/* endpoint over real HTTP,+// against a real Postgres, through the real server route table. No mocks, no+// fixtures, no funds: the stud-fee path is proved at its 402/409 boundaries,+// which is exactly where it stops BEFORE any settlement is trusted.+//+// Why this exists: tests/genome-*.test.js pin the handlers' decisions against a+// mocked DB (fast, deterministic), but a mock cannot prove the things this audit+// cares about:+// 1. the handlers are actually ROUTED (server/index.mjs filesystem mapping),+// 2. their SQL is valid against a real schema (a typo in a join or a column+// that only exists after a migration fails here, not in production),+// 3. malformed input returns JSON, never an HTML error page or a stack trace,+// 4. the stud-listing write has PATCH semantics (an omitted field keeps its+// stored value) and survives a concurrent write to a sibling meta key.+//+// What it proves, in order:+// 1. edges public, cached, bounded; excludes deleted agents+// 2. stud GET public market listing, rarest first+// 3. stud POST owner-only, CSRF-gated, PATCH semantics, meta-preserving+// 4. lineage family tree on parent and child, verify=1 re-derives the genome,+// and a forged genome fails verification+// 5. preview deterministic offspring, same seed -> byte-identical genome+// 6. breed validation, auth, cooldown, and the 402 stud-fee gate+//+// Usage:+// node scripts/genome-endpoints-proof.mjs # full run, prints transcript+// node scripts/genome-endpoints-proof.mjs --keep # leave the pg container up+//+// Environment: needs `docker` (postgres:16 image) and ports 5823/5824/3823 free.+// `pg` is loaded from node_modules if present, else installed with --no-save.++import { spawn, spawnSync } from 'node:child_process';+import path from 'node:path';+import fs from 'node:fs';+import net from 'node:net';+import crypto from 'node:crypto';+import { fileURLToPath } from 'node:url';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const KEEP = process.argv.includes('--keep');++const PG_PORT = 5823;+const SHIM_PORT = 5824;+const HTTP_PORT = 3823;+const PG_CONTAINER = 'genome-proof-pg';+const PG_URL = `postgres://[email protected]:${PG_PORT}/proof`;+const SHIM_URL = `http://127.0.0.1:${SHIM_PORT}/sql`;+const BASE = `http://127.0.0.1:${HTTP_PORT}`;+const TMP = path.join(root, '.genome-proof-tmp');++// ── transcript ───────────────────────────────────────────────────────────────+const results = [];+let failed = 0;+function step(name) { console.log(`\n-- ${name}`); }+function pass(name, detail) { results.push({ name, ok: true }); console.log(` PASS ${name}${detail ? ` - ${detail}` : ''}`); }+function fail(name, detail) { failed += 1; results.push({ name, ok: false }); console.error(` FAIL ${name} - ${detail}`); }+function check(name, cond, detail) { if (cond) pass(name, detail); else fail(name, detail); return !!cond; }++const cleanup = [];+async function shutdown() {+ for (const fn of cleanup.splice(0).reverse()) { try { await fn(); } catch { /* best effort */ } }+}+process.on('SIGINT', async () => { await shutdown(); process.exit(130); });++function run(cmd, args, opts = {}) {+ const r = spawnSync(cmd, args, { encoding: 'utf8', ...opts });+ return { code: r.status, out: (r.stdout || '') + (r.stderr || '') };+}++async function waitFor(fn, { tries = 90, delayMs = 500, label = 'dependency' } = {}) {+ for (let i = 0; i < tries; i++) {+ try { const v = await fn(); if (v) return v; } catch { /* not ready */ }+ await new Promise((r) => setTimeout(r, delayMs));+ }+ throw new Error(`timed out waiting for ${label}`);+}++async function portFree(port) {+ return new Promise((resolve) => {+ const s = net.createServer();+ s.once('error', () => resolve(false));+ s.once('listening', () => s.close(() => resolve(true)));+ s.listen(port, '127.0.0.1');+ });+}++async function loadPg() {+ try { return await import('pg'); } catch {+ console.log(' installing pg (--no-save) for the local Postgres bridge');+ const r = run('npm', ['i', '--no-save', '--no-audit', '--no-fund', 'pg'], { cwd: root });+ if (r.code !== 0) throw new Error(`npm i pg failed: ${r.out.slice(-400)}`);+ return await import('pg');+ }+}++// ── neon HTTP shim: bridges api/_lib/db.js (neon serverless HTTP driver) onto+// the local Postgres, serializing per column type so the driver sees the same+// JSON shapes Neon's own endpoint returns.+function startShim() {+ fs.mkdirSync(TMP, { recursive: true });+ const shimPath = path.join(TMP, 'shim.mjs');+ const preloadPath = path.join(TMP, 'preload.mjs');+ fs.writeFileSync(shimPath, `+import http from 'node:http';+import pg from ${JSON.stringify(path.join(root, 'node_modules/pg/esm/index.mjs'))};+const pool = new pg.Pool({ connectionString: ${JSON.stringify(PG_URL)}, max: 8 });+const NUMERIC_OIDS = new Set([700, 701, 1700]);+const INT_OIDS = new Set([20, 21, 23, 26]);+const JSON_OIDS = new Set([114, 3802]);+function coerce(value, oid) {+ if (value === null || value === undefined) return null;+ if (oid === 16) return value === 't' || value === 'true';+ if (INT_OIDS.has(oid)) { const n = BigInt(value); return n <= 9007199254740991n && n >= -9007199254740991n ? Number(n) : value; }+ if (NUMERIC_OIDS.has(oid)) return Number(value);+ if (JSON_OIDS.has(oid)) { try { return JSON.parse(value); } catch { return value; } }+ return value;+}+http.createServer(async (req, res) => {+ if (req.method !== 'POST') { res.writeHead(405); res.end(); return; }+ let body = '';+ for await (const c of req) body += c;+ try {+ const { query, params } = JSON.parse(body || '{}');+ const r = await pool.query({+ text: query, values: params || [], rowMode: 'array',+ types: { getTypeParser: () => (v) => v },+ });+ const rows = r.rows.map((row) => row.map((v, i) => coerce(v, r.fields[i].dataTypeID)));+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({+ fields: r.fields.map((f) => ({ name: f.name, dataTypeID: f.dataTypeID })),+ rows, rowCount: r.rowCount, command: r.command,+ }));+ } catch (e) {+ res.writeHead(500, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ message: String(e && e.message || e), code: e && e.code, constraint: e && e.constraint }));+ }+}).listen(${SHIM_PORT}, '127.0.0.1');+`);+ fs.writeFileSync(preloadPath, `+import { neonConfig } from ${JSON.stringify(path.join(root, 'node_modules/@neondatabase/serverless/index.mjs'))};+neonConfig.fetchEndpoint = () => ${JSON.stringify(SHIM_URL)};+`);+ const shim = spawn('node', [shimPath], { stdio: 'inherit' });+ cleanup.push(() => shim.kill('SIGKILL'));+ return { preloadPath };+}++// ── HTTP client with a cookie jar ────────────────────────────────────────────+function makeHttp() {+ const cookies = new Map();+ function capture(res) {+ const set = res.headers.getSetCookie ? res.headers.getSetCookie() : [];+ for (const c of set) {+ const [pair] = c.split(';');+ const i = pair.indexOf('=');+ cookies.set(pair.slice(0, i).trim(), pair.slice(i + 1).trim());+ }+ }+ async function req(method, p, { body, headers = {}, raw } = {}) {+ const res = await fetch(BASE + p, {+ method,+ headers: {+ cookie: [...cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; '),+ ...(body !== undefined ? { 'content-type': 'application/json' } : {}),+ ...headers,+ },+ body: raw !== undefined ? raw : body !== undefined ? JSON.stringify(body) : undefined,+ redirect: 'manual',+ });+ capture(res);+ const text = await res.text();+ let json = null;+ try { json = JSON.parse(text); } catch { /* html or empty */ }+ return { status: res.status, json, text, headers: res.headers };+ }+ async function csrf() {+ const r = await req('GET', '/api/csrf-token');+ if (r.status !== 200 || !r.json?.token) throw new Error(`csrf-token failed: ${r.status} ${r.text.slice(0, 200)}`);+ return r.json.token;+ }+ // Every authenticated write below goes through here, so a missing CSRF token+ // can never silently turn into a "the endpoint accepted it" pass.+ async function post(p, body) {+ return req('POST', p, { body, headers: { 'x-csrf-token': await csrf() } });+ }+ return { req, post, csrf, cookies };+}++async function main() {+ console.log('genome endpoints proof - real Postgres, real HTTP route table, no funds move\n');++ step('0. environment');+ for (const [port, name] of [[PG_PORT, 'postgres'], [SHIM_PORT, 'shim'], [HTTP_PORT, 'http']]) {+ if (!(await portFree(port))) throw new Error(`port ${port} (${name}) is in use`);+ }+ check('docker available', run('docker', ['--version']).code === 0);+ run('docker', ['rm', '-f', PG_CONTAINER]);+ const up = run('docker', [+ 'run', '-d', '--name', PG_CONTAINER,+ '-e', 'POSTGRES_HOST_AUTH_METHOD=trust', '-e', 'POSTGRES_DB=proof',+ '-p', `${PG_PORT}:5432`, 'postgres:16',+ ]);+ if (up.code !== 0) throw new Error(`docker run failed: ${up.out}`);+ if (!KEEP) cleanup.push(() => run('docker', ['rm', '-f', PG_CONTAINER]));+ cleanup.push(() => fs.rmSync(TMP, { recursive: true, force: true }));+ pass('throwaway postgres started', `${PG_CONTAINER} on :${PG_PORT}`);++ const pg = await loadPg();+ let db = null;+ await waitFor(async () => {+ const c = new pg.Client(PG_URL);+ c.on('error', () => {});+ await c.connect();+ await c.query('select 1');+ db = c;+ return true;+ }, { label: 'postgres accepting queries' });+ cleanup.push(() => db?.end().catch(() => {}));+ pass('postgres accepting queries');++ step('1. schema');+ const migrationsDir = path.join(root, 'api/_lib/migrations');+ const files = [+ path.join(migrationsDir, '2026-04-30-notifications.sql'),+ path.join(root, 'api/_lib/schema.sql'),+ ...fs.readdirSync(migrationsDir).filter((f) => f.endsWith('.sql')).sort().map((f) => path.join(migrationsDir, f)),+ ];+ let applied = 0;+ for (const f of files) {+ const r = run('docker', ['exec', '-i', PG_CONTAINER, 'psql', '-U', 'postgres', '-d', 'proof', '-v', 'ON_ERROR_STOP=1', '-q'], { input: fs.readFileSync(f, 'utf8') });+ if (r.code === 0) applied += 1;+ }+ const required = ['users', 'sessions', 'csrf_tokens', 'agent_identities', 'genome_breedings'];+ const missing = [];+ for (const t of required) {+ const { rows } = await db.query('select to_regclass($1) as r', [`public.${t}`]);+ if (!rows[0].r) missing.push(t);+ }+ if (missing.length) throw new Error(`required tables missing: ${missing.join(', ')}`);+ check('schema applied', applied > 0, `${applied}/${files.length} files applied; ${required.join(', ')} present`);+ // The audit's own migration must be in effect, or breed.js records a fee it+ // cannot persist and the stud-fee replay guard is not atomic.+ const { rows: feeCols } = await db.query(+ `select column_name from information_schema.columns where table_name = 'genome_breedings' and column_name = 'stud_fee_atomics'`,+ );+ const { rows: feeIdx } = await db.query(+ `select indexname from pg_indexes where tablename = 'genome_breedings' and indexname = 'genome_breedings_stud_fee_signature'`,+ );+ check('stud-fee integrity migration applied', feeCols.length === 1 && feeIdx.length === 1,+ `stud_fee_atomics column ${feeCols.length === 1 ? 'present' : 'MISSING'}, unique signature index ${feeIdx.length === 1 ? 'present' : 'MISSING'}`);++ step('2. seed real rows');+ const stamp = process.env.GENOME_PROOF_STAMP || String(process.pid);+ const { rows: [owner] } = await db.query(+ `insert into users (email, password_hash, email_verified) values ($1, 'x', true) returning id`,+ [`genome-owner-${stamp}@proof.local`],+ );+ const { rows: [stranger] } = await db.query(+ `insert into users (email, password_hash, email_verified) values ($1, 'x', true) returning id`,+ [`genome-stranger-${stamp}@proof.local`],+ );+ const mkAgent = async (userId, name, meta = {}, isPublic = true) => {+ const { rows: [a] } = await db.query(+ `insert into agent_identities (user_id, name, is_public, skills, persona_tone_tags,+ voice_provider, voice_id, voice_model, voice_settings, meta)+ values ($1, $2, $3, $4::jsonb, $5::jsonb, 'elevenlabs', $6, 'eleven_flash_v2_5', $7::jsonb, $8::jsonb)+ returning id`,+ [userId, name, isPublic, JSON.stringify(['trading', 'research']), JSON.stringify(['precise']),+ `voice-${name}`, JSON.stringify({ stability: 0.4, similarity_boost: 0.8, style: 0.3, use_speaker_boost: true }),+ JSON.stringify(meta)],+ );+ return a.id;+ };+ const parentA = await mkAgent(owner.id, 'Proof Parent A', { solana_address: 'ProofSolA1111111111111111111111111111111111' });+ const parentB = await mkAgent(owner.id, 'Proof Parent B', { solana_address: 'ProofSolB2222222222222222222222222222222222' });+ const paidStud = await mkAgent(stranger.id, 'Proof Paid Stud', {+ solana_address: 'ProofSolS3333333333333333333333333333333333',+ genome_breeding: { breedable: true, stud: true, stud_fee_three: 25 },+ });+ const privateAgent = await mkAgent(stranger.id, 'Proof Private', {}, false);+ pass('users + agents seeded', `owner=${owner.id.slice(0, 8)} parents=${parentA.slice(0, 8)},${parentB.slice(0, 8)} stud=${paidStud.slice(0, 8)}`);++ // A real session cookie for the owner, minted the way api/_lib/auth.js reads it.+ const sessionToken = crypto.randomBytes(32).toString('hex');+ const sessionHash = crypto.createHash('sha256').update(sessionToken).digest('hex');+ await db.query(+ `insert into sessions (user_id, token_hash, expires_at) values ($1, $2, now() + interval '1 day')`,+ [owner.id, sessionHash],+ );+ pass('owner session minted');++ step('3. start the real server on the local database');+ const { preloadPath } = startShim();+ await waitFor(async () => {+ const r = await fetch(SHIM_URL, { method: 'POST', body: JSON.stringify({ query: 'select 1', params: [] }) });+ return r.ok;+ }, { label: 'sql shim' });+ pass('neon HTTP shim up', SHIM_URL);++ const server = spawn('node', ['--import', preloadPath, path.join(root, 'server/index.mjs')], {+ cwd: root,+ stdio: ['ignore', 'pipe', 'pipe'],+ env: {+ ...process.env,+ PORT: String(HTTP_PORT),+ DATABASE_URL: PG_URL,+ NODE_ENV: 'development',+ SESSION_SECRET: process.env.SESSION_SECRET || crypto.randomBytes(32).toString('hex'),+ JWT_SECRET: process.env.JWT_SECRET || crypto.randomBytes(32).toString('hex'),+ },+ });+ const serverLog = [];+ server.stdout.on('data', (d) => serverLog.push(String(d)));+ server.stderr.on('data', (d) => serverLog.push(String(d)));+ cleanup.push(() => server.kill('SIGKILL'));+ await waitFor(async () => {+ const r = await fetch(`${BASE}/api/genome/edges?limit=1`);+ return r.status === 200;+ }, { label: 'api server', tries: 120 });+ pass('server listening on the proof database', BASE);++ const http = makeHttp();+ const anon = makeHttp();+ http.cookies.set('session', sessionToken);++ // ── 4. edges ──────────────────────────────────────────────────────────────+ step('4. GET /api/genome/edges');+ const edges0 = await anon.req('GET', '/api/genome/edges?limit=5');+ check('edges 200 public JSON', edges0.status === 200 && Array.isArray(edges0.json?.edges),+ `status ${edges0.status}, ${edges0.json?.edges?.length ?? 'no'} edges, cache-control "${edges0.headers.get('cache-control')}"`);+ const edgesBad = await anon.req('GET', '/api/genome/edges?limit=not-a-number');+ check('edges clamps junk limit instead of erroring', edgesBad.status === 200, `status ${edgesBad.status}`);+ const edgesPost = await anon.req('POST', '/api/genome/edges', { body: {} });+ check('edges rejects POST with 405 JSON', edgesPost.status === 405 && !!edgesPost.json, `status ${edgesPost.status}, body ${edgesPost.text.slice(0, 80)}`);++ // ── 5. stud market ────────────────────────────────────────────────────────+ step('5. GET/POST /api/genome/stud');+ const studs0 = await anon.req('GET', '/api/genome/stud');+ check('stud GET lists the seeded paid stud', studs0.status === 200 && studs0.json?.studs?.some((s) => s.id === paidStud),+ `status ${studs0.status}, ${studs0.json?.studs?.length ?? 0} listed`);+ const studAnon = await anon.req('POST', '/api/genome/stud', { body: { agent_id: parentA, stud: true } });+ check('stud POST is 401 without a session', studAnon.status === 401, `status ${studAnon.status}`);+ const noCsrf = await http.req('POST', '/api/genome/stud', { body: { agent_id: parentA, stud: true } });+ check('stud POST is 403 without a CSRF token', noCsrf.status === 403, `status ${noCsrf.status} ${noCsrf.json?.error || ''}`);+ const notOwned = await http.post('/api/genome/stud', { agent_id: paidStud, stud: true });+ check('stud POST refuses an agent you do not own', notOwned.status === 403, `status ${notOwned.status} ${notOwned.json?.error || ''}`);+ const badId = await http.post('/api/genome/stud', { agent_id: 'nope' });+ check('stud POST rejects a malformed id with 400 JSON', badId.status === 400 && badId.json?.error === 'validation_error', `status ${badId.status}`);+ const missing = await http.post('/api/genome/stud', { agent_id: '11111111-1111-4111-8111-111111111111' });+ check('stud POST 404s an unknown agent', missing.status === 404, `status ${missing.status}`);++ // Poison meta with a sibling key, then list: the write must preserve it.+ await db.query(`update agent_identities set meta = meta || '{"sentinel":"keep-me"}'::jsonb where id = $1`, [parentA]);+ const listed = await http.post('/api/genome/stud', { agent_id: parentA, stud: true, stud_fee_three: 40 });+ check('stud POST lists the agent at the requested fee',+ listed.status === 200 && listed.json?.genome_breeding?.stud === true && listed.json?.genome_breeding?.stud_fee_three === 40,+ JSON.stringify(listed.json?.genome_breeding));+ const { rows: [afterList] } = await db.query('select meta from agent_identities where id = $1', [parentA]);+ check('stud POST preserves unrelated meta keys', afterList.meta.sentinel === 'keep-me' && afterList.meta.solana_address,+ `sentinel=${afterList.meta.sentinel}, wallet ${afterList.meta.solana_address ? 'intact' : 'LOST'}`);++ // PATCH semantics: a fee-only body must not silently unlist the agent.+ const feeOnly = await http.post('/api/genome/stud', { agent_id: parentA, stud_fee_three: 12 });+ check('a fee-only update keeps the agent listed',+ feeOnly.status === 200 && feeOnly.json?.genome_breeding?.stud === true && feeOnly.json?.genome_breeding?.stud_fee_three === 12,+ JSON.stringify(feeOnly.json?.genome_breeding));+ const junkFee = await http.post('/api/genome/stud', { agent_id: parentA, stud_fee_three: 'free-please' });+ check('a junk fee clamps to 0 rather than 500ing',+ junkFee.status === 200 && junkFee.json?.genome_breeding?.stud_fee_three === 0, JSON.stringify(junkFee.json?.genome_breeding));+ const hugeFee = await http.post('/api/genome/stud', { agent_id: parentA, stud_fee_three: 9e18 });+ check('an absurd fee clamps to the ceiling',+ hugeFee.status === 200 && hugeFee.json?.genome_breeding?.stud_fee_three === 1_000_000, JSON.stringify(hugeFee.json?.genome_breeding));+ const unlisted = await http.post('/api/genome/stud', { agent_id: parentA, stud: false });+ check('unlisting works and keeps the fee on record',+ unlisted.status === 200 && unlisted.json?.genome_breeding?.stud === false, JSON.stringify(unlisted.json?.genome_breeding));+ const studsAfter = await anon.req('GET', '/api/genome/stud');+ check('an unlisted agent leaves the public market', !studsAfter.json?.studs?.some((s) => s.id === parentA));++ // ── 6. preview ────────────────────────────────────────────────────────────+ step('6. POST /api/genome/preview');+ const prevAnon = await anon.req('POST', '/api/genome/preview', { body: { parent_a: parentA, parent_b: parentB } });+ check('preview requires auth', prevAnon.status === 401, `status ${prevAnon.status}`);+ const prevSelf = await http.post('/api/genome/preview', { parent_a: parentA, parent_b: parentA });+ check('preview rejects self-breeding with 400 JSON', prevSelf.status === 400 && prevSelf.json?.error === 'validation_error', `status ${prevSelf.status}`);+ const prevJunk = await http.post('/api/genome/preview', { parent_a: 'x', parent_b: 'y' });+ check('preview rejects malformed ids with 400 JSON', prevJunk.status === 400, `status ${prevJunk.status}`);+ const prevPrivate = await http.post('/api/genome/preview', { parent_a: parentA, parent_b: privateAgent });+ check('preview refuses a private agent you do not own',+ prevPrivate.status === 403 && prevPrivate.json?.error === 'parent_ineligible', `status ${prevPrivate.status} ${prevPrivate.json?.reason || ''}`);+ const prevNotJson = await http.req('POST', '/api/genome/preview', { raw: 'not json', headers: { 'content-type': 'text/plain' } });+ check('preview rejects a non-JSON body with a JSON error, not a stack trace',+ prevNotJson.status === 415 && !!prevNotJson.json && !/at \w+ \(/.test(prevNotJson.text), `status ${prevNotJson.status} ${prevNotJson.text.slice(0, 90)}`);+ const preview1 = await http.post('/api/genome/preview', { parent_a: parentA, parent_b: parentB, seed: 'proof-seed' });+ check('preview derives a real child genome',+ preview1.status === 200 && preview1.json?.genome?.generation === 1 && Array.isArray(preview1.json?.genome?.skills),+ `gen ${preview1.json?.genome?.generation}, ${preview1.json?.genome?.skills?.length} skill alleles, tier ${preview1.json?.genome?.pedigree?.tier}`);+ const preview2 = await http.post('/api/genome/preview', { parent_a: parentA, parent_b: parentB, seed: 'proof-seed' });+ check('the same seed derives a byte-identical child',+ JSON.stringify(preview1.json?.genome) === JSON.stringify(preview2.json?.genome));+ const preview3 = await http.post('/api/genome/preview', { parent_a: parentA, parent_b: parentB, seed: 'other-seed' });+ check('a different seed derives a different child',+ JSON.stringify(preview1.json?.genome) !== JSON.stringify(preview3.json?.genome));+ const longName = await http.post('/api/genome/preview', { parent_a: parentA, parent_b: parentB, name: 'z'.repeat(500) });+ check('preview caps the child name at breed.js\'s 80 chars',+ longName.status === 200 && longName.json?.child_name?.length === 80, `name length ${longName.json?.child_name?.length}`);+ const studPreview = await http.post('/api/genome/preview', { parent_a: parentA, parent_b: paidStud });+ check('preview quotes the cross-owner stud fee up front',+ studPreview.status === 200 && studPreview.json?.stud_fee_three === 25 && studPreview.json?.consent_required === true,+ `fee ${studPreview.json?.stud_fee_three} $THREE, consent ${studPreview.json?.consent_required}`);++ // ── 7. breed (boundaries only; no settlement is ever trusted here) ─────────+ step('7. POST /api/genome/breed');+ const breedAnon = await anon.req('POST', '/api/genome/breed', { body: { parent_a: parentA, parent_b: parentB } });+ check('breed requires auth', breedAnon.status === 401, `status ${breedAnon.status}`);+ const breedNoCsrf = await http.req('POST', '/api/genome/breed', { body: { parent_a: parentA, parent_b: parentB } });+ check('breed requires CSRF on a cookie session', breedNoCsrf.status === 403, `status ${breedNoCsrf.status}`);+ const breedSelf = await http.post('/api/genome/breed', { parent_a: parentA, parent_b: parentA });+ check('breed rejects self-breeding', breedSelf.status === 400, `status ${breedSelf.status}`);+ const breedMissing = await http.post('/api/genome/breed', { parent_a: parentA, parent_b: '11111111-1111-4111-8111-111111111111' });+ check('breed 404s an unknown parent', breedMissing.status === 404, `status ${breedMissing.status}`);+ const breedPaid = await http.post('/api/genome/breed', { parent_a: parentA, parent_b: paidStud });+ check('breed 402s a fee-bearing stud with the exact $THREE terms',+ breedPaid.status === 402 && breedPaid.json?.error === 'stud_fee_required' && breedPaid.json?.stud_fee_three === 25 && breedPaid.json?.coin === '$THREE',+ `status ${breedPaid.status} ${breedPaid.json?.error} ${breedPaid.json?.stud_fee_three} ${breedPaid.json?.coin}`);+ const breedBadSig = await http.post('/api/genome/breed', { parent_a: parentA, parent_b: paidStud, stud_fee_signature: 'not-a-signature' });+ check('a bogus settlement signature is refused, never trusted',+ breedBadSig.status === 402 && breedBadSig.json?.error === 'stud_fee_unverified',+ `status ${breedBadSig.status} ${breedBadSig.json?.error}`);++ // Cooldown must be decided BEFORE the fee gate, so a breeder is never charged+ // for a breeding that was always going to be refused.+ await db.query(+ `insert into genome_breedings (breeding_key, parent_a_agent_id, parent_b_agent_id, child_agent_id,+ seed, genome, genome_hash, generation, pedigree_tier, bred_by, status)+ values ($1, $2, $3, null, 'cooldown-seed', '{}'::jsonb, 'x', 1, 'common', $4, 'born')`,+ [`cooldown-${stamp}`, parentA, parentB, owner.id],+ );+ const cooled = await http.post('/api/genome/breed', { parent_a: parentA, parent_b: paidStud });+ check('a parent on cooldown 409s BEFORE the 402 fee demand',+ cooled.status === 409 && cooled.json?.error === 'breeding_cooldown' && cooled.json?.cooldown_remaining_ms > 0,+ `status ${cooled.status} ${cooled.json?.error}, ${cooled.json?.cooldown_remaining_min} min left`);+ await db.query('delete from genome_breedings where breeding_key = $1', [`cooldown-${stamp}`]);++ // ── 8. lineage over a recorded breeding ───────────────────────────────────+ step('8. GET /api/genome/lineage');+ const badAgent = await anon.req('GET', '/api/genome/lineage?agentId=nope');+ check('lineage rejects a malformed id with 400 JSON', badAgent.status === 400 && badAgent.json?.error === 'validation_error', `status ${badAgent.status}`);+ const noAgent = await anon.req('GET', '/api/genome/lineage?agentId=11111111-1111-4111-8111-111111111111');+ check('lineage 404s an unknown agent', noAgent.status === 404, `status ${noAgent.status}`);++ // Record a real breeding the way breed.js does, deriving the genome with the+ // same pure module the endpoint uses, so verify=1 has something honest to check.+ const { deriveGenome, hashGenome, genomeFromAgent } = await import(path.join(root, 'api/_lib/genome.js'));+ const rowFor = async (id) => {+ const { rows: [r] } = await db.query('select * from agent_identities where id = $1', [id]);+ return genomeFromAgent({+ id: r.id, meta: r.meta || {}, persona_tone_tags: r.persona_tone_tags || [],+ voice_provider: r.voice_provider, voice_id: r.voice_id, voice_model: r.voice_model,+ voice_settings: r.voice_settings, appearance: {}, skills: r.skills || [], avatar_id: r.avatar_id,+ });+ };+ const gA = await rowFor(parentA);+ const gB = await rowFor(parentB);+ const seed = 'lineage-proof-seed';+ const childGenome = deriveGenome({ parentA: gA, parentB: gB, seed });+ const childMeta = {+ genome: childGenome,+ bred_from: {+ breeding_key: `lineage-${stamp}`, seed,+ parent_a: { agent_id: parentA, name: 'Proof Parent A', genome: gA },+ parent_b: { agent_id: parentB, name: 'Proof Parent B', genome: gB },+ generation: childGenome.generation,+ },+ };+ const child = await mkAgent(owner.id, 'Proof Child', childMeta);+ await db.query(+ `insert into genome_breedings (breeding_key, parent_a_agent_id, parent_b_agent_id, child_agent_id,+ seed, genome, genome_hash, generation, pedigree_tier, bred_by, status)+ values ($1, $2, $3, $4, $5, $6::jsonb, $7, $8, 'common', $9, 'born')`,+ [`lineage-${stamp}`, parentA, parentB, child, seed, JSON.stringify(childGenome),+ childGenome.genome_hash || hashGenome(childGenome), childGenome.generation, owner.id],+ );+ pass('a real breeding recorded', `child ${child.slice(0, 8)} gen ${childGenome.generation}`);++ const lineChild = await anon.req('GET', `/api/genome/lineage?agentId=${child}`);+ check('lineage on the child shows both parents',+ lineChild.status === 200 && lineChild.json?.bred === true && lineChild.json?.parents?.length === 2,+ `bred=${lineChild.json?.bred}, ${lineChild.json?.parents?.length} parents, ${lineChild.json?.ancestors?.length} ancestors`);+ const lineParent = await anon.req('GET', `/api/genome/lineage?agentId=${parentA}`);+ check('lineage on a parent shows the child and its co-parent',+ lineParent.status === 200 && lineParent.json?.children?.[0]?.id === child && lineParent.json?.children?.[0]?.co_parent?.id === parentB,+ `${lineParent.json?.children?.length} children, co-parent ${lineParent.json?.children?.[0]?.co_parent?.name}`);+ const verified = await anon.req('GET', `/api/genome/lineage?agentId=${child}&verify=1`);+ check('verify=1 re-derives the genome and confirms it',+ verified.status === 200 && verified.json?.verifiable === true && verified.json?.valid === true,+ `verifiable=${verified.json?.verifiable} valid=${verified.json?.valid} hash ${String(verified.json?.genome_hash).slice(0, 16)}`);+ const verifyOff = await anon.req('GET', `/api/genome/lineage?agentId=${child}&verify=0`);+ check('verify=0 returns the tree, not a verification',+ verifyOff.status === 200 && verifyOff.json?.verifiable === undefined && Array.isArray(verifyOff.json?.parents),+ `keys ${Object.keys(verifyOff.json || {}).slice(0, 4).join(',')}`);++ // Forge the child's genome. Verification must catch it: that is the whole point.+ await db.query(+ `update agent_identities set meta = jsonb_set(meta, '{genome,brain,curiosity}', '0.999'::jsonb, true) where id = $1`,+ [child],+ );+ const forged = await anon.req('GET', `/api/genome/lineage?agentId=${child}&verify=1`);+ check('a forged genome fails verification',+ forged.status === 200 && forged.json?.verifiable === true && forged.json?.valid === false,+ `valid=${forged.json?.valid} reason=${forged.json?.reason}`);+ await db.query(+ `update agent_identities set meta = jsonb_set(meta, '{genome}', $2::jsonb, true) where id = $1`,+ [child, JSON.stringify(childGenome)],+ );++ // ── 9. edges reflects the breeding, and drops deleted nodes ───────────────+ step('9. edges over real lineage');+ const edges1 = await anon.req('GET', '/api/genome/edges?limit=100');+ check('the recorded breeding appears as a descent edge',+ edges1.json?.edges?.some((e) => e.child === child && e.a === parentA && e.b === parentB),+ `${edges1.json?.edges?.length} edges`);+ await db.query('update agent_identities set deleted_at = now() where id = $1', [child]);+ const edges2 = await anon.req('GET', '/api/genome/edges?limit=100');+ check('a deleted child leaves no dangling edge on the star map',+ !edges2.json?.edges?.some((e) => e.child === child), `${edges2.json?.edges?.length} edges after delete`);+ await db.query('update agent_identities set deleted_at = null where id = $1', [child]);++ step('10. no handler leaked an HTML error page or a stack trace');+ const unhandled = serverLog.join('').match(/\[api\] unhandled/g) || [];+ check('server logged no unhandled exception', unhandled.length === 0, `${unhandled.length} unhandled`);++ console.log(`\n${failed === 0 ? 'ALL CHECKS PASSED' : `${failed} CHECK(S) FAILED`} - ${results.length} assertions`);+ if (KEEP) console.log(`postgres left running: ${PG_CONTAINER} (${PG_URL})`);+}++main()+ .then(async () => { await shutdown(); process.exit(failed === 0 ? 0 : 1); })+ .catch(async (e) => { console.error('\nPROOF ABORTED:', e?.message || e); await shutdown(); process.exit(2); });diff --git a/specs/ECONOMY_CONTRACT_INVARIANTS.md b/specs/ECONOMY_CONTRACT_INVARIANTS.mdindex 94a7caaed..ea58ac0ed 100644--- a/specs/ECONOMY_CONTRACT_INVARIANTS.md+++ b/specs/ECONOMY_CONTRACT_INVARIANTS.md@@ -8,9 +8,15 @@ vectors against agent *registration*, this one states the properties theRead this together with:-- [`contracts/AUDIT-README.md`](../contracts/AUDIT-README.md) - the entry point for a review: scope, versions, build and test commands, deploy status.-- [`contracts/THREAT_MODEL.md`](../contracts/THREAT_MODEL.md) - assets, actors, trust boundaries, and failure modes per contract.-- [`contracts/audit/`](../contracts/audit) - committed static-analysis output and the written disposition of every finding.+- [`contracts/README.md`](../contracts/README.md) - what each registry is, plus the build and test commands a reviewer runs first.+- [`contracts/DEPLOYMENTS.md`](../contracts/DEPLOYMENTS.md) - the deploy-status table: which bytecode is live, at which address, on which chains, and how each address is verified.+- [`SECURITY.md`](./SECURITY.md) - the abuse vectors against agent registration that sit upstream of these contracts.++A dedicated audit pack (a single review entry point plus a per-contract threat+model and committed static-analysis findings) is scoped in+[`prompts/swarm-100/roadmap-p3-contracts-audit-pack.md`](../prompts/swarm-100/roadmap-p3-contracts-audit-pack.md)+and has not been written yet. Until it lands, this document plus the two files+above are the review surface.## How to read an invariant@@ -26,7 +32,7 @@ break it). The test that proves an invariant names its id in a comment, so`grep -rn "AP-7" contracts/test` finds the proof.Invariants marked **[deployed]** govern bytecode that is already live on a public-chain (see the deploy-status table in `contracts/AUDIT-README.md`). Those are the+chain (see the deploy-status table in [`contracts/DEPLOYMENTS.md`](../contracts/DEPLOYMENTS.md)). Those are theones where a violation is an incident rather than a bug.---diff --git a/src/agent-screen.js b/src/agent-screen.jsindex b66ec0876..59e3cb2fa 100644--- a/src/agent-screen.js+++ b/src/agent-screen.js@@ -1894,8 +1894,8 @@ async function boot(id) {if (!token) { hmTooltip.hidden = true; return; }const pct = (n) => (n == null ? '—' : `${n >= 0 ? '+' : ''}${Number(n).toFixed(1)}%`);const vol = token.volume24h ? `$${Intl.NumberFormat('en', { notation: 'compact' }).format(token.volume24h)}` : '—';- const sent = token.sentiment && Number.isFinite(token.sentiment.score)- ? `<div class="asc-hm-tip-row"><span>sentiment</span><b>${token.sentiment.posPct}% bullish</b></div>` : '';+ const sent = token.flow && Number.isFinite(token.flow.score)+ ? `<div class="asc-hm-tip-row"><span>24h flow</span><b>${token.flow.buyPct}% buys</b></div>` : '';hmTooltip.innerHTML = `<div class="asc-hm-tip-head">${esc(token.label)}${token.featured ? ' <span class="asc-hm-tip-anchor">$THREE</span>' : ''}</div><div class="asc-hm-tip-row"><span>momentum</span><b>${pct(token.change24h)}</b></div>diff --git a/src/conversions.js b/src/conversions.jsindex e939e76dd..2ea8a6f7d 100644--- a/src/conversions.js+++ b/src/conversions.js@@ -155,7 +155,7 @@ function renderSeller(data) {{ value: s.sold, label: 'Converted to sales' },{value: s.potential.display,- unit: mintLabel(data.queue.find((q) => q.price)?.price.mint),+ unit: mintLabel(s.potential.mint),label: 'Sitting in the queue',tone: 'money',},diff --git a/src/genome.js b/src/genome.jsindex c4285a61c..5c31c6360 100644--- a/src/genome.js+++ b/src/genome.js@@ -17,6 +17,7 @@ const state = {preview: null,picking: null, // 'a' | 'b'busy: false,+ signedIn: false,};// ── Boot ─────────────────────────────────────────────────────────────────────@@ -54,9 +55,11 @@ async function loadMyAgents() {if (r.status === 401) { note('Sign in to breed your agents.', 'error'); return; }const j = await r.json();state.myAgents = (j.agents || []).map(normalizeAgent);+ state.signedIn = true;} catch (e) {note('Could not load your agents — check your connection and retry.', 'error');}+ renderMyStuds();}async function loadStuds() {@@ -76,6 +79,9 @@ function normalizeAgent(a) {generation: a.meta?.genome?.generation ?? 0,fee: 0,cross_owner: false,+ is_public: a.is_public !== false,+ listed: a.is_stud === true,+ listed_fee: Math.max(0, Number(a.stud_fee_three) || 0),};}@@ -365,7 +371,7 @@ async function playVoice(voice) {function renderStuds(studs) {const host = $('gnStuds');if (!studs.length) {- host.innerHTML = `<p class="gn-pick-sub">No agents are open for stud yet. Open one of yours from its profile to list it here.</p>`;+ host.innerHTML = `<p class="gn-pick-sub">No agents are open for stud yet. Open one of yours for breeding under <a class="gn-hero-link" href="#gnMyStudsSection">Your stud listings</a> below and it appears here.</p>`;return;}host.innerHTML = studs@@ -391,6 +397,106 @@ function renderStuds(studs) {});}+// ── Your stud listings (the supply side of the market) ───────────────────────+function renderMyStuds() {+ const section = $('gnMyStudsSection');+ const host = $('gnMyStuds');+ if (!section || !host) return;+ if (!state.signedIn) { section.hidden = true; return; }+ section.hidden = false;+ if (!state.myAgents.length) {+ host.innerHTML = `<p class="gn-pick-sub">You have no agents to list yet. <a href="/create">Create one →</a></p>`;+ return;+ }+ host.innerHTML = state.myAgents.map(myStudCard).join('');+ host.querySelectorAll('.gn-mystud').forEach(wireMyStud);+}++function myStudCard(a) {+ // A private agent can't be a stud: /api/genome/stud only lists public agents,+ // so say that here instead of letting the toggle look broken.+ const blocked = !a.is_public;+ return `<div class="gn-mystud" data-id="${escapeAttr(a.id)}" data-listed="${a.listed}">+ <div class="gn-mystud-head">+ <span class="gn-mystud-name" title="${escapeAttr(a.name)}">${escapeHtml(a.name)}</span>+ <span class="gn-pick-sub">gen ${a.generation}</span>+ </div>+ <label class="gn-switch">+ <input type="checkbox" class="gn-mystud-toggle" ${a.listed ? 'checked' : ''} ${blocked ? 'disabled' : ''}+ aria-label="List ${escapeAttr(a.name)} in the stud market" />+ <span class="gn-switch-track" aria-hidden="true"></span>+ <span>${a.listed ? 'Listed for stud' : 'Not listed'}</span>+ </label>+ <div class="gn-mystud-row">+ <label class="gn-pick-sub" for="fee-${escapeAttr(a.id)}">Fee</label>+ <input class="gn-fee-input" id="fee-${escapeAttr(a.id)}" type="number" min="0" step="1" inputmode="numeric"+ value="${a.listed_fee}" ${blocked ? 'disabled' : ''} aria-label="Stud fee in THREE for ${escapeAttr(a.name)}" />+ <span class="gn-pick-sub">$THREE</span>+ </div>+ <div class="gn-mystud-state"${blocked ? ' data-kind="error"' : ''}>${blocked ? 'Make this agent public to open it for stud.' : ''}</div>+ </div>`;+}++function wireMyStud(card) {+ const toggle = card.querySelector('.gn-mystud-toggle');+ const fee = card.querySelector('.gn-fee-input');+ if (!toggle || toggle.disabled) return;+ toggle.addEventListener('change', () => saveStud(card, { stud: toggle.checked }));+ // Commit the fee on blur and on Enter, never on every keystroke.+ fee.addEventListener('change', () => saveStud(card, { stud_fee_three: Math.max(0, Number(fee.value) || 0) }));+ fee.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); fee.blur(); } });+}++async function saveStud(card, patch) {+ const id = card.dataset.id;+ const agent = state.myAgents.find((x) => x.id === id);+ const status = card.querySelector('.gn-mystud-state');+ const toggle = card.querySelector('.gn-mystud-toggle');+ const fee = card.querySelector('.gn-fee-input');+ toggle.disabled = true;+ fee.disabled = true;+ status.removeAttribute('data-kind');+ status.textContent = 'Saving…';+ try {+ const r = await apiFetch('/api/genome/stud', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agent_id: id, ...patch }),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) {+ status.dataset.kind = 'error';+ status.textContent = j.error_description || 'Could not save that listing. Retry in a moment.';+ // Snap the controls back to the last state the server confirmed.+ toggle.checked = !!agent?.listed;+ fee.value = agent?.listed_fee ?? 0;+ return;+ }+ const policy = j.genome_breeding || {};+ if (agent) {+ agent.listed = policy.stud === true;+ agent.listed_fee = Math.max(0, Number(policy.stud_fee_three) || 0);+ }+ toggle.checked = !!agent?.listed;+ fee.value = agent?.listed_fee ?? 0;+ card.dataset.listed = String(!!agent?.listed);+ card.querySelector('.gn-switch span:last-child').textContent = agent?.listed ? 'Listed for stud' : 'Not listed';+ status.dataset.kind = 'ok';+ status.textContent = agent?.listed+ ? `Open for stud at ${agent.listed_fee} $THREE.`+ : 'Unlisted. Nobody can breed with this agent.';+ loadStuds();+ } catch {+ status.dataset.kind = 'error';+ status.textContent = 'Network error. Your listing was not changed.';+ toggle.checked = !!agent?.listed;+ fee.value = agent?.listed_fee ?? 0;+ } finally {+ toggle.disabled = false;+ fee.disabled = false;+ }+}+// ── Helpers ──────────────────────────────────────────────────────────────────function tierBadge(p) {const tier = (p && p.tier) || 'common';diff --git a/src/marketplace.js b/src/marketplace.jsindex 667af47b8..f677fa6f9 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -2010,7 +2010,6 @@ async function manageSubscription(subId, btn) {try {const token = await getCsrfToken();- _csrf = null;const r = await fetch(`/api/subscriptions/${encodeURIComponent(subId)}`, {method: 'DELETE',headers: { 'X-CSRF-Token': token },@@ -3509,17 +3508,12 @@ function bindAgentPricingModal() {try {await Promise.all(rows.map(async (row) => {const amount = Math.round(parseFloat(row.amount_usd || '0') * 1e6);- const r = await fetch(`${API}/marketplace/set-skill-price`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- credentials: 'include',- body: JSON.stringify({- agent_id: agentId,- skill: row.skill,- amount,- currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',- chain: 'solana',- }),+ const r = await apiPostWithCsrf(`${API}/marketplace/set-skill-price`, {+ agent_id: agentId,+ skill: row.skill,+ amount,+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ chain: 'solana',});if (!r.ok) {const j = await r.json().catch(() => ({}));@@ -5714,7 +5708,6 @@ async function deleteReview() {reviewsState.submitting = true;try {const token = await getCsrfToken();- _csrf = null;const r = await fetch(`${API}/marketplace/agents/${reviewsState.agentId}/reviews`, {method: 'DELETE',headers: { 'X-CSRF-Token': token },@@ -6442,17 +6435,12 @@ function bindSubmit() {Promise.all(sfPriceRows.map((row) => {const amount = Math.round(parseFloat(row.amount_usd || '0') * 1e6);if (!amount) return Promise.resolve();- return fetch(`${API}/marketplace/set-skill-price`, {- method: 'POST',- headers: { 'content-type': 'application/json' },- credentials: 'include',- body: JSON.stringify({- agent_id: agentId,- skill: row.skill,- amount,- currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',- chain: 'solana',- }),+ return apiPostWithCsrf(`${API}/marketplace/set-skill-price`, {+ agent_id: agentId,+ skill: row.skill,+ amount,+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ chain: 'solana',});})).catch(() => {});}@@ -7263,19 +7251,19 @@ async function openPurchaseFlow(agentId, skill) {updateWalletUI();}-// CSRF token cache; single-use, refetched lazily.-let _csrf = null;+// A CSRF token is consumed by the request that presents it (the API deletes+// the row in the same statement that validates it), so every write fetches its+// own. Caching one is not an optimization here: two writes issued together (a+// bulk price save fans out one request per skill) would read the same cached+// token and the second would come back 403.async function getCsrfToken() {- if (_csrf && _csrf.expiresAt > Date.now() + 5_000) return _csrf.token;const r = await fetch('/api/csrf-token', { credentials: 'include' });if (!r.ok) throw new Error('Could not obtain CSRF token; sign in again.');const j = await r.json();- _csrf = { token: j.data.token, expiresAt: Date.now() + (j.data.expires_in - 30) * 1000 };- return _csrf.token;+ return j.data.token;}async function apiPostWithCsrf(url, body) {const token = await getCsrfToken();- _csrf = null;return fetch(url, {method: 'POST',headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': token },diff --git a/src/sentiment-heatmap-data.js b/src/sentiment-heatmap-data.jsindex 72a8b0b1c..e35015100 100644--- a/src/sentiment-heatmap-data.js+++ b/src/sentiment-heatmap-data.js@@ -47,7 +47,7 @@ export function normalizeToken(raw, { maxLogVolume } = {}) {volume24h: vol,marketCap: Number.isFinite(raw?.marketCap) ? raw.marketCap : null,featured: !!raw?.featured,- sentiment: raw?.sentiment || null,+ flow: raw?.flow || null,};}@@ -134,9 +134,10 @@ export function buildNarrationContext({ spikes, movers }) {if (movers?.anchor) {const a = movers.anchor;const parts = [`$THREE ${fmtPct(a.change24h)} 24h`];- if (a.sentiment && Number.isFinite(a.sentiment.score)) {- const mood = a.sentiment.score > 0.15 ? 'positive' : a.sentiment.score < -0.15 ? 'negative' : 'mixed';- parts.push(`chat sentiment ${mood} (${a.sentiment.posPct}% bullish, ${a.sentiment.count} msgs)`);+ if (a.flow && Number.isFinite(a.flow.score)) {+ const mood = a.flow.score > 0.15 ? 'buyers leading' : a.flow.score < -0.15 ? 'sellers leading' : 'two-sided';+ const trades = (a.flow.buys24h || 0) + (a.flow.sells24h || 0);+ parts.push(`order flow ${mood} (${a.flow.buyPct}% buys of ${trades} trades 24h)`);}lines.push(parts.join(', '));}diff --git a/tests/api-guardian-assess.test.js b/tests/api-guardian-assess.test.jsindex 7901baf92..a7385c267 100644--- a/tests/api-guardian-assess.test.js+++ b/tests/api-guardian-assess.test.js@@ -24,6 +24,7 @@ vi.mock('../api/_lib/rate-limit.js', () => ({}));import { Readable } from 'node:stream';+import { limits } from '../api/_lib/rate-limit.js';// Handler imported AFTER mocks are registered.const { default: handler } = await import('../api/guardian/assess.js');@@ -68,12 +69,12 @@ afterEach(() => {});// ── Helpers ───────────────────────────────────────────────────────────────────-function makeReq(body, method = 'POST') {+function makeReq(body, method = 'POST', headers = {}) {const json = JSON.stringify(body);const stream = Readable.from([Buffer.from(json)]);// Attach Express-like properties.stream.method = method;- stream.headers = { 'content-type': 'application/json', origin: 'https://three.ws' };+ stream.headers = { 'content-type': 'application/json', origin: 'https://three.ws', ...headers };stream.socket = { remoteAddress: '127.0.0.1' };return stream;}@@ -92,8 +93,8 @@ function makeRes() {return r;}-async function call(body) {- const req = makeReq(body);+async function call(body, { method = 'POST', headers } = {}) {+ const req = makeReq(body, method, headers);const res = makeRes();await handler(req, res);return res;@@ -125,6 +126,23 @@ describe('input validation', () => {it('400 — non-positive action.usd', async () => {expect((await call({ text: 'hi', action: { type: 'sendSol', usd: -1 } }))._s).toBe(400);});+ it('400 on a non-object JSON body', async () => {+ const r = await call(42);+ expect(r._s).toBe(400);+ expect(r.json().error_description).toMatch(/JSON object/);+ });+ it('415 when content-type is not application/json', async () => {+ const r = await call({ text: 'hi' }, { headers: { 'content-type': 'text/plain' } });+ expect(r._s).toBe(415);+ expect(r.json().error).toBe('bad_request');+ });+ it('413 when the body is over the 100 KB read limit', async () => {+ const r = await call({ text: 'hi', pad: 'x'.repeat(150_000) });+ expect(r._s).toBe(413);+ });+ it('405 on a non-POST method', async () => {+ expect((await call({ text: 'hi' }, { method: 'GET' }))._s).toBe(405);+ });});// ── Config gate ───────────────────────────────────────────────────────────────@@ -149,6 +167,26 @@ describe('rate limiting', () => {rl.globalOk = false;expect((await call({ text: 'hi' }))._s).toBe(429);});++ // The global bucket is the watsonx spend cap. Charging it on requests that+ // never reach watsonx let one client with a malformed body 429 the whole+ // platform for the rest of the hour.+ it('does not charge the global spend cap on an invalid body', async () => {+ limits.guardianGlobal.mockClear();+ expect((await call({}))._s).toBe(400);+ expect(limits.guardianGlobal).not.toHaveBeenCalled();+ });+ it('does not charge the global spend cap when watsonx is unconfigured', async () => {+ delete process.env.WATSONX_API_KEY;+ limits.guardianGlobal.mockClear();+ expect((await call({ text: 'hi' }))._s).toBe(503);+ expect(limits.guardianGlobal).not.toHaveBeenCalled();+ });+ it('charges the global spend cap on a real assessment', async () => {+ limits.guardianGlobal.mockClear();+ expect((await call({ text: 'hi' }))._s).toBe(200);+ expect(limits.guardianGlobal).toHaveBeenCalledTimes(1);+ });});// ── Upstream failure ──────────────────────────────────────────────────────────diff --git a/tests/api/forever-inscribe-status.test.js b/tests/api/forever-inscribe-status.test.jsnew file mode 100644index 000000000..c55e15345--- /dev/null+++ b/tests/api/forever-inscribe-status.test.js@@ -0,0 +1,414 @@+// Contract tests for the two Bitcoin inscription handlers, api/forever/inscribe.js+// and api/forever/status.js.+//+// OrdinalsBot is stubbed at `fetch` with the exact response shapes the live API+// returns (verified against api.ordinalsbot.com), so every layer under it runs+// for real: validation, upstream status mapping, state derivation, and the+// Esplora confirmation lookup. These cover the defects the audit found:+// - OrdinalsBot reports failures as HTTP 200 with {status:"error"}. inscribe+// propagated that 200 verbatim, so an error envelope shipped under a success+// status and the pay screen rendered an order that was never created.+// - It answers a rejected payload with a bare 404 and an internal axios+// string, and would answer a key/quota fault with 401/403. Those were+// propagated too, telling an authenticated caller they were unauthorized.+// - status mapped only an upstream HTTP 404 to a 404, but an unknown id comes+// back as HTTP 200 + "invalid orderId", so every dead order id surfaced as a+// 502 (confirmed against production).+// - `paid` was derived as "not waiting-payment", which reported an expired or+// cancelled order the user never paid for as paid.+// - A malformed receiveAddress passed the shape regex with a broken checksum+// and was only caught upstream, as an opaque proxy error.+// - `id` was unbounded and status was unlimited, so both spent the platform's+// metered upstream budget on arbitrary input.++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';++// Synthetic, deliberately unspendable P2TR program. Checksum-valid so it+// exercises the real bech32m decode, owned by nobody.+const TAPROOT = 'bc1pqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpqqenm';+// Same address with the final checksum character flipped.+const TAPROOT_BAD_CHECKSUM = 'bc1pqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqpqqenq';+const REVEAL_TXID = 'a'.repeat(64);++vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: async () => (authed ? { id: 'user-1' } : null),+ authenticateBearer: async () => null,+ extractBearer: () => null,+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ clientIp: () => '198.51.100.7',+ limits: {+ inscribeIp: async () => rateLimit,+ inscribeStatusIp: async () => rateLimit,+ },+}));++let authed = true;+let rateLimit = { success: true, limit: 10, remaining: 9, reset: 0 };+let ordinalsbot = null;+let esplora = null;+let ordinalsbotCalls = [];++const ORIGINAL_FETCH = globalThis.fetch;+const ORIGINAL_VAULT = process.env.BTC_INSCRIPTION_RECEIVE_ADDRESS;+delete process.env.ORDINALSBOT_BASE_URL;++globalThis.fetch = async (input, init = {}) => {+ const url = typeof input === 'string' ? input : input.url;+ if (url.includes('api.ordinalsbot.com')) {+ ordinalsbotCalls.push({ url, body: init.body ? JSON.parse(init.body) : null });+ if (!ordinalsbot) throw new Error(`unstubbed OrdinalsBot call: ${url}`);+ return ordinalsbot(url);+ }+ if (url.includes('blockstream.info')) {+ if (!esplora) throw new Error(`unstubbed Esplora call: ${url}`);+ return esplora(url);+ }+ throw new Error(`unexpected fetch: ${url}`);+};++const { default: inscribeHandler } = await import('../../api/forever/inscribe.js');+const { default: statusHandler } = await import('../../api/forever/status.js');+const { clearEsploraCache } = await import('../../api/_lib/esplora.js');++function jsonResponse(body, status = 200) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ });+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ headersSent: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ end(chunk) {+ if (chunk !== undefined) this.body += chunk;+ this.writableEnded = true;+ this.headersSent = true;+ },+ };+}++async function invoke(handler, { url, method, body }) {+ const req = {+ method,+ url,+ headers: { 'content-type': 'application/json', 'x-forwarded-for': '198.51.100.7' },+ socket: { remoteAddress: '198.51.100.7' },+ };+ if (body !== undefined) req.body = body;+ const res = makeRes();+ await handler(req, res);+ let payload = null;+ if (res.body) {+ try {+ payload = JSON.parse(res.body);+ } catch {+ payload = res.body;+ }+ }+ return { status: res.statusCode, payload, headers: res.headers };+}++const inscribe = (body, method = 'POST') =>+ invoke(inscribeHandler, { url: '/api/forever/inscribe', method, body });+const status = (id, method = 'GET') =>+ invoke(statusHandler, {+ url: id === undefined ? '/api/forever/status' : `/api/forever/status?id=${encodeURIComponent(id)}`,+ method,+ });++beforeEach(() => {+ authed = true;+ rateLimit = { success: true, limit: 10, remaining: 9, reset: 0 };+ ordinalsbot = null;+ esplora = null;+ ordinalsbotCalls = [];+ process.env.BTC_INSCRIPTION_RECEIVE_ADDRESS = TAPROOT;+ clearEsploraCache();+});++afterAll(() => {+ globalThis.fetch = ORIGINAL_FETCH;+ if (ORIGINAL_VAULT === undefined) delete process.env.BTC_INSCRIPTION_RECEIVE_ADDRESS;+ else process.env.BTC_INSCRIPTION_RECEIVE_ADDRESS = ORIGINAL_VAULT;+});++describe('POST /api/forever/inscribe', () => {+ it('creates a real order and shapes the charge for the pay screen', async () => {+ ordinalsbot = () =>+ jsonResponse({+ status: 'ok',+ id: 'order-abc',+ charge: {+ address: TAPROOT,+ amount: 24500,+ lightning_invoice: { payreq: 'lnbc245u1p' },+ expires_at: 1786582273,+ },+ });++ const r = await inscribe({ message: 'hello forever', feeRate: 12 });++ expect(r.status).toBe(200);+ expect(r.payload.orderId).toBe('order-abc');+ expect(r.payload.charge.amount).toBe(24500);+ expect(r.payload.charge.amountBtc).toBeCloseTo(0.000245, 9);+ expect(r.payload.charge.lightningInvoice).toBe('lnbc245u1p');+ expect(r.payload.feeRate).toBe(12);+ expect(r.payload.sizeBytes).toBe(13);+ expect(r.payload.receiveAddress).toBe(TAPROOT);++ // The message reaches OrdinalsBot as a real base64 text/plain data URL.+ const sent = ordinalsbotCalls[0].body;+ expect(sent.fee).toBe(12);+ expect(Buffer.from(sent.files[0].dataURL.split('base64,')[1], 'base64').toString('utf8')).toBe(+ 'hello forever',+ );+ });++ it('rejects a non-POST method', async () => {+ const r = await inscribe(undefined, 'GET');+ expect(r.status).toBe(405);+ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('requires a signed-in user or bearer token', async () => {+ authed = false;+ const r = await inscribe({ message: 'hello' });+ expect(r.status).toBe(401);+ expect(r.payload.error).toBe('unauthorized');+ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('returns 429 when the per-IP ceiling is hit', async () => {+ rateLimit = { success: false, limit: 10, remaining: 0, reset: Date.now() + 60_000 };+ const r = await inscribe({ message: 'hello' });+ expect(r.status).toBe(429);+ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('rejects a body that is not a JSON object', async () => {+ for (const body of ['a string', [1, 2]]) {+ const r = await inscribe(body);+ expect(r.status).toBe(400);+ expect(r.payload.error).toBe('bad_request');+ }+ // A literal JSON `null` body is normalized to `{}` by the server's body+ // parser before the handler sees it, so it lands on the message check.+ // Either way it is a designed 400, never a crash on `body.message`.+ const nullBody = await inscribe(null);+ expect(nullBody.status).toBe(400);+ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('rejects an empty, non-string, or oversized message', async () => {+ expect((await inscribe({ message: ' ' })).status).toBe(400);+ expect((await inscribe({ message: 42 })).status).toBe(400);+ const long = await inscribe({ message: 'x'.repeat(1501) });+ expect(long.status).toBe(400);+ expect(long.payload.error).toBe('invalid_message');+ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('rejects an address that is not Taproot, and one whose checksum is broken', async () => {+ const shape = await inscribe({ message: 'hi', receiveAddress: '1BoatSLRHtKNngkdXEeobR76b53LETtpyT' });+ expect(shape.status).toBe(400);+ expect(shape.payload.error).toBe('invalid_receive_address');++ // Correct bc1p… shape, wrong bech32m checksum: only the real decode catches+ // this, and before the fix it reached OrdinalsBot as an opaque proxy error.+ const checksum = await inscribe({ message: 'hi', receiveAddress: TAPROOT_BAD_CHECKSUM });+ expect(checksum.status).toBe(400);+ expect(checksum.payload.error).toBe('invalid_receive_address');+ expect(checksum.payload.error_description).toMatch(/checksum/i);++ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('rejects a fee rate that is not an integer in range', async () => {+ for (const feeRate of [0, 201, 1.5, 'fast']) {+ const r = await inscribe({ message: 'hi', feeRate });+ expect(r.status).toBe(400);+ expect(r.payload.error).toBe('invalid_fee_rate');+ }+ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('defaults the fee rate and falls back to the configured vault address', async () => {+ ordinalsbot = () => jsonResponse({ id: 'order-def', charge: { address: TAPROOT, amount: 1000 } });+ const r = await inscribe({ message: 'hi' });+ expect(r.status).toBe(200);+ expect(r.payload.feeRate).toBe(8);+ expect(ordinalsbotCalls[0].body.receiveAddress).toBe(TAPROOT);+ });++ it('returns 503 when no address is provided and none is configured', async () => {+ delete process.env.BTC_INSCRIPTION_RECEIVE_ADDRESS;+ const r = await inscribe({ message: 'hi' });+ expect(r.status).toBe(503);+ expect(r.payload.error).toBe('no_receive_address');+ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('returns 503 rather than inscribing into a misconfigured vault address', async () => {+ process.env.BTC_INSCRIPTION_RECEIVE_ADDRESS = TAPROOT_BAD_CHECKSUM;+ const r = await inscribe({ message: 'hi' });+ expect(r.status).toBe(503);+ expect(r.payload.error).toBe('invalid_vault_address');+ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('never returns 2xx when OrdinalsBot fails with HTTP 200 + status:error', async () => {+ // The live API's actual failure shape. Propagating its 200 made the client+ // treat an error envelope as a created order.+ ordinalsbot = () => jsonResponse({ status: 'error', error: ['Request failed with status code 404'] });+ const r = await inscribe({ message: 'hi' });+ expect(r.status).toBe(502);+ expect(r.payload.error).toBe('inscription_failed');+ expect(r.payload.error_description).toMatch(/Request failed with status code 404/);+ });++ it('maps an upstream 404 and an upstream auth fault to 502, never to the caller', async () => {+ for (const upstreamStatus of [404, 401, 403]) {+ ordinalsbot = () => jsonResponse({ status: 'error', error: 'nope' }, upstreamStatus);+ const r = await inscribe({ message: 'hi' });+ expect(r.status).toBe(502);+ expect(r.payload.error).toBe('inscription_failed');+ }+ });++ it('relays an upstream throttle as 429', async () => {+ ordinalsbot = () => jsonResponse({ status: 'error', error: 'rate limited' }, 429);+ const r = await inscribe({ message: 'hi' });+ expect(r.status).toBe(429);+ expect(r.payload.error).toBe('upstream_rate_limited');+ });++ it('returns 502 when OrdinalsBot answers with non-JSON', async () => {+ ordinalsbot = () => new Response('<html>502 Bad Gateway</html>', { status: 502 });+ const r = await inscribe({ message: 'hi' });+ expect(r.status).toBe(502);+ expect(r.payload.error).toBe('inscription_failed');+ expect(r.payload.error_description).toMatch(/non-JSON/);+ });+});++describe('GET /api/forever/status', () => {+ it('reports a waiting order as unpaid with its charge and no inscription', async () => {+ ordinalsbot = () =>+ jsonResponse({ id: 'order-abc', status: 'waiting-payment', charge: { address: TAPROOT, amount: 24500 } });++ const r = await status('order-abc');++ expect(r.status).toBe(200);+ expect(r.payload.state).toBe('waiting-payment');+ expect(r.payload.paid).toBe(false);+ expect(r.payload.inscribed).toBe(false);+ expect(r.payload.charge.amountBtc).toBeCloseTo(0.000245, 9);+ expect(r.payload.inscription).toBeNull();+ expect(r.payload.links.chargeAddress).toBe(`https://mempool.space/address/${TAPROOT}`);+ });++ it('reports a completed order with real chain confirmations from Esplora', async () => {+ ordinalsbot = () =>+ jsonResponse({+ id: 'order-abc',+ status: 'completed',+ inscriptionId: `${REVEAL_TXID}i0`,+ tx: { reveal: REVEAL_TXID, commit: 'b'.repeat(64) },+ });+ esplora = (url) =>+ url.endsWith('/blocks/tip/height')+ ? new Response('900010', { status: 200, headers: { 'content-type': 'text/plain' } })+ : jsonResponse({ confirmed: true, block_height: 900000, block_time: 1786582273 });++ const r = await status('order-abc');++ expect(r.status).toBe(200);+ expect(r.payload.state).toBe('inscribed');+ expect(r.payload.paid).toBe(true);+ expect(r.payload.inscribed).toBe(true);+ expect(r.payload.inscription.revealTxid).toBe(REVEAL_TXID);+ expect(r.payload.inscription.onchain).toEqual({+ confirmed: true,+ confirmations: 11,+ blockHeight: 900000,+ blockTime: 1786582273,+ source: 'esplora',+ });+ expect(r.payload.links.inscription).toBe(`https://ordinals.com/inscription/${REVEAL_TXID}i0`);+ });++ it('degrades onchain to null when Esplora is down, without failing the response', async () => {+ ordinalsbot = () =>+ jsonResponse({ id: 'order-abc', status: 'completed', inscriptionId: `${REVEAL_TXID}i0` });+ esplora = () => new Response('gateway timeout', { status: 504 });++ const r = await status('order-abc');++ expect(r.status).toBe(200);+ expect(r.payload.state).toBe('inscribed');+ expect(r.payload.inscription.onchain).toBeNull();+ });++ it('does not report a failed order as paid', async () => {+ // An expired or cancelled order is normally one the user never paid for.+ ordinalsbot = () => jsonResponse({ id: 'order-abc', status: 'expired' });+ const r = await status('order-abc');+ expect(r.payload.state).toBe('failed');+ expect(r.payload.paid).toBe(false);+ expect(r.payload.inscribed).toBe(false);+ });++ it('returns 404 for an unknown order id, which OrdinalsBot reports as HTTP 200', async () => {+ ordinalsbot = () => jsonResponse({ status: 'error', error: 'invalid orderId' });+ const r = await status('order-that-never-existed');+ expect(r.status).toBe(404);+ expect(r.payload.error).toBe('order_not_found');+ });++ it('returns 502 for a genuine upstream fault', async () => {+ ordinalsbot = () => jsonResponse({ status: 'error', error: 'internal server error' }, 500);+ const r = await status('order-abc');+ expect(r.status).toBe(502);+ expect(r.payload.error).toBe('status_lookup_failed');+ });++ it('rejects a missing or malformed id before spending an upstream call', async () => {+ const missing = await status(undefined);+ expect(missing.status).toBe(400);+ expect(missing.payload.error).toBe('missing_id');++ for (const id of ['x'.repeat(129), 'has spaces', '../../etc/passwd']) {+ const r = await status(id);+ expect(r.status).toBe(400);+ expect(r.payload.error).toBe('invalid_id');+ }+ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('rejects a non-GET method', async () => {+ const r = await status('order-abc', 'POST');+ expect(r.status).toBe(405);+ expect(ordinalsbotCalls).toHaveLength(0);+ });++ it('caps polling per IP so the shared upstream budget cannot be drained', async () => {+ rateLimit = { success: false, limit: 200, remaining: 0, reset: Date.now() + 60_000 };+ const r = await status('order-abc');+ expect(r.status).toBe(429);+ expect(ordinalsbotCalls).toHaveLength(0);+ });+});diff --git a/tests/api/granite-oracle.test.js b/tests/api/granite-oracle.test.jsindex cc91d7f46..51f191663 100644--- a/tests/api/granite-oracle.test.js+++ b/tests/api/granite-oracle.test.js@@ -192,3 +192,34 @@ describe('/api/ibm/oracle', () => {expect(body.error).toBe('bad_request');});});++// The shared market-upstream contract (api/_lib/market/upstream-error.js), which+// every Granite market handler now answers with. The upstream body is never+// echoed: it carries vendor ref ids and nothing a caller can act on.+describe('market data upstream failures', () => {+ const upstreamFault = (status) =>+ Object.assign(new Error(`GeckoTerminal ${status}: {"meta":{"ref_id":"abc"}}`), { status });++ it('maps a missing pool to 404 pool_not_found', async () => {+ fetchOhlcv.mockRejectedValueOnce(upstreamFault(404));+ const { res, body } = await call(`/api/ibm/oracle?pool=${POOL}`);+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('pool_not_found');+ expect(body.error_description).not.toMatch(/ref_id/);+ });++ it('maps a throttle to a retryable 503', async () => {+ fetchOhlcv.mockRejectedValueOnce(upstreamFault(429));+ const { res, body } = await call(`/api/ibm/oracle?pool=${POOL}`);+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('upstream_rate_limited');+ expect(body.retryable).toBe(true);+ });++ it('maps an upstream outage to 502 upstream_error', async () => {+ trendingPools.mockRejectedValueOnce(upstreamFault(502));+ const { res, body } = await call('/api/ibm/oracle?list=trending');+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('upstream_error');+ });+});diff --git a/tests/api/ibm-attest.test.js b/tests/api/ibm-attest.test.jsindex f1e09b7dc..6aedb0aa2 100644--- a/tests/api/ibm-attest.test.js+++ b/tests/api/ibm-attest.test.js@@ -9,6 +9,8 @@import { describe, it, expect, beforeEach, vi } from 'vitest';import { Readable } from 'node:stream';+const upstreamFault = (status) => Object.assign(new Error(`GeckoTerminal ${status}`), { status });+const ADDR = 'So11111111111111111111111111111111111111112';const POOL = '5ByL7MZoLABYnwMPZKPKjf4MGkZ7FeBzrAnos19Pre2z';const GUARDIAN_MODEL = 'ibm/granite-guardian-3-8b';@@ -79,14 +81,27 @@ vi.mock('../../api/_lib/watsonx.js', () => ({}: { configured: false, reason: 'WATSONX_API_KEY + project not set' },),- watsonxChatComplete: vi.fn(async (_cfg, opts) =>- opts?.model === GUARDIAN_MODEL- ? { text: state.guardianVerdict, model: GUARDIAN_MODEL }- : {- text: 'The token climbs steadily. Conviction holds into the next session.',- model: 'ibm/granite-3-8b-instruct',- },- ),+ watsonxChatComplete: vi.fn(async () => ({+ text: 'The token climbs steadily. Conviction holds into the next session.',+ model: 'ibm/granite-3-8b-instruct',+ })),+}));++// Governance runs through the canonical Granite Guardian client (the same one+// api/ibm/oracle.js and api/ibm/twin.js use), not a bespoke chat prompt.+vi.mock('../../api/_lib/granite-guardian.js', () => ({+ guardianConfig: vi.fn(() => ({ configured: true, wx: {}, model: GUARDIAN_MODEL })),+ assessRisk: vi.fn(async () => {+ const flagged = state.guardianVerdict === 'Yes';+ return {+ flagged,+ risk: 'harm',+ label: flagged ? 'Harm' : 'Safe',+ probability: flagged ? 0.94 : 0.03,+ confidence: 'high',+ model: GUARDIAN_MODEL,+ };+ }),}));vi.mock('../../api/_lib/watsonx-forecast.js', () => ({@@ -124,6 +139,9 @@ vi.mock('../../api/_lib/avatar-wallet.js', () => ({explorerAccountUrl: vi.fn((a) => `https://solscan.io/account/${a}`),}));+import { limits } from '../../api/_lib/rate-limit.js';+import { fetchOhlcv, topPoolForToken, trendingPools } from '../../api/_lib/market/ohlcv.js';+const handler = (await import('../../api/ibm/attest.js')).default;// ── Helpers ──────────────────────────────────────────────────────────────@@ -160,6 +178,7 @@ async function invoke(reqOpts) {}beforeEach(() => {+ vi.clearAllMocks(); // call counts only — the factory implementations survivestate.wxConfigured = false;state.guardianVerdict = 'No';state.walletConfigured = false;@@ -317,4 +336,74 @@ describe('POST /api/ibm/attest (notarize)', () => {expect(body.onchain.submitted).toBe(false);expect(state.sendSolArgs).toBeNull();});++ // The daily ceiling protects the shared attester wallet's SOL. Charging it+ // before the preconditions let any signed-in caller exhaust the platform's+ // budget with requests that could never reach the chain.+ it('does not consume the daily attestation budget when there is nothing to notarize', async () => {+ state.wxConfigured = false; // no forecast, so no proof+ state.walletConfigured = true;+ const { body } = await invoke({ method: 'POST', body: { pool: POOL, submit: true } });+ expect(body.onchain.submitted).toBe(false);+ expect(limits.attestSubmitDaily).not.toHaveBeenCalled();+ });++ it('does not consume the daily attestation budget on a Guardian veto', async () => {+ state.wxConfigured = true;+ state.walletConfigured = true;+ state.guardianVerdict = 'Yes';+ await invoke({ method: 'POST', body: { pool: POOL, submit: true } });+ expect(limits.attestSubmitDaily).not.toHaveBeenCalled();+ expect(state.sendSolArgs).toBeNull();+ });++ it('consumes the daily attestation budget only when it actually broadcasts', async () => {+ state.wxConfigured = true;+ state.walletConfigured = true;+ await invoke({ method: 'POST', body: { pool: POOL, submit: true } });+ expect(limits.attestSubmitDaily).toHaveBeenCalledWith(ADDR);+ expect(state.sendSolArgs).not.toBeNull();+ });+});++// A GeckoTerminal fault is a third party's problem. It must come back with a real+// error code (an upstream error carries a status but never a code, which used to+// produce a body with no `error` field at all) and must not read as a 5xx bug.+describe('GET /api/ibm/attest — market data upstream failures', () => {+ it('maps a missing pool to 404 pool_not_found', async () => {+ fetchOhlcv.mockRejectedValueOnce(upstreamFault(404));+ const { status, body } = await invoke({ url: `/api/ibm/attest?pool=${POOL}` });+ expect(status).toBe(404);+ expect(body.error).toBe('pool_not_found');+ expect(body.error_description).not.toMatch(/GeckoTerminal/);+ });++ it('maps a throttle to a retryable 503', async () => {+ fetchOhlcv.mockRejectedValueOnce(upstreamFault(429));+ const { status, body } = await invoke({ url: `/api/ibm/attest?pool=${POOL}` });+ expect(status).toBe(503);+ expect(body.error).toBe('upstream_rate_limited');+ expect(body.retryable).toBe(true);+ });++ it('maps an upstream outage to 502 upstream_error instead of an unhandled 500', async () => {+ fetchOhlcv.mockRejectedValueOnce(upstreamFault(502));+ const { status, body } = await invoke({ url: `/api/ibm/attest?pool=${POOL}` });+ expect(status).toBe(502);+ expect(body.error).toBe('upstream_error');+ });++ it('maps a token-resolution failure the same way', async () => {+ topPoolForToken.mockRejectedValueOnce(upstreamFault(429));+ const { status, body } = await invoke({ url: `/api/ibm/attest?token=${ADDR}` });+ expect(status).toBe(503);+ expect(body.error).toBe('upstream_rate_limited');+ });++ it('maps a trending-list failure the same way', async () => {+ trendingPools.mockRejectedValueOnce(upstreamFault(502));+ const { status, body } = await invoke({ url: '/api/ibm/attest?list=trending' });+ expect(status).toBe(502);+ expect(body.error).toBe('upstream_error');+ });});diff --git a/tests/api/ibm-mcp-discovery.test.js b/tests/api/ibm-mcp-discovery.test.jsnew file mode 100644index 000000000..7fd38752c--- /dev/null+++ b/tests/api/ibm-mcp-discovery.test.js@@ -0,0 +1,87 @@+// Discovery metadata for the hosted IBM Granite MCP endpoint (/api/ibm-mcp).+//+// api/_mcpibm/discovery.js is what x402 facilitators (CDP Bazaar,+// agentic.market, x402scan) read out of the 402 challenge to index the+// endpoint. A malformed entry does not fail the request path, it silently+// de-lists the server, so the shape is asserted here instead of being trusted.+//+// Unlike tests/api/ibm-mcp.test.js this file does NOT mock the bazaar helpers:+// the point is to check the metadata the real @x402/extensions declarators emit.+import { describe, it, expect } from 'vitest';+import Ajv2020 from 'ajv/dist/2020.js';++process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';++const { GRANITE_CHALLENGE, RESOURCE_DESCRIPTION } = await import('../../api/_mcpibm/discovery.js');++const ajv = new Ajv2020({ allErrors: true, strict: false });++const PAID_TOOLS = [+ 'ibm_granite_chat',+ 'ibm_granite_code',+ 'ibm_granite_embed',+ 'ibm_granite_analyze',+ 'ibm_granite_forecast',+];++describe('IBM Granite MCP: 402 challenge metadata', () => {+ it('describes the endpoint and every paid tool it exposes', () => {+ expect(GRANITE_CHALLENGE.description).toBe(RESOURCE_DESCRIPTION);+ for (const tool of PAID_TOOLS) expect(RESOURCE_DESCRIPTION).toContain(tool);+ expect(RESOURCE_DESCRIPTION).toContain('three.ws');+ });++ // Facilitator soft-drop rules: an over-long field is discarded silently and+ // the endpoint gets indexed with partial metadata. Keep every field in range.+ it('service metadata stays inside the facilitator field limits', () => {+ expect(GRANITE_CHALLENGE.serviceName).toBe('three.ws Granite x402');+ expect(GRANITE_CHALLENGE.serviceName.length).toBeLessThanOrEqual(32);+ expect(GRANITE_CHALLENGE.tags.length).toBeLessThanOrEqual(5);+ for (const tag of GRANITE_CHALLENGE.tags) {+ expect(tag.length).toBeLessThanOrEqual(32);+ expect(tag).toMatch(/^[\x20-\x7e]+$/);+ }+ expect(GRANITE_CHALLENGE.tags).toContain('granite');+ expect(GRANITE_CHALLENGE.iconUrl).toMatch(/^https:\/\//);+ });++ it('advertises a discoverable v2 bazaar extension for a JSON-RPC POST', () => {+ const bazaar = GRANITE_CHALLENGE.bazaar;+ expect(bazaar.discoverable).toBe(true);+ expect(bazaar.info.input).toMatchObject({ type: 'http', method: 'POST', bodyType: 'json' });+ expect(bazaar.info.input.body.method).toBe('tools/call');+ expect(bazaar.info.output.type).toBe('json');+ expect(bazaar.info.output.example.result.content[0].type).toBe('text');+ });++ it('the declared info validates against the extension meta-schema', () => {+ const validate = ajv.compile(GRANITE_CHALLENGE.bazaar.schema);+ expect(validate(GRANITE_CHALLENGE.bazaar.info)).toBe(true);+ });++ // Failure path: a meta-schema that accepts anything would pass the check above+ // while telling a facilitator nothing. Prove it actually constrains.+ it('the meta-schema rejects an info block that misdescribes the call', () => {+ const validate = ajv.compile(GRANITE_CHALLENGE.bazaar.schema);+ const noBodyType = structuredClone(GRANITE_CHALLENGE.bazaar.info);+ delete noBodyType.input.bodyType;+ expect(validate(noBodyType)).toBe(false);++ const wrongMethod = structuredClone(GRANITE_CHALLENGE.bazaar.info);+ wrongMethod.input.method = 'GET';+ expect(validate(wrongMethod)).toBe(false);++ const strayField = structuredClone(GRANITE_CHALLENGE.bazaar.info);+ strayField.input.queryParams = { foo: 'bar' };+ expect(validate(strayField)).toBe(false);+ });++ it('the advertised example body satisfies the request-body schema it ships', () => {+ const bodySchema = GRANITE_CHALLENGE.bazaar.schema.properties.input.properties.body;+ const validateBody = ajv.compile(bodySchema);+ expect(validateBody(GRANITE_CHALLENGE.bazaar.info.input.body)).toBe(true);+ // Failure path: an unsupported JSON-RPC method is rejected, so a client+ // generating calls from this schema cannot invent one.+ expect(validateBody({ jsonrpc: '2.0', id: 1, method: 'tools/destroy' })).toBe(false);+ });+});diff --git a/tests/api/ibm-mcp.test.js b/tests/api/ibm-mcp.test.jsindex 86e3c34f7..a6b9a9ab6 100644--- a/tests/api/ibm-mcp.test.js+++ b/tests/api/ibm-mcp.test.js@@ -55,8 +55,10 @@ vi.mock('../../api/_lib/usage.js', () => ({}));const { dispatch, PROTOCOL_VERSION } = await import('../../api/_mcpibm/dispatch.js');-const { graniteX402Amount, priceFor } = await import('../../api/_mcpibm/pricing.js');-const { isFreeTool } = await import('../../api/_mcpibm/catalog.js');+const { graniteX402Amount, priceFor, formatUsdPrice, TOOL_PRICING } = await import(+ '../../api/_mcpibm/pricing.js'+);+const { isFreeTool, TOOL_CATALOG } = await import('../../api/_mcpibm/catalog.js');const AUTH = { userId: null, rateKey: 'test', scope: '', source: 'x402', x402Paid: true };const call = (name, args) =>@@ -216,6 +218,38 @@ describe('IBM Granite MCP — dispatch', () => {expect(r.result.structuredContent.parse_error).toBeTruthy();});+ it('ibm_granite_analyze rejects JSON that is not an analysis object', async () => {+ // A bare quoted string is valid JSON. Spreading it into the result would+ // splatter one numbered key per character, so it takes the raw fallback.+ wx.chat.mockResolvedValueOnce({+ text: '"Not enough context to analyze."',+ usage: {},+ model: 'ibm/granite-3-8b-instruct',+ });+ const r = await call('ibm_granite_analyze', { document: 'x' });+ const out = r.result.structuredContent;+ expect(out).toMatchObject({+ ok: true,+ analysis_type: 'general',+ raw_response: '"Not enough context to analyze."',+ });+ expect(out.parse_error).toBeTruthy();+ expect(Object.keys(out)).not.toContain('0');+ });++ it('ibm_granite_analyze rejects a JSON array the same way', async () => {+ wx.chat.mockResolvedValueOnce({+ text: '[{"summary":"ok"}]',+ usage: {},+ model: 'ibm/granite-3-8b-instruct',+ });+ const r = await call('ibm_granite_analyze', { document: 'x' });+ const out = r.result.structuredContent;+ expect(out.parse_error).toBeTruthy();+ expect(out.raw_response).toBe('[{"summary":"ok"}]');+ expect(Object.keys(out)).not.toContain('0');+ });+it('ibm_granite_forecast returns timestamped forecast points', async () => {const { timestamps, values } = makeSeries(64);const r = await call('ibm_granite_forecast', {@@ -269,5 +303,75 @@ describe('IBM Granite MCP — pricing', () => {it('returns null for an unpriced / unknown tool', () => {expect(graniteX402Amount('nope')).toBeNull();expect(priceFor('nope')).toBeNull();+ expect(formatUsdPrice('nope')).toBeNull();+ });++ it('does not resolve an inherited Object member as a priced tool', () => {+ for (const name of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) {+ expect(priceFor(name)).toBeNull();+ expect(graniteX402Amount(name)).toBeNull();+ expect(formatUsdPrice(name)).toBeNull();+ }+ });++ it('formats the display price without truncating a fractional cent', () => {+ expect(formatUsdPrice('ibm_granite_chat')).toBe('$0.02');+ expect(formatUsdPrice('ibm_granite_code')).toBe('$0.025');+ expect(formatUsdPrice('ibm_granite_embed')).toBe('$0.005');+ });+});++// Every human-readable price this server advertises has to agree with+// TOOL_PRICING, the map the 402 challenge and the settle path both read. A+// number quoted anywhere else is a number a caller can be shown before paying a+// different one.+describe('IBM Granite MCP — advertised prices match the charged price', () => {+ const PRICED = Object.keys(TOOL_PRICING);++ it('every priced tool title quotes its own price', () => {+ for (const name of PRICED) {+ const tool = TOOL_CATALOG.find((t) => t.name === name);+ expect(tool, name).toBeTruthy();+ expect(tool.title, `${name}: title`).toContain(formatUsdPrice(name));+ }+ });++ it('every priced tool description quotes its own price', () => {+ for (const name of PRICED) {+ const tool = TOOL_CATALOG.find((t) => t.name === name);+ expect(tool.description, `${name}: description`).toContain(formatUsdPrice(name));+ }+ });++ it('the catalog pricing block carries the USDC amount from TOOL_PRICING', () => {+ for (const name of PRICED) {+ const tool = TOOL_CATALOG.find((t) => t.name === name);+ expect(tool.pricing.amount_usdc, name).toBe(TOOL_PRICING[name].amount_usdc);+ expect(tool.pricing.currency).toBe('USDC');+ }+ });++ it('the free getting-started payload quotes the same prices', async () => {+ const r = await call('ibm_granite_getting_started', {});+ const out = r.result.structuredContent;+ for (const name of PRICED) {+ const entry = out.tools.find((t) => t.name === name);+ expect(entry, name).toBeTruthy();+ expect(entry.price, `${name}: getting_started price`).toBe(formatUsdPrice(name));+ expect(out.pricing).toContain(`${name}: ${formatUsdPrice(name)}/call`);+ }+ // The list is exhaustive: no paid tool is missing from the orientation.+ expect(out.tools.map((t) => t.name).sort()).toEqual([...PRICED].sort());+ });++ it('the server instructions quote the same prices', async () => {+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'initialize' }, AUTH);+ const instructions = r.result.instructions;+ for (const name of PRICED) {+ expect(instructions, `${name}: instructions`).toContain(+ `${name}(`,+ );+ expect(instructions).toContain(`(${formatUsdPrice(name)})`);+ }});});diff --git a/tests/api/ibm-twin.test.js b/tests/api/ibm-twin.test.jsindex 4920c8e3d..f955189c5 100644--- a/tests/api/ibm-twin.test.js+++ b/tests/api/ibm-twin.test.js@@ -451,6 +451,58 @@ describe('rate limiting', () => {});});+// ── Market data upstream failures ─────────────────────────────────────────────+// GeckoTerminal throttles and outages are a third party's problem. They must map+// to a real client contract rather than bubbling into wrap()'s unhandled-5xx+// path, which logs, captures to Sentry, and pages ops once per request.+describe('market data upstream failures', () => {+ const upstreamFault = (status) =>+ Object.assign(new Error(`GeckoTerminal ${status}`), { status });++ it('maps a missing pool to 404 pool_not_found', async () => {+ fetchOhlcv.mockRejectedValueOnce(upstreamFault(404));+ const { res, body } = await callGet(`/api/ibm/twin?pool=${POOL}`);+ expect(res.statusCode).toBe(404);+ expect(body.error).toBe('pool_not_found');+ expect(body.error_description).not.toMatch(/GeckoTerminal/);+ });++ it('maps a throttle to a retryable 503', async () => {+ fetchOhlcv.mockRejectedValueOnce(upstreamFault(429));+ const { res, body } = await callGet(`/api/ibm/twin?pool=${POOL}`);+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('upstream_rate_limited');+ expect(body.retryable).toBe(true);+ });++ it('maps an upstream outage to 502 upstream_error', async () => {+ fetchOhlcv.mockRejectedValueOnce(upstreamFault(502));+ const { res, body } = await callGet(`/api/ibm/twin?pool=${POOL}`);+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('upstream_error');+ });++ it('maps a trending-list failure the same way', async () => {+ trendingPools.mockRejectedValueOnce(upstreamFault(429));+ const { res, body } = await callGet('/api/ibm/twin?list=trending');+ expect(res.statusCode).toBe(503);+ expect(body.error).toBe('upstream_rate_limited');+ });++ it('maps a POST what-if upstream failure the same way', async () => {+ fetchOhlcv.mockRejectedValueOnce(upstreamFault(502));+ const { res, body } = await callPost({ pool: POOL, scenario: {} });+ expect(res.statusCode).toBe(502);+ expect(body.error).toBe('upstream_error');+ });++ it('keeps the handler own validation errors intact', async () => {+ const { res, body } = await callGet('/api/ibm/twin?token=not-base58');+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('bad_token');+ });+});+// ── Method guard ──────────────────────────────────────────────────────────────describe('method guard', () => {it('returns 405 for unsupported methods', async () => {diff --git a/tests/api/leaderboard-daily-match.test.js b/tests/api/leaderboard-daily-match.test.jsnew file mode 100644index 000000000..5fa11b887--- /dev/null+++ b/tests/api/leaderboard-daily-match.test.js@@ -0,0 +1,186 @@+// Unit tests for GET /api/leaderboard/daily-match, the agents' Daily Match+// board. Every column is a COUNT/SUM over a real activity table for one UTC+// day; the handler's own job is the contract around that: clamping `limit`,+// scoring with the published weights, ranking, the yesterday winner, the live+// feed, CORS/caching, and refusing anything that is not a GET.+//+// Mocks: sql (the three queries the handler fires) and rate-limit. Offline.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const sqlQueue = [];+const sqlCalls = [];+vi.mock('../../api/_lib/db.js', () => ({+ sql: Object.assign(+ vi.fn((strings, ...vals) => {+ sqlCalls.push({ text: strings.join('?'), vals });+ return Promise.resolve(sqlQueue.length ? sqlQueue.shift() : []);+ }),+ { transaction: vi.fn(async (fns) => { for (const f of fns) await f; }) },+ ),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const rlState = { success: true, limit: 60, remaining: 0, reset: 0 };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => rlState) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const { default: handler } = await import('../../api/leaderboard/daily-match.js');++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(query = {}, { method = 'GET', headers = {} } = {}) {+ const qs = new URLSearchParams(query).toString();+ const res = makeRes();+ await handler({ method, headers, query, url: `/api/leaderboard/daily-match${qs ? `?${qs}` : ''}` }, res);+ let body = null;+ try { body = JSON.parse(res._body); } catch { /* non-JSON bodies are asserted via statusCode */ }+ return { res, body };+}++const A1 = '00000000-0000-0000-0000-0000000000b1';+const A2 = '00000000-0000-0000-0000-0000000000b2';++// Shape of one standings row as the aggregate query returns it (pg gives the+// bigint sum back as a string, which is exactly what mapRow has to survive).+function row(agentId, over = {}) {+ return {+ agent_id: agentId,+ name: 'Agent ' + agentId.slice(-2),+ avatar_url: null,+ profile_image_url: null,+ actions: 0,+ launches: 0,+ trades: 0,+ sales: 0,+ pnl_lamports: '0',+ score: 0,+ ...over,+ };+}++beforeEach(() => {+ sqlQueue.length = 0;+ sqlCalls.length = 0;+ rlState.success = true;+ delete rlState.reason;+});++describe('GET /api/leaderboard/daily-match: contract', () => {+ it('serves an empty board with the day window, weights, and CDN caching', async () => {+ const { res, body } = await call();+ expect(res.statusCode).toBe(200);+ expect(body.data.standings).toEqual([]);+ expect(body.data.yesterday_winner).toBeNull();+ expect(body.data.recent).toEqual([]);+ expect(body.data.weights).toEqual({ actions: 1, trades: 5, sales: 15, launches: 25 });+ // The window is a real UTC day that resets exactly 24h after it opened.+ const start = new Date(body.data.day_start);+ const end = new Date(body.data.resets_at);+ expect(start.getUTCHours()).toBe(0);+ expect(start.getUTCMinutes()).toBe(0);+ expect(end.getTime() - start.getTime()).toBe(86_400_000);+ expect(res.getHeader('cache-control')).toContain('s-maxage=30');+ });++ it('allows any origin, so the public board is fetchable cross-origin', async () => {+ await call({}, { headers: { origin: 'https://example.com' } });+ const { res } = await call({}, { headers: { origin: 'https://example.com' } });+ expect(res.getHeader('access-control-allow-origin')).toBe('*');+ expect(res.getHeader('access-control-allow-methods')).toBe('GET,OPTIONS');+ });++ it('refuses a non-GET method instead of running the aggregate', async () => {+ const { res, body } = await call({}, { method: 'POST' });+ expect(res.statusCode).toBe(405);+ expect(body.error).toBe('method_not_allowed');+ expect(sqlCalls).toHaveLength(0);+ });++ it('returns 429 with a retry hint when the public IP bucket is exhausted', async () => {+ rlState.success = false;+ const { res, body } = await call();+ expect(res.statusCode).toBe(429);+ expect(body.error).toBe('rate_limited');+ expect(sqlCalls).toHaveLength(0);+ });+});++describe('GET /api/leaderboard/daily-match: standings', () => {+ it('ranks in query order and maps every real output column', async () => {+ sqlQueue.push([+ row(A1, { actions: 4, launches: 1, trades: 2, sales: 1, pnl_lamports: '-2669993', score: 54 }),+ row(A2, { actions: 1, profile_image_url: 'https://cdn.example/a2.png', score: 1 }),+ ]);+ sqlQueue.push([]); // yesterday+ sqlQueue.push([]); // recent feed++ const { body } = await call();+ expect(body.data.standings.map((r) => [r.rank, r.agent_id, r.score])).toEqual([+ [1, A1, 54],+ [2, A2, 1],+ ]);+ expect(body.data.standings[0]).toMatchObject({+ actions: 4, launches: 1, trades: 2, sales: 1,+ });+ // Lamport P&L stays a string so a bigint never loses precision in JSON.+ expect(body.data.standings[0].pnl_lamports).toBe('-2669993');+ // The uploaded profile image wins over the generated avatar, and a row+ // with neither reports null rather than undefined.+ expect(body.data.standings[1].avatar_url).toBe('https://cdn.example/a2.png');+ expect(body.data.standings[0].avatar_url).toBeNull();+ });++ it('clamps limit into 1..50 and defaults a junk value to 20', async () => {+ const limitOf = async (q) => {+ sqlQueue.length = 0; sqlCalls.length = 0;+ await call(q);+ // Call 0 is today's standings; its last bound value is the LIMIT.+ return sqlCalls[0].vals[sqlCalls[0].vals.length - 1];+ };+ expect(await limitOf({})).toBe(20);+ expect(await limitOf({ limit: 'abc' })).toBe(20);+ expect(await limitOf({ limit: '0' })).toBe(20);+ expect(await limitOf({ limit: '-5' })).toBe(1);+ expect(await limitOf({ limit: '9999' })).toBe(50);+ expect(await limitOf({ limit: '7' })).toBe(7);+ });++ it('reads yesterday from the previous UTC day and returns its winner at rank 1', async () => {+ sqlQueue.push([]); // today: nobody shipped yet+ sqlQueue.push([row(A2, { actions: 3, score: 3 })]);+ sqlQueue.push([]);++ const { body } = await call();+ expect(body.data.standings).toEqual([]);+ expect(body.data.yesterday_winner).toMatchObject({ rank: 1, agent_id: A2, score: 3 });+ // The yesterday query is the same aggregate one day back, capped at one row.+ expect(sqlCalls[1].vals).toContain(1);+ });++ it('returns the live feed with its skill attribution normalized', async () => {+ sqlQueue.push([]);+ sqlQueue.push([]);+ sqlQueue.push([+ { agent_id: A1, name: 'Agent b1', type: 'skill_call', source_skill: 'forge', created_at: '2026-08-13T04:00:00.000Z' },+ { agent_id: A2, name: 'Agent b2', type: 'trade', source_skill: null, created_at: '2026-08-13T03:00:00.000Z' },+ ]);++ const { body } = await call();+ expect(body.data.recent).toEqual([+ { agent_id: A1, name: 'Agent b1', type: 'skill_call', source_skill: 'forge', at: '2026-08-13T04:00:00.000Z' },+ { agent_id: A2, name: 'Agent b2', type: 'trade', source_skill: null, at: '2026-08-13T03:00:00.000Z' },+ ]);+ });+});diff --git a/tests/api/leaderboard-unified.test.js b/tests/api/leaderboard-unified.test.jsindex a21c478b4..e3f90286d 100644--- a/tests/api/leaderboard-unified.test.js+++ b/tests/api/leaderboard-unified.test.js@@ -9,9 +9,13 @@import { describe, it, expect, vi, beforeEach } from 'vitest';const sqlQueue = [];+const sqlText = [];vi.mock('../../api/_lib/db.js', () => ({sql: Object.assign(- vi.fn(() => Promise.resolve(sqlQueue.length ? sqlQueue.shift() : [])),+ vi.fn((strings) => {+ sqlText.push(strings.join('?').replace(/\s+/g, ' '));+ return Promise.resolve(sqlQueue.length ? sqlQueue.shift() : []);+ }),{ transaction: vi.fn(async (fns) => { for (const f of fns) await f; }) },),isDbUnavailableError: () => false,@@ -61,6 +65,7 @@ const U3 = '00000000-0000-0000-0000-0000000000a3';beforeEach(() => {sqlQueue.length = 0;+ sqlText.length = 0;rlState.success = true;authState.session = null;authState.bearer = null;@@ -93,6 +98,17 @@ describe('GET /api/leaderboard/unified: contract', () => {}});+ it('counts only finished derivatives by other creators as remixes received', async () => {+ sqlQueue.push([]);+ await call({ metric: 'remixes_received' });+ const q = sqlText[0];+ // A creator re-refining their own model also writes parent_creation_id+ // (forge-store's linkRefineLineage), so the ranking query must exclude+ // self-parented rows and unfinished generations or the board is farmable.+ expect(q).toContain('c.user_id is distinct from m.user_id');+ expect(q).toContain("c.status = 'done'");+ });+it('serves an empty board without a profile lookup, and never 500s', async () => {sqlQueue.push([]); // ranking rowsconst { res, body } = await call();diff --git a/tests/api/legal-tos-ack.test.js b/tests/api/legal-tos-ack.test.jsindex 1dd76e891..e71518e0b 100644--- a/tests/api/legal-tos-ack.test.js+++ b/tests/api/legal-tos-ack.test.js@@ -123,7 +123,7 @@ describe('POST /api/legal/tos-ack', () => {it('records an anonymous acceptance in the audit log only', async () => {const { status, body } = await invoke({ context: 'register-page', path: '/register' });expect(status).toBe(200);- expect(body).toEqual({ ok: true, version: TOS_VERSION });+ expect(body).toEqual({ ok: true, version: TOS_VERSION, recorded: true });const audits = sqlState.calls.filter((c) => /insert into audit_log/.test(c.query));expect(audits).toHaveLength(1);expect(audits[0].values).toContain('tos-accept');@@ -135,7 +135,7 @@ describe('POST /api/legal/tos-ack', () => {sessionState.user = { id: 'user-9' };const { status, body } = await invoke({});expect(status).toBe(200);- expect(body.ok).toBe(true);+ expect(body).toEqual({ ok: true, version: TOS_VERSION, recorded: true });const stamps = sqlState.calls.filter((c) => /update users\s+set tos_accepted_version/.test(c.query));expect(stamps).toHaveLength(1);expect(stamps[0].values).toContain('user-9');@@ -143,6 +143,30 @@ describe('POST /api/legal/tos-ack', () => {expect(audits).toHaveLength(1);});+ it('keeps the accepting page in the audit meta for a signed-in user', async () => {+ sessionState.user = { id: 'user-9' };+ const { status } = await invoke({ context: 'settings', path: '/settings' });+ expect(status).toBe(200);+ const audit = sqlState.calls.find((c) => /insert into audit_log/.test(c.query));+ expect(audit.values).toContainEqual({ version: TOS_VERSION, context: 'settings', path: '/settings' });+ });++ it('drops a malformed path instead of storing it', async () => {+ const { status } = await invoke({ context: 'settings', path: 'no-leading-slash' });+ expect(status).toBe(200);+ const audit = sqlState.calls.find((c) => /insert into audit_log/.test(c.query));+ expect(audit.values).toContainEqual({ version: TOS_VERSION, context: 'settings', path: null });+ });++ it('reports recorded:false when the durable write fails', async () => {+ // A deterministic SQL error, not a transient connection blip: db-retry+ // surfaces it on the first attempt instead of retrying.+ sqlState.queue = [new Error('relation "audit_log" does not exist')];+ const { status, body } = await invoke({ context: 'register-page' });+ expect(status).toBe(200);+ expect(body).toEqual({ ok: true, version: TOS_VERSION, recorded: false });+ });+it('rejects a version that does not exist', async () => {const { status, body } = await invoke({ version: TOS_VERSION + 1 });expect(status).toBe(400);diff --git a/tests/api/mcp-animation-tools.test.js b/tests/api/mcp-animation-tools.test.jsnew file mode 100644index 000000000..699d07364--- /dev/null+++ b/tests/api/mcp-animation-tools.test.js@@ -0,0 +1,270 @@+// Handler tests for the MCP animation tools (api/_mcp/tools/animations.js).+//+// The catalogue tools read the platform's own published artifacts+// (public/animations/manifest.json and signatures.json), so the suite serves+// that real directory over an ephemeral HTTP server and lets the handlers fetch+// it exactly as they do in production. No fixture manifests, no stubbed fetch:+// if the published artifacts change shape, these tests notice.++import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import http from 'node:http';+import { createReadStream } from 'node:fs';+import { stat } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');+const ANIMATIONS_DIR = path.join(ROOT, 'public', 'animations');++const { toolDefs } = await import('../../api/_mcp/tools/animations.js');+const tool = (name) => toolDefs.find((t) => t.name === name);++// resolveOrigin prefers explicit env over the Host header, so the origin env+// has to be out of the way for the handlers to reach the local server.+const ORIGIN_ENV = ['APP_ORIGIN', 'PUBLIC_ORIGIN', 'PUBLIC_APP_ORIGIN', 'VERCEL_URL'];+const savedEnv = {};++let server;+let req;+// A second server that answers every request with 404, for the failure path+// where the published artifacts are unreachable.+let emptyServer;+let missingReq;++function listen(handler) {+ return new Promise((resolve) => {+ const s = http.createServer(handler);+ s.listen(0, '127.0.0.1', () => resolve(s));+ });+}++beforeAll(async () => {+ for (const key of ORIGIN_ENV) {+ savedEnv[key] = process.env[key];+ delete process.env[key];+ }++ server = await listen(async (rq, rs) => {+ // Only /animations/** is served, and only by basename, so a traversal+ // attempt in a test can never read outside the published directory.+ const rel = rq.url.split('?')[0].replace(/^\/animations\//, '');+ const file = path.join(ANIMATIONS_DIR, path.normalize(rel).replace(/^(\.\.[/\\])+/, ''));+ try {+ const info = await stat(file);+ if (!info.isFile()) throw new Error('not a file');+ rs.writeHead(200, { 'content-type': 'application/json' });+ createReadStream(file).pipe(rs);+ } catch {+ rs.writeHead(404).end('not found');+ }+ });+ emptyServer = await listen((_rq, rs) => rs.writeHead(404).end('not found'));++ req = { headers: { host: `127.0.0.1:${server.address().port}` } };+ missingReq = { headers: { host: `127.0.0.1:${emptyServer.address().port}` } };+});++afterAll(async () => {+ for (const key of ORIGIN_ENV) {+ if (savedEnv[key] === undefined) delete process.env[key];+ else process.env[key] = savedEnv[key];+ }+ await Promise.all(+ [server, emptyServer].map((s) => new Promise((resolve) => s.close(resolve))),+ );+});++const auth = { userId: null, rateKey: 'test', scope: '', source: 'free' };++describe('catalog assembly', () => {+ it('exports the five animation tools with explicit MCP annotations', () => {+ const names = toolDefs.map((t) => t.name);+ expect(names).toEqual([+ 'list_animations',+ 'animation_signature',+ 'find_similar_animations',+ 'apply_animation',+ 'text_to_animation',+ ]);+ for (const t of toolDefs) {+ // destructiveHint defaults to true when omitted, so every tool must+ // state all four hints rather than inherit a wrong default.+ expect(Object.keys(t.annotations).sort()).toEqual([+ 'destructiveHint',+ 'idempotentHint',+ 'openWorldHint',+ 'readOnlyHint',+ ]);+ }+ });+});++describe('list_animations', () => {+ it('lists the published presets with category and loop flags', async () => {+ const out = await tool('list_animations').handler({}, auth, req);+ const { count, animations } = out.structuredContent;+ expect(count).toBeGreaterThan(0);+ expect(count).toBe(animations.length);+ expect(out.content[0].text).toContain(`${count} animation presets:`);++ const idle = animations.find((a) => a.name === 'idle');+ expect(idle).toMatchObject({ name: 'idle', loop: true });+ expect(typeof idle.category).toBe('string');+ expect(idle.label.length).toBeGreaterThan(0);+ });++ it('filters to a single category, case-insensitively', async () => {+ const all = await tool('list_animations').handler({}, auth, req);+ const category = all.structuredContent.animations[0].category;+ const filtered = await tool('list_animations').handler(+ { category: category.toUpperCase() },+ auth,+ req,+ );+ expect(filtered.structuredContent.count).toBeGreaterThan(0);+ expect(filtered.structuredContent.count).toBeLessThan(all.structuredContent.count);+ expect(filtered.structuredContent.animations.every((a) => a.category === category)).toBe(+ true,+ );+ });++ it('returns an empty, well-formed list for a category nothing matches', async () => {+ const out = await tool('list_animations').handler({ category: 'no-such-category' }, auth, req);+ expect(out.structuredContent).toEqual({ count: 0, animations: [] });+ expect(out.content[0].text).toContain('0 animation presets:');+ });++ // Failure path: the catalogue is a published artifact, so an unreachable one+ // is reported as a fetch failure rather than silently listed as empty.+ it('throws when the manifest cannot be fetched', async () => {+ await expect(tool('list_animations').handler({}, auth, missingReq)).rejects.toThrow(+ /manifest fetch failed \(HTTP 404\)/,+ );+ });+});++describe('animation_signature', () => {+ it('returns the measured signature and energy band for a real clip', async () => {+ const out = await tool('animation_signature').handler({ clip: 'idle' }, auth, req);+ const { signature } = out.structuredContent;+ expect(signature.clip).toBe('idle');+ expect(signature.duration).toBeGreaterThan(0);+ expect(typeof signature.band).toBe('string');+ expect(out.content[0].text).toMatch(/^idle: /);+ expect(out.structuredContent.fit).toBeUndefined();+ });++ it('adds a slot fit verdict when a runtime slot is supplied', async () => {+ const out = await tool('animation_signature').handler({ clip: 'idle', slot: 'idle' }, auth, req);+ const { fit } = out.structuredContent;+ expect(fit.slot).toBe('idle');+ expect(fit.level).toBeTruthy();+ expect(fit.message).toBeTruthy();+ expect(out.content[0].text).toContain('Fit for "idle"');+ });++ it('rejects an unknown clip with invalid-params and points at list_animations', async () => {+ await expect(+ tool('animation_signature').handler({ clip: 'not-a-clip' }, auth, req),+ ).rejects.toMatchObject({ code: -32602, message: expect.stringContaining('list_animations') });+ });++ // The signature index comes back from JSON.parse and carries Object.prototype,+ // so an inherited member name must not read as a clip.+ it('does not resolve an inherited Object member as a clip', async () => {+ for (const clip of ['constructor', 'toString', '__proto__']) {+ await expect(tool('animation_signature').handler({ clip }, auth, req)).rejects.toMatchObject(+ { code: -32602 },+ );+ }+ });++ it('rejects a slot that is not a runtime slot', async () => {+ await expect(+ tool('animation_signature').handler({ clip: 'idle', slot: 'nonsense' }, auth, req),+ ).rejects.toMatchObject({ code: -32602, message: expect.stringContaining('Slots:') });+ });+});++describe('find_similar_animations', () => {+ it('ranks neighbours by measured-motion distance, nearest first', async () => {+ const out = await tool('find_similar_animations').handler(+ { clip: 'idle', limit: 3 },+ auth,+ req,+ );+ const { clip, similar } = out.structuredContent;+ expect(clip).toBe('idle');+ expect(similar).toHaveLength(3);+ expect(similar.map((m) => m.clip)).not.toContain('idle');+ const distances = similar.map((m) => m.distance);+ expect([...distances].sort((a, b) => a - b)).toEqual(distances);+ expect(out.content[0].text).toContain('nearest to idle');+ });++ it('clamps the limit into the documented 1..20 range', async () => {+ const out = await tool('find_similar_animations').handler({ clip: 'idle', limit: 999 }, auth, req);+ expect(out.structuredContent.similar).toHaveLength(20);+ });++ it('rejects an unknown reference clip with invalid-params', async () => {+ await expect(+ tool('find_similar_animations').handler({ clip: 'not-a-clip' }, auth, req),+ ).rejects.toMatchObject({ code: -32602 });+ });++ it('throws when the signature index cannot be fetched', async () => {+ await expect(+ tool('find_similar_animations').handler({ clip: 'idle' }, auth, missingReq),+ ).rejects.toThrow(/signatures fetch failed \(HTTP 404\)/);+ });+});++describe('apply_animation', () => {+ // Failure path only: the success path fetches a caller-supplied rigged GLB+ // over the SSRF-hardened fetcher, which by design refuses a loopback URL, so+ // a real retarget belongs to the browser/pose suites rather than here.+ it('rejects an unknown preset before fetching the caller model', async () => {+ await expect(+ tool('apply_animation').handler(+ { model_url: 'https://three.ws/models/rig.glb', animation: 'not-a-preset' },+ auth,+ req,+ ),+ ).rejects.toMatchObject({+ code: -32602,+ data: { hint: 'call list_animations for valid names' },+ });+ });++ it('refuses a non-public model URL (SSRF guard) rather than fetching it', async () => {+ await expect(+ tool('apply_animation').handler(+ { model_url: 'http://169.254.169.254/latest/meta-data/', animation: 'idle' },+ auth,+ req,+ ),+ ).rejects.toThrow(/fetch failed/);+ });+});++describe('text_to_animation', () => {+ // The motion model lives on the GPU worker; with no worker configured the+ // tool must say so rather than fabricate a clip.+ it('reports that generation is unconfigured instead of inventing motion', async () => {+ const saved = process.env.GCP_TEXT2MOTION_URL;+ delete process.env.GCP_TEXT2MOTION_URL;+ try {+ await expect(+ tool('text_to_animation').handler(+ { prompt: 'a celebratory jump', model_url: 'https://three.ws/models/rig.glb' },+ auth,+ req,+ ),+ ).rejects.toMatchObject({ code: -32001 });+ } finally {+ if (saved === undefined) delete process.env.GCP_TEXT2MOTION_URL;+ else process.env.GCP_TEXT2MOTION_URL = saved;+ }+ });+});diff --git a/tests/api/mcp-avatar-persist.test.js b/tests/api/mcp-avatar-persist.test.jsindex c7e0ffa74..c329768a0 100644--- a/tests/api/mcp-avatar-persist.test.js+++ b/tests/api/mcp-avatar-persist.test.js@@ -261,3 +261,78 @@ describe('render_avatar_image', () => {expect(renderState.fn).not.toHaveBeenCalled();});});++describe('render_avatar', () => {+ const AUTH = { userId: 'user-1', scope: 'avatars:read', source: 'session' };+ const AVATAR = {+ id: '11111111-1111-4111-8111-111111111111',+ name: 'Hero',+ visibility: 'public',+ model_url: 'https://cdn.test/m.glb',+ };++ it('returns viewer HTML as an inline text/html resource, not as chat text', async () => {+ avState.avatar = AVATAR;+ const r = await avatarTool('render_avatar').handler({ id: AVATAR.id }, AUTH);++ expect(r.isError).toBeUndefined();+ // Chat text stays short; the document rides in the resource entry.+ expect(r.content[0].type).toBe('text');+ expect(r.content[0].text).not.toContain('<model-viewer');+ const resource = r.content[1];+ expect(resource.type).toBe('resource');+ expect(resource.resource.mimeType).toBe('text/html');+ expect(resource.resource.uri).toBe(`avatar://${AVATAR.id}`);+ expect(resource.resource.text).toContain('<model-viewer');+ expect(resource.resource.text).toContain('src="https://cdn.test/m.glb"');+ expect(r.structuredContent.html).toBe(resource.resource.text);+ });++ it('drops CSS and poster arguments that could break out of the document', async () => {+ avState.avatar = AVATAR;+ const r = await avatarTool('render_avatar').handler(+ {+ id: AVATAR.id,+ background: 'red;}body{background:url(https://evil.test/beacon)}',+ poster: 'javascript:alert(1)',+ },+ AUTH,+ );+ const html = r.structuredContent.html;+ expect(html).not.toContain('evil.test');+ expect(html).not.toContain('javascript:alert(1)');+ expect(html).toContain('background:transparent');+ });++ // The surfaces.mcp gate: an agent that has switched the MCP surface off must+ // get a machine-readable slug AND a reason a client can show its user.+ it('refuses an avatar whose agent disallows the MCP surface', async () => {+ avState.avatar = AVATAR;+ const { sql } = await import('../../api/_lib/db.js');+ sql.mockResolvedValueOnce([{ embed_policy: { surfaces: { mcp: false } } }]);++ await expect(+ avatarTool('render_avatar').handler({ id: AVATAR.id }, AUTH),+ ).rejects.toMatchObject({+ code: -32000,+ message: 'embed_denied_surface',+ data: { reason: expect.stringContaining('MCP surface'), avatar_id: AVATAR.id },+ });+ });++ it('renders normally when the owning agent leaves the MCP surface enabled', async () => {+ avState.avatar = AVATAR;+ const { sql } = await import('../../api/_lib/db.js');+ sql.mockResolvedValueOnce([{ embed_policy: { surfaces: { mcp: true } } }]);++ const r = await avatarTool('render_avatar').handler({ id: AVATAR.id }, AUTH);+ expect(r.structuredContent.html).toContain('<model-viewer');+ });++ it('reports a missing avatar as not found', async () => {+ avState.avatar = null;+ await expect(avatarTool('render_avatar').handler({ id: AVATAR.id }, AUTH)).rejects.toThrow(+ /not found/i,+ );+ });+});diff --git a/tests/api/mcp-render-origin.test.js b/tests/api/mcp-render-origin.test.jsindex f51d9c022..9d3768218 100644--- a/tests/api/mcp-render-origin.test.js+++ b/tests/api/mcp-render-origin.test.js@@ -49,6 +49,17 @@ describe('render.js sanitizers', () => {expect(safeCssValue('', 'fallback')).toBe('fallback');});+ // Parens and slashes are legal in gradients, so the character class alone+ // still let a background smuggle in an external fetch: a beacon that leaks+ // every viewer's IP and referrer to whoever supplied the value.+ it('rejects url() even when every character is otherwise allowed', () => {+ expect(safeCssValue('url(//beacon.example/p.png)', 'transparent')).toBe('transparent');+ expect(safeCssValue('URL (//beacon.example/p.png)', 'transparent')).toBe('transparent');+ expect(safeCssValue('linear-gradient(#0b0c10, #6a5cff)', 'transparent')).toBe(+ 'linear-gradient(#0b0c10, #6a5cff)',+ );+ });+it('is idempotent, so re-sanitizing an already-clean value is a no-op', () => {for (const value of ['transparent', '#6a5cff', '0deg 80deg 2m', 'rgb(1, 2, 3)']) {expect(safeCssValue(safeCssValue(value, 'x'), 'x')).toBe(value);@@ -195,6 +206,20 @@ describe('resolveOrigin', () => {expect(resolveOrigin({ headers: { host: 'three.ws' } })).toBe('https://three.ws');expect(resolveOrigin({ headers: { host: 'localhost:3000' } })).toBe('http://localhost:3000');expect(resolveOrigin({ headers: { host: '127.0.0.1:3000' } })).toBe('http://127.0.0.1:3000');+ expect(resolveOrigin({ headers: { host: '[::1]:3000' } })).toBe('http://[::1]:3000');+ });++ // The loopback test used to be an unanchored alternation, so any remote host+ // merely CONTAINING the loopback literal was served an http:// origin and+ // every link built from it downgraded off TLS.+ it('treats a remote host that merely contains a loopback literal as https', () => {+ clearOriginEnv();+ expect(resolveOrigin({ headers: { host: 'evil-127.0.0.1.example.com' } })).toBe(+ 'https://evil-127.0.0.1.example.com',+ );+ expect(resolveOrigin({ headers: { host: 'localhost.evil.example' } })).toBe(+ 'https://localhost.evil.example',+ );});it('falls back to VERCEL_URL when there is no env origin and no Host', () => {diff --git a/tests/api/okx-3d-services.test.js b/tests/api/okx-3d-services.test.jsindex 9cf625e2a..b0f027672 100644--- a/tests/api/okx-3d-services.test.js+++ b/tests/api/okx-3d-services.test.js@@ -12,6 +12,8 @@*/import { describe, it, expect, vi, beforeEach } from 'vitest';import { Readable } from 'node:stream';+import Ajv from 'ajv';+import addFormats from 'ajv-formats';process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';process.env.X402_PAY_TO_XLAYER ||= '0x75d00a2713565171f33216e5aa2a375e076ecf69';@@ -370,7 +372,15 @@ describe('paid dispatch — verify → engine → settle', () => {it('fbx-export routes to remesh_model convert with rig-preserving fbx default', async () => {const original = studioCatalog.TOOLS.remesh_model.handler;studioCatalog.TOOLS.remesh_model.handler = vi.fn(async (args) => {- expect(args).toMatchObject({ operation: 'convert', format: 'fbx' });+ // remesh_model speaks mesh_url/output_format, NOT the catalog row's+ // model_url/format. Passing the OKX names made every paid fbx-export+ // call 400 on "mesh_url must be a public https URL" and silently drop+ // the requested format.+ expect(args).toMatchObject({+ mesh_url: VALID_INPUT['fbx-export'].model_url,+ operation: 'convert',+ output_format: 'fbx',+ });return { content: [{ type: 'text', text: 'ok' }], structuredContent: { job_id: 'remesh-1' } };});try {@@ -385,6 +395,46 @@ describe('paid dispatch — verify → engine → settle', () => {});});+// The three tool-backed rows call an MCP tool handler DIRECTLY, bypassing the+// studio dispatcher that would normally validate arguments — so a renamed key+// fails at runtime, on a paid call, with nothing catching it in between. This+// holds each adapter to the engine tool's own published schema.+describe('engine argument contract', () => {+ const ENGINE_FOR = {+ retarget: 'apply_animation',+ 'pose-seed': 'pose_model',+ 'fbx-export': 'remesh_model',+ };+ const schemaAjv = new Ajv({ allErrors: true, strict: false });+ addFormats(schemaAjv);++ for (const [service, tool] of Object.entries(ENGINE_FOR)) {+ it(`${service} passes arguments ${tool} actually accepts`, async () => {+ const schema = studioCatalog.TOOL_CATALOG.find((t) => t.name === tool)?.inputSchema;+ expect(schema, `${tool} publishes an inputSchema`).toBeTruthy();+ const validate = schemaAjv.compile(schema);+ const original = studioCatalog.TOOLS[tool].handler;+ let seen = null;+ studioCatalog.TOOLS[tool].handler = vi.fn(async (args) => {+ seen = args;+ return { content: [{ type: 'text', text: 'ok' }], structuredContent: {} };+ });+ try {+ const res = makeRes();+ await handler(+ makeReq({ service, body: VALID_INPUT[service], headers: { 'payment-signature': 'c2ln' } }),+ res,+ );+ expect(res.statusCode).toBe(200);+ } finally {+ studioCatalog.TOOLS[tool].handler = original;+ }+ expect(seen, `${service} never reached ${tool}`).toBeTruthy();+ expect(validate(seen) ? [] : validate.errors).toEqual([]);+ });+ }+});+describe('failure paths never charge', () => {function paidReq(service, body) {return makeReq({ service, body, headers: { 'payment-signature': 'c2ln' } });diff --git a/tests/erc8004-import.test.js b/tests/erc8004-import.test.jsnew file mode 100644index 000000000..cabe6c032--- /dev/null+++ b/tests/erc8004-import.test.js@@ -0,0 +1,235 @@+// POST /api/erc8004/import: pulling an ERC-8004 agent the caller already owns+// on-chain into their three.ws account.+//+// Three properties are pinned here, each of them a bug this endpoint shipped:+//+// 1. An unreachable registration manifest must NOT block the import. The+// handler treated ANY `resolved.error` as fatal and answered 400, so a+// throttled ipfs.io gateway locked owners out of agents whose registry read+// had already succeeded. The row only needs a name, and there is an on-chain+// fallback for that.+// 2. Ownership is re-checked against the LIVE registry answer. The index row is+// crawler state and goes stale, so an agent transferred after the last crawl+// would otherwise still import for its former owner.+// 3. A chain-read failure answers 502 with a fixed message. The old code echoed+// the raw upstream text, which on an Alchemy-backed chain embeds the keyed+// provider URL (…g.alchemy.com/v2/<key>) straight into the response body.+//+// I/O is mocked at the module seams (db.js, auth.js, onchain.js): the test never+// touches a real database or RPC endpoint.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const CHAIN_ID = 8453;+const AGENT_ID = '4242';+// Synthetic EVM addresses; nothing is ever sent to them.+const OWNER = '0x00000000000000000000000000000000000000a1';+const OTHER = '0x00000000000000000000000000000000000000b2';++let indexOwner = OWNER;+let userWallets = [OWNER];+let alreadyImported = false;+const statements = [];++function sqlMock(strings, ...values) {+ const text = strings.join('?');+ statements.push({ text, values });+ if (text.includes('FROM agent_identities')) {+ return Promise.resolve(alreadyImported ? [{ id: 'existing-row' }] : []);+ }+ if (text.includes('FROM erc8004_agents_index')) {+ return Promise.resolve([{ owner: indexOwner, agent_uri: 'ipfs://bafyagentmanifest' }]);+ }+ if (text.includes('FROM user_wallets')) {+ return Promise.resolve(userWallets.map((address) => ({ address })));+ }+ if (text.includes('INSERT INTO agent_identities')) {+ return Promise.resolve([{ id: 'new-agent-row' }]);+ }+ return Promise.resolve([]);+}+vi.mock('../api/_lib/db.js', () => ({ sql: sqlMock, isDbUnavailableError: () => false, isDbCapacityError: () => false, isStoragePressured: async () => ({ pressured: false }) }));++vi.mock('../api/_lib/auth.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, getSessionUser: async () => ({ id: 'user-1' }) };+});++vi.mock('../api/_lib/rate-limit.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ clientIp: () => '203.0.113.9',+ limits: { ...actual.limits, authIp: async () => ({ success: true }) },+ };+});++let resolveResult = null;+let resolveThrows = null;+vi.mock('../api/_lib/onchain.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ resolveOnChainAgent: async () => {+ if (resolveThrows) throw resolveThrows;+ return resolveResult;+ },+ };+});++const handler = (await import('../api/erc8004/[action].js')).default;++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ removeHeader(k) {+ delete this.headers[k.toLowerCase()];+ },+ writeHead(code) {+ this.statusCode = code;+ return this;+ },+ end(payload) {+ if (payload !== undefined && this.body === null) this.body = payload;+ this.finished = true;+ return this;+ },+ };+}++async function importAgent(body = { chainId: CHAIN_ID, agentId: AGENT_ID }) {+ const res = makeRes();+ await handler(+ {+ method: 'POST',+ url: '/api/erc8004/import',+ headers: { 'content-type': 'application/json' },+ query: { action: 'import' },+ body,+ },+ res,+ );+ let parsed = null;+ try {+ parsed = typeof res.body === 'string' ? JSON.parse(res.body) : res.body;+ } catch {+ parsed = res.body;+ }+ return { status: res.statusCode, body: parsed };+}++// The shape resolveOnChainAgent returns when the registry read succeeded.+function resolvedAgent(overrides = {}) {+ return {+ chainId: CHAIN_ID,+ agentId: AGENT_ID,+ owner: OWNER,+ name: 'Courier',+ description: 'A delivery agent',+ image: 'https://cdn.example/agent.png',+ bodyURI: null,+ error: null,+ ...overrides,+ };+}++beforeEach(() => {+ statements.length = 0;+ indexOwner = OWNER;+ userWallets = [OWNER];+ alreadyImported = false;+ resolveResult = resolvedAgent();+ resolveThrows = null;+});++describe('POST /api/erc8004/import', () => {+ it('imports an owned agent and returns the new row', async () => {+ const { status, body } = await importAgent();+ expect(status).toBe(201);+ expect(body.agent).toMatchObject({+ id: 'new-agent-row',+ erc8004_agent_id: AGENT_ID,+ erc8004_agent_id_chain_id: CHAIN_ID,+ name: 'Courier',+ });+ expect(statements.some((s) => s.text.includes('INSERT INTO agent_identities'))).toBe(true);+ });++ it('still imports when the registration manifest could not be fetched', async () => {+ // Registry read fine, off-chain manifest host down: the agent exists and is+ // owned, so the import proceeds with the on-chain fallback name.+ resolveResult = resolvedAgent({+ name: null,+ description: null,+ image: null,+ error: 'manifest_fetch: fetch failed',+ });+ const { status, body } = await importAgent();+ expect(status).toBe(201);+ expect(body.agent.name).toBe(`Agent #${AGENT_ID}`);+ });++ it('rejects the former owner when the index row is stale', async () => {+ // The crawler still lists this wallet as owner, but the live registry says+ // the agent was transferred away.+ resolveResult = resolvedAgent({ owner: OTHER });+ const { status, body } = await importAgent();+ expect(status).toBe(403);+ expect(body.error).toBe('forbidden');+ expect(statements.some((s) => s.text.includes('INSERT INTO agent_identities'))).toBe(false);+ });++ it('rejects a wallet that never owned the agent', async () => {+ indexOwner = OTHER;+ const { status, body } = await importAgent();+ expect(status).toBe(403);+ expect(body.error).toBe('forbidden');+ });++ it('answers 502 without echoing the keyed RPC URL when the chain read fails', async () => {+ resolveResult = resolvedAgent({+ owner: null,+ error: 'chain_read: could not reach https://base-mainnet.g.alchemy.com/v2/SUPERSECRETKEY',+ });+ const { status, body } = await importAgent();+ expect(status).toBe(502);+ expect(body.error).toBe('resolve_failed');+ expect(JSON.stringify(body)).not.toContain('SUPERSECRETKEY');+ expect(JSON.stringify(body)).not.toContain('alchemy');+ });++ it('answers 502 without echoing the message when the resolver throws', async () => {+ resolveThrows = new Error('connect ECONNREFUSED https://base-mainnet.g.alchemy.com/v2/SUPERSECRETKEY');+ const { status, body } = await importAgent();+ expect(status).toBe(502);+ expect(body.error).toBe('resolve_failed');+ expect(JSON.stringify(body)).not.toContain('SUPERSECRETKEY');+ });++ it('refuses a second import of the same agent', async () => {+ alreadyImported = true;+ const { status, body } = await importAgent();+ expect(status).toBe(409);+ expect(body.error).toBe('conflict');+ });++ it('rejects an unsupported chain before touching the database', async () => {+ const { status, body } = await importAgent({ chainId: 999_999, agentId: AGENT_ID });+ expect(status).toBe(400);+ expect(body.error_description).toContain('unsupported chain');+ expect(statements).toHaveLength(0);+ });++ it('rejects a non-numeric agentId', async () => {+ const { status } = await importAgent({ chainId: CHAIN_ID, agentId: 'not-a-number' });+ expect(status).toBe(400);+ });+});diff --git a/tests/erc8004-register-confirm.test.js b/tests/erc8004-register-confirm.test.jsnew file mode 100644index 000000000..7f5cbb485--- /dev/null+++ b/tests/erc8004-register-confirm.test.js@@ -0,0 +1,249 @@+// POST /api/erc8004/register-confirm: the step that turns a just-broadcast+// Identity Registry mint into an indexed three.ws agent.+//+// Two shipped bugs are pinned here:+//+// 1. The receipt was read over `chain.rpcUrls` directly. That list is only the+// KEYLESS TAIL of the platform failover chain (api/_lib/evm/rpc.js), so the+// operator's RPC_URL_<chainId> override and Alchemy were skipped entirely+// and confirmation raced the slowest tier: a tx that WAS mined came back as+// `tx_not_mined` whenever a public node lagged.+// 2. When every endpoint failed, the raw fetch error bubbled to wrap() and the+// caller got an opaque 500 `internal_error`, which reads as a bug in the+// registration rather than an upstream outage it should retry.+//+// The receipt itself is a real ERC-8004 `Registered(uint256,string,address)` log+// shape; only the transport and the database are mocked.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { id as keccakId } from 'ethers';++const CHAIN_ID = 8453;+const REGISTRY = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';+const OVERRIDE_RPC = 'https://operator-node.test/rpc';+const TX_HASH = '0x' + 'ab'.repeat(32);+const AGENT_ID = '7';+// Synthetic EVM owner; nothing is ever sent to it.+const OWNER = '0x00000000000000000000000000000000000000a1';++process.env.RPC_URL_8453 = OVERRIDE_RPC;++const statements = [];+function sqlMock(strings, ...values) {+ const text = strings.join('?');+ statements.push({ text, values });+ if (text.includes('SELECT id, meta FROM agent_identities')) return Promise.resolve([]);+ return Promise.resolve([]);+}+vi.mock('../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false }),+}));++vi.mock('../api/_lib/auth.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, getSessionUser: async () => ({ id: 'user-1' }) };+});++vi.mock('../api/_lib/rate-limit.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ clientIp: () => '203.0.113.9',+ limits: { ...actual.limits, registerIp: async () => ({ success: true }) },+ };+});++// enrichMetadata's manifest fetch: always a miss, so the tests stay on the+// receipt-verification path this file is about.+vi.mock('../api/_lib/ssrf-guard.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, fetchSafePublicUrlPinned: async () => ({ ok: false, status: 404 }) };+});++const handler = (await import('../api/erc8004/register-confirm.js')).default;++const REGISTERED_TOPIC = keccakId('Registered(uint256,string,address)');++function receipt({ agentId = AGENT_ID, owner = OWNER, status = '0x1', address = REGISTRY } = {}) {+ return {+ status,+ blockNumber: '0x1e240',+ logs: [+ {+ address,+ topics: [+ REGISTERED_TOPIC,+ '0x' + BigInt(agentId).toString(16).padStart(64, '0'),+ '0x' + owner.slice(2).padStart(64, '0'),+ ],+ },+ ],+ };+}++// Per-URL transport script: each entry is a function of the endpoint URL.+let transport = () => {+ throw new Error('unscripted RPC call');+};+const calledUrls = [];++beforeEach(() => {+ statements.length = 0;+ calledUrls.length = 0;+ vi.stubGlobal('fetch', async (url) => {+ calledUrls.push(String(url));+ return transport(String(url));+ });+});++function rpcOk(result) {+ return () => ({+ ok: true,+ status: 200,+ json: async () => ({ jsonrpc: '2.0', id: 1, result }),+ });+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ removeHeader(k) {+ delete this.headers[k.toLowerCase()];+ },+ writeHead(code) {+ this.statusCode = code;+ return this;+ },+ end(payload) {+ if (payload !== undefined && this.body === null) this.body = payload;+ this.finished = true;+ return this;+ },+ };+}++async function confirm(overrides = {}) {+ const res = makeRes();+ await handler(+ {+ method: 'POST',+ url: '/api/erc8004/register-confirm',+ headers: { 'content-type': 'application/json' },+ query: {},+ body: {+ chainId: CHAIN_ID,+ txHash: TX_HASH,+ agentId: AGENT_ID,+ metadataUri: 'ipfs://bafyagentmanifest',+ ownerAddress: OWNER,+ ...overrides,+ },+ },+ res,+ );+ let parsed = null;+ try {+ parsed = typeof res.body === 'string' ? JSON.parse(res.body) : res.body;+ } catch {+ parsed = res.body;+ }+ return { status: res.statusCode, body: parsed };+}++describe('POST /api/erc8004/register-confirm', () => {+ it('reads the receipt from the operator RPC override before any public node', async () => {+ transport = rpcOk(receipt());+ const { status, body } = await confirm();+ expect(status).toBe(200);+ expect(body).toMatchObject({ success: true, agentId: AGENT_ID, chainId: CHAIN_ID });+ // The override is tried FIRST; the keyless public list is only a fallback.+ expect(calledUrls[0]).toBe(OVERRIDE_RPC);+ expect(statements.some((s) => s.text.includes('INSERT INTO erc8004_agents_index'))).toBe(true);+ });++ it('fails over to the next endpoint when the first one is down', async () => {+ let first = true;+ transport = (url) => {+ if (first) {+ first = false;+ throw new Error(`connect ECONNREFUSED ${url}`);+ }+ return rpcOk(receipt())();+ };+ const { status } = await confirm();+ expect(status).toBe(200);+ expect(calledUrls.length).toBeGreaterThan(1);+ });++ it('answers 503 rpc_unavailable when every endpoint fails', async () => {+ transport = (url) => {+ throw new Error(`connect ECONNREFUSED ${url}`);+ };+ const { status, body } = await confirm();+ expect(status).toBe(503);+ expect(body.error).toBe('rpc_unavailable');+ expect(body.error_description).toContain('retry shortly');+ // More than one endpoint was attempted before giving up.+ expect(calledUrls.length).toBeGreaterThan(1);+ expect(statements.some((s) => s.text.includes('INSERT INTO erc8004_agents_index'))).toBe(false);+ });++ it('reports an unmined tx as 422 rather than indexing nothing silently', async () => {+ transport = rpcOk(null);+ const { status, body } = await confirm();+ expect(status).toBe(422);+ expect(body.error).toBe('tx_not_mined');+ });++ it('rejects a reverted tx', async () => {+ transport = rpcOk(receipt({ status: '0x0' }));+ const { status, body } = await confirm();+ expect(status).toBe(422);+ expect(body.error).toBe('tx_failed');+ });++ it('rejects a receipt whose Registered log came from another contract', async () => {+ transport = rpcOk(receipt({ address: '0x00000000000000000000000000000000000000ff' }));+ const { status, body } = await confirm();+ expect(status).toBe(422);+ expect(body.error).toBe('event_not_found');+ });++ it('rejects a claimed agentId the event does not match', async () => {+ transport = rpcOk(receipt({ agentId: '99' }));+ const { status, body } = await confirm();+ expect(status).toBe(422);+ expect(body.error).toBe('mismatch');+ });++ it('rejects a claimed owner the event does not match', async () => {+ transport = rpcOk(receipt({ owner: '0x00000000000000000000000000000000000000b2' }));+ const { status, body } = await confirm();+ expect(status).toBe(422);+ expect(body.error).toBe('mismatch');+ });++ it('rejects an unsupported chain before any RPC call', async () => {+ const { status, body } = await confirm({ chainId: 999_999 });+ expect(status).toBe(400);+ expect(body.error_description).toContain('unsupported chain');+ expect(calledUrls).toHaveLength(0);+ });++ it('rejects an oversized metadataUri instead of writing it to the index', async () => {+ const { status } = await confirm({ metadataUri: 'ipfs://' + 'a'.repeat(2100) });+ expect(status).toBe(400);+ expect(calledUrls).toHaveLength(0);+ });+});diff --git a/tests/galaxy-flows-endpoint.test.js b/tests/galaxy-flows-endpoint.test.jsnew file mode 100644index 000000000..e0218ff07--- /dev/null+++ b/tests/galaxy-flows-endpoint.test.js@@ -0,0 +1,221 @@+/**+ * GET /api/galaxy/flows — request handling + degraded-path contracts.+ *+ * The pure row shaping lives in tests/galaxy-flows.test.js. This file pins the+ * endpoint's own behaviour: how it sanitises query params before they reach+ * Postgres, and how its three request shapes (first page, delta poll, backfill+ * page) each degrade when the feed query fails.+ *+ * The last-good snapshot is the load-bearing part. It is keyed by+ * (network, type, limit) only, so a delta poll and the first page collide on it+ * while carrying completely different slices of the feed — which is why only the+ * first page may write or read it.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const h = vi.hoisted(() => ({+ queries: [],+ rows: [],+ failNext: false,+ cache: new Map(),+ sets: [],+}));++vi.mock('../api/_lib/db.js', () => ({+ // Tagged-template stand-in: fragments and the final query both land here. Only+ // the outermost call is awaited, so every call can return the same thenable.+ sql: (strings, ...values) => {+ const text = strings.join('?');+ h.queries.push({ text, values });+ return {+ text,+ values,+ then(resolve, reject) {+ if (h.failNext && text.includes('ORDER BY feed.ts DESC')) {+ reject(new Error('relation "agent_custody_events" does not exist'));+ return;+ }+ resolve(h.rows);+ },+ };+ },+ isDbUnavailableError: () => false,+}));++vi.mock('../api/_lib/cache.js', () => ({+ cacheGet: vi.fn(async (k) => (h.cache.has(k) ? h.cache.get(k) : null)),+ cacheSet: vi.fn(async (k, v) => { h.sets.push(k); h.cache.set(k, v); }),+}));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { galaxyIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '198.51.100.7',+}));++vi.mock('../api/_lib/http.js', () => ({+ cors: () => false,+ method: () => true,+ rateLimited: (res) => { res._rateLimited = true; },+ json: (res, status, body) => { res._json = { status, body }; return res; },+}));++import handler from '../api/galaxy/flows.js';+import { encodeCursor } from '../api/_lib/galaxy-flows.js';++function fakeRes() {+ const headers = {};+ return {+ statusCode: 200,+ setHeader(k, v) { headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return headers[String(k).toLowerCase()]; },+ end() {},+ };+}++const call = async (query) => {+ const res = fakeRes();+ await handler({ method: 'GET', url: `/api/galaxy/flows${query}`, headers: {} }, res);+ return res;+};++// One real-shaped custody row: an outbound trade with no platform counterparty.+const ROW = {+ ts: new Date('2026-08-12T09:00:00Z'),+ kind: 'trade',+ direction: 'out',+ row_id: 'c900',+ network: 'mainnet',+ actor_id: 'agent-A',+ actor_name: 'Nova',+ actor_addr: 'NOVAwallet',+ actor_vp: null,+ actor_vs: null,+ asset: 'SOL',+ amount_lamports: '2000000',+ amount_raw: null,+ usd: 0.15,+ signature: 'SIGTRADE',+ counterparty_addr: null,+ counterparty_id: null,+ counterparty_name: null,+ mint: null,+ symbol: null,+ coin_name: null,+};++const feedQuery = () => h.queries.find((q) => q.text.includes('ORDER BY feed.ts DESC'));+const limitArg = () => { const q = feedQuery(); return q.values[q.values.length - 1]; };++beforeEach(() => {+ h.queries = [];+ h.rows = [ROW];+ h.failNext = false;+ h.cache = new Map();+ h.sets = [];+});++describe('query param sanitising', () => {+ it('floors a fractional ?limit so LIMIT stays an integer Postgres accepts', async () => {+ const res = await call('?limit=1.5&network=mainnet');+ expect(res._json.status).toBe(200);+ // LIMIT is sent as limit + 1 for the has_more probe; 1.5 once sent 2.5 and+ // errored the query, degrading a healthy feed to an empty window.+ expect(Number.isInteger(limitArg())).toBe(true);+ expect(limitArg()).toBe(2);+ });++ it('clamps out-of-range and unparseable limits without erroring', async () => {+ await call('?limit=99999');+ expect(limitArg()).toBe(201); // MAX_LIMIT + 1++ h.queries = [];+ await call('?limit=abc');+ expect(limitArg()).toBe(81); // DEFAULT_LIMIT + 1++ h.queries = [];+ await call('?limit=-5');+ expect(limitArg()).toBe(2);+ });++ it('falls back to the safe defaults for an unknown type/network', async () => {+ const res = await call('?type=bogus&network=bogus');+ expect(res._json.body.data.type).toBe('all');+ expect(res._json.body.data.network).toBe('mainnet');+ });+});++describe('last-good snapshot ownership', () => {+ it('writes the snapshot on a first-page build', async () => {+ await call('?limit=40&type=tips');+ expect(h.sets).toContain('galaxy:flows:lastgood:mainnet:tips:40');+ });++ it('never lets a delta poll overwrite the first page snapshot', async () => {+ const cur = encodeCursor('2026-08-12T09:00:00.000Z', 'c900');+ await call(`?limit=41&type=tips&since=${cur}`);+ expect(h.sets).not.toContain('galaxy:flows:lastgood:mainnet:tips:41');+ // A delta poll is live data: it must not be served from the feed cache either.+ expect(h.sets).toHaveLength(0);+ });++ it('never lets a backfill page overwrite the first page snapshot', async () => {+ const cur = encodeCursor('2026-08-12T09:00:00.000Z', 'c900');+ await call(`?limit=42&type=tips&cursor=${cur}`);+ expect(h.sets).not.toContain('galaxy:flows:lastgood:mainnet:tips:42');+ });+});++describe('degraded paths', () => {+ it('serves the last-good snapshot when a first-page build fails', async () => {+ const snapshot = { flows: [{ id: 'c900' }], head_cursor: 'HEAD', network: 'mainnet', type: 'all' };+ h.cache.set('galaxy:flows:lastgood:mainnet:all:50', snapshot);+ h.failNext = true;++ const res = await call('?limit=50');+ expect(res._json.status).toBe(200);+ expect(res.getHeader('x-galaxy-flows-degraded')).toBe('error');+ expect(res._json.body.data).toEqual(snapshot);+ });++ it('answers a failed delta poll with an empty window that echoes the client cursor', async () => {+ const cur = encodeCursor('2026-08-12T09:00:00.000Z', 'c900');+ // A stale first-page snapshot exists — the poll must NOT be answered with it,+ // or the client rewinds its cursor and replays past flows as new light.+ h.cache.set('galaxy:flows:lastgood:mainnet:all:50', { flows: [{ id: 'c1' }], head_cursor: 'OLDHEAD' });+ h.failNext = true;++ const res = await call(`?limit=50&since=${cur}`);+ expect(res._json.status).toBe(200);+ expect(res.getHeader('x-galaxy-flows-degraded')).toBe('error-empty');+ const body = res._json.body.data;+ expect(body.flows).toEqual([]);+ expect(body.head_cursor).toBe(cur); // client keeps its place+ expect(body.summary.count).toBe(0);+ });++ it('answers a failed backfill page with an exhausted window, not a newer one', async () => {+ const cur = encodeCursor('2026-08-12T09:00:00.000Z', 'c900');+ h.cache.set('galaxy:flows:lastgood:mainnet:all:50', { flows: [{ id: 'c1' }], head_cursor: 'OLDHEAD' });+ h.failNext = true;++ const res = await call(`?limit=50&cursor=${cur}`);+ expect(res._json.body.data.flows).toEqual([]);+ expect(res._json.body.data.next_cursor).toBeNull();+ expect(res._json.body.data.head_cursor).toBeNull();+ });+});++describe('successful feed shape', () => {+ it('summarises exactly what it returned and offers a head cursor to poll from', async () => {+ const res = await call('?limit=10');+ const body = res._json.body.data;+ expect(body.flows).toHaveLength(1);+ expect(body.flows[0]).toMatchObject({ id: 'c900', kind: 'trade', direction: 'out' });+ expect(body.summary).toMatchObject({ count: 1, edges: 0, flares: 1 });+ expect(body.summary.by_kind.trade).toBe(1);+ expect(body.has_more).toBe(false);+ expect(body.head_cursor).toBe(encodeCursor('2026-08-12T09:00:00.000Z', 'c900'));+ expect(res.getHeader('cache-control')).toBe('public, max-age=6');+ });+});diff --git a/tests/inference-livepeer.test.js b/tests/inference-livepeer.test.jsnew file mode 100644index 000000000..966f9c183--- /dev/null+++ b/tests/inference-livepeer.test.js@@ -0,0 +1,329 @@+// /api/inference/livepeer behavior tests.+//+// The endpoint runs two inference legs side by side: the three.ws provider+// chain and a Livepeer AI gateway. What has to hold, and what these pin:+//+// 1. GET reports the resolved gateway, whether it is keyed, and whether it+// is usable at all, so the demo can warn before a run instead of after.+// 2. The unkeyed public gateway is REFUSED, not dialed. Its hostname stopped+// being Livepeer (docs/ops/livepeer-federation.md); dialing it would ship+// the user's prompt to an unidentified host.+// 3. LIVEPEER_GATEWAY_URL routes the leg at a self-hosted gateway, with the+// documented OpenAI-compatible envelope on the wire.+// 4. Both response shapes the gateway family returns (OpenAI `choices`, the+// older `{ response, tokens_used }`) parse into the same leg envelope.+// 5. Failures are per-leg, never per-request: a dead Livepeer gateway still+// returns 200 with the platform reply intact, coded and hinted.+// 6. Input validation rejects at the boundary with a 4xx JSON error.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const llmCompleteMock = vi.fn();+vi.mock('../api/_lib/llm.js', () => ({+ llmComplete: (...a) => llmCompleteMock(...a),+ LlmUnavailableError: class extends Error {},+}));++const rateLimitMock = vi.fn(async () => ({ success: true }));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { livepeerIp: (...a) => rateLimitMock(...a) },+ clientIp: () => '203.0.113.7',+}));++const { default: handler } = await import('../api/inference/livepeer.js');++const ENV_KEYS = ['LIVEPEER_API_KEY', 'LIVEPEER_GATEWAY_URL'];++function mkReq({ method = 'POST', body = null, headers = {} } = {}) {+ const hdrs = { ...headers };+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';+ return {+ method,+ url: '/api/inference/livepeer',+ headers: hdrs,+ on(event, cb) {+ if (event === 'data' && body != null) {+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));+ queueMicrotask(() => {+ cb(buf);+ this._endCb?.();+ });+ } else if (event === 'end') {+ this._endCb = cb;+ if (body == null) queueMicrotask(cb);+ }+ },+ destroy() {},+ };+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ writableEnded: false,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ end(b) {+ this.body = b;+ this.writableEnded = true;+ },+ };+}++const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);++async function call(req) {+ const res = mkRes();+ await handler(req, res);+ return { res, json: parse(res) };+}++function gatewayResponse(status, body) {+ return {+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+ text: async () => (typeof body === 'string' ? body : JSON.stringify(body)),+ };+}++const GOOD_PLATFORM = {+ text: 'pong',+ provider: 'groq',+ model: 'llama-3.3-70b',+ usage: { input: 8, output: 1 },+};++let fetchMock;++beforeEach(() => {+ for (const k of ENV_KEYS) delete process.env[k];+ llmCompleteMock.mockReset().mockResolvedValue(GOOD_PLATFORM);+ rateLimitMock.mockReset().mockResolvedValue({ success: true });+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+ for (const k of ENV_KEYS) delete process.env[k];+});++describe('GET /api/inference/livepeer', () => {+ it('reports the unkeyed public gateway as unusable, with the fix named', async () => {+ const { res, json } = await call(mkReq({ method: 'GET' }));+ expect(res.statusCode).toBe(200);+ expect(json.gateway).toBe('public');+ expect(json.keyed).toBe(false);+ expect(json.usable).toBe(false);+ expect(json.hint).toMatch(/LIVEPEER_API_KEY/);+ expect(json.models).toContain(json.default_model);+ });++ it('reports a keyed studio gateway as usable', async () => {+ process.env.LIVEPEER_API_KEY = 'lp_key_123';+ const { json } = await call(mkReq({ method: 'GET' }));+ expect(json).toMatchObject({+ gateway: 'studio',+ gateway_url: 'https://livepeer.studio/api/generate/llm',+ keyed: true,+ usable: true,+ });+ expect(json.hint).toBeUndefined();+ });++ it('reports a self-hosted override gateway', async () => {+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal:8088/';+ const { json } = await call(mkReq({ method: 'GET' }));+ expect(json.gateway).toBe('override');+ expect(json.gateway_url).toBe('https://gateway.internal:8088/llm');+ expect(json.usable).toBe(true);+ });+});++describe('POST /api/inference/livepeer input validation', () => {+ it('rejects a missing prompt with a 400 JSON error', async () => {+ const { res, json } = await call(mkReq({ body: {} }));+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('bad_request');+ expect(fetchMock).not.toHaveBeenCalled();+ expect(llmCompleteMock).not.toHaveBeenCalled();+ });++ it('rejects a whitespace-only prompt', async () => {+ const { res, json } = await call(mkReq({ body: { prompt: ' \n ' } }));+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('bad_request');+ });++ it('rejects malformed JSON with a 400, not a stack trace', async () => {+ const { res, json } = await call(mkReq({ body: '{not json' }));+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('bad_request');+ expect(String(json.error_description)).not.toMatch(/\bat \w+ \(/);+ });++ it('rejects a non-POST, non-GET method', async () => {+ const { res } = await call(mkReq({ method: 'PUT' }));+ expect(res.statusCode).toBe(405);+ });++ it('returns 429 when the per-IP limiter trips, before any upstream call', async () => {+ rateLimitMock.mockResolvedValue({ success: false, limit: 20, remaining: 0, reset: Date.now() + 1000 });+ const { res } = await call(mkReq({ body: { prompt: 'hi' } }));+ expect(res.statusCode).toBe(429);+ expect(llmCompleteMock).not.toHaveBeenCalled();+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('clamps max_tokens and temperature into range', async () => {+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal';+ fetchMock.mockResolvedValue(gatewayResponse(200, { choices: [{ message: { content: 'ok' } }] }));+ const { json } = await call(mkReq({ body: { prompt: 'hi', max_tokens: 999999, temperature: 12 } }));+ expect(json.max_tokens).toBe(2048);+ expect(json.temperature).toBe(2);+ const sent = JSON.parse(fetchMock.mock.calls[0][1].body);+ expect(sent.max_tokens).toBe(2048);+ expect(sent.temperature).toBe(2);+ });+});++describe('POST /api/inference/livepeer Livepeer leg', () => {+ it('refuses the unkeyed public gateway instead of dialing it', async () => {+ const { res, json } = await call(mkReq({ body: { prompt: 'hi' } }));+ expect(res.statusCode).toBe(200);+ expect(fetchMock).not.toHaveBeenCalled();+ expect(json.livepeer).toMatchObject({ ok: false, gateway: 'public', error: 'gateway_unavailable' });+ expect(json.livepeer.hint).toMatch(/LIVEPEER_GATEWAY_URL/);+ // The refusal is per leg: the platform side still answered.+ expect(json.platform).toMatchObject({ ok: true, provider: 'groq', reply: 'pong' });+ });++ it('posts the OpenAI-compatible envelope to a keyed studio gateway', async () => {+ process.env.LIVEPEER_API_KEY = 'lp_key_123';+ fetchMock.mockResolvedValue(+ gatewayResponse(200, {+ choices: [{ message: { content: ' hello from an orchestrator ' } }],+ usage: { prompt_tokens: 11, completion_tokens: 5 },+ }),+ );++ const { json } = await call(mkReq({ body: { prompt: 'hi', model: 'Qwen/Qwen2.5-7B-Instruct' } }));++ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('https://livepeer.studio/api/generate/llm');+ expect(init.headers.authorization).toBe('Bearer lp_key_123');+ expect(JSON.parse(init.body)).toMatchObject({+ model: 'Qwen/Qwen2.5-7B-Instruct',+ messages: [{ role: 'user', content: 'hi' }],+ stream: false,+ });+ expect(init.signal).toBeInstanceOf(AbortSignal);++ expect(json.livepeer).toMatchObject({+ ok: true,+ network: 'Livepeer',+ gateway: 'studio',+ reply: 'hello from an orchestrator',+ prompt_tokens: 11,+ completion_tokens: 5,+ });+ });++ it('parses the older { response, tokens_used } gateway shape', async () => {+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal';+ fetchMock.mockResolvedValue(gatewayResponse(200, { response: 'legacy reply', tokens_used: 40 }));++ const { json } = await call(mkReq({ body: { prompt: 'a'.repeat(40) } }));++ expect(fetchMock.mock.calls[0][0]).toBe('https://gateway.internal/llm');+ expect(json.livepeer.ok).toBe(true);+ expect(json.livepeer.reply).toBe('legacy reply');+ expect(json.livepeer.prompt_tokens).toBe(10);+ expect(json.livepeer.completion_tokens).toBe(30);+ });++ it('codes a non-2xx gateway as upstream_error and keeps the request 200', async () => {+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal';+ fetchMock.mockResolvedValue(gatewayResponse(503, 'no orchestrators available'));++ const { res, json } = await call(mkReq({ body: { prompt: 'hi' } }));++ expect(res.statusCode).toBe(200);+ expect(json.ok).toBe(true);+ expect(json.livepeer).toMatchObject({+ ok: false,+ error: 'upstream_error',+ upstream_status: 503,+ upstream_body: 'no orchestrators available',+ });+ expect(json.livepeer.hint).toMatch(/another model/i);+ expect(json.platform.ok).toBe(true);+ });++ it('codes an aborted gateway call as gateway_timeout, not a socket error', async () => {+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal';+ fetchMock.mockRejectedValue(Object.assign(new Error('The operation was aborted due to timeout'), { name: 'TimeoutError' }));++ const { json } = await call(mkReq({ body: { prompt: 'hi' } }));++ expect(json.livepeer).toMatchObject({ ok: false, error: 'gateway_timeout' });+ expect(json.livepeer.error_message).toMatch(/45s/);+ });++ it('codes a socket failure as gateway_unreachable', async () => {+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal';+ fetchMock.mockRejectedValue(new TypeError('fetch failed'));++ const { json } = await call(mkReq({ body: { prompt: 'hi' } }));++ expect(json.livepeer).toMatchObject({ ok: false, error: 'gateway_unreachable' });+ expect(json.livepeer.error_message).toMatch(/fetch failed/);+ });++ it('flags a 200 with no usable text as empty_response', async () => {+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal';+ fetchMock.mockResolvedValue(gatewayResponse(200, { choices: [] }));++ const { json } = await call(mkReq({ body: { prompt: 'hi' } }));++ expect(json.livepeer.ok).toBe(false);+ expect(json.livepeer.error).toBe('empty_response');+ });+});++describe('POST /api/inference/livepeer platform leg', () => {+ it('names the provider that actually answered, never a fixed vendor', async () => {+ llmCompleteMock.mockResolvedValue({+ text: 'hi there',+ provider: 'ovh',+ model: 'Meta-Llama-3_3-70B-Instruct',+ usage: { input: 4, output: 2 },+ });++ const { json } = await call(mkReq({ body: { prompt: 'hi' } }));++ expect(json.platform).toMatchObject({+ ok: true,+ network: 'three.ws',+ provider: 'ovh',+ model: 'Meta-Llama-3_3-70B-Instruct',+ });+ });++ it('reports no_provider_configured when the whole chain is unavailable', async () => {+ llmCompleteMock.mockRejectedValue(Object.assign(new Error('no provider'), { code: 'llm_unavailable' }));+ process.env.LIVEPEER_GATEWAY_URL = 'https://gateway.internal';+ fetchMock.mockResolvedValue(gatewayResponse(200, { choices: [{ message: { content: 'up' } }] }));++ const { res, json } = await call(mkReq({ body: { prompt: 'hi' } }));++ expect(res.statusCode).toBe(200);+ expect(json.platform).toMatchObject({ ok: false, error: 'no_provider_configured', provider: null });+ // The other leg is unaffected: one dead provider must not blank the page.+ expect(json.livepeer.ok).toBe(true);+ });+});diff --git a/tests/intel-endpoints.test.js b/tests/intel-endpoints.test.jsnew file mode 100644index 000000000..b4c39746b--- /dev/null+++ b/tests/intel-endpoints.test.js@@ -0,0 +1,247 @@+// Handler tests for the four public /api/intel read endpoints:+// GET /api/intel/heatmap (live token field behind the 3D heatmap)+// GET /api/intel/yields (DeFiLlama yield pools)+// GET /api/intel/smart-money (coin + wallet reputation reads)+// GET /api/intel/wallet/:addr (one wallet's reputation card)+//+// Each endpoint gets its success path and one failure path. The upstreams+// (pump.fun, Dexscreener, DeFiLlama, the reputation graph) are the seams the+// handlers own, so those are stubbed here; the handler logic itself, including+// the anchor pinning, the flow pulse, address validation, and the 502/400+// boundaries, runs for real.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ publicIp: vi.fn(async () => ({ success: true })),+ mcpIp: vi.fn(async () => ({ success: true })),+ },+ clientIp: () => '127.0.0.1',+}));++const getYieldPoolsMock = vi.fn();+vi.mock('../api/_lib/market-data.js', () => ({ getYieldPools: (...a) => getYieldPoolsMock(...a) }));++const getSmartMoneyForMintMock = vi.fn();+const getWalletReputationMock = vi.fn();+vi.mock('../api/_lib/smart-money.js', () => ({+ getSmartMoneyForMint: (...a) => getSmartMoneyForMintMock(...a),+ getWalletReputation: (...a) => getWalletReputationMock(...a),+}));++const { default: heatmapHandler, _resetHeatmapCache } = await import('../api/intel/heatmap.js');+const { default: yieldsHandler } = await import('../api/intel/yields.js');+const { default: smartMoneyHandler } = await import('../api/intel/smart-money.js');+const { default: walletHandler } = await import('../api/intel/wallet/[address].js');++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const OTHER_MINT = 'THREEsynthetic1111111111111111111111111111';+const WALLET = 'THREEsyntheticWa11et1111111111111111111111';++function mkReq({ method = 'GET', url = '/', headers = {} } = {}) {+ return { method, url, headers: { host: 'three.ws', ...headers }, socket: {}, on() {}, destroy() {} };+}+function mkRes() {+ return {+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(b) { this.body = b; this.writableEnded = true; },+ };+}+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);++// One Dexscreener pair as the live API shapes it (only the fields the handler reads).+const pair = (mint, over = {}) => ({+ baseToken: { address: mint, symbol: 'sym', name: 'name' },+ priceUsd: '0.0016',+ priceChange: { h24: -4.03 },+ volume: { h24: 79088.64 },+ txns: { h24: { buys: 700, sells: 300 } },+ marketCap: 1625310,+ info: { imageUrl: 'https://cdn.example/img.png' },+ ...over,+});++// Routes the handler's three upstream calls (pump trending, Dexscreener batch,+// pump coin metadata) off one table so a case can fail exactly one of them.+function stubUpstreams({ trending = [OTHER_MINT], pairs = null, meta = { symbol: 'three', name: 'three.ws' }, dexStatus = 200 } = {}) {+ const dexPairs = pairs ?? [pair(THREE_MINT), pair(OTHER_MINT)];+ vi.stubGlobal('fetch', vi.fn(async (input) => {+ const url = String(input);+ if (url.includes('/coins?') || /\/coins\?/.test(url)) {+ return new Response(JSON.stringify(trending.map((mint) => ({ mint }))), { status: 200 });+ }+ if (url.includes('/latest/dex/tokens/')) {+ if (dexStatus !== 200) return new Response('upstream down', { status: dexStatus });+ return new Response(JSON.stringify({ pairs: dexPairs }), { status: 200 });+ }+ if (url.includes('/coins/')) {+ return new Response(JSON.stringify(meta ?? { error: 'not found' }), { status: 200 });+ }+ return new Response('not found', { status: 404 });+ }));+}++beforeEach(() => {+ vi.unstubAllGlobals();+ _resetHeatmapCache();+ getYieldPoolsMock.mockReset();+ getSmartMoneyForMintMock.mockReset();+ getWalletReputationMock.mockReset();+});++describe('GET /api/intel/heatmap', () => {+ it('pins $THREE first, flags it featured, and folds in its 24h order flow', async () => {+ stubUpstreams();+ const res = mkRes();+ await heatmapHandler(mkReq({ url: '/api/intel/heatmap?limit=5' }), res);++ expect(res.statusCode).toBe(200);+ const body = parse(res);+ expect(body.ok).toBe(true);+ expect(body.anchor).toBe(THREE_MINT);+ expect(body.tokens[0].id).toBe(THREE_MINT);+ expect(body.tokens[0].featured).toBe(true);+ // 700 buys / 300 sells => 70% buys, score +0.4.+ expect(body.tokens[0].flow).toEqual({ buys24h: 700, sells24h: 300, buyPct: 70, score: 0.4 });+ // The flow pulse is an anchor-only enrichment.+ expect(body.tokens[1].featured).toBe(false);+ expect(body.tokens[1].flow).toBeUndefined();+ });++ it('keeps the field alive with no anchor trade history (flow omitted, tile still served)', async () => {+ stubUpstreams({ pairs: [pair(THREE_MINT, { txns: { h24: { buys: 0, sells: 0 } } }), pair(OTHER_MINT)] });+ const res = mkRes();+ await heatmapHandler(mkReq({ url: '/api/intel/heatmap?limit=5' }), res);++ expect(res.statusCode).toBe(200);+ const body = parse(res);+ expect(body.tokens[0].id).toBe(THREE_MINT);+ expect(body.tokens[0].flow).toBeUndefined();+ });++ it('502s with a JSON error when every market upstream is down', async () => {+ stubUpstreams({ trending: [], pairs: [], dexStatus: 503, meta: null });+ const res = mkRes();+ await heatmapHandler(mkReq({ url: '/api/intel/heatmap' }), res);++ expect(res.statusCode).toBe(502);+ expect(parse(res).error).toBe('upstream_error');+ });++ it('rejects a non-GET method', async () => {+ stubUpstreams();+ const res = mkRes();+ await heatmapHandler(mkReq({ method: 'POST', url: '/api/intel/heatmap' }), res);+ expect(res.statusCode).toBe(405);+ });+});++describe('GET /api/intel/yields', () => {+ it('returns live pools and strips the upstream ilRisk field', async () => {+ getYieldPoolsMock.mockResolvedValue([+ { pool: 'p1', project: 'lido', chain: 'Ethereum', symbol: 'STETH', tvlUsd: 1e9, apy: 2.1, apyBase: 2.1, apyReward: 0, stablecoin: false, ilRisk: 'no' },+ ]);+ const res = mkRes();+ await yieldsHandler(mkReq({ url: '/api/intel/yields?chain=Ethereum&stablecoin=false&limit=1' }), res);++ expect(res.statusCode).toBe(200);+ expect(getYieldPoolsMock).toHaveBeenCalledWith({ chain: 'Ethereum', project: undefined, stablecoin: false, limit: 1 });+ const body = parse(res);+ expect(body.pools).toHaveLength(1);+ expect(body.pools[0].project).toBe('lido');+ expect(body.pools[0]).not.toHaveProperty('ilRisk');+ });++ it('clamps a junk limit to the default and an oversized one to the max', async () => {+ getYieldPoolsMock.mockResolvedValue([]);+ await yieldsHandler(mkReq({ url: '/api/intel/yields?limit=abc' }), mkRes());+ expect(getYieldPoolsMock.mock.calls[0][0].limit).toBe(25);++ await yieldsHandler(mkReq({ url: '/api/intel/yields?limit=99999' }), mkRes());+ expect(getYieldPoolsMock.mock.calls[1][0].limit).toBe(100);+ });++ it('502s with a JSON error when DeFiLlama is unreachable', async () => {+ getYieldPoolsMock.mockRejectedValue(new Error('llama down'));+ const res = mkRes();+ await yieldsHandler(mkReq({ url: '/api/intel/yields' }), res);++ expect(res.statusCode).toBe(502);+ expect(parse(res).error).toBe('upstream_error');+ });+});++describe('GET /api/intel/smart-money', () => {+ it('serves a coin read for a valid mint', async () => {+ getSmartMoneyForMintMock.mockResolvedValue({ mint: THREE_MINT, network: 'mainnet', smart_money_score: 42, computed: true });+ const res = mkRes();+ await smartMoneyHandler(mkReq({ url: `/api/intel/smart-money?mint=${THREE_MINT}` }), res);++ expect(res.statusCode).toBe(200);+ expect(getSmartMoneyForMintMock).toHaveBeenCalledWith(THREE_MINT, 'mainnet');+ expect(parse(res).smart_money_score).toBe(42);+ });++ it('serves a wallet read and honours the devnet network param', async () => {+ getWalletReputationMock.mockResolvedValue({ address: WALLET, network: 'devnet', computed: false });+ const res = mkRes();+ await smartMoneyHandler(mkReq({ url: `/api/intel/smart-money?wallet=${WALLET}&network=devnet` }), res);++ expect(res.statusCode).toBe(200);+ expect(getWalletReputationMock).toHaveBeenCalledWith(WALLET, 'devnet');+ });++ it('400s when neither mint nor wallet is supplied', async () => {+ const res = mkRes();+ await smartMoneyHandler(mkReq({ url: '/api/intel/smart-money' }), res);++ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('bad_request');+ });++ it('400s on a non-base58 address instead of querying the graph with junk', async () => {+ const bad = mkRes();+ await smartMoneyHandler(mkReq({ url: '/api/intel/smart-money?wallet=%3Cscript%3E' }), bad);+ expect(bad.statusCode).toBe(400);++ const badMint = mkRes();+ await smartMoneyHandler(mkReq({ url: '/api/intel/smart-money?mint=not-a-mint' }), badMint);+ expect(badMint.statusCode).toBe(400);++ expect(getWalletReputationMock).not.toHaveBeenCalled();+ expect(getSmartMoneyForMintMock).not.toHaveBeenCalled();+ });+});++describe('GET /api/intel/wallet/:address', () => {+ it('reads the address from the path when no query param is injected', async () => {+ getWalletReputationMock.mockResolvedValue({ address: WALLET, network: 'mainnet', computed: false });+ const res = mkRes();+ await walletHandler(mkReq({ url: `/api/intel/wallet/${WALLET}` }), res);++ expect(res.statusCode).toBe(200);+ expect(getWalletReputationMock).toHaveBeenCalledWith(WALLET, 'mainnet');+ expect(parse(res).computed).toBe(false);+ });++ it('prefers the injected address query param (the routed shape)', async () => {+ getWalletReputationMock.mockResolvedValue({ address: WALLET, network: 'mainnet', computed: true });+ const res = mkRes();+ await walletHandler(mkReq({ url: `/api/intel/wallet/[address]?address=${WALLET}` }), res);++ expect(res.statusCode).toBe(200);+ expect(getWalletReputationMock).toHaveBeenCalledWith(WALLET, 'mainnet');+ });++ it('400s on a malformed address', async () => {+ const res = mkRes();+ await walletHandler(mkReq({ url: '/api/intel/wallet/xyz' }), res);++ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('bad_request');+ expect(getWalletReputationMock).not.toHaveBeenCalled();+ });+});diff --git a/tests/labor-tick-batch.test.js b/tests/labor-tick-batch.test.jsnew file mode 100644index 000000000..b43b9e05b--- /dev/null+++ b/tests/labor-tick-batch.test.js@@ -0,0 +1,240 @@+// Regression guard for the Agent Labor Market cron driver (api/labor/tick.js).+//+// 2026-08-13 audit found three defects in the batch loops, all of which look like+// an idle market from the outside:+//+// 1. HEAD-OF-LINE STARVATION. Both scans are `ORDER BY created_at ASC LIMIT 10`,+// so a row the driver can never advance holds a slot on every tick forever.+// The job scan selected any 'working' job, but runAutopilot returns+// immediately unless the worker opted into autonomy — so ten jobs held by+// manual workers (who deliver through /deliver, on their own time) consumed+// the whole batch and no autonomous job was ever driven again. The bounty scan+// admitted any open bounty with >= 1 pending bid, but autoAwardIfReady+// declines until the poster's min_bids is met, so under-bid bounties could+// block award-ready ones out of the batch.+// 2. IDEMPOTENT SETTLES COUNTED AS WORK. runSettlement returns+// `{ idempotent: true, status: 'settled' }` when another caller already won the+// claim. The tick counted that as a settlement it performed, inflating the+// number the economy heartbeat reports.+// 3. NO ERROR ISOLATION OR REPORTING. Row reads inside the loop were unguarded,+// so one transient failure aborted the rest of the batch, and every driver+// failure was swallowed by `.catch(() => null)` — a fully stalled lane+// reported `{ ok: true, settled: 0 }`, indistinguishable from a quiet minute.+//+// The sql double models only what those bugs turn on: which rows each scan asks+// for. A handler that drops the worker_enabled requirement, the min_bids+// priority, or the per-row guards fails here.++import { describe, it, expect, beforeEach, vi } from 'vitest';++const h = vi.hoisted(() => {+ process.env.CRON_SECRET = 'test-cron-secret';+ return {+ sql: vi.fn(),+ runAutopilot: vi.fn(),+ runSettlement: vi.fn(),+ getBounty: vi.fn(),+ getJob: vi.fn(),+ };+});++vi.mock('../api/_lib/db.js', () => ({+ sql: (...a) => h.sql(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));+vi.mock('../api/_lib/agent-labor.js', () => ({+ ensureLaborTables: vi.fn(async () => true),+ getBounty: (...a) => h.getBounty(...a),+ getJob: (...a) => h.getJob(...a),+}));+vi.mock('../api/_lib/labor-settle.js', () => ({+ runAutopilot: (...a) => h.runAutopilot(...a),+ runSettlement: (...a) => h.runSettlement(...a),+}));++const { default: handler } = await import('../api/labor/tick.js');++function mockRes() {+ return {+ statusCode: 0,+ headersSent: false,+ writableEnded: false,+ headers: {},+ body: null,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(payload) {+ this.writableEnded = true;+ this.body = payload ? JSON.parse(payload) : null;+ },+ };+}++const req = (over = {}) => ({+ method: 'POST',+ url: '/api/labor/tick',+ headers: { authorization: 'Bearer test-cron-secret' },+ ...over,+});++// The rows each scan would return, and the query text the handler asked with.+let bountyRows;+let jobRows;+let queries;++function installSql() {+ queries = { bounties: null, jobs: null };+ h.sql.mockImplementation((strings) => {+ const q = Array.isArray(strings) ? strings.join(' ? ') : String(strings);+ if (/FROM agent_bounties/i.test(q)) {+ queries.bounties = q;+ return Promise.resolve(bountyRows);+ }+ if (/FROM agent_jobs/i.test(q)) {+ queries.jobs = q;+ return Promise.resolve(jobRows);+ }+ return Promise.resolve([]);+ });+}++async function tick(over) {+ const res = mockRes();+ await handler(req(over), res);+ return res;+}++beforeEach(() => {+ vi.clearAllMocks();+ bountyRows = [];+ jobRows = [];+ installSql();+ h.runAutopilot.mockResolvedValue({ bids: 0, awarded: false, settled: null, settledNow: false });+ h.runSettlement.mockResolvedValue({ settled: true, status: 'settled' });+ h.getBounty.mockResolvedValue({ id: 'b1', title: 'T', poster_agent_id: 'p' });+ h.getJob.mockImplementation(async (id) => ({ id, status: 'delivered', worker_agent_id: 'w' }));+});++describe('labor tick — auth and method gates', () => {+ it('rejects a caller without the cron secret', async () => {+ const res = await tick({ headers: {} });+ expect(res.statusCode).toBe(401);+ expect(h.sql).not.toHaveBeenCalled();+ });++ it('rejects a method the handler does not serve', async () => {+ const res = await tick({ method: 'DELETE' });+ expect(res.statusCode).toBe(405);+ expect(h.sql).not.toHaveBeenCalled();+ });+});++describe('labor tick — scans only rows it can advance', () => {+ it('requires an autonomous worker before scanning a working job', async () => {+ await tick();+ // A 'working' job is only admitted alongside an enabled worker policy: that+ // is the whole fix for the manual-worker head-of-line block.+ expect(queries.jobs).toMatch(/agent_labor_policies/);+ expect(queries.jobs).toMatch(/worker_enabled/);+ expect(queries.jobs).toMatch(/delivered/);+ expect(queries.jobs).toMatch(/verifying/);+ });++ it('sorts award-ready bounties ahead of ones still gathering bids', async () => {+ await tick();+ expect(queries.bounties).toMatch(/min_bids/);+ expect(queries.bounties).toMatch(/pending_bids >= min_bids\) DESC/);+ });++ it('bounds both scans inside the statement', async () => {+ await tick();+ expect(queries.bounties).toMatch(/LIMIT/i);+ expect(queries.jobs).toMatch(/LIMIT/i);+ });+});++describe('labor tick — counting', () => {+ it('reports real progress across both lanes', async () => {+ bountyRows = [{ id: 'b1' }, { id: 'b2' }];+ jobRows = [{ id: 'j1', bounty_id: 'b9', status: 'delivered' }];+ h.runAutopilot+ .mockResolvedValueOnce({ bids: 2, awarded: true, settled: 'settled', settledNow: true })+ .mockResolvedValueOnce({ bids: 1, awarded: false, settled: null, settledNow: false });++ const res = await tick();+ expect(res.statusCode).toBe(200);+ expect(res.body).toMatchObject({+ ok: true, scanned: 3, bids: 3, awarded: 1, settled: 2, failed: 0,+ });+ expect(res.body.errors).toBeUndefined();+ });++ it('does not count a settle another caller already claimed', async () => {+ jobRows = [{ id: 'j1', bounty_id: 'b1', status: 'verifying' }];+ h.runSettlement.mockResolvedValue({ idempotent: true, status: 'settled' });++ const res = await tick();+ expect(res.body).toMatchObject({ ok: true, scanned: 1, settled: 0, failed: 0 });+ });++ it('does not count an autopilot settle that only observed a prior payout', async () => {+ bountyRows = [{ id: 'b1' }];+ h.runAutopilot.mockResolvedValue({ bids: 0, awarded: false, settled: 'settled', settledNow: false });++ const res = await tick();+ expect(res.body).toMatchObject({ scanned: 1, settled: 0 });+ });++ it('drives a working job without re-fetching its bounty', async () => {+ jobRows = [{ id: 'j1', bounty_id: 'b1', status: 'working' }];+ await tick();+ expect(h.runAutopilot).toHaveBeenCalledWith('b1');+ expect(h.getBounty).not.toHaveBeenCalled();+ });+});++describe('labor tick — failure isolation', () => {+ it('finishes the batch when one row fails, and says which', async () => {+ jobRows = [+ { id: 'j1', bounty_id: 'b1', status: 'delivered' },+ { id: 'j2', bounty_id: 'b2', status: 'delivered' },+ ];+ h.getJob.mockImplementationOnce(async () => { throw new Error('connection reset'); });++ const res = await tick();+ expect(res.statusCode).toBe(200);+ expect(res.body).toMatchObject({ ok: true, scanned: 2, settled: 1, failed: 1 });+ expect(res.body.errors).toHaveLength(1);+ expect(res.body.errors[0]).toContain('j1');+ expect(res.body.errors[0]).toContain('connection reset');+ expect(res.body.reason).toBe('1/2 items failed');+ // The second job still settled: the throw did not abort the loop.+ expect(h.runSettlement).toHaveBeenCalledTimes(1);+ });++ it('reports a lane where every row failed as an outage, not an idle tick', async () => {+ jobRows = [{ id: 'j1', bounty_id: 'b1', status: 'delivered' }];+ h.runSettlement.mockRejectedValue(new Error('escrow unreachable'));++ const res = await tick();+ expect(res.statusCode).toBe(502);+ expect(res.body).toMatchObject({ ok: false, scanned: 1, settled: 0, failed: 1 });+ });++ it('caps the reported errors so a batch-wide failure cannot bloat the response', async () => {+ jobRows = Array.from({ length: 8 }, (_, i) => ({ id: `j${i}`, bounty_id: 'b1', status: 'delivered' }));+ h.runSettlement.mockRejectedValue(new Error('escrow unreachable'));++ const res = await tick();+ expect(res.body.failed).toBe(8);+ expect(res.body.errors).toHaveLength(5);+ });++ it('stays quiet and healthy when there is nothing to do', async () => {+ const res = await tick();+ expect(res.statusCode).toBe(200);+ expect(res.body).toMatchObject({ ok: true, scanned: 0, settled: 0, failed: 0 });+ expect(res.body.reason).toBeUndefined();+ });+});diff --git a/tests/ledger-endpoints.test.js b/tests/ledger-endpoints.test.jsnew file mode 100644index 000000000..550fab74a--- /dev/null+++ b/tests/ledger-endpoints.test.js@@ -0,0 +1,313 @@+/**+ * GET /api/ledger/:agentId and GET /api/ledger/verify/:agentId — the two public+ * Reasoning Ledger reads.+ *+ * Both handlers run for real against an in-memory `sql` that speaks enough of the+ * agent_decisions / decision_outcomes / agent_identities / ledger_anchors schema+ * for their actual queries (composed fragments included). The chains under test+ * are built with the real buildChain, so every hash the verify endpoint checks is+ * a genuine one and a tampered entry fails exactly the way production would.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++const h = vi.hoisted(() => {+ const store = { decisions: [], outcomes: [], identities: [], anchors: [] };++ // Flatten a tagged template (with nested fragments) the way api/_lib/db.js does.+ function flatten(node) {+ let text = '';+ const params = [];+ const walk = (strings, values) => {+ for (let i = 0; i < strings.length; i++) {+ text += strings[i];+ if (i < values.length) {+ const v = values[i];+ if (v && v.__frag) walk(v.strings, v.values);+ else { params.push(v); text += '$' + params.length; }+ }+ }+ };+ walk(node.strings, node.values);+ return { text: text.toLowerCase().replace(/\s+/g, ' '), params };+ }++ function exec({ text, params }) {+ if (text.includes('from agent_identities')) {+ const [id] = params;+ const row = store.identities.find((a) => a.id === id);+ return row ? [{ ...row }] : [];+ }+ if (text.includes('from ledger_anchors')) {+ const [agentId] = params;+ const anchored = text.includes("status = 'anchored'");+ const rows = store.anchors+ .filter((a) => a.agent_id === agentId && (!anchored || a.status === 'anchored'))+ .sort((a, b) => Number(b.through_seq) - Number(a.through_seq));+ return rows.length ? [{ ...rows[0] }] : [];+ }+ // Reputation records: one row per decision, outcome left-joined.+ if (text.includes('d.kind, d.confidence, d.decided_at')) {+ const [agentId] = params;+ return store.decisions.filter((d) => d.agent_id === agentId).map((d) => {+ const o = store.outcomes.find((x) => x.decision_id === d.id);+ return { kind: d.kind, confidence: d.confidence, decided_at: d.decided_at, was_correct: o ? o.was_correct : null, pnl_sol: o ? o.pnl_sol : null };+ });+ }+ // Timeline, newest first, with the optional kind / q / before fragments.+ if (text.includes('order by d.seq desc')) {+ let i = 0;+ const agentId = params[i++];+ const kind = text.includes('d.kind = $') ? params[i++] : null;+ const q = text.includes('ilike') ? (i += 2, params[i - 2]) : null;+ const beforeSeq = text.includes('d.seq < $') ? params[i++] : null;+ const limit = Number(params[i]);+ const needle = q ? String(q).replace(/%/g, '').toLowerCase() : null;+ return store.decisions+ .filter((d) => d.agent_id === agentId)+ .filter((d) => (kind ? d.kind === kind : true))+ .filter((d) => (beforeSeq != null ? Number(d.seq) < Number(beforeSeq) : true))+ .filter((d) => (needle+ ? String(d.rationale || '').toLowerCase().includes(needle) || String(d.subject_ref || '').toLowerCase().includes(needle)+ : true))+ .sort((a, b) => Number(b.seq) - Number(a.seq))+ .slice(0, limit)+ .map((d) => {+ const o = store.outcomes.find((x) => x.decision_id === d.id);+ return {+ ...d,+ observed: o ? o.observed : null,+ was_correct: o ? o.was_correct : null,+ pnl_sol: o ? o.pnl_sol : null,+ impact: o ? o.impact : null,+ outcome_status: o ? o.status : null,+ reconciled_at: o ? o.reconciled_at : null,+ };+ });+ }+ // Full chain, ascending — what the verify endpoint rehashes.+ if (text.includes('from agent_decisions') && text.includes('order by seq asc')) {+ const [agentId] = params;+ return store.decisions.filter((d) => d.agent_id === agentId).sort((a, b) => Number(a.seq) - Number(b.seq)).map((d) => ({ ...d }));+ }+ return [];+ }++ const fakeSql = (strings, ...values) => {+ let settled = null;+ const run = () => (settled ||= Promise.resolve().then(() => exec(flatten(node))));+ const node = {+ __frag: true,+ strings,+ values,+ then: (a, b) => run().then(a, b),+ catch: (b) => run().catch(b),+ finally: (f) => run().finally(f),+ };+ return node;+ };+ return { store, fakeSql };+});++vi.mock('../api/_lib/db.js', () => ({+ sql: h.fakeSql,+ sqlValues: () => {},+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false }),+}));++const { buildChain } = await import('../api/_lib/reasoning-ledger.js');+const { default: timelineHandler } = await import('../api/ledger/[agentId].js');+const { default: verifyHandler } = await import('../api/ledger/verify/[agentId].js');++const AGENT = '22222222-2222-2222-2222-222222222222';++function makeReq(url, query) {+ return { method: 'GET', url, headers: {}, ...(query ? { query } : {}) };+}+function makeRes() {+ const r = { statusCode: 200, _h: {}, _b: null, headersSent: false, writableEnded: false };+ r.setHeader = (k, v) => { r._h[k.toLowerCase()] = v; };+ r.getHeader = (k) => r._h[k.toLowerCase()];+ r.end = (b) => { r._b = b; r.writableEnded = true; };+ r.body = () => JSON.parse(r._b);+ return r;+}+async function call(handler, url, query) {+ const res = makeRes();+ await handler(makeReq(url, query), res);+ return res;+}++/** Seed `n` real chain entries (hashes computed by the production builder). */+async function seedChain(n, over = {}) {+ const raw = Array.from({ length: n }, (_, i) => ({+ kind: 'snipe',+ subject_ref: `mint-${i + 1}`,+ action_ref: `pos-${i + 1}`,+ inputs: { position_id: `pos-${i + 1}` },+ rationale: `decision number ${i + 1}`,+ prediction: { direction: 'up' },+ confidence: 0.8,+ network: 'mainnet',+ decided_at: new Date(1_700_000_000_000 + i * 1000).toISOString(),+ ...over,+ }));+ const chain = await buildChain(AGENT, raw);+ store().decisions.push(...chain.map((e, i) => ({ ...e, id: `dec-${i + 1}` })));+ return chain;+}+const store = () => h.store;++beforeEach(() => {+ h.store.decisions = [];+ h.store.outcomes = [];+ h.store.identities = [];+ h.store.anchors = [];+});++describe('GET /api/ledger/:agentId', () => {+ it('returns the timeline, reputation, and a reconciled outcome', async () => {+ await seedChain(3);+ h.store.identities.push({ id: AGENT, name: 'Sniper One', profile_image_url: 'https://cdn.example/a.png', avatar_url: null, is_public: true, deleted_at: null });+ h.store.outcomes.push({ decision_id: 'dec-1', observed: { sell_sig: 'sig-1' }, was_correct: true, pnl_sol: 1.5, impact: 0.2, status: 'reconciled', reconciled_at: '2026-08-01T00:00:00.000Z' });++ const res = await call(timelineHandler, `/api/ledger/${AGENT}`);+ expect(res.statusCode).toBe(200);+ const body = res.body();+ expect(body.agent).toEqual({ id: AGENT, name: 'Sniper One', image: 'https://cdn.example/a.png' });+ expect(body.decisions).toHaveLength(3);+ expect(body.decisions[0].seq).toBe(3);+ expect(body.decisions[0].outcome.status).toBe('pending');+ const reconciled = body.decisions.find((d) => d.seq === 1);+ expect(reconciled.outcome).toMatchObject({ status: 'reconciled', was_correct: true, pnl_sol: 1.5 });+ expect(reconciled.outcome.proof_url).toBe('https://solscan.io/tx/sig-1');+ expect(body.reputation.sample_size).toBe(1);+ expect(body.reputation.pending_count).toBe(2);+ expect(body.paging.next_before_seq).toBeNull();+ expect(res.getHeader('cache-control')).toContain('s-maxage');+ });++ it('pages: a full page hands back the cursor the next call resumes from', async () => {+ await seedChain(3);+ const first = await call(timelineHandler, `/api/ledger/${AGENT}?limit=2`);+ expect(first.body().decisions.map((d) => d.seq)).toEqual([3, 2]);+ expect(first.body().paging.next_before_seq).toBe(2);++ const second = await call(timelineHandler, `/api/ledger/${AGENT}?limit=2&before=2`);+ expect(second.body().decisions.map((d) => d.seq)).toEqual([1]);+ expect(second.body().paging.next_before_seq).toBeNull();+ });++ it('filters by kind and free text', async () => {+ await seedChain(2);+ await (async () => {+ const extra = await buildChain(AGENT, [{ kind: 'exit', subject_ref: 'mint-9', action_ref: 'pos-9', inputs: {}, rationale: 'took profit', prediction: {}, confidence: 0.4, network: 'mainnet', decided_at: '2026-08-02T00:00:00.000Z' }], 3, h.store.decisions[1].entry_hash);+ h.store.decisions.push({ ...extra[0], id: 'dec-3' });+ })();++ const byKind = await call(timelineHandler, `/api/ledger/${AGENT}?kind=exit`);+ expect(byKind.body().decisions.map((d) => d.kind)).toEqual(['exit']);+ const byText = await call(timelineHandler, `/api/ledger/${AGENT}?q=took%20profit`);+ expect(byText.body().decisions).toHaveLength(1);+ expect(byText.body().filters).toEqual({ kind: null, q: 'took profit' });+ });++ it('never publishes the name or avatar of a private or deleted agent', async () => {+ await seedChain(1);+ h.store.identities.push({ id: AGENT, name: 'Hidden', profile_image_url: 'https://cdn.example/h.png', avatar_url: null, is_public: false, deleted_at: null });+ const res = await call(timelineHandler, `/api/ledger/${AGENT}`);+ expect(res.body().agent).toEqual({ id: AGENT, name: null, image: null });+ expect(res.body().decisions).toHaveLength(1);++ h.store.identities[0] = { ...h.store.identities[0], is_public: true, deleted_at: '2026-08-01T00:00:00.000Z' };+ const deleted = await call(timelineHandler, `/api/ledger/${AGENT}`);+ expect(deleted.body().agent).toEqual({ id: AGENT, name: null, image: null });+ });++ it('rejects a malformed agent id, cursor, page size, and filter', async () => {+ const badId = await call(timelineHandler, '/api/ledger/not-a-uuid');+ expect(badId.statusCode).toBe(400);+ expect(badId.body().error).toBe('bad_request');++ const badCursor = await call(timelineHandler, `/api/ledger/${AGENT}?before=abc`);+ expect(badCursor.statusCode).toBe(400);+ expect(badCursor.body().error_description).toMatch(/before/);++ const overLimit = await call(timelineHandler, `/api/ledger/${AGENT}?limit=500`);+ expect(overLimit.statusCode).toBe(400);+ expect(overLimit.body().error_description).toMatch(/limit/);++ const longFilter = await call(timelineHandler, `/api/ledger/${AGENT}?q=${'x'.repeat(201)}`);+ expect(longFilter.statusCode).toBe(400);+ });++ it('treats an empty page-size param as unset and reads the id from req.query', async () => {+ await seedChain(1);+ const res = await call(timelineHandler, '/api/ledger/[agentId]?limit=', { agentId: AGENT });+ expect(res.statusCode).toBe(200);+ expect(res.body().decisions).toHaveLength(1);+ });++ it('answers 405 with an Allow header on a write attempt', async () => {+ const res = makeRes();+ await timelineHandler({ method: 'POST', url: `/api/ledger/${AGENT}`, headers: {} }, res);+ expect(res.statusCode).toBe(405);+ expect(String(res.getHeader('allow'))).toContain('GET');+ });+});++describe('GET /api/ledger/verify/:agentId', () => {+ it('reports an empty ledger as empty, not as a failure', async () => {+ const res = await call(verifyHandler, `/api/ledger/verify/${AGENT}`);+ expect(res.statusCode).toBe(200);+ expect(res.body().status).toBe('empty');+ expect(res.body().chain).toMatchObject({ ok: true, count: 0 });+ expect(res.getHeader('cache-control')).toBe('no-store');+ });++ it('verifies an intact but unanchored chain', async () => {+ await seedChain(3);+ const res = await call(verifyHandler, `/api/ledger/verify/${AGENT}`);+ expect(res.body().status).toBe('verified_unanchored');+ expect(res.body().chain.ok).toBe(true);+ expect(res.body().anchor).toBeNull();+ });++ it('verifies a chain whose head matches the on-chain anchor', async () => {+ const chain = await seedChain(3);+ h.store.anchors.push({+ agent_id: AGENT, network: 'mainnet', through_seq: 3, head_hash: chain[2].entry_hash,+ entry_count: 3, signature: 'anchor-sig', status: 'anchored', anchored_at: '2026-08-01T00:00:00.000Z',+ });+ const res = await call(verifyHandler, `/api/ledger/verify/${AGENT}`);+ expect(res.body().status).toBe('verified');+ expect(res.body().anchor).toMatchObject({ matches_chain: true, through_seq: 3, explorer_url: 'https://solscan.io/tx/anchor-sig' });+ });++ it('pinpoints a tampered entry and still shows the anchor it no longer matches', async () => {+ const chain = await seedChain(3);+ h.store.anchors.push({+ agent_id: AGENT, network: 'mainnet', through_seq: 3, head_hash: chain[2].entry_hash,+ entry_count: 3, signature: 'anchor-sig', status: 'anchored', anchored_at: '2026-08-01T00:00:00.000Z',+ });+ h.store.decisions[1].rationale = 'rewritten after the fact';++ const res = await call(verifyHandler, `/api/ledger/verify/${AGENT}`);+ expect(res.body().status).toBe('verification_failed');+ expect(res.body().chain).toMatchObject({ ok: false, broken_at: 2 });+ expect(res.body().chain.reason).toMatch(/altered/);+ expect(res.body().anchor).toMatchObject({ matches_chain: false, signature: 'anchor-sig' });+ });++ it('rejects a malformed agent id and a write attempt', async () => {+ const bad = await call(verifyHandler, '/api/ledger/verify/nope');+ expect(bad.statusCode).toBe(400);+ expect(bad.body().error).toBe('bad_request');++ const res = makeRes();+ await verifyHandler({ method: 'POST', url: `/api/ledger/verify/${AGENT}`, headers: {} }, res);+ expect(res.statusCode).toBe(405);+ });+});diff --git a/tests/mcp-trader-tools.test.js b/tests/mcp-trader-tools.test.jsnew file mode 100644index 000000000..f88d5a495--- /dev/null+++ b/tests/mcp-trader-tools.test.js@@ -0,0 +1,462 @@+/**+ * Trader MCP tools (api/_mcp/tools/trader.js) — the four tools that close the+ * autonomous copy-trading loop: trader_leaderboard, trader_profile,+ * copy_subscribe, copy_status.+ *+ * The handlers themselves are the real shipped code. Only their leaf boundaries+ * are stubbed: the Neon client, the trader-stats aggregators, and the rate+ * limiter. That keeps the assertions on what actually reaches Postgres, which is+ * where this module's real defects lived:+ *+ * - copy_subscribe read `cfg.telegramChatId` from a normalizer that returns+ * `telegram_chat_id`, so the alert chat was dropped on create and WIPED on+ * update.+ * - copy_subscribe never denormalized leader_wallet, so /api/copy/settle-fee+ * could never pay the leader's performance fee on an MCP-created row.+ * - every query was wrapped in `.catch(() => [])`, so a DB outage answered+ * "leader not found" / "no subscriptions" instead of saying it was down.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++/** Rows each awaited `sql` template resolves to, in call order. */+let queued = [];+/** One entry per awaited query: { text, params }. */+let executed = [];+/** When set, the next awaited query rejects with this error. */+let queryError = null;++function queue(...rowSets) {+ queued.push(...rowSets);+}++vi.mock('../api/_lib/db.js', () => {+ const flatten = (strings, values) => {+ let text = '';+ const params = [];+ for (let i = 0; i < strings.length; i++) {+ text += strings[i];+ if (i < values.length) {+ params.push(values[i]);+ text += '$' + params.length;+ }+ }+ return { text: text.replace(/\s+/g, ' ').trim(), params };+ };++ const run = (strings, values) => {+ const { text, params } = flatten(strings, values);+ executed.push({ text, params });+ if (queryError) {+ const err = queryError;+ queryError = null;+ return Promise.reject(err);+ }+ if (!queued.length) throw new Error(`unexpected query: ${text}`);+ return Promise.resolve(queued.shift());+ };++ const sql = (strings, ...values) => ({+ then: (ok, no) => run(strings, values).then(ok, no),+ catch: (no) => run(strings, values).catch(no),+ finally: (fn) => run(strings, values).finally(fn),+ });++ // Mirrors the real classifier closely enough for these tests: a connection+ // level failure is "unavailable", a statement fault (undefined column,+ // constraint violation) is a genuine bug that must keep propagating.+ const isDbUnavailableError = (err) =>+ /Error connecting to database|fetch failed|ECONNRESET|Missing required env var: DATABASE_URL/i.test(+ String(err?.message || ''),+ );++ return { sql, isDbUnavailableError, isDbCapacityError: () => false };+});++const getLeaderboard = vi.fn();+const getTraderStats = vi.fn();+vi.mock('../api/_lib/trader-stats.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ getLeaderboard: (...a) => getLeaderboard(...a),+ getTraderStats: (...a) => getTraderStats(...a),+ };+});++const mcpIp = vi.fn(async () => ({ success: true, limit: 600, remaining: 599, reset: 0 }));+vi.mock('../api/_lib/rate-limit.js', () => ({+ clientIp: () => '203.0.113.7',+ limits: { mcpIp: (...a) => mcpIp(...a) },+}));++const { toolDefs } = await import('../api/_mcp/tools/trader.js');+const TOOLS = Object.fromEntries(toolDefs.map((t) => [t.name, t]));++const ANON = { userId: null, rateKey: 'ip:203.0.113.7', scope: '', source: 'free' };+const USER = { userId: 'u-1111-2222', rateKey: 'user:u-1111-2222', scope: 'agents:read agents:write', source: 'oauth' };+const LEADER_ID = '11111111-2222-4333-8444-555555555555';+const LEADER_WALLET = 'So11111111111111111111111111111111111111112';+const COPIER_WALLET = '3XmnvxYtNvbYYDkVfsMbrJyVJUxCFyAMBjsqFYPRZUFn';++/** Parse the JSON payload an MCP ok-result carries. */+function payloadOf(result) {+ expect(result.isError).toBeFalsy();+ return result.structuredContent;+}++function textOf(result) {+ return result.content[0].text;+}++function boardRow(over = {}) {+ return {+ rank: 1,+ agent_id: LEADER_ID,+ agent_name: 'Sniper One',+ image: null,+ score: 82,+ verified: true,+ closed: 30,+ open_positions: 2,+ wins: 21,+ losses: 9,+ win_rate: 70,+ realized_pnl_sol: 12.5,+ realized_pnl_usd: 2500,+ roi_pct: 41.2,+ profit_factor: 2.1,+ max_drawdown_pct: 18,+ copiers: 4,+ last_active_at: '2026-08-10T00:00:00.000Z',+ ...over,+ };+}++beforeEach(() => {+ queued = [];+ executed = [];+ queryError = null;+ getLeaderboard.mockReset();+ getTraderStats.mockReset();+ mcpIp.mockClear();+ mcpIp.mockResolvedValue({ success: true, limit: 600, remaining: 599, reset: 0 });+});++describe('tool surface', () => {+ it('exports the four trader tools with handlers and input schemas', () => {+ expect(Object.keys(TOOLS).sort()).toEqual(+ ['copy_status', 'copy_subscribe', 'trader_leaderboard', 'trader_profile'],+ );+ for (const t of toolDefs) {+ expect(typeof t.handler).toBe('function');+ expect(t.inputSchema.type).toBe('object');+ expect(t.inputSchema.additionalProperties).toBe(false);+ expect(t.description.length).toBeGreaterThan(40);+ }+ });++ it('gates the write tool on agents:write and the private read on agents:read', () => {+ expect(TOOLS.copy_subscribe.scope).toBe('agents:write');+ expect(TOOLS.copy_status.scope).toBe('agents:read');+ expect(TOOLS.trader_leaderboard.scope).toBeUndefined();+ expect(TOOLS.trader_profile.scope).toBeUndefined();+ expect(TOOLS.copy_subscribe.annotations.readOnlyHint).toBe(false);+ expect(TOOLS.copy_status.annotations.readOnlyHint).toBe(true);+ });+});++describe('trader_leaderboard', () => {+ it('shapes real rows, ranks them, and counts copy candidates', async () => {+ getLeaderboard.mockResolvedValue({+ network: 'mainnet',+ window: '30d',+ sort: 'score',+ sol_usd: 200,+ leaderboard: [+ boardRow(),+ boardRow({ rank: 2, agent_id: 'aaaa', agent_name: 'Rookie', score: 41, verified: false, win_rate: 30, closed: 3 }),+ ],+ });++ const out = payloadOf(await TOOLS.trader_leaderboard.handler({ limit: 5 }, ANON));++ expect(out.count).toBe(2);+ expect(out.copy_candidates).toBe(1);+ expect(out.traders[0].recommendation).toBe('copy');+ expect(out.traders[1].recommendation).toBe('skip');+ expect(out.traders[0].profile_url).toBe(`https://three.ws/trader/${LEADER_ID}`);+ expect(out.traders[0].win_rate_pct).toBe(70);+ expect(out.hint).toContain('Sniper One');+ expect(getLeaderboard).toHaveBeenCalledWith({+ network: 'mainnet', window: '30d', sort: 'score', limit: 5, verifiedOnly: false,+ });+ });++ it('clamps a non-finite limit instead of passing NaN into slice()', async () => {+ getLeaderboard.mockResolvedValue({ sol_usd: null, leaderboard: [] });+ await TOOLS.trader_leaderboard.handler({ limit: 'many' }, ANON);+ expect(getLeaderboard.mock.calls[0][0].limit).toBe(10);+ });++ it('falls back to defaults for unknown window / sort / network', async () => {+ getLeaderboard.mockResolvedValue({ sol_usd: null, leaderboard: [] });+ await TOOLS.trader_leaderboard.handler({ window: '99y', sort: 'vibes', network: 'testnet' }, ANON);+ expect(getLeaderboard.mock.calls[0][0]).toMatchObject({ window: '30d', sort: 'score', network: 'mainnet' });+ });++ it('reports a DB outage as temporarily unavailable', async () => {+ getLeaderboard.mockRejectedValue(new Error('Error connecting to database: fetch failed'));+ const res = await TOOLS.trader_leaderboard.handler({}, ANON);+ expect(res.isError).toBe(true);+ expect(textOf(res)).toMatch(/temporarily unavailable/i);+ });++ it('propagates a real SQL fault to the MCP dispatcher rather than swallowing it', async () => {+ const bug = new Error('column "nope" does not exist');+ bug.code = '42703';+ getLeaderboard.mockRejectedValue(bug);+ await expect(TOOLS.trader_leaderboard.handler({}, ANON)).rejects.toThrow('column "nope" does not exist');+ });++ it('refuses when the caller is over the MCP rate limit', async () => {+ mcpIp.mockResolvedValue({ success: false, limit: 600, remaining: 0, reset: 0 });+ const res = await TOOLS.trader_leaderboard.handler({}, ANON);+ expect(res.isError).toBe(true);+ expect(textOf(res)).toMatch(/rate limit/i);+ expect(getLeaderboard).not.toHaveBeenCalled();+ });+});++describe('trader_profile', () => {+ const stats = {+ agent: { id: LEADER_ID, name: 'Sniper One', image: null, is_public: true, copiers: 4 },+ sol_usd: 200,+ metrics: {+ score: 82, verified: true, closed_count: 30, open_count: 1, wins: 21, losses: 9,+ win_rate: 70, realized_pnl_sol: 12.5, realized_pnl_usd: 2500, roi_pct: 41.2,+ profit_factor: 2.1, avg_pnl_pct: 8, best_pnl_pct: 120, max_drawdown_pct: 18,+ avg_hold_seconds: 420, unique_coins: 14,+ },+ closed: [+ { symbol: 'THREE', mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', realized_pnl_pct: 42, realized_pnl_sol: 1.2, hold_seconds: 300, exit_reason: 'take_profit', closed_at: '2026-08-10T00:00:00.000Z', sell_solscan: 'https://solscan.io/tx/sell1', buy_solscan: 'https://solscan.io/tx/buy1' },+ { symbol: 'THREE', mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', realized_pnl_pct: -12, realized_pnl_sol: -0.3, hold_seconds: 120, exit_reason: 'stop_loss', closed_at: '2026-08-09T00:00:00.000Z', sell_solscan: null, buy_solscan: 'https://solscan.io/tx/buy2' },+ ],+ open: [+ { id: 'p-1', symbol: 'THREE', mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', entry_sol: 0.5, current_sol: 0.8, unrealized_pct: 60, opened_at: '2026-08-11T00:00:00.000Z', buy_url: 'https://solscan.io/tx/buy3' },+ ],+ oracle: null,+ };++ it('returns metrics, proof-linked recent trades, and the open positions it advertises', async () => {+ getTraderStats.mockResolvedValue(stats);+ const out = payloadOf(await TOOLS.trader_profile.handler({ agent_id: LEADER_ID }, ANON));++ expect(out.score).toBe(82);+ expect(out.recommendation).toBe('copy');+ expect(out.metrics.win_rate_pct).toBe(70);+ expect(out.recent_trades).toHaveLength(2);+ expect(out.recent_trades[0]).toMatchObject({ outcome: 'win', proof_url: 'https://solscan.io/tx/sell1' });+ expect(out.recent_trades[1]).toMatchObject({ outcome: 'loss', proof_url: 'https://solscan.io/tx/buy2' });+ expect(out.open_positions).toEqual([+ {+ symbol: 'THREE',+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ entry_sol: 0.5,+ current_sol: 0.8,+ unrealized_pct: 60,+ opened_at: '2026-08-11T00:00:00.000Z',+ proof_url: 'https://solscan.io/tx/buy3',+ },+ ]);+ });++ it('rejects a non-UUID agent_id before touching the aggregator', async () => {+ const res = await TOOLS.trader_profile.handler({ agent_id: 'sniper-one' }, ANON);+ expect(res.isError).toBe(true);+ expect(textOf(res)).toMatch(/must be a UUID/i);+ expect(getTraderStats).not.toHaveBeenCalled();+ });++ it('distinguishes an unknown agent from a private one', async () => {+ getTraderStats.mockResolvedValueOnce(null);+ const missing = await TOOLS.trader_profile.handler({ agent_id: LEADER_ID }, ANON);+ expect(missing.isError).toBe(true);+ expect(textOf(missing)).toMatch(/not found/i);++ getTraderStats.mockResolvedValueOnce({ ...stats, agent: { ...stats.agent, is_public: false } });+ const private_ = await TOOLS.trader_profile.handler({ agent_id: LEADER_ID }, ANON);+ expect(private_.isError).toBe(true);+ expect(textOf(private_)).toMatch(/not public/i);+ });++ it('reports a DB outage as temporarily unavailable, not as a missing agent', async () => {+ getTraderStats.mockRejectedValue(new Error('Error connecting to database: fetch failed'));+ const res = await TOOLS.trader_profile.handler({ agent_id: LEADER_ID }, ANON);+ expect(res.isError).toBe(true);+ expect(textOf(res)).toMatch(/temporarily unavailable/i);+ expect(textOf(res)).not.toMatch(/not found/i);+ });+});++describe('copy_subscribe', () => {+ const goodArgs = {+ leader_agent_id: LEADER_ID,+ copier_wallet: COPIER_WALLET,+ sizing_rule: 'fixed',+ fixed_sol: 0.02,+ per_trade_cap_sol: 0.05,+ daily_budget_sol: 0.5,+ telegram_chat_id: '-1002233445566',+ };++ function queueHappyPath({ inserted = true } = {}) {+ queue(+ [{ id: LEADER_ID, name: 'Sniper One', is_public: true }],+ [{ wallet: LEADER_WALLET }],+ [{ id: 'sub-1', status: 'active', created_at: 'now', updated_at: 'now', inserted }],+ );+ }++ it('requires a signed-in principal', async () => {+ const res = await TOOLS.copy_subscribe.handler(goodArgs, ANON);+ expect(res.isError).toBe(true);+ expect(textOf(res)).toMatch(/sign in/i);+ expect(executed).toHaveLength(0);+ });++ it('rejects a non-UUID leader and a non-base58 wallet before any query', async () => {+ const badLeader = await TOOLS.copy_subscribe.handler({ ...goodArgs, leader_agent_id: 'top-guy' }, USER);+ expect(badLeader.isError).toBe(true);+ expect(textOf(badLeader)).toMatch(/leader_agent_id/);++ const badWallet = await TOOLS.copy_subscribe.handler({ ...goodArgs, copier_wallet: '0xdeadbeef' }, USER);+ expect(badWallet.isError).toBe(true);+ expect(textOf(badWallet)).toMatch(/copier_wallet/);++ expect(executed).toHaveLength(0);+ });++ it('persists telegram_chat_id and the denormalized leader_wallet', async () => {+ queueHappyPath();+ const out = payloadOf(await TOOLS.copy_subscribe.handler(goodArgs, USER));++ expect(out.action).toBe('created');+ expect(out.subscription_id).toBe('sub-1');+ expect(out.leader_name).toBe('Sniper One');++ const upsert = executed.at(-1);+ expect(upsert.text).toMatch(/insert into copy_subscriptions/i);+ expect(upsert.text).toMatch(/on conflict \(copier_user_id, leader_agent_id, network\) do update/i);+ // The alert chat used to be read off a camelCase key the normalizer never+ // sets, so it reached Postgres as null on create and erased the stored+ // value on update.+ expect(upsert.params).toContain('-1002233445566');+ // Without this the leader can never be paid their performance fee.+ expect(upsert.params).toContain(LEADER_WALLET);+ expect(upsert.params).toContain(USER.userId);+ expect(upsert.params).toContain(COPIER_WALLET);+ });++ it('reports an update when the upsert hit the existing row', async () => {+ queueHappyPath({ inserted: false });+ const out = payloadOf(await TOOLS.copy_subscribe.handler(goodArgs, USER));+ expect(out.action).toBe('updated');+ expect(out.message).toMatch(/updated/);+ });++ it('keeps a previously recorded leader_wallet when the leader has no position yet', async () => {+ queue(+ [{ id: LEADER_ID, name: 'Sniper One', is_public: true }],+ [],+ [{ id: 'sub-1', status: 'active', created_at: 'now', updated_at: 'now', inserted: false }],+ );+ payloadOf(await TOOLS.copy_subscribe.handler(goodArgs, USER));+ const upsert = executed.at(-1);+ expect(upsert.text).toMatch(/leader_wallet = coalesce\(excluded\.leader_wallet, copy_subscriptions\.leader_wallet\)/i);+ });++ it('refuses a leader that does not exist or is not public', async () => {+ queue([]);+ const missing = await TOOLS.copy_subscribe.handler(goodArgs, USER);+ expect(missing.isError).toBe(true);+ expect(textOf(missing)).toMatch(/not found/i);++ queue([{ id: LEADER_ID, name: 'Hidden', is_public: false }]);+ const hidden = await TOOLS.copy_subscribe.handler(goodArgs, USER);+ expect(hidden.isError).toBe(true);+ expect(textOf(hidden)).toMatch(/not public/i);+ });++ it('rejects unsafe sizing before writing anything', async () => {+ queue([{ id: LEADER_ID, name: 'Sniper One', is_public: true }]);+ const res = await TOOLS.copy_subscribe.handler({ ...goodArgs, per_trade_cap_sol: 0 }, USER);+ expect(res.isError).toBe(true);+ expect(textOf(res)).toMatch(/per_trade_cap_sol must be greater than 0/);+ expect(executed).toHaveLength(1);+ });++ it('reports a DB outage instead of claiming the leader does not exist', async () => {+ queryError = new Error('Error connecting to database: fetch failed');+ const res = await TOOLS.copy_subscribe.handler(goodArgs, USER);+ expect(res.isError).toBe(true);+ expect(textOf(res)).toMatch(/temporarily unavailable/i);+ expect(textOf(res)).not.toMatch(/not found/i);+ });+});++describe('copy_status', () => {+ it('requires a signed-in principal', async () => {+ const res = await TOOLS.copy_status.handler({}, ANON);+ expect(res.isError).toBe(true);+ expect(textOf(res)).toMatch(/sign in/i);+ expect(executed).toHaveLength(0);+ });++ it('separates active from paused rows and totals the pending intents', async () => {+ queue([+ {+ id: 'sub-1', leader_agent_id: LEADER_ID, status: 'active', network: 'mainnet',+ copier_wallet: COPIER_WALLET, sizing_rule: 'fixed', fixed_sol: '0.02', multiplier: null,+ pct_balance: null, per_trade_cap_sol: '0.05', daily_budget_sol: '0.5', max_open_copies: 5,+ min_oracle_score: 70, perf_fee_bps: 1000, created_at: 'now', updated_at: 'now',+ leader_name: 'Sniper One', leader_image: null, pending_count: 2, acted_count: 7,+ },+ {+ id: 'sub-2', leader_agent_id: LEADER_ID, status: 'paused', network: 'mainnet',+ copier_wallet: COPIER_WALLET, sizing_rule: 'multiplier', fixed_sol: null, multiplier: '0.5',+ pct_balance: null, per_trade_cap_sol: '0.1', daily_budget_sol: '1', max_open_copies: 3,+ min_oracle_score: null, perf_fee_bps: 500, created_at: 'now', updated_at: 'now',+ leader_name: 'Sniper Two', leader_image: null, pending_count: 0, acted_count: 1,+ },+ ]);++ const out = payloadOf(await TOOLS.copy_status.handler({}, USER));++ expect(out.count).toBe(2);+ expect(out.active_count).toBe(1);+ expect(out.paused_count).toBe(1);+ expect(out.pending_total).toBe(2);+ expect(out.acted_total).toBe(8);+ expect(out.hint).toContain('1 active subscription');+ expect(out.hint).toContain('1 paused');+ expect(out.subscriptions[0].fixed_sol).toBe(0.02);+ expect(out.subscriptions[1].multiplier).toBe(0.5);+ expect(out.subscriptions[0].profile_url).toBe(`https://three.ws/trader/${LEADER_ID}`);+ expect(executed[0].params).toContain(USER.userId);+ });++ it('points a new copier at the discovery path when they have no subscriptions', async () => {+ queue([]);+ const out = payloadOf(await TOOLS.copy_status.handler({}, USER));+ expect(out.count).toBe(0);+ expect(out.hint).toMatch(/trader_leaderboard/);+ });++ it('reports a DB outage instead of an empty subscription list', async () => {+ queryError = new Error('Error connecting to database: fetch failed');+ const res = await TOOLS.copy_status.handler({}, USER);+ expect(res.isError).toBe(true);+ expect(textOf(res)).toMatch(/temporarily unavailable/i);+ });+});diff --git a/tests/mirror-leaderboard.test.js b/tests/mirror-leaderboard.test.jsnew file mode 100644index 000000000..988740183--- /dev/null+++ b/tests/mirror-leaderboard.test.js@@ -0,0 +1,138 @@+import { describe, it, expect } from 'vitest';+import { rankLeaders } from '../api/mirror/leaderboard.js';++// Rows in the exact shape postgres hands back for GET /api/mirror/leaderboard:+// every lamport SUM is cast ::text (bigint sums overflow JS numbers), counts are+// ::int, and an agent with no closed round-trips carries the COALESCE'd zeros.+const row = (o) => ({+ id: o.id,+ name: o.name,+ avatar_url: o.avatar_url ?? null,+ profile_image_url: o.profile_image_url ?? null,+ settled: o.settled ?? 0,+ wins: o.wins ?? 0,+ pnl_lamports: o.pnl_lamports ?? '0',+ entry_lamports: o.entry_lamports ?? '0',+ trades: o.trades ?? 0,+ buy_lamports: o.buy_lamports ?? '0',+ last_trade_at: o.last_trade_at ?? null,+ followers: o.followers ?? 0,+ active_followers: o.active_followers ?? 0,+});++// 20 settled round-trips, 13 wins, +2 SOL on 20 SOL deployed: a real track record.+const CONSISTENT = row({+ id: 'aaaaaaaa-0000-4000-8000-000000000001',+ name: 'Consistent',+ settled: 20, wins: 13,+ pnl_lamports: '2000000000', entry_lamports: '20000000000',+ followers: 3, active_followers: 2,+});+// One lucky round-trip that doubled: same 100% ROI, no sample behind it.+const FLUKE = row({+ id: 'aaaaaaaa-0000-4000-8000-000000000002',+ name: 'Fluke',+ settled: 1, wins: 1,+ pnl_lamports: '1000000000', entry_lamports: '1000000000',+});+// Discretionary-only: real custody volume, nothing settled, so no P&L to show.+const DISCRETIONARY = row({+ id: 'aaaaaaaa-0000-4000-8000-000000000003',+ name: 'Discretionary',+ trades: 7, buy_lamports: '4500000000',+ last_trade_at: '2026-08-04T08:57:12.524Z',+ followers: 1, active_followers: 1,+});+// A real loser: down 1.5 SOL over 12 settled trades. Losers stay on the board.+const LOSER = row({+ id: 'aaaaaaaa-0000-4000-8000-000000000004',+ name: 'Loser',+ settled: 12, wins: 3,+ pnl_lamports: '-1500000000', entry_lamports: '10000000000',+ followers: 9, active_followers: 8,+});++const ALL = [CONSISTENT, FLUKE, DISCRETIONARY, LOSER];+const byId = (ranked, id) => ranked.find((l) => l.agent_id === id);++describe('rankLeaders', () => {+ it('ranks real rows by composite score and numbers them from 1', () => {+ const ranked = rankLeaders(ALL, { sort: 'score', limit: 25 });+ expect(ranked).toHaveLength(4);+ expect(ranked.map((l) => l.rank)).toEqual([1, 2, 3, 4]);+ expect(ranked[0].agent_id).toBe(CONSISTENT.id);+ });++ it('weights ROI by sample size so a single lucky trade cannot top a track record', () => {+ const ranked = rankLeaders([FLUKE, CONSISTENT], { sort: 'score' });+ expect(ranked[0].agent_id).toBe(CONSISTENT.id);+ // The fluke's 100% ROI is real and still shown, just discounted in the score.+ expect(byId(ranked, FLUKE.id).roi_pct).toBe(100);+ expect(byId(ranked, FLUKE.id).score).toBeLessThan(byId(ranked, CONSISTENT.id).score);+ });++ it('converts lamport strings to SOL without losing the sign or precision', () => {+ const ranked = rankLeaders(ALL);+ expect(byId(ranked, CONSISTENT.id).pnl_sol).toBe(2);+ expect(byId(ranked, CONSISTENT.id).roi_pct).toBe(10);+ expect(byId(ranked, CONSISTENT.id).win_rate).toBe(65);+ expect(byId(ranked, LOSER.id).pnl_sol).toBe(-1.5);+ expect(byId(ranked, LOSER.id).roi_pct).toBe(-15);+ expect(byId(ranked, DISCRETIONARY.id).volume_sol).toBe(4.5);+ });++ it('reports no track record as null, never a fabricated number', () => {+ const d = byId(rankLeaders(ALL), DISCRETIONARY.id);+ expect(d.win_rate).toBeNull();+ expect(d.roi_pct).toBeNull();+ expect(d.pnl_sol).toBe(0);+ expect(d.settled).toBe(0);+ expect(d.trades).toBe(7);+ });++ it('keeps losing agents on the board', () => {+ const ranked = rankLeaders(ALL, { sort: 'pnl' });+ expect(byId(ranked, LOSER.id)).toBeDefined();+ expect(ranked[ranked.length - 1].agent_id).toBe(LOSER.id);+ });++ it('honours every supported sort', () => {+ expect(rankLeaders(ALL, { sort: 'pnl' })[0].agent_id).toBe(CONSISTENT.id);+ expect(rankLeaders(ALL, { sort: 'followers' })[0].agent_id).toBe(LOSER.id);+ expect(rankLeaders(ALL, { sort: 'volume' })[0].agent_id).toBe(DISCRETIONARY.id);+ expect(rankLeaders(ALL, { sort: 'winrate' })[0].agent_id).toBe(FLUKE.id);+ });++ it('sorts agents with no win rate last instead of ahead of real ones', () => {+ const ranked = rankLeaders(ALL, { sort: 'winrate' });+ expect(ranked[ranked.length - 1].agent_id).toBe(DISCRETIONARY.id);+ expect(ranked[ranked.length - 1].win_rate).toBeNull();+ });++ it('falls back to score for an unknown sort and defaults the limit', () => {+ const ranked = rankLeaders(ALL, { sort: 'not-a-sort' });+ expect(ranked.map((l) => l.agent_id)).toEqual(rankLeaders(ALL, { sort: 'score' }).map((l) => l.agent_id));+ });++ it('applies the limit after ranking, not before', () => {+ const ranked = rankLeaders(ALL, { sort: 'score', limit: 2 });+ expect(ranked).toHaveLength(2);+ expect(ranked[0].agent_id).toBe(CONSISTENT.id);+ expect(ranked.map((l) => l.rank)).toEqual([1, 2]);+ });++ it('ranks tied agents in one fixed order regardless of row order', () => {+ const tieA = row({ id: 'bbbbbbbb-0000-4000-8000-000000000001', name: 'Tie A', trades: 2 });+ const tieB = row({ id: 'bbbbbbbb-0000-4000-8000-000000000002', name: 'Tie B', trades: 2 });+ expect(tieA.buy_lamports).toBe(tieB.buy_lamports);+ const forward = rankLeaders([tieA, tieB]).map((l) => l.agent_id);+ const reversed = rankLeaders([tieB, tieA]).map((l) => l.agent_id);+ expect(forward).toEqual(reversed);+ expect(forward[0]).toBe(tieA.id);+ });++ it('returns an empty board for no candidates', () => {+ expect(rankLeaders([])).toEqual([]);+ expect(rankLeaders([], { sort: 'pnl', limit: 5 })).toEqual([]);+ });+});diff --git a/tests/sentiment-heatmap-data.test.js b/tests/sentiment-heatmap-data.test.jsindex 7afb728c6..c05b2b793 100644--- a/tests/sentiment-heatmap-data.test.js+++ b/tests/sentiment-heatmap-data.test.js@@ -52,11 +52,11 @@ describe('normalizeToken', () => {expect(normalizeToken({ id: 'a', volume24h: -5 }).magnitude).toBe(0);});- it('derives a label and preserves featured + sentiment', () => {- const t = normalizeToken({ id: 'mintmintmint', featured: true, sentiment: { score: 0.4, posPct: 60 } });+ it('derives a label and preserves featured + the anchor flow pulse', () => {+ const t = normalizeToken({ id: 'mintmintmint', featured: true, flow: { score: 0.4, buyPct: 70 } });expect(t.label).toBe('mint…');expect(t.featured).toBe(true);- expect(t.sentiment.posPct).toBe(60);+ expect(t.flow.buyPct).toBe(70);});});@@ -211,9 +211,9 @@ describe('rankMovers', () => {});describe('buildNarrationContext', () => {- it('always names $THREE for the anchor and folds in its sentiment', () => {+ it('always names $THREE for the anchor and folds in its order flow', () => {const movers = {- anchor: { label: 'THREE', featured: true, change24h: 8, sentiment: { score: 0.4, posPct: 62, count: 30 } },+ anchor: { label: 'THREE', featured: true, change24h: 8, flow: { score: 0.4, buyPct: 70, buys24h: 70, sells24h: 30 } },gainers: [{ label: 'A', change24h: 15 }],losers: [{ label: 'B', change24h: -10 }],avgMomentum: 0.2,@@ -222,7 +222,7 @@ describe('buildNarrationContext', () => {const ctx = buildNarrationContext({ spikes: [], movers });expect(ctx).toMatch(/\$THREE/);expect(ctx).toMatch(/Heating across the board/);- expect(ctx).toMatch(/62% bullish/);+ expect(ctx).toMatch(/order flow buyers leading \(70% buys of 100 trades 24h\)/);});it('describes a cooling tape and a fresh spike', () => {