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(oracle): refuse a live arm whose raw trade size the clamp would have inflated
nirholas1b4054689060
diff --git a/api/_lib/oracle/store.js b/api/_lib/oracle/store.jsindex 8ea5ba030..2a73040de 100644--- a/api/_lib/oracle/store.js+++ b/api/_lib/oracle/store.js@@ -4,7 +4,7 @@// the read APIs (lazy-score-on-miss, so the feed is warm even before the worker// has swept a brand-new coin).-import { sql } from '../db.js';+import { sql, isDbUnavailableError } from '../db.js';import { assembleIntel, walletProfile, coinOutcome } from './sources.js';import { classifyNarrative } from './narrative.js';import { convict, hitRateFor, PREDICTED_EVENT } from './conviction.js';@@ -401,7 +401,11 @@ export async function upsertWatch(agentId, userId, network, cfg) {return row[0];}-/** Conviction score history for a coin (newest first, up to 48 points). */+/**+ * Conviction score history for a coin, oldest point first, up to 200 points.+ * The ascending order is load-bearing: /api/oracle/history derives its rising /+ * falling trend from the first and last elements.+ */export async function readScoreHistory(mint, network = 'mainnet', hours = 72) {const rows = await sql`select score, tier, pedigree, structure, narrative, momentum, scored_at@@ -410,7 +414,14 @@ export async function readScoreHistory(mint, network = 'mainnet', hours = 72) {and scored_at > now() - (${hours} || ' hours')::intervalorder by scored_at asclimit 200- `.catch(() => []);+ `.catch((err) => {+ // The sparkline reads an empty series as "this coin has no recorded+ // conviction movement", which is what the caller sees during a+ // connectivity failure too — cached for 60s by /api/oracle/history.+ // Propagate so wrap() answers 503; a statement fault still degrades.+ if (isDbUnavailableError(err)) throw err;+ return [];+ });return rows.map((r) => ({score: r.score,tier: r.tier,diff --git a/api/oracle/movers.js b/api/oracle/movers.jsindex 7f43d9a92..55970b89e 100644--- a/api/oracle/movers.js+++ b/api/oracle/movers.js@@ -25,7 +25,7 @@import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { sql } from '../_lib/db.js';+import { sql, isDbUnavailableError } from '../_lib/db.js';import { QUOTE_MINT_LIST } from '../_lib/quote-mints.js';const NETWORKS = new Set(['mainnet', 'devnet']);@@ -94,7 +94,15 @@ export default wrap(async (req, res) => {case when ${direction}::text = 'falling' then (d.first_score - c.score) else (c.score - d.first_score) end desc,c.score desclimit ${limit}- `.catch(() => []);+ `.catch((err) => {+ // This query IS the response. A connectivity failure used to become a+ // confident "nothing is moving" with a 90-second CDN cache, so a blip+ // lasting seconds flatlined the movers panel for the next minute and a+ // half. Rethrow so wrap() answers 503 + Retry-After and nothing caches+ // the lie; a statement-level fault still degrades to an empty board.+ if (isDbUnavailableError(err)) throw err;+ return [];+ });const items = rows.map((r) => ({mint: r.mint,diff --git a/api/oracle/og.js b/api/oracle/og.jsindex d69fb00dd..f2569a1d9 100644--- a/api/oracle/og.js+++ b/api/oracle/og.js@@ -24,6 +24,11 @@ import { isQuoteMint } from '../_lib/quote-mints.js';const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;const PUMP_FRONTEND_V3 = 'https://frontend-api-v3.pump.fun';const CACHE = 'public, max-age=120, s-maxage=900, stale-while-revalidate=60';+// A card built from a failed read is still a card — an OG scraper needs an image+// back, not a 500 — but it is not an answer worth keeping for 15 minutes. Serve+// the degraded render uncached so the next scrape re-reads a recovered database+// instead of pinning "Not yet scored" on a real prime coin for a quarter hour.+const CACHE_DEGRADED = 'no-store';function x(s) {return String(s || '')@@ -345,15 +350,17 @@ export default wrap(async (req, res) => {}let data;+ let degraded = false;try {data = await buildCardData(mint);} catch {+ degraded = true;data = { cv: null, outcome: null, name: '', symbol: '', logoBase64: null, category: '', liveMcap: null };}const svg = renderCard(mint, data);res.statusCode = 200;res.setHeader('content-type', 'image/svg+xml; charset=utf-8');- res.setHeader('cache-control', CACHE);+ res.setHeader('cache-control', degraded ? CACHE_DEGRADED : CACHE);res.end(svg);});diff --git a/api/oracle/signal.js b/api/oracle/signal.jsindex fbf9d9220..993304714 100644--- a/api/oracle/signal.js+++ b/api/oracle/signal.js@@ -12,6 +12,7 @@import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';+import { isDbUnavailableError } from '../_lib/db.js';import { readFeed, scoreCoin } from '../_lib/oracle/store.js';const NETWORKS = new Set(['mainnet', 'devnet']);@@ -85,7 +86,16 @@ export default wrap(async (req, res) => {const category = CATEGORIES.has(p.get('category')) ? p.get('category') : null;const limit = Math.min(25, Math.max(1, Number(p.get('limit')) || 5));- const items = await readFeed({ network, limit, minScore, category, sinceSeconds: 6 * 3600 }).catch(() => []);+ // An autonomous agent reads `count: 0` as "the oracle sees no plays right now"+ // and stands down. During a DB outage that is a wrong answer dressed as a+ // verdict, and the single-mint branch above already refuses to fake one, so+ // the list branch answers the same way: propagate (wrap() → 503 + Retry-After)+ // on a connectivity failure, degrade to an empty board on a statement fault.+ const items = await readFeed({ network, limit, minScore, category, sinceSeconds: 6 * 3600 })+ .catch((err) => {+ if (isDbUnavailableError(err)) throw err;+ return [];+ });const plays = items.map(shape);return json(res, 200, {network,diff --git a/api/oracle/social.js b/api/oracle/social.jsindex f9504d824..d7b773e58 100644--- a/api/oracle/social.js+++ b/api/oracle/social.js@@ -13,16 +13,16 @@* Tweet shape (XActions format):* { id, text, createdAt, url, author:{ username }, metrics:{ views, likes, retweets } }*- * A KOL author (wallet in known-wallets.json, or twitter_username present)- * gets a 2× virality multiplier vs an anonymous account.+ * An author in KOL_ACCOUNTS below gets a 1.5× virality multiplier vs an+ * anonymous account.*- * Rate-limited to 30 req/min per IP. Auth: optional — unauthenticated calls- * are accepted so XActions → Oracle works without session overhead.+ * Rate-limited per IP (limits.oracleSocialIp). Auth: optional — unauthenticated+ * calls are accepted so XActions → Oracle works without session overhead.*/import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { sql, sqlValues } from '../_lib/db.js';+import { sql, sqlValues, isDbUnavailableError } from '../_lib/db.js';const NETWORK = 'mainnet';@@ -94,7 +94,15 @@ export default wrap(async (req, res) => {where network = ${network}and upper(symbol) = any(${symbols})order by first_seen_at desc- `.catch(() => []);+ `.catch((err) => {+ // An empty lookup answers "no known mints matched the mentioned symbols",+ // which tells the caller its batch was useless and should not be retried.+ // During a connectivity failure that discards real social signal for good,+ // so propagate (wrap() → 503 + Retry-After) and let the sender retry; a+ // statement fault still degrades to the documented empty answer.+ if (isDbUnavailableError(err)) throw err;+ return [];+ });// Dedupe: keep the most recent mint per symbolconst mintBySymbol = new Map();@@ -120,8 +128,13 @@ export default wrap(async (req, res) => {// to 500 tweets can mention dozens of known mints, and N sequential INSERTs// would serialize the whole request behind DB latency. classified_at is bound// per row; the ON CONFLICT branch still uses now() for the update path.+ // Not guarded: this write IS the request. A swallowed failure used to answer+ // `ok: true` with `mints_updated: 0` next to a populated `updated` array — a+ // self-contradicting receipt that told the sender its batch had landed when+ // nothing was written. wrap() classifies instead (503 on a connectivity+ // failure, 500 on a statement fault), so the sender knows to retry.const rows = updates.map((u) => [u.mint, u.network, u.virality, 0.4, 'heuristic', new Date()]);- const upserted = await sql`+ await sql`insert into oracle_narrative (mint, network, virality, confidence, source, classified_at)values ${sqlValues(rows)}on conflict (mint, network) do update set@@ -133,14 +146,13 @@ export default wrap(async (req, res) => {when oracle_narrative.source = 'llm' then oracle_narrative.classified_atelse now()end- `.catch(() => null);- const mints_updated = upserted === null ? 0 : updates.length;+ `;return json(res, 200, {ok: true,tweet_count: tweets.length,symbols_found: symbolMap.size,- mints_updated,+ mints_updated: updates.length,updated: updates.map(u => ({ mint: u.mint, virality: u.virality, tweets: u.tweetCount })),});});diff --git a/api/oracle/stats.js b/api/oracle/stats.jsindex 40d04c53c..49368ca6e 100644--- a/api/oracle/stats.js+++ b/api/oracle/stats.js@@ -38,11 +38,24 @@import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';-import { sql } from '../_lib/db.js';+import { sql, isDbUnavailableError } from '../_lib/db.js';import { QUOTE_MINT_LIST } from '../_lib/quote-mints.js';const NETWORKS = new Set(['mainnet', 'devnet']);+/**+ * Per-query guard for the five independent summaries below. A statement-level+ * fault in one of them still degrades that panel to its empty row, so the rest+ * of the dashboard paints. A CONNECTIVITY failure hits all five at once and used+ * to render "0 coins scored, 0 armed agents, no win rate" as if the engine had+ * never run — cached for 60 seconds. That is a confident wrong answer, so it+ * propagates and wrap() turns it into 503 + Retry-After.+ */+function emptyOnStatementFault(err) {+ if (isDbUnavailableError(err)) throw err;+ return [{}];+}+/*** Public join URL for the Oracle signals channel. Only @handle chat IDs are* public: a numeric -100… ID is a private channel with no join link, so it@@ -75,7 +88,7 @@ export default wrap(async (req, res) => {from oracle_convictionwhere network = ${network}and mint <> all(${QUOTE_MINT_LIST}::text[])- `.catch(() => [{}]),+ `.catch(emptyOnStatementFault),// Open oracle_watch_actions (not yet settled).sql`@@ -83,7 +96,7 @@ export default wrap(async (req, res) => {from oracle_watch_actionswhere network = ${network}and outcome = 'open'- `.catch(() => [{}]),+ `.catch(emptyOnStatementFault),// Outcome win-rates, both scopes in one pass. "Calls" = lean/strong/prime —// the tiers the oracle actually tells people to act on. Everything else it@@ -103,7 +116,7 @@ export default wrap(async (req, res) => {where c.network = ${network}and (o.graduated or o.rugged or o.ath_multiple is not null)and c.mint <> all(${QUOTE_MINT_LIST}::text[])- `.catch(() => [{}]),+ `.catch(emptyOnStatementFault),// Distinct armed agents.sql`@@ -111,7 +124,7 @@ export default wrap(async (req, res) => {from oracle_agent_watchwhere network = ${network}and armed = true- `.catch(() => [{}]),+ `.catch(emptyOnStatementFault),// Durable lifetime scored counter. oracle_conviction is retention-pruned// (db-retention firehose family), so its count(*) is a rolling-window@@ -120,7 +133,7 @@ export default wrap(async (req, res) => {select value as scored_lifetimefrom oracle_counterswhere network = ${network} and key = 'scored_lifetime'- `.catch(() => [{}]),+ `.catch(emptyOnStatementFault),]);const c = convRow[0] || {};diff --git a/api/oracle/trades.js b/api/oracle/trades.jsindex 849c9758e..bc95c904d 100644--- a/api/oracle/trades.js+++ b/api/oracle/trades.js@@ -144,8 +144,19 @@ export default async function handleOracleTrades(req, res) {try { res.end(); } catch {}}+ // Returns false when the socket could not be constructed at all. The SSE head+ // is already on the wire by this point, so an unguarded throw here escaped as+ // a rejected handler and left the caller holding an open stream that would+ // never emit a trade, a bye, or an error until the 45 s rotate timer fired.function openWs() {- ws = new WebSocket(pumpPortalWsUrl());+ try {+ ws = new WebSocket(pumpPortalWsUrl());+ } catch (e) {+ console.warn('[oracle/trades] ws open failed:', e?.message);+ send('bye', { reason: 'ws_unavailable' });+ cleanup();+ return false;+ }ws.on('open', () => {ws.send(JSON.stringify({ method: 'subscribeTokenTrade', keys: [mint] }));@@ -170,9 +181,11 @@ export default async function handleOracleTrades(req, res) {if (active) send('bye', { reason: 'ws_closed' });cleanup();});+ return true;}- openWs();+ // Nothing to keep alive or rotate if the socket never opened.+ if (!openWs()) return;pingTimer = setInterval(() => send('ping', { ts: Date.now() }), PING_INTERVAL_MS);stopTimer = setTimeout(() => {diff --git a/api/oracle/watch.js b/api/oracle/watch.jsindex 00b33647f..f4675c3a0 100644--- a/api/oracle/watch.js+++ b/api/oracle/watch.js@@ -24,6 +24,10 @@ import { getWatch, upsertWatch, recentActions, actionsSummary } from '../_lib/orconst NETWORKS = new Set(['mainnet', 'devnet']);const TIERS = new Set(['prime', 'strong', 'lean', 'watch']);+// Smallest per-trade size the loop will ever place. Also the floor the clamp+// below applies, which is why a live arm has to be checked against the raw+// request instead of the clamped result (see the live-arm guard).+const MIN_TRADE_SOL = 0.001;const CATEGORIES = new Set(['meme', 'tech', 'ai', 'culture', 'community', 'political', 'news', 'animal', 'celebrity', 'utility', 'unknown']);const numish = z.union([z.string(), z.number()]);@@ -102,13 +106,27 @@ export default wrap(async (req, res) => {const minScore = clampInt(cfg.min_score, 0, 100, 80);const minTier = TIERS.has(cfg.min_tier) ? cfg.min_tier : 'strong';const categories = Array.isArray(cfg.categories) ? cfg.categories.filter((c) => CATEGORIES.has(c)).slice(0, 11) : [];- const perTrade = clampNum(cfg.per_trade_sol, 0.001, 5, 0.05);+ const perTrade = clampNum(cfg.per_trade_sol, MIN_TRADE_SOL, 5, 0.05);const maxDaily = clampNum(cfg.max_daily_sol, perTrade, 50, Math.max(0.5, perTrade * 10));const maxOpen = clampInt(cfg.max_open, 1, 50, 5);- // A live, armed agent with no size makes no sense — guard it.- if (cfg.armed && cfg.mode === 'live' && perTrade <= 0) {- return error(res, 400, 'validation_error', 'set a per-trade size before arming a live agent');+ // Arming live commits the agent's own SOL, so a clamp must never round the+ // caller's number UP into a larger real-money commitment than they asked for.+ // `perTrade` floors at MIN_TRADE_SOL and `maxDaily` floors at `perTrade`, so+ // `{armed:true, mode:'live', per_trade_sol:0}` armed a real-spend loop at+ // 0.001 SOL a trade with a 0.5 SOL daily ceiling. The guard that was meant to+ // catch this read the already-clamped value (`perTrade <= 0`) and therefore+ // could never fire. Judge the caller's raw numbers, and only when the request+ // actually puts funds at risk: a simulate run keeps the forgiving clamps.+ if (cfg.armed && cfg.mode === 'live') {+ const rawPerTrade = cfg.per_trade_sol == null ? null : Number(cfg.per_trade_sol);+ if (rawPerTrade != null && !(rawPerTrade >= MIN_TRADE_SOL)) {+ return error(res, 400, 'validation_error', `per_trade_sol must be at least ${MIN_TRADE_SOL} SOL to arm a live agent`);+ }+ const rawDaily = cfg.max_daily_sol == null ? null : Number(cfg.max_daily_sol);+ if (rawDaily != null && !(rawDaily >= perTrade)) {+ return error(res, 400, 'validation_error', 'max_daily_sol must be at least per_trade_sol to arm a live agent');+ }}// Sanitize telegram_chat_id: allow numeric IDs (positive or negative) anddiff --git a/src/arm.js b/src/arm.jsindex 4f0c25c19..9c32d2d74 100644--- a/src/arm.js+++ b/src/arm.js@@ -441,7 +441,12 @@ async function saveWatch() {loadActions(state.agentId);} else {note.className = 'save-note warn';- note.textContent = data?.error?.message || 'Could not save — sign in and make sure you own this agent.';+ // The API answers `{error: "<code>", error_description: "<sentence>"}`, so+ // the old `data.error.message` lookup was always undefined and every+ // failure rendered the same generic line. A caller who was told+ // "per_trade_sol must be at least 0.001 SOL to arm a live agent" or "you do+ // not own this agent" now sees exactly that.+ note.textContent = data?.error_description || data?.error || 'Could not save. Sign in and make sure you own this agent.';}}@@ -466,7 +471,10 @@ async function sendTelegramTest() {note.textContent = '✓ Test message delivered. Check Telegram.';} else {note.className = 'tg-note warn';- note.textContent = (data?.error || 'Delivery failed.') + (data?.hint ? ' ' + data.hint : '');+ // A 200 with `ok:false` carries the reason in `error`; a 4xx/503 carries it+ // in `error_description` and leaves `error` as the machine code, which used+ // to surface to the user as the bare string "not_configured".+ note.textContent = (data?.error_description || data?.error || 'Delivery failed.') + (data?.hint ? ' ' + data.hint : '');}}diff --git a/tests/oracle/api-db-outage.test.js b/tests/oracle/api-db-outage.test.jsindex 9451dc868..eb281ebfc 100644--- a/tests/oracle/api-db-outage.test.js+++ b/tests/oracle/api-db-outage.test.js@@ -15,6 +15,16 @@// /api/oracle/follow DEL `{ ok: true }` while the row survived, so the// caller believed they had opted out and kept// receiving alerts+// /api/oracle/movers 200 "nothing is moving", cached 90s+// /api/oracle/signal `count: 0` to an autonomous agent, which reads it+// as a verdict and stands down+// /api/oracle/social `ok: true` with `mints_updated: 0` next to a+// populated `updated` array — a receipt for a write+// that never landed+// /api/oracle/stats "0 coins scored, 0 armed agents", cached 60s, on+// the oracle landing hero+// /api/oracle/history an empty series, so the sparkline drew a coin with+// no conviction movement//// Each test below pins both halves of the contract: a connectivity failure// propagates (wrap() turns it into the shared 503 + Retry-After), and an@@ -48,6 +58,7 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({publicIp: vi.fn(async () => ({ success: true })),mcpIp: vi.fn(async () => ({ success: true })),oracleFollowIp: vi.fn(async () => ({ success: true })),+ oracleSocialIp: vi.fn(async () => ({ success: true })),},clientIp: () => '1.2.3.4',}));@@ -56,12 +67,22 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({// handlers route on isDbUnavailableError() correctly, so mocking that function// would test nothing. `nextDbError` decides what the next tagged-template read// rejects with (null = resolve empty).+// `dbQueue` overrides it per call, in order, for the handlers whose first read+// must succeed before the read under test fails (oracle/social looks the mints+// up, then writes them).let nextDbError = null;+let dbQueue = [];vi.mock('../../api/_lib/db.js', async () => {const actual = await vi.importActual('../../api/_lib/db.js');return {...actual,- sql: () => (nextDbError ? Promise.reject(nextDbError) : Promise.resolve([])),+ sql: () => {+ if (dbQueue.length) {+ const next = dbQueue.shift();+ return next instanceof Error ? Promise.reject(next) : Promise.resolve(next);+ }+ return nextDbError ? Promise.reject(nextDbError) : Promise.resolve([]);+ },};});@@ -79,14 +100,21 @@ const NO_URL_ERROR = new Error('Missing required env var: DATABASE_URL');// A deterministic SQL bug. Never a 503: the empty-result degrade is correct here.const STATEMENT_ERROR = new Error('column "nope" does not exist');+// The real store module on top of the mocked db.js above, so readScoreHistory's+// own guard is the thing under test rather than a stub of it. The named+// overrides after the spread keep the stubbed reads the older cases rely on.const storeBehaviour = { readFeed: async () => [] };-vi.mock('../../api/_lib/oracle/store.js', () => ({- readFeed: (...args) => storeBehaviour.readFeed(...args),- convictionBacktest: async () => [],- scoreCoin: async () => null,- recentActions: async () => [],- actionsSummary: async () => ({ total: 0, wins: 0, losses: 0, open: 0, win_rate: null }),-}));+vi.mock('../../api/_lib/oracle/store.js', async () => {+ const actual = await vi.importActual('../../api/_lib/oracle/store.js');+ return {+ ...actual,+ readFeed: (...args) => storeBehaviour.readFeed(...args),+ convictionBacktest: async () => [],+ scoreCoin: async () => null,+ recentActions: async () => [],+ actionsSummary: async () => ({ total: 0, wins: 0, losses: 0, open: 0, win_rate: null }),+ };+});vi.mock('../../api/_lib/oracle/sources.js', () => ({ recentMints: async () => [] }));@@ -95,6 +123,11 @@ import feed from '../../api/oracle/feed.js';import categories from '../../api/oracle/categories.js';import agentStats from '../../api/oracle/agent-stats.js';import follow from '../../api/oracle/follow.js';+import movers from '../../api/oracle/movers.js';+import signal from '../../api/oracle/signal.js';+import social from '../../api/oracle/social.js';+import stats from '../../api/oracle/stats.js';+import history from '../../api/oracle/history.js';const AGENT_ID = '5e05f68f-eead-4ef9-b6b4-fc85ea73bbe9';@@ -121,6 +154,7 @@ function fakeReq(url, { method = 'GET', body = null } = {}) {beforeEach(() => {nextDbError = null;+ dbQueue = [];storeBehaviour.readFeed = async () => [];});@@ -205,3 +239,107 @@ describe('/api/oracle/follow', () => {expect(res._json.body.following).toBe(false);});});++// The same contract, extended over the rest of the Oracle read surface. Each of+// these carried the identical blanket `.catch()` and the identical failure mode:+// a confident, CDN-cached wrong answer during a connectivity blip.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++describe('GET /api/oracle/movers', () => {+ it('propagates a connectivity failure instead of CDN-caching a flat market', async () => {+ nextDbError = CONN_ERROR;+ await expect(movers(fakeReq('/api/oracle/movers'), fakeRes())).rejects.toThrow(/connecting to database/);+ });++ it('still degrades a statement fault to an empty board', async () => {+ nextDbError = STATEMENT_ERROR;+ const res = fakeRes();+ await movers(fakeReq('/api/oracle/movers'), res);+ expect(res._json.status).toBe(200);+ expect(res._json.body.items).toEqual([]);+ expect(res._json.body.count).toBe(0);+ });+});++describe('GET /api/oracle/signal', () => {+ it('propagates a connectivity failure instead of telling an agent there are no plays', async () => {+ storeBehaviour.readFeed = async () => { throw CONN_ERROR; };+ await expect(signal(fakeReq('/api/oracle/signal'), fakeRes())).rejects.toThrow(/connecting to database/);+ });++ it('still degrades a statement fault to an empty play list', async () => {+ storeBehaviour.readFeed = async () => { throw STATEMENT_ERROR; };+ const res = fakeRes();+ await signal(fakeReq('/api/oracle/signal'), res);+ expect(res._json.status).toBe(200);+ expect(res._json.body.plays).toEqual([]);+ expect(res._json.body.top).toBeNull();+ });+});++describe('POST /api/oracle/social', () => {+ const batch = { tweets: [{ text: '$THREE is live', url: 'https://x.com/i/status/1', metrics: { views: 10000, likes: 100, retweets: 20 } }] };++ it('propagates a connectivity failure on the mint lookup instead of discarding the batch', async () => {+ nextDbError = CONN_ERROR;+ const req = fakeReq('/api/oracle/social', { method: 'POST', body: batch });+ await expect(social(req, fakeRes())).rejects.toThrow(/connecting to database/);+ });++ it('propagates a failed upsert instead of receipting a write that never landed', async () => {+ dbQueue = [[{ mint: THREE_MINT, symbol: 'THREE' }], CONN_ERROR];+ const req = fakeReq('/api/oracle/social', { method: 'POST', body: batch });+ await expect(social(req, fakeRes())).rejects.toThrow(/connecting to database/);+ });++ it('receipts exactly what it wrote when the upsert lands', async () => {+ dbQueue = [[{ mint: THREE_MINT, symbol: 'THREE' }], []];+ const res = fakeRes();+ await social(fakeReq('/api/oracle/social', { method: 'POST', body: batch }), res);+ expect(res._json.status).toBe(200);+ expect(res._json.body.mints_updated).toBe(1);+ expect(res._json.body.updated).toHaveLength(1);+ expect(res._json.body.updated[0].mint).toBe(THREE_MINT);+ });++ it('still answers 200 when no known mint matches the mentioned symbols', async () => {+ const res = fakeRes();+ await social(fakeReq('/api/oracle/social', { method: 'POST', body: batch }), res);+ expect(res._json.status).toBe(200);+ expect(res._json.body.mints_updated).toBe(0);+ expect(res._json.body.symbols_found).toBe(1);+ });+});++describe('GET /api/oracle/stats', () => {+ it('propagates a connectivity failure instead of publishing "nothing was ever scored"', async () => {+ nextDbError = CONN_ERROR;+ await expect(stats(fakeReq('/api/oracle/stats'), fakeRes())).rejects.toThrow(/connecting to database/);+ });++ it('still degrades a statement fault to zeroed counters', async () => {+ nextDbError = STATEMENT_ERROR;+ const res = fakeRes();+ await stats(fakeReq('/api/oracle/stats'), res);+ expect(res._json.status).toBe(200);+ expect(res._json.body.scored_total).toBe(0);+ expect(res._json.body.win_rate).toBeNull();+ });+});++describe('GET /api/oracle/history', () => {+ it('propagates a connectivity failure instead of drawing a flat sparkline', async () => {+ nextDbError = CONN_ERROR;+ await expect(history(fakeReq(`/api/oracle/history?mint=${THREE_MINT}`), fakeRes()))+ .rejects.toThrow(/connecting to database/);+ });++ it('still degrades a statement fault to an empty series with no trend', async () => {+ nextDbError = STATEMENT_ERROR;+ const res = fakeRes();+ await history(fakeReq(`/api/oracle/history?mint=${THREE_MINT}`), res);+ expect(res._json.status).toBe(200);+ expect(res._json.body.points).toEqual([]);+ expect(res._json.body.trend).toBeNull();+ });+});diff --git a/tests/oracle/watch-live-arm.test.js b/tests/oracle/watch-live-arm.test.jsnew file mode 100644index 000000000..94a1726bf--- /dev/null+++ b/tests/oracle/watch-live-arm.test.js@@ -0,0 +1,159 @@+// Spend-safety contract for POST /api/oracle/watch.+//+// Arming an agent in `live` mode commits its custodial SOL, so the risk knobs+// are clamped server-side. The clamps have floors (per_trade_sol >= 0.001,+// max_daily_sol >= per_trade_sol), which means a caller asking for LESS than+// the floor used to be silently rounded UP: `{armed:true, mode:'live',+// per_trade_sol:0, max_daily_sol:0}` stored an armed live loop at 0.001 SOL a+// trade with a 0.5 SOL daily ceiling. The guard meant to stop that read the+// clamped value (`perTrade <= 0`) and could never fire.+//+// These tests pin the fix: a live arm rejects a raw request below the floor,+// a simulate run keeps the forgiving clamps, and an omitted knob still gets+// its default.++import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../../api/_lib/http.js', async () => {+ const actual = await vi.importActual('../../api/_lib/http.js');+ return {+ ...actual,+ wrap: (fn) => fn,+ cors: () => false,+ method: () => true,+ rateLimited: (res) => { res._rateLimited = true; },+ json: (res, status, body) => { res._json = { status, body }; return res; },+ error: (res, status, code, message) => {+ res._json = { status, body: { error: code, error_description: message } };+ return res;+ },+ readJson: async (req) => JSON.parse(req._rawBody),+ };+});++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { mcpIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '1.2.3.4',+}));++const USER_ID = 'ab2aabd2-39f7-493b-8191-c9f174af62ab';+const AGENT_ID = '5e05f68f-eead-4ef9-b6b4-fc85ea73bbe9';++vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: async () => ({ id: USER_ID }),+ authenticateBearer: async () => null,+ extractBearer: () => null,+}));++// Ownership check is a single tagged-template read; the caller owns the agent.+vi.mock('../../api/_lib/db.js', () => ({+ sql: () => Promise.resolve([{ id: AGENT_ID }]),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const upserts = [];+vi.mock('../../api/_lib/oracle/store.js', () => ({+ getWatch: async () => null,+ upsertWatch: async (agentId, userId, network, cfg) => {+ upserts.push({ agentId, userId, network, cfg });+ return { agent_id: agentId, network, ...cfg };+ },+ recentActions: async () => [],+ actionsSummary: async () => ({ total: 0, wins: 0, losses: 0, open: 0, win_rate: null }),+}));++import watch from '../../api/oracle/watch.js';++function fakeRes() {+ return {+ statusCode: 200,+ _headers: {},+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end() { this.writableEnded = true; },+ };+}++function post(body) {+ return {+ method: 'POST',+ url: '/api/oracle/watch',+ headers: { host: 'three.ws', 'content-type': 'application/json' },+ _rawBody: JSON.stringify(body),+ on() {},+ };+}++beforeEach(() => { upserts.length = 0; });++describe('POST /api/oracle/watch live-arm spend guard', () => {+ it('refuses to arm live when per_trade_sol is below the floor', async () => {+ const res = fakeRes();+ await watch(post({ agent_id: AGENT_ID, armed: true, mode: 'live', per_trade_sol: 0 }), res);+ expect(res._json.status).toBe(400);+ expect(res._json.body.error).toBe('validation_error');+ expect(res._json.body.error_description).toMatch(/per_trade_sol/);+ // The point of the guard: nothing was armed.+ expect(upserts).toHaveLength(0);+ });++ it('refuses to arm live when per_trade_sol is not a number', async () => {+ const res = fakeRes();+ await watch(post({ agent_id: AGENT_ID, armed: true, mode: 'live', per_trade_sol: 'lots' }), res);+ expect(res._json.status).toBe(400);+ expect(upserts).toHaveLength(0);+ });++ it('refuses to arm live when max_daily_sol is under one trade', async () => {+ const res = fakeRes();+ await watch(post({+ agent_id: AGENT_ID, armed: true, mode: 'live',+ per_trade_sol: 0.05, max_daily_sol: 0.01,+ }), res);+ expect(res._json.status).toBe(400);+ expect(res._json.body.error_description).toMatch(/max_daily_sol/);+ expect(upserts).toHaveLength(0);+ });++ it('arms live with coherent sizes and clamps them to the ceiling', async () => {+ const res = fakeRes();+ await watch(post({+ agent_id: AGENT_ID, armed: true, mode: 'live',+ per_trade_sol: 99, max_daily_sol: 999,+ }), res);+ expect(res._json.status).toBe(200);+ expect(upserts).toHaveLength(1);+ // Clamping DOWN to the ceiling is always safe; only rounding up is not.+ expect(upserts[0].cfg.per_trade_sol).toBe(5);+ expect(upserts[0].cfg.max_daily_sol).toBe(50);+ expect(upserts[0].cfg.armed).toBe(true);+ expect(upserts[0].cfg.mode).toBe('live');+ });++ it('applies defaults for a live arm that omits the sizes entirely', async () => {+ const res = fakeRes();+ await watch(post({ agent_id: AGENT_ID, armed: true, mode: 'live' }), res);+ expect(res._json.status).toBe(200);+ expect(upserts[0].cfg.per_trade_sol).toBe(0.05);+ expect(upserts[0].cfg.max_daily_sol).toBe(0.5);+ });++ it('keeps the forgiving clamps for a simulate run', async () => {+ const res = fakeRes();+ await watch(post({+ agent_id: AGENT_ID, armed: true, mode: 'simulate',+ per_trade_sol: 0, max_daily_sol: 0,+ }), res);+ expect(res._json.status).toBe(200);+ expect(upserts[0].cfg.per_trade_sol).toBe(0.001);+ expect(upserts[0].cfg.mode).toBe('simulate');+ });++ it('keeps the forgiving clamps for an unarmed live config', async () => {+ const res = fakeRes();+ await watch(post({ agent_id: AGENT_ID, armed: false, mode: 'live', per_trade_sol: 0 }), res);+ expect(res._json.status).toBe(200);+ expect(upserts[0].cfg.armed).toBe(false);+ });+});