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(sniper): make the trade journal actually record and read, and correct three endpoint counts
nirholas1f607cff33c9
diff --git a/api/_lib/migrations/20260816070000_trading_journal_uuid_keys.sql b/api/_lib/migrations/20260816070000_trading_journal_uuid_keys.sqlnew file mode 100644index 000000000..cad608479--- /dev/null+++ b/api/_lib/migrations/20260816070000_trading_journal_uuid_keys.sql@@ -0,0 +1,22 @@+-- trading_journal: give agent_id and position_id their real types.+--+-- The table was created with `agent_id text` and `position_id bigint`, but both+-- writers in workers/agent-sniper/journal.js pass uuids:+-- agent_sniper_strategies.agent_id and agent_sniper_positions.id are uuid+-- columns. Every INSERT therefore died on `invalid input syntax for type+-- bigint`, and because a journal write is deliberately best-effort (a dropped+-- row must never fail a trade) the failure was swallowed as a warning. The+-- table has held zero rows since it was created, across 323 real closed+-- positions.+--+-- The read side failed for the matching reason: /api/sniper/journal scopes rows+-- to the caller through `agent_sniper_strategies.agent_id = trading_journal.agent_id`,+-- which Postgres rejects outright as `operator does not exist: uuid = text`, so+-- the endpoint 500'd on every request rather than returning an empty journal.+--+-- Retyping is safe precisely because nothing ever landed: the USING clauses+-- below run over an empty table. Indexes on both columns are rebuilt by the+-- ALTER.+ALTER TABLE trading_journal+ ALTER COLUMN agent_id TYPE uuid USING nullif(agent_id, '')::uuid,+ ALTER COLUMN position_id TYPE uuid USING nullif(position_id::text, '')::uuid;diff --git a/api/sniper/exit-lab.js b/api/sniper/exit-lab.jsindex 9aa6ec75e..6dc887637 100644--- a/api/sniper/exit-lab.js+++ b/api/sniper/exit-lab.js@@ -53,6 +53,28 @@ function numOrNull(v) {return Number.isFinite(n) ? n : null;}+/**+ * Resolve the corpus query from a URLSearchParams. Exported because the limit is+ * easy to get wrong in exactly one direction: an ABSENT `limit` reads back as+ * null, and `Number(null)` is 0, which is finite, so a naive parse clamped the+ * default request down to a single trade and the console rendered a fleet of one.+ * An absent or unparseable limit takes DEFAULT_LIMIT; an explicit one is clamped+ * into [1, MAX_LIMIT].+ */+export function corpusQuery(searchParams) {+ const networkRaw = searchParams.get('network');+ const windowRaw = searchParams.get('window');+ const limitRaw = searchParams.get('limit');+ const limitNum = limitRaw == null || limitRaw === '' ? NaN : Number(limitRaw);+ return {+ network: NETWORKS.has(networkRaw) ? networkRaw : 'mainnet',+ window: WINDOWS.has(windowRaw) ? windowRaw : '90',+ limit: Number.isFinite(limitNum)+ ? Math.min(MAX_LIMIT, Math.max(1, Math.floor(limitNum)))+ : DEFAULT_LIMIT,+ };+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -61,11 +83,7 @@ export default wrap(async (req, res) => {if (!rl.success) return rateLimited(res, rl);const url = new URL(req.url, 'http://localhost');- const network = NETWORKS.has(url.searchParams.get('network') || '') ? url.searchParams.get('network') : 'mainnet';- const windowRaw = url.searchParams.get('window') || '90';- const win = WINDOWS.has(windowRaw) ? windowRaw : '90';- const limitRaw = Number(url.searchParams.get('limit'));- const limit = Number.isFinite(limitRaw) ? Math.min(MAX_LIMIT, Math.max(1, Math.floor(limitRaw))) : DEFAULT_LIMIT;+ const { network, window: win, limit } = corpusQuery(url.searchParams);const start = win === 'all' ? new Date(0) : new Date(Date.now() - Number(win) * 86_400_000);diff --git a/api/sniper/journal.js b/api/sniper/journal.jsindex 6cfae34dd..185cf3dea 100644--- a/api/sniper/journal.js+++ b/api/sniper/journal.js@@ -46,8 +46,10 @@ export default wrap(async (req, res) => {const agentId = isUuid(agentIdParam) ? agentIdParam : null;// The journal is joined to the caller's own strategies so a user only ever- // sees journal rows for agents they own — trading_journal has no user_id of- // its own, so ownership is enforced through agent_sniper_strategies.+ // sees journal rows for agents they own: trading_journal has no user_id of+ // its own, so ownership is enforced through agent_sniper_strategies. Both+ // agent_id columns are uuid (migration 20260816070000), so the EXISTS join+ // is a native uuid comparison and uses trading_journal_agent_ts_idx.let rows = [];try {rows = agentId@@ -78,7 +80,7 @@ export default wrap(async (req, res) => {id: Number(r.id),ts: r.ts,agent_id: r.agent_id,- position_id: r.position_id != null ? Number(r.position_id) : null,+ position_id: r.position_id ?? null,mint: r.mint,symbol: r.symbol || 'UNKNOWN',event: r.event,diff --git a/api/sniper/radar-stream.js b/api/sniper/radar-stream.jsindex c41fe3563..670afb914 100644--- a/api/sniper/radar-stream.js+++ b/api/sniper/radar-stream.js@@ -29,6 +29,23 @@ function trunc(addr) {return `${addr.slice(0, 4)}…${addr.slice(-4)}`;}+/**+ * Advance the poll cursor past a row's timestamp.+ *+ * The cursor is an ISO string because that is what the query binds, but Neon+ * hands timestamptz columns back as Date objects. `someDate > someIsoString`+ * coerces BOTH sides to numbers, the string becomes NaN, and the comparison is+ * always false, so the cursor froze at connect time and every 1.5s poll+ * re-emitted the whole backlog it had already sent. Normalising to ISO text+ * makes the comparison lexicographic and correct (both sides are UTC, same+ * width), and keeps the cursor in the exact form the next query needs.+ */+export function advanceCursor(cursor, value) {+ if (value == null) return cursor;+ const at = value instanceof Date ? value.toISOString() : String(value);+ return at > cursor ? at : cursor;+}+async function resolveUserId(req) {try {const session = await getSessionUser(req);@@ -112,7 +129,7 @@ export default async function handleRadarStream(req, res) {at: r.created_at,fired: isOwner ? firedMints.has(r.mint) : undefined,});- if (r.created_at > cursor) cursor = r.created_at;+ cursor = advanceCursor(cursor, r.created_at);}} catch {send('error', { message: 'poll_failed' });diff --git a/api/sniper/radar.js b/api/sniper/radar.jsindex 461566a1e..5d411be5c 100644--- a/api/sniper/radar.js+++ b/api/sniper/radar.js@@ -82,9 +82,9 @@ export default wrap(async (req, res) => {const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';const userId = await resolveUserId(req);- let status, watchRows, eventRows, counts;+ let status, watchRows, eventRows, counts, watchedTotal;try {- [status, watchRows, eventRows, counts] = await Promise.all([+ [status, watchRows, eventRows, counts, watchedTotal] = await Promise.all([radarStatus(),sql`select address, reason, source, score, creator_graduated, realized_score, labels,@@ -110,13 +110,19 @@ export default wrap(async (req, res) => {from radar_eventswhere network = ${network}`.then((r) => r[0] || {}),+ // How many wallets the radar actually watches. The list above is the top+ // 100 by score, so reporting its length made the dashboard's "Watched+ // wallets" KPI read 100 while the worker's own heartbeat, rendered on the+ // same screen, reported the real (much larger) figure.+ sql`select count(*)::int as n from radar_watchlist where network = ${network}`+ .then((r) => Number(r[0]?.n) || 0),]);} catch (err) {return json(res, 200, {ok: false, network, state: 'unknown',error: err?.code || 'db_error',status: { state: 'unknown', reason: 'radar store unreachable' },- watchlist: [], events: [], counts: { events_1h: 0, events_24h: 0, armable_24h: 0 },+ watchlist: [], events: [], counts: { events_1h: 0, events_24h: 0, armable_24h: 0, watched: 0, listed: 0 },}, { 'cache-control': 'public, max-age=5' });}@@ -209,7 +215,8 @@ export default wrap(async (req, res) => {events_1h: Number(counts.events_1h || 0),events_24h: Number(counts.events_24h || 0),armable_24h: Number(counts.armable_24h || 0),- watched: watchlist.length,+ watched: watchedTotal,+ listed: watchlist.length,},armed,}, { 'cache-control': isOwner ? 'private, no-store' : 'public, max-age=5' });diff --git a/src/dashboard-next/pages/prelaunch-radar.js b/src/dashboard-next/pages/prelaunch-radar.jsindex f76095042..ab7753a85 100644--- a/src/dashboard-next/pages/prelaunch-radar.js+++ b/src/dashboard-next/pages/prelaunch-radar.js@@ -175,6 +175,15 @@ async function refresh(root, quiet = false) {startSse();}+// The API returns the top 100 watched wallets by score, not the whole set, so+// say which of the two this panel is showing rather than letting the shown count+// contradict the "Watched wallets" KPI beside it.+function watchlistCaption(data) {+ const shown = (data.watchlist || []).length;+ const total = data.counts?.watched ?? shown;+ return total > shown ? `top ${shown} of ${total}` : `${shown} wallets`;+}+function render(data) {const st = data.status || { state: 'unknown' };const counts = data.counts || {};@@ -199,7 +208,7 @@ function render(data) {<div class="rd-panel"><div class="rd-panel-head"><span class="rd-panel-title">Watchlist</span>- <span class="rd-src">${(data.watchlist || []).length} wallets</span>+ <span class="rd-src">${watchlistCaption(data)}</span></div><div class="rd-wl" tabindex="0" role="region" aria-label="Watched wallets (scrollable)">${watchlistList(data.watchlist || [])}</div></div>diff --git a/tests/sniper-endpoint-params.test.js b/tests/sniper-endpoint-params.test.jsnew file mode 100644index 000000000..bccaab4cc--- /dev/null+++ b/tests/sniper-endpoint-params.test.js@@ -0,0 +1,82 @@+// Regression cover for two sniper endpoint bugs that were invisible from the+// code and only showed up against a live server: a corpus request that silently+// shrank to one trade, and an SSE cursor that never moved.+import { describe, it, expect } from 'vitest';+import { corpusQuery } from '../api/sniper/exit-lab.js';+import { advanceCursor } from '../api/sniper/radar-stream.js';++const q = (search) => corpusQuery(new URLSearchParams(search));++describe('exit-lab corpusQuery', () => {+ // The bug: Number(null) is 0, and 0 is finite, so the "is this parseable"+ // check passed for an ABSENT limit and the clamp floored it to 1. A bare+ // GET /api/sniper/exit-lab answered with a single trade and the replay+ // console reported a fleet that had traded once.+ it('uses the full default page size when limit is absent', () => {+ expect(q('').limit).toBe(400);+ expect(q('window=30').limit).toBe(400);+ });++ it('still defaults when limit is present but unparseable', () => {+ expect(q('limit=abc').limit).toBe(400);+ expect(q('limit=').limit).toBe(400);+ });++ it('honours an explicit limit and clamps it into range', () => {+ expect(q('limit=25').limit).toBe(25);+ expect(q('limit=500').limit).toBe(500);+ expect(q('limit=99999').limit).toBe(500);+ expect(q('limit=0').limit).toBe(1);+ expect(q('limit=-5').limit).toBe(1);+ expect(q('limit=12.9').limit).toBe(12);+ });++ it('falls back to mainnet and the 90-day window on unknown values', () => {+ expect(q('network=evil&window=999')).toMatchObject({ network: 'mainnet', window: '90' });+ expect(q('')).toMatchObject({ network: 'mainnet', window: '90' });+ });++ it('accepts every documented network and window', () => {+ expect(q('network=devnet').network).toBe('devnet');+ for (const w of ['7', '30', '90', 'all']) expect(q(`window=${w}`).window).toBe(w);+ });+});++describe('radar-stream advanceCursor', () => {+ const T0 = '2026-08-16T06:00:00.000Z';++ // The bug: Neon returns timestamptz as a Date, and `aDate > anIsoString`+ // coerces both to numbers, making the string NaN and the comparison always+ // false. The cursor froze at connect time, so every poll re-sent the same+ // precursors and the live tape filled with duplicates.+ it('advances past a Date row, which a raw > comparison never did', () => {+ const row = new Date('2026-08-16T06:00:05.000Z');+ expect(row > T0).toBe(false); // the original expression+ expect(advanceCursor(T0, row)).toBe('2026-08-16T06:00:05.000Z');+ });++ it('advances past an ISO string row', () => {+ expect(advanceCursor(T0, '2026-08-16T06:00:05.000Z')).toBe('2026-08-16T06:00:05.000Z');+ });++ it('never rewinds on an older or equal row', () => {+ expect(advanceCursor(T0, new Date('2026-08-16T05:59:00.000Z'))).toBe(T0);+ expect(advanceCursor(T0, new Date(T0))).toBe(T0);+ });++ it('ignores a missing timestamp', () => {+ expect(advanceCursor(T0, null)).toBe(T0);+ expect(advanceCursor(T0, undefined)).toBe(T0);+ });++ it('keeps the newest timestamp across a batch of rows', () => {+ const rows = [+ new Date('2026-08-16T06:00:01.000Z'),+ new Date('2026-08-16T06:00:09.000Z'),+ new Date('2026-08-16T06:00:04.000Z'),+ ];+ let cursor = T0;+ for (const at of rows) cursor = advanceCursor(cursor, at);+ expect(cursor).toBe('2026-08-16T06:00:09.000Z');+ });+});diff --git a/workers/agent-sniper/journal.js b/workers/agent-sniper/journal.jsindex 3030a8c75..fa6b73428 100644--- a/workers/agent-sniper/journal.js+++ b/workers/agent-sniper/journal.js@@ -12,7 +12,12 @@import { sql } from '../../api/_lib/db.js';import { log } from './log.js';-/** Lazy table create so a fresh env journals whether the migration ran or not. */+/**+ * Lazy table create so a fresh env journals whether the migration ran or not.+ * agent_id and position_id are uuid because that is what every caller passes+ * (agent_sniper_strategies.agent_id and agent_sniper_positions.id are both+ * uuid); the original text/bigint shape made every INSERT here fail silently.+ */let _ensured = false;async function ensure() {if (_ensured) return;@@ -20,8 +25,8 @@ async function ensure() {CREATE TABLE IF NOT EXISTS trading_journal (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,ts timestamptz NOT NULL DEFAULT now(),- agent_id text,- position_id bigint,+ agent_id uuid,+ position_id uuid,network text,mint text,symbol text,