Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(scout): Sentiment Scout ships momentum where every claim carries its receipt

nirholas433ea3941f97
diff --git a/api/_lib/migrations/20260929120000_sentiment_scout_reads.sql b/api/_lib/migrations/20260929120000_sentiment_scout_reads.sql
new file mode 100644
index 000000000..964152b76
--- /dev/null
+++ b/api/_lib/migrations/20260929120000_sentiment_scout_reads.sql
@@ -0,0 +1,58 @@
+-- 20260929120000_sentiment_scout_reads.sql
+--
+-- The Sentiment Scout (api/_lib/sentiment-scout.js, GET /api/pump/sentiment-scout)
+-- ranks pump.fun launches by sourced momentum and hands back every claim with
+-- its receipt: the source link, the time the fact was true, and the on-chain
+-- facts a social claim was checked against. Until now nothing it said was kept,
+-- so two questions had no answer:
+--
+-- 1. "Had the Scout flagged this coin before the agent bought it?" A trade
+-- receipt (api/_lib/trade-receipt.js) can only show that if the first
+-- sighting, with the evidence as it stood then, was recorded.
+-- 2. "Is the Scout any good?" Its calls can only be graded against the Coin
+-- Intelligence Engine's outcome labels (pump_coin_outcomes) if the calls
+-- were kept.
+--
+-- One row per coin. The first_* columns are written once, on the first board
+-- appearance, and never change: they are what receipts and the track record
+-- read. The last_* / evidence columns follow the latest read.
+--
+-- Also: agent_sniper_strategies.llm_scout_context, a per-strategy opt-in that
+-- hands the Scout's read to that strategy's LLM judge. Off by default, so every
+-- running LLM experiment keeps asking exactly the question it was asking.
+--
+-- Additive and idempotent, safe to re-run.
+
+create table if not exists sentiment_scout_reads (
+ mint text not null,
+ network text not null default 'mainnet' check (network in ('mainnet', 'devnet')),
+ symbol text,
+ first_scouted_at timestamptz not null default now(),
+ first_score smallint not null check (first_score between 0 and 100),
+ first_evidence jsonb not null default '[]'::jsonb,
+ first_caution text,
+ last_scouted_at timestamptz not null default now(),
+ last_score smallint not null check (last_score between 0 and 100),
+ peak_score smallint not null check (peak_score between 0 and 100),
+ evidence jsonb not null default '[]'::jsonb,
+ caution text,
+ x_summary jsonb,
+ posts jsonb,
+ primary key (mint, network)
+);
+
+create index if not exists sentiment_scout_reads_first_idx
+ on sentiment_scout_reads (network, first_scouted_at desc);
+
+comment on table sentiment_scout_reads is
+ 'Every coin the Sentiment Scout put on its board: the first sighting (score, evidence, caution; immutable) and the latest read. Read by trade receipts and the Scout track record.';
+comment on column sentiment_scout_reads.first_evidence is
+ 'Evidence lines as they stood at the first sighting: [{type, detail, source, at, checked_against?}]. Never updated.';
+comment on column sentiment_scout_reads.posts is
+ 'Up to three X posts quoting the exact contract address, as receipts: [{url, author, followers, verified, at, text, likes, reposts}].';
+
+alter table agent_sniper_strategies
+ add column if not exists llm_scout_context boolean not null default false;
+
+comment on column agent_sniper_strategies.llm_scout_context is
+ 'When true, this LLM-judged strategy''s judge is also shown the Sentiment Scout''s sourced read of the coin (evidence lines, momentum score, caution). Off by default so existing experiments are unchanged.';
diff --git a/api/_lib/scout-notes.js b/api/_lib/scout-notes.js
new file mode 100644
index 000000000..8b77e3a5a
--- /dev/null
+++ b/api/_lib/scout-notes.js
@@ -0,0 +1,190 @@
+// The Sentiment Scout's read: one or two plain sentences per candidate,
+// written by the platform LLM chain FROM the evidence lines and nothing else.
+//
+// The evidence is built deterministically (api/_lib/sentiment-scout.js); this
+// layer only turns it into something a first-time reader can take in at a
+// glance. Because a model will happily invent a follower count or a "10x", no
+// note is trusted as written. validateScoutNote() rejects any note that:
+// - contains a number that does not appear in that candidate's evidence,
+// caution or score (so it cannot add a fact),
+// - names a ticker other than the candidate's own or $THREE,
+// - carries a link, or
+// - makes a promise or a call to action ("guaranteed", "can't lose", "buy now").
+// A rejected note is dropped, never repaired: the candidate simply shows its
+// evidence without a summary. The completion function is injectable so the
+// tests drive the real prompt building, parsing and validation.
+
+import { llmComplete } from './llm.js';
+
+export const MAX_NOTE_CHARS = 260;
+const NOTE_TIMEOUT_MS = 20_000;
+const NOTE_CACHE_TTL_MS = 10 * 60_000;
+
+const PROMISE_RE = /\b(guarantee[ds]?|guaranteed|risk[- ]free|can'?t lose|cannot lose|sure thing|free money|to the moon|will (?:moon|pump|10x|100x|explode)|buy now|ape in|load up|send it|don'?t miss|not financial advice|nfa)\b/i;
+const URL_RE = /(https?:\/\/|www\.|\b[a-z0-9-]+\.(?:com|io|fun|xyz|net|org|ws|app|gg)\b)/i;
+// Venue names that appear in the evidence itself are words here, not links.
+const VENUE_NAMES_RE = /\b(?:pump\.fun|three\.ws)\b/gi;
+const TICKER_RE = /\$([A-Za-z][A-Za-z0-9]{1,15})\b/g;
+const NUMBER_RE = /\d+(?:[.,]\d+)?/g;
+
+export const SCOUT_NOTE_SYSTEM = `You write the Sentiment Scout's read for pump.fun token candidates. You do NOT trade and you do NOT advise trading.
+
+For each candidate you are given its ticker, a momentum score, evidence lines, and a caution line. Write TWO short plain-English sentences, under ${MAX_NOTE_CHARS - 40} characters in total: the first says what the strongest evidence shows, the second names the main risk in your own words (do not paste the caution line).
+
+Hard rules:
+- Use ONLY facts in that candidate's evidence and caution. Every number you write must appear there exactly. Never add a follower count, a price, a multiple, or a percentage that is not given.
+- If the evidence is thin or comes from one voice, say so plainly. Do not pad it.
+- Mention no token other than the candidate's own ticker or $THREE.
+- No links, no emojis, no hype, no promises, no instructions to buy or sell.
+
+Reply with STRICT JSON and nothing else:
+{"notes":[{"mint":"<mint>","note":"<one or two sentences>"}]}`;
+
+/** The user prompt for a batch of candidates. Pure. */
+export function buildScoutNotePrompt(candidates) {
+ const blocks = candidates.map((c) => [
+ `mint: ${c.mint}`,
+ `ticker: ${c.ticker || '(none)'}`,
+ `momentum_score: ${c.momentum_score}/100`,
+ 'evidence:',
+ ...c.evidence.map((e) => `- ${e.type}: ${e.detail}`),
+ `caution: ${c.caution}`,
+ ].join('\n'));
+ return `Write the Scout's read for each candidate below.\n\n${blocks.join('\n\n')}`;
+}
+
+/** Pull the notes array out of a model reply. Tolerates fences and prose. Pure. */
+export function parseScoutNotes(text) {
+ if (!text) return [];
+ const match = String(text).match(/\{[\s\S]*\}/);
+ if (!match) return [];
+ let obj;
+ try {
+ obj = JSON.parse(match[0]);
+ } catch {
+ return [];
+ }
+ const list = Array.isArray(obj?.notes) ? obj.notes : [];
+ return list
+ .filter((n) => n && typeof n.mint === 'string' && typeof n.note === 'string')
+ .map((n) => ({ mint: n.mint.trim(), note: n.note.replace(/\s+/g, ' ').trim() }));
+}
+
+// Counts spelled out as words are facts too ("five other coins"). "one" is
+// left out: it is used idiomatically ("one voice", "one account") far more
+// often than as a count a reader would check.
+const WORD_NUMBERS = {
+ two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10,
+ eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16,
+ seventeen: 17, eighteen: 18, nineteen: 19, twenty: 20, dozen: 12, hundred: 100,
+};
+const WORD_NUMBER_RE = new RegExp(`\\b(${Object.keys(WORD_NUMBERS).join('|')})\\b`, 'gi');
+
+function numbersIn(text) {
+ return (String(text).match(NUMBER_RE) || []).map((n) => n.replace(',', '.'));
+}
+
+// Word counts in prose, as digit strings. "$THREE" is a ticker, not a count.
+function wordNumbersIn(text) {
+ const prose = String(text).replace(TICKER_RE, '');
+ return [...prose.matchAll(WORD_NUMBER_RE)].map((m) => String(WORD_NUMBERS[m[1].toLowerCase()]));
+}
+
+/**
+ * Check one note against the candidate it describes. Pure.
+ * @returns {{ ok: boolean, reason?: string }}
+ */
+export function validateScoutNote(note, candidate) {
+ const text = String(note || '').trim();
+ if (text.length < 20) return { ok: false, reason: 'too_short' };
+ if (text.length > MAX_NOTE_CHARS) return { ok: false, reason: 'too_long' };
+ if (URL_RE.test(text.replace(VENUE_NAMES_RE, ''))) return { ok: false, reason: 'link' };
+ if (PROMISE_RE.test(text)) return { ok: false, reason: 'promise' };
+
+ const own = String(candidate.ticker || '').replace(/^\$/, '').toLowerCase();
+ for (const m of text.matchAll(TICKER_RE)) {
+ const t = m[1].toLowerCase();
+ if (t !== own && t !== 'three') return { ok: false, reason: 'foreign_ticker' };
+ }
+
+ const grounded = new Set([
+ ...numbersIn(candidate.caution || ''),
+ ...candidate.evidence.flatMap((e) => numbersIn(e.detail)),
+ String(candidate.momentum_score),
+ '100', // "out of 100" when restating the score
+ ]);
+ // The ticker itself may contain digits ($ABC2); those are not facts.
+ const tickerDigits = new Set(numbersIn(own));
+ for (const n of [...numbersIn(text), ...wordNumbersIn(text)]) {
+ if (grounded.has(n) || tickerDigits.has(n)) continue;
+ return { ok: false, reason: `ungrounded_number:${n}` };
+ }
+ return { ok: true };
+}
+
+/** A stable key for "the evidence this note was written from". Pure. */
+export function noteSignature(candidate) {
+ return [
+ candidate.mint,
+ Math.round(candidate.momentum_score / 5),
+ candidate.caution,
+ ...candidate.evidence.map((e) => `${e.type}:${e.detail}`),
+ ].join('|');
+}
+
+const _notes = new Map(); // signature -> { value, at }
+
+/**
+ * Write validated notes for a batch of candidates in ONE completion. Returns
+ * a Map of mint -> { note, model, provider }. A candidate whose note failed
+ * validation, or a batch whose completion failed, is simply absent: the
+ * caller shows evidence without a summary.
+ *
+ * @param {Array<object>} candidates shaped Scout candidates
+ * @param {{ complete?: Function, timeoutMs?: number }} [opts]
+ */
+export async function writeScoutNotes(candidates, { complete = llmComplete, timeoutMs = NOTE_TIMEOUT_MS } = {}) {
+ const out = new Map();
+ const now = Date.now();
+ const todo = [];
+ for (const c of candidates || []) {
+ if (!c?.evidence?.length) continue;
+ const hit = _notes.get(noteSignature(c));
+ if (hit && now - hit.at < NOTE_CACHE_TTL_MS) {
+ if (hit.value) out.set(c.mint, hit.value);
+ } else {
+ todo.push(c);
+ }
+ }
+ if (!todo.length) return out;
+
+ let res;
+ try {
+ res = await complete({
+ system: SCOUT_NOTE_SYSTEM,
+ user: buildScoutNotePrompt(todo),
+ maxTokens: 120 * todo.length + 80,
+ timeoutMs,
+ track: { tool: 'sentiment_scout_notes' },
+ });
+ } catch {
+ return out;
+ }
+ const byMint = new Map(parseScoutNotes(res?.text).map((n) => [n.mint, n.note]));
+ for (const c of todo) {
+ const note = byMint.get(c.mint);
+ const verdict = note ? validateScoutNote(note, c) : { ok: false };
+ const value = verdict.ok ? { note, model: res?.model || null, provider: res?.provider || null } : null;
+ _notes.set(noteSignature(c), { value, at: now });
+ if (value) out.set(c.mint, value);
+ }
+ if (_notes.size > 500) {
+ for (const [k, v] of _notes) if (now - v.at > NOTE_CACHE_TTL_MS) _notes.delete(k);
+ }
+ return out;
+}
+
+/** Test seam. */
+export function _resetScoutNotes() {
+ _notes.clear();
+}
diff --git a/api/_lib/sentiment-scout.js b/api/_lib/sentiment-scout.js
index 779ee8dae..d9973c072 100644
--- a/api/_lib/sentiment-scout.js
+++ b/api/_lib/sentiment-scout.js
@@ -3,13 +3,16 @@
//
// Contract (roadmap 917, prompt 14.2):
// { mint, ticker, momentum_score: 0-100,
-// evidence: [{ type, detail, source }], caution }
+// evidence: [{ type, detail, source, at, checked_against? }], caution }
//
// "Cite only real, retrievable evidence; never fabricate" is enforced by
// construction rather than by asking a model nicely: every evidence line is
-// rendered from a row or an upstream read this module just made, and carries a
-// source a reader can open to check it. A signal we could not read is left out
-// (and listed under `unavailable`), never estimated.
+// rendered from a row or an upstream read this module just made, carries a
+// source a reader can open to check it, and the time the fact was true. A
+// social claim (an X post, a pump.fun callout, a paid market read) also names
+// the on-chain facts it was checked against at scout time, so a reader can see
+// a loud post next to a chart that did or did not back it up. A signal we
+// could not read is left out (and listed under `unavailable`), never estimated.
//
// Pipeline (cheap on everything, expensive on candidates):
// 1. Window: every coin the Coin Intelligence Engine observed in the last
@@ -19,17 +22,22 @@
// has one buyer, so "40x the median" would be noise dressed as signal.
// 3. Screen: coordinated launches and dumped devs never qualify; a coin has
// to sit in the top quartile of its window on buy volume.
-// 4. Enrich the survivors only: live bonding-curve state, pump.fun
-// callouts (the coin page's community commentary; pump.fun now serves
-// these only to signed-in sessions, so they usually land under
-// `unavailable`), and the fleet's paid Crypto Intel sentiment reads,
-// each backed by the x402 payment transaction that bought it.
+// 4. Enrich the survivors only: live bonding-curve state, X posts quoting
+// the exact contract address (api/_lib/x-search.js), pump.fun callouts
+// (served only to signed-in sessions now, so they usually land under
+// `unavailable`), and the fleet's paid Crypto Intel sentiment reads, each
+// backed by the x402 payment transaction that bought it.
// 5. Score + one caution line, both deterministic and explainable.
+// 6. Record every board candidate (sentiment_scout_reads) so a trade receipt
+// can show what the Scout had flagged before an entry, and so the Scout's
+// own calls are graded against labeled outcomes (scoutTrackRecord).
import { sql } from './db.js';
+import { cacheGet, cacheSet, cacheWrap } from './cache.js';
import { getBondingStatus } from './pump-bonding.js';
import { fetchPumpFunCallouts } from './pump-callouts.js';
import { receiptTxUrl } from './trade-receipt.js';
+import { searchMintPosts, summarizePosts, xSearchConfigured } from './x-search.js';
export const EVIDENCE_TYPES = Object.freeze([
'volume_spike',
@@ -54,6 +62,18 @@ const MIN_BUYERS = 3;
const ENRICH_TIMEOUT_MS = 6000;
const CACHE_TTL_MS = 30_000;
const PAID_SIGNAL_MAX_AGE_H = 6;
+// X posts about a coin move slowly next to its chart, and search is metered:
+// one read per coin per ten minutes is plenty.
+const X_CACHE_TTL_S = 600;
+const X_FAIL_TTL_S = 60;
+// Posts from before a coin existed cannot be about it; allow a little slack
+// for creators who tease an address minutes before the first trade.
+const X_LOOKBACK_BEFORE_LAUNCH_MS = 10 * 60 * 1000;
+const MAX_POST_RECEIPTS = 3;
+// A curve back at the start after real early buying means the buyers left.
+const CURVE_RESET_PCT = 2;
+const CURVE_RESET_MIN_SOL = 5;
+const JUDGE_STATS_TTL_MS = 60_000;
const cache = new Map();
@@ -62,6 +82,20 @@ const clamp01 = (n) => Math.max(0, Math.min(1, n));
const round = (n, d = 2) => (n == null || !Number.isFinite(n) ? null : Math.round(n * 10 ** d) / 10 ** d);
const pct = (x) => `${Math.round(x * 100)}%`;
const fmtSol = (x) => (x >= 10 ? x.toFixed(1) : x.toFixed(2));
+const iso = (t) => {
+ if (t == null) return null;
+ const ms = t instanceof Date ? t.getTime() : Date.parse(t);
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
+};
+
+/** 1234 -> "1.2k", 2500000 -> "2.5M". Follower counts read at a glance. */
+export function fmtCount(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return null;
+ if (v >= 1e6) return `${(v / 1e6).toFixed(v >= 1e7 ? 0 : 1)}M`;
+ if (v >= 1e3) return `${(v / 1e3).toFixed(v >= 1e4 ? 0 : 1)}k`;
+ return String(Math.round(v));
+}
export function appOrigin() {
return (process.env.PUBLIC_APP_ORIGIN || 'https://three.ws').replace(/\/+$/, '');
@@ -182,18 +216,41 @@ export function preScore(r, stats) {
return m;
}
+/**
+ * True when the X chatter about a coin is one account talking to itself: at
+ * least three posts and one poster wrote 70%+ of them. Pure.
+ */
+export function isSingleVoice(x) {
+ if (!x || !x.posts) return false;
+ return x.posts >= 3 && (x.authors === 1 || x.top_poster_share >= 0.7);
+}
+
+/**
+ * How much independent X attention a coin has, 0..1. Distinct accounts count,
+ * reach counts a little, and one account posting on repeat counts for almost
+ * nothing, because that is promotion rather than interest. Pure.
+ */
+export function xAttention(x) {
+ if (!x || !x.posts) return 0;
+ const breadth = clamp01((x.authors - 1) / 4);
+ const reach = clamp01(Math.log10(1 + (x.reach_followers || 0)) / 5);
+ const raw = 0.7 * breadth + 0.3 * reach;
+ return isSingleVoice(x) ? raw * 0.25 : raw;
+}
+
/**
* Final 0-100 momentum score with its parts, so a reader can see why. Pure.
*/
-export function momentumScore(pre, { curve, calloutCount, newsMatch, paidSignal, flags, copycats }) {
+export function momentumScore(pre, { curve, calloutCount, newsMatch, paidSignal, flags, copycats, xSummary = null }) {
let curveScore = 0;
if (curve?.graduated) curveScore = 0.6;
else if (curve?.bondingProgressPct != null) curveScore = clamp01(curve.bondingProgressPct / 100);
const paidBoost = paidSignal?.signal === 'bullish' ? 0.4 * clamp01(Number(paidSignal.confidence) || 0) : 0;
- const socialScore = clamp01((calloutCount || 0) / 5 + (newsMatch ? 0.5 : 0) + paidBoost);
+ const socialScore = clamp01((calloutCount || 0) / 5 + (newsMatch ? 0.5 : 0) + paidBoost + 0.6 * xAttention(xSummary));
let penalty = 8 * (flags || []).length;
if (copycats > 0) penalty += 10;
if (pre.concPct != null && pre.concPct >= 0.9) penalty += 10;
+ if (isSingleVoice(xSummary)) penalty += 5;
const parts = {
volume: round(30 * pre.volPct, 1),
buyers: round(25 * pre.buyerPct, 1),
@@ -207,22 +264,50 @@ export function momentumScore(pre, { curve, calloutCount, newsMatch, paidSignal,
return { score: Math.max(0, Math.min(100, Math.round(total))), parts };
}
+/** When the launch-window facts were true: the end of the observation window. */
+function observedAt(r) {
+ const first = Date.parse(r.first_seen_at instanceof Date ? r.first_seen_at.toISOString() : r.first_seen_at);
+ if (!Number.isFinite(first)) return null;
+ const obs = Number(r.observation_seconds) || 0;
+ return new Date(first + obs * 1000).toISOString();
+}
+
/**
- * Build the evidence list. Every line comes from a value read in this run and
- * points at a source that returns it. Pure.
+ * The on-chain facts a social claim is checked against, in one line. Built
+ * only from reads this run made: the launch window (always) and the live
+ * bonding curve (when it answered). Pure.
*/
-export function buildEvidence(r, pre, stats, { curve, callouts, paidSignal, origin }) {
+export function marketCheckLine(pre, r, curve, checkedAt) {
+ const obs = Number(r.observation_seconds) || null;
+ const parts = [`${fmtSol(pre.vol)} SOL bought by ${pre.nBuyers} wallets in the first ${obs ? `${obs}s` : 'minutes'}`];
+ if (curve?.graduated) parts.push(`graduated${curve.migratedTo ? ` to ${curve.migratedTo}` : ''}`);
+ else if (curve?.bondingProgressPct != null) parts.push(`bonding curve at ${Math.round(curve.bondingProgressPct)}%`);
+ const when = iso(checkedAt);
+ return `On-chain${when ? ` at ${when.slice(11, 16)} UTC` : ''}: ${parts.join('; ')}`;
+}
+
+/**
+ * Build the evidence list. Every line comes from a value read in this run,
+ * carries the time the fact was true, and points at a source that returns it.
+ * Social and paid lines also carry the on-chain facts they were checked
+ * against. Pure.
+ */
+export function buildEvidence(r, pre, stats, { curve, callouts, paidSignal, origin, xSummary = null, xPosts = null, checkedAt = null }) {
const mint = r.mint;
const intelApi = `${origin}/api/pump/coin-intel?mint=${encodeURIComponent(mint)}`;
const pumpPage = `https://pump.fun/coin/${encodeURIComponent(mint)}`;
const obs = Number(r.observation_seconds) || null;
const inWindow = obs ? `in its first ${obs}s` : 'in its observation window';
+ const launchAt = observedAt(r);
+ const readAt = iso(checkedAt) || new Date().toISOString();
+ const check = marketCheckLine(pre, r, curve, readAt);
const evidence = [];
evidence.push({
type: 'volume_spike',
detail: `${fmtSol(pre.vol)} SOL bought ${inWindow}, top ${topPct(pre.volPct)}% of ${stats.size} launches in the window (median ${fmtSol(stats.medianVol)} SOL)`,
source: intelApi,
+ at: launchAt,
});
const fresh = r.fresh_wallet_ratio != null ? Number(r.fresh_wallet_ratio) : null;
@@ -232,6 +317,7 @@ export function buildEvidence(r, pre, stats, { curve, callouts, paidSignal, orig
+ (fresh != null ? `; ${pct(fresh)} of them brand-new wallets` : '')
+ (pre.bsr != null ? `; ${round(pre.bsr, 2)} buys per sell` : ''),
source: intelApi,
+ at: launchAt,
});
const sm = Number(r.smart_money_count) || 0;
@@ -246,6 +332,7 @@ export function buildEvidence(r, pre, stats, { curve, callouts, paidSignal, orig
detail: `${sm} wallet${sm === 1 ? '' : 's'} with a profitable pump.fun record bought early`
+ (best != null ? ` (best win rate ${pct(best > 1 ? best / 100 : best)})` : ''),
source: intelApi,
+ at: launchAt,
});
}
@@ -254,6 +341,7 @@ export function buildEvidence(r, pre, stats, { curve, callouts, paidSignal, orig
type: 'graduation_approach',
detail: `already graduated off the bonding curve${curve.migratedTo ? ` to ${curve.migratedTo}` : ''}`,
source: pumpPage,
+ at: readAt,
});
} else if (curve?.bondingProgressPct != null) {
evidence.push({
@@ -261,6 +349,27 @@ export function buildEvidence(r, pre, stats, { curve, callouts, paidSignal, orig
detail: `bonding curve ${Math.round(curve.bondingProgressPct)}% of the way to graduation`
+ (curve.solInCurve != null ? `, ${fmtSol(curve.solInCurve)} SOL in the curve` : ''),
source: pumpPage,
+ at: readAt,
+ });
+ }
+
+ if (xSummary?.posts && Array.isArray(xPosts) && xPosts.length) {
+ // Quote the most-followed account's post: the one with the most reach is
+ // the one a follower is most likely to have seen.
+ const lead = xPosts.slice().sort((a, b) => (b.author?.followers || 0) - (a.author?.followers || 0))[0];
+ const flat = String(lead.text || '').replace(/https?:\/\/\S+/g, '').replace(/\s+/g, ' ').trim();
+ const quote = flat.length > 140 ? `${flat.slice(0, 140)}...` : flat;
+ const who = lead.author?.username ? `@${lead.author.username}` : 'an account';
+ const followers = fmtCount(lead.author?.followers);
+ evidence.push({
+ type: 'social_mention',
+ platform: 'x',
+ detail: `${xSummary.posts} X post${xSummary.posts === 1 ? '' : 's'} quoted this exact contract address, from ${xSummary.authors} account${xSummary.authors === 1 ? '' : 's'}`
+ + `; most-followed ${who}${followers ? ` (${followers} followers)` : ''}`
+ + (quote ? `: "${quote}"` : ''),
+ source: lead.url,
+ at: iso(lead.created_at),
+ checked_against: check,
});
}
@@ -270,10 +379,13 @@ export function buildEvidence(r, pre, stats, { curve, callouts, paidSignal, orig
const quote = flat.length > 140 ? `${flat.slice(0, 140)}...` : flat;
evidence.push({
type: 'social_mention',
+ platform: 'pump.fun',
detail: `${callouts.length} pump.fun callout${callouts.length === 1 ? '' : 's'}; latest`
+ (latest.author ? ` from @${latest.author}` : '')
+ `: "${quote}"`,
source: pumpPage,
+ at: iso(latest.ts),
+ checked_against: check,
});
}
@@ -284,6 +396,8 @@ export function buildEvidence(r, pre, stats, { curve, callouts, paidSignal, orig
detail: `paid ${paidSignal.source || 'sentiment'} read (x402${Number.isFinite(conf) ? `, confidence ${pct(conf)}` : ''}): ${paidSignal.signal}`
+ (paidSignal.headline ? `, "${String(paidSignal.headline).slice(0, 120)}"` : ''),
source: receiptTxUrl(paidSignal.tx_signature) || intelApi,
+ at: iso(paidSignal.checked_at),
+ checked_against: check,
});
}
@@ -293,6 +407,8 @@ export function buildEvidence(r, pre, stats, { curve, callouts, paidSignal, orig
type: 'news_match',
detail: `name matches a live news story: "${String(headline).slice(0, 140)}"`,
source: r.signals?.news_url || intelApi,
+ at: launchAt,
+ checked_against: check,
});
}
return evidence;
@@ -302,7 +418,7 @@ export function buildEvidence(r, pre, stats, { curve, callouts, paidSignal, orig
* The single most important risk, in one line. Deterministic priority order,
* worst first. Pure.
*/
-export function cautionFor(r, { copycats = 0, calloutCount = 0, calloutsRead = true, paidSignal = null, concPct = null } = {}) {
+export function cautionFor(r, { copycats = 0, calloutCount = 0, calloutsRead = true, paidSignal = null, concPct = null, curve = null, earlyVolSol = null, xSummary = null } = {}) {
const flags = new Set(Array.isArray(r.risk_flags) ? r.risk_flags : []);
const fresh = r.fresh_wallet_ratio != null ? Number(r.fresh_wallet_ratio) : null;
const top10 = r.concentration_top10 != null ? Number(r.concentration_top10) : null;
@@ -310,10 +426,20 @@ export function cautionFor(r, { copycats = 0, calloutCount = 0, calloutsRead = t
const sym = r.symbol ? `$${r.symbol}` : 'this name';
if (flags.has('dev_dumped')) return 'The creator already sold; momentum from here is exit liquidity.';
if (flags.has('bundle_launch')) return 'Launch was bundled: a coordinated group bought the early supply.';
+ if (curve && !curve.graduated && curve.bondingProgressPct != null && curve.bondingProgressPct < CURVE_RESET_PCT
+ && earlyVolSol != null && earlyVolSol >= CURVE_RESET_MIN_SOL) {
+ return `The bonding curve is back at ${Math.round(curve.bondingProgressPct)}% after ${fmtSol(earlyVolSol)} SOL of early buying: the early buyers have already sold.`;
+ }
if (flags.has('single_whale')) return 'One wallet holds most of the early supply; a single sell can erase the move.';
if (flags.has('fresh_wallet_swarm') || (fresh != null && fresh >= 0.5)) {
return `${fresh != null ? pct(fresh) : 'Most'} of early buyers are brand-new wallets, a common sign of manufactured volume.`;
}
+ if (isSingleVoice(xSummary)) {
+ const who = xSummary.top_poster?.username ? `@${xSummary.top_poster.username}` : 'one account';
+ return xSummary.authors === 1
+ ? `All ${xSummary.posts} X posts quoting this contract came from ${who}: that is promotion, not independent interest.`
+ : `${who} wrote ${xSummary.top_poster?.posts} of the ${xSummary.posts} X posts quoting this contract: the chatter is mostly one voice.`;
+ }
if (top10 != null && concPct != null && concPct >= 0.8) {
return `The top 10 wallets hold ${pct(top10)} of what was bought early, more concentrated than ${Math.floor(concPct * 100)}% of comparable launches; exits can be sudden.`;
}
@@ -329,7 +455,7 @@ export function cautionFor(r, { copycats = 0, calloutCount = 0, calloutsRead = t
if (flags.has('sniped')) {
return `${snipe != null ? pct(snipe) : 'Much'} of early volume came from first-block snipers, who usually sell into the first pump.`;
}
- if (!r.twitter && !r.telegram && !r.website && !calloutCount) {
+ if (!r.twitter && !r.telegram && !r.website && !calloutCount && !xSummary?.posts) {
return calloutsRead
? 'No X, Telegram, website or callouts: nothing outside the chart is holding attention.'
: 'No X, Telegram or website linked: nothing outside the chart is holding attention.';
@@ -399,13 +525,53 @@ async function loadPaidSignals(network, mints) {
return rows ? new Map(rows.map((r) => [r.mint, r])) : null;
}
-async function enrich(mint) {
- const [curveRes, calloutRes] = await Promise.all([
+/** The post receipts a candidate ships with: the most-followed few, trimmed. Pure. */
+export function postReceipts(posts, n = MAX_POST_RECEIPTS) {
+ return (posts || [])
+ .slice()
+ .sort((a, b) => (b.author?.followers || 0) - (a.author?.followers || 0) || Date.parse(b.created_at) - Date.parse(a.created_at))
+ .slice(0, n)
+ .map((p) => ({
+ url: p.url,
+ author: p.author?.username || null,
+ followers: p.author?.followers ?? null,
+ verified: p.author?.verified === true,
+ at: iso(p.created_at),
+ text: String(p.text || '').replace(/\s+/g, ' ').slice(0, 280),
+ likes: p.likes,
+ reposts: p.reposts,
+ }));
+}
+
+// X posts quoting one mint, cached per mint. A failed read is cached briefly
+// as a failure, so an X outage does not turn every board refresh into a wait.
+async function readXPosts(mint, firstSeenAt) {
+ if (!xSearchConfigured()) return { unavailable: 'not_configured' };
+ const key = `scout:x:v1:${mint}`;
+ const hit = await cacheGet(key).catch(() => null);
+ if (hit) return hit;
+ let value;
+ try {
+ const first = Date.parse(firstSeenAt instanceof Date ? firstSeenAt.toISOString() : firstSeenAt);
+ const sinceIso = Number.isFinite(first) ? new Date(first - X_LOOKBACK_BEFORE_LAUNCH_MS).toISOString() : null;
+ const posts = await searchMintPosts(mint, { sinceIso, maxResults: 25 });
+ value = { posts, summary: summarizePosts(posts), read_at: new Date().toISOString() };
+ cacheSet(key, value, X_CACHE_TTL_S).catch(() => {});
+ } catch (err) {
+ value = { unavailable: err?.reason || 'upstream_error' };
+ cacheSet(key, value, X_FAIL_TTL_S).catch(() => {});
+ }
+ return value;
+}
+
+async function enrich(mint, firstSeenAt) {
+ const [curveRes, calloutRes, xRes] = await Promise.all([
withTimeout(getBondingStatus(mint).catch(() => ({ kind: 'upstream_down' })), ENRICH_TIMEOUT_MS),
withTimeout(
fetchPumpFunCallouts(mint, 20, { timeoutMs: ENRICH_TIMEOUT_MS - 500 }).catch(() => ({ error: 'unreachable' })),
ENRICH_TIMEOUT_MS,
),
+ withTimeout(readXPosts(mint, firstSeenAt), ENRICH_TIMEOUT_MS),
]);
const unavailable = [];
let curve = null;
@@ -421,7 +587,20 @@ async function enrich(mint) {
let callouts = [];
if (Array.isArray(calloutRes?.posts)) callouts = calloutRes.posts;
else unavailable.push('callouts');
- return { curve, callouts, socials, calloutsRead: !unavailable.includes('callouts'), unavailable };
+ let xPosts = null;
+ let xSummary = null;
+ if (Array.isArray(xRes?.posts)) {
+ xPosts = xRes.posts;
+ xSummary = xRes.summary;
+ } else {
+ unavailable.push('x_posts');
+ }
+ return {
+ curve, callouts, socials, xPosts, xSummary,
+ calloutsRead: !unavailable.includes('callouts'),
+ checkedAt: new Date().toISOString(),
+ unavailable,
+ };
}
export function shapeCandidate(row, pre, stats, extra, origin) {
@@ -434,16 +613,19 @@ export function shapeCandidate(row, pre, stats, extra, origin) {
};
const copycats = Math.max(0, (stats.symbols.get(symbolKey(r.symbol)) || 1) - 1);
const flags = Array.isArray(r.risk_flags) ? r.risk_flags : [];
+ const callouts = extra.callouts || [];
const { score, parts } = momentumScore(pre, {
curve: extra.curve,
- calloutCount: extra.callouts.length,
+ calloutCount: callouts.length,
paidSignal: extra.paidSignal,
newsMatch: !!(r.is_news_meme && r.signals?.news_headline),
flags,
copycats,
+ xSummary: extra.xSummary,
});
const disqualified = flags.some((f) => DISQUALIFYING_FLAGS.has(f));
const mint = r.mint;
+ const checkedAt = extra.checkedAt || new Date().toISOString();
return {
mint,
ticker: r.symbol ? `$${r.symbol}` : null,
@@ -451,32 +633,227 @@ export function shapeCandidate(row, pre, stats, extra, origin) {
image_uri: r.image_uri || null,
momentum_score: disqualified ? 0 : score,
score_parts: parts,
- evidence: buildEvidence(r, pre, stats, { ...extra, origin }),
+ evidence: buildEvidence(r, pre, stats, { ...extra, callouts, origin, checkedAt }),
caution: cautionFor(r, {
copycats,
- calloutCount: extra.callouts.length,
+ calloutCount: callouts.length,
calloutsRead: extra.calloutsRead !== false,
paidSignal: extra.paidSignal,
concPct: pre.concPct,
+ curve: extra.curve,
+ earlyVolSol: pre.vol,
+ xSummary: extra.xSummary,
}),
+ market_check: {
+ checked_at: checkedAt,
+ early_buy_volume_sol: round(pre.vol, 3),
+ early_buyers: pre.nBuyers,
+ observation_seconds: Number(r.observation_seconds) || null,
+ graduated: extra.curve ? extra.curve.graduated === true : null,
+ bonding_progress_pct: extra.curve?.bondingProgressPct != null ? round(extra.curve.bondingProgressPct, 1) : null,
+ sol_in_curve: extra.curve?.solInCurve != null ? round(extra.curve.solInCurve, 3) : null,
+ },
+ x: extra.xSummary || null,
+ posts: postReceipts(extra.xPosts),
socials: { twitter: r.twitter, telegram: r.telegram, website: r.website },
risk_flags: flags,
quality_score: r.quality_score ?? null,
first_seen_at: r.first_seen_at,
- unavailable: extra.unavailable,
+ unavailable: extra.unavailable || [],
links: {
- intel: `${origin}/oracle?mint=${encodeURIComponent(mint)}`,
+ intel: `${origin}/coin-intel?mint=${encodeURIComponent(mint)}`,
+ oracle: `${origin}/oracle/coin/${encodeURIComponent(mint)}`,
pump: `https://pump.fun/coin/${encodeURIComponent(mint)}`,
fork: `${origin}/trades?fork=${encodeURIComponent(mint)}`,
},
};
}
+// ── persistence: what the Scout flagged, and when ──────────────────────────
+
+/**
+ * Record board candidates. The first sighting is kept forever (it is what a
+ * trade receipt compares an entry against, and what the track record grades);
+ * the latest read overwrites the rest. Best-effort: a write failure never
+ * fails the board.
+ */
+export async function recordScoutReads(network, candidates) {
+ const rows = (candidates || []).filter((c) => c?.mint);
+ await Promise.all(rows.map((c) => sql`
+ insert into sentiment_scout_reads (
+ mint, network, symbol,
+ first_scouted_at, first_score, first_evidence, first_caution,
+ last_scouted_at, last_score, peak_score, evidence, caution, x_summary, posts
+ ) values (
+ ${c.mint}, ${network}, ${c.ticker ? c.ticker.replace(/^\$/, '') : null},
+ now(), ${c.momentum_score}, ${JSON.stringify(c.evidence)}::jsonb, ${c.caution},
+ now(), ${c.momentum_score}, ${c.momentum_score}, ${JSON.stringify(c.evidence)}::jsonb, ${c.caution},
+ ${c.x ? JSON.stringify(c.x) : null}::jsonb, ${c.posts?.length ? JSON.stringify(c.posts) : null}::jsonb
+ )
+ on conflict (mint, network) do update set
+ last_scouted_at = now(),
+ last_score = excluded.last_score,
+ peak_score = greatest(sentiment_scout_reads.peak_score, excluded.last_score),
+ evidence = excluded.evidence,
+ caution = excluded.caution,
+ x_summary = coalesce(excluded.x_summary, sentiment_scout_reads.x_summary),
+ posts = coalesce(excluded.posts, sentiment_scout_reads.posts)
+ `.catch(() => null)));
+}
+
+/** The recorded Scout read for one coin, or null. Best-effort. */
+export async function loadScoutRead(mint, network = 'mainnet') {
+ const [row] = await sql`
+ select mint, network, symbol, first_scouted_at, first_score, first_evidence, first_caution,
+ last_scouted_at, last_score, peak_score, evidence, caution, x_summary, posts
+ from sentiment_scout_reads
+ where mint = ${mint} and network = ${network}
+ limit 1
+ `.catch(() => []);
+ return row || null;
+}
+
+/**
+ * Grade the Scout's own calls. Of the coins it flagged in the last `days`,
+ * how many went on to graduate or pump, next to the same rate for every
+ * labeled coin the engine observed over the same days. A scout that cannot
+ * beat the base rate is noise, and this is where a reader finds that out.
+ * Pure shaping of the two aggregate rows.
+ */
+export function shapeTrackRecord(scout, base, days) {
+ const rate = (good, n) => (n > 0 ? round(good / n, 4) : null);
+ const bands = ['70_plus', '50_69', 'under_50'].map((band) => {
+ const n = Number(scout?.[`labeled_${band}`]) || 0;
+ const good = Number(scout?.[`good_${band}`]) || 0;
+ return { band, labeled: n, good, good_rate: rate(good, n) };
+ });
+ const labeled = Number(scout?.labeled) || 0;
+ const good = Number(scout?.good) || 0;
+ const baseLabeled = Number(base?.labeled) || 0;
+ const baseGood = Number(base?.good) || 0;
+ const scoutRate = rate(good, labeled);
+ const baseRate = rate(baseGood, baseLabeled);
+ return {
+ days,
+ scouted: Number(scout?.scouted) || 0,
+ labeled,
+ graduated: Number(scout?.graduated) || 0,
+ pumped: Number(scout?.pumped) || 0,
+ rugged: Number(scout?.rugged) || 0,
+ good_rate: scoutRate,
+ base_rate: baseRate,
+ base_labeled: baseLabeled,
+ lift: scoutRate != null && baseRate ? round(scoutRate / baseRate, 2) : null,
+ bands,
+ definition: 'good = the coin graduated off the bonding curve or pumped (the Coin Intelligence Engine\'s own outcome labels); unknown outcomes are excluded',
+ };
+}
+
+export async function scoutTrackRecord(network = 'mainnet', { days = 14 } = {}) {
+ const d = Math.max(1, Math.min(60, Math.round(Number(days) || 14)));
+ return cacheWrap(`scout:track:v1:${network}:${d}`, 600, async () => {
+ const [[scout], [base]] = await Promise.all([
+ sql`
+ select count(*) as scouted,
+ count(o.mint) as labeled,
+ count(*) filter (where o.outcome = 'graduated') as graduated,
+ count(*) filter (where o.outcome = 'pumped') as pumped,
+ count(*) filter (where o.outcome = 'rugged') as rugged,
+ count(*) filter (where o.outcome in ('graduated', 'pumped')) as good,
+ count(o.mint) filter (where s.first_score >= 70) as labeled_70_plus,
+ count(*) filter (where s.first_score >= 70 and o.outcome in ('graduated', 'pumped')) as good_70_plus,
+ count(o.mint) filter (where s.first_score between 50 and 69) as labeled_50_69,
+ count(*) filter (where s.first_score between 50 and 69 and o.outcome in ('graduated', 'pumped')) as good_50_69,
+ count(o.mint) filter (where s.first_score < 50) as labeled_under_50,
+ count(*) filter (where s.first_score < 50 and o.outcome in ('graduated', 'pumped')) as good_under_50
+ from sentiment_scout_reads s
+ left join pump_coin_outcomes o on o.mint = s.mint and o.outcome is not null and o.outcome <> 'unknown'
+ where s.network = ${network}
+ and s.first_scouted_at > now() - make_interval(days => ${d})
+ `,
+ sql`
+ select count(*) as labeled,
+ count(*) filter (where o.outcome in ('graduated', 'pumped')) as good
+ from pump_coin_intel i
+ join pump_coin_outcomes o on o.mint = i.mint and o.outcome is not null and o.outcome <> 'unknown'
+ where i.network = ${network}
+ and i.first_seen_at > now() - make_interval(days => ${d})
+ `,
+ ]);
+ return shapeTrackRecord(scout, base, d);
+ });
+}
+
+// ── the judge's view ────────────────────────────────────────────────────────
+
+let _judgeStats = null;
+
+async function judgeWindowStats(network) {
+ if (_judgeStats && _judgeStats.network === network && Date.now() - _judgeStats.at < JUDGE_STATS_TTL_MS) {
+ return _judgeStats.stats;
+ }
+ const rows = await loadWindow({ network, windowMinutes: DEFAULT_WINDOW_MIN });
+ const stats = windowStats(rows);
+ _judgeStats = { network, at: Date.now(), stats };
+ return stats;
+}
+
+/**
+ * Render a Scout read as the plain-text block an LLM judge is handed. Every
+ * line is an evidence line the Scout built, so the judge sees the same
+ * receipts a human does. Pure.
+ */
+export function formatJudgeBlock(candidate) {
+ if (!candidate) return '';
+ const lines = [
+ '',
+ 'Sentiment Scout read (every line below is sourced, timestamped, and was checked against on-chain data at read time):',
+ `momentum_score: ${candidate.momentum_score}/100`,
+ ...candidate.evidence.map((e) => `- ${e.type}${e.platform ? ` (${e.platform})` : ''}: ${e.detail}`),
+ `caution: ${candidate.caution}`,
+ 'Weigh this as evidence, not as a verdict. Thin or one-voice evidence should lower your confidence, not raise it.',
+ ];
+ return lines.join('\n');
+}
+
+/**
+ * The Scout's read of one observed coin, for the sniper's LLM judge, built
+ * without any network call on the hot path: the launch window row, a cached
+ * window to rank it against, the latest paid read, and any X posts the board
+ * already recorded for it. Returns '' when the coin has not been observed.
+ */
+export async function scoutJudgeBlock(mint, network = 'mainnet') {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ const [[row], stats, paid, recorded] = await Promise.all([
+ sql`select ${intelColumns()} from pump_coin_intel where mint = ${mint} and network = ${net} limit 1`,
+ judgeWindowStats(net),
+ loadPaidSignals(net, [mint]),
+ loadScoutRead(mint, net),
+ ]);
+ if (!row) return '';
+ const pre = measure(row, stats.size ? stats : windowStats([row]));
+ const posts = Array.isArray(recorded?.posts) ? recorded.posts.map((p) => ({
+ url: p.url, text: p.text, created_at: p.at, author: { username: p.author, followers: p.followers },
+ })) : null;
+ const candidate = shapeCandidate(row, pre, stats.size ? stats : windowStats([row]), {
+ curve: null,
+ callouts: [],
+ calloutsRead: false,
+ paidSignal: paid?.get(mint) || null,
+ xSummary: recorded?.x_summary || null,
+ xPosts: posts,
+ unavailable: ['bonding_curve'],
+ }, appOrigin());
+ return formatJudgeBlock(candidate);
+}
+
+// ── the run ─────────────────────────────────────────────────────────────────
+
/**
* Run the scout.
- * @param {{ network?: 'mainnet'|'devnet', windowMinutes?: number, limit?: number, mint?: string|null }} opts
+ * @param {{ network?: 'mainnet'|'devnet', windowMinutes?: number, limit?: number, mint?: string|null, record?: boolean }} opts
*/
-export async function runSentimentScout({ network = 'mainnet', windowMinutes, limit, mint = null } = {}) {
+export async function runSentimentScout({ network = 'mainnet', windowMinutes, limit, mint = null, record = true } = {}) {
const net = network === 'devnet' ? 'devnet' : 'mainnet';
const win = clampWindow(windowMinutes);
const lim = clampLimit(limit);
@@ -499,12 +876,21 @@ export async function runSentimentScout({ network = 'mainnet', windowMinutes, li
};
} else {
const stats = windowStats(peers.length ? peers : [row]);
- const [extra, paid] = await Promise.all([enrich(row.mint), loadPaidSignals(net, [row.mint])]);
+ const [extra, paid, recorded] = await Promise.all([
+ enrich(row.mint, row.first_seen_at),
+ loadPaidSignals(net, [row.mint]),
+ loadScoutRead(row.mint, net),
+ ]);
extra.paidSignal = paid?.get(row.mint) || null;
if (!paid) extra.unavailable.push('paid_signals');
+ const candidate = shapeCandidate(row, measure(row, stats), stats, extra, origin);
+ candidate.qualifies = preScore(row, stats) != null;
+ candidate.scouted = recorded
+ ? { first_at: iso(recorded.first_scouted_at), first_score: recorded.first_score, peak_score: recorded.peak_score }
+ : null;
value = {
network: net, window_minutes: win, observed: stats.size, generated_at, found: true,
- candidates: [shapeCandidate(row, measure(row, stats), stats, extra, origin)],
+ candidates: [candidate],
};
}
} else {
@@ -520,7 +906,7 @@ export async function runSentimentScout({ network = 'mainnet', windowMinutes, li
const paid = await loadPaidSignals(net, shortlist.map(({ r }) => r.mint));
const enriched = await Promise.all(
shortlist.map(async ({ r, pre }) => {
- const extra = await enrich(r.mint);
+ const extra = await enrich(r.mint, r.first_seen_at);
extra.paidSignal = paid?.get(r.mint) || null;
if (!paid) extra.unavailable.push('paid_signals');
return shapeCandidate(r, pre, stats, extra, origin);
@@ -540,6 +926,7 @@ export async function runSentimentScout({ network = 'mainnet', windowMinutes, li
? `None of the ${stats.size} launches in the last ${win} minutes cleared the screen (top-quartile buy volume, ${MIN_BUYERS}+ buyers, no bundle or dev dump).`
: `The Coin Intelligence Engine has observed no ${net} launches in the last ${win} minutes.`;
}
+ if (record && value.candidates.length) await recordScoutReads(net, value.candidates);
}
cache.set(key, { at: Date.now(), value });
@@ -549,4 +936,5 @@ export async function runSentimentScout({ network = 'mainnet', windowMinutes, li
export function _resetScoutCache() {
cache.clear();
+ _judgeStats = null;
}
diff --git a/api/_lib/trade-receipt.js b/api/_lib/trade-receipt.js
index b4294b423..98002e6b0 100644
--- a/api/_lib/trade-receipt.js
+++ b/api/_lib/trade-receipt.js
@@ -17,6 +17,8 @@
* sentiment sniper_coin_sentiment (paid x402 market read, with its tx)
* token risk token_intel_risk (paid x402 rug-pull score, with its tx)
* intel pump_coin_intel (observed launch structure)
+ * scout sentiment_scout_reads (the Sentiment Scout's first flag of the
+ * coin: its score, sourced evidence lines and caution then)
* legs trading_journal (every entry / partial / exit leg + its tx)
*
* Honesty rules, enforced here so no renderer can break them:
@@ -242,6 +244,31 @@ function shapeIntel(row, position) {
};
}
+/** At most this many Scout evidence lines on a receipt: the ones it led with. */
+const MAX_SCOUT_LINES = 6;
+
+function shapeScout(row, position) {
+ if (!row) return null;
+ const timing = evidenceTiming(row.first_scouted_at, position.opened_at, position.closed_at);
+ if (!timing || timing === 'after_exit') return null;
+ const lines = Array.isArray(row.first_evidence) ? row.first_evidence : [];
+ return {
+ score: num(row.first_score),
+ peak_score: num(row.peak_score),
+ caution: row.first_caution || null,
+ evidence: lines.slice(0, MAX_SCOUT_LINES).map((e) => ({
+ type: String(e?.type || ''),
+ platform: e?.platform || null,
+ detail: String(e?.detail || ''),
+ source: typeof e?.source === 'string' && /^https?:\/\//.test(e.source) ? e.source : null,
+ at: e?.at || null,
+ checked_against: e?.checked_against || null,
+ })).filter((e) => e.type && e.detail),
+ at: iso(row.first_scouted_at),
+ timing,
+ };
+}
+
function shapeLeg(row, network) {
return {
event: row.event,
@@ -283,6 +310,7 @@ export function summarizeReceipt(r) {
drivers.push(`LLM judge voted ${e.judge.buy ? 'buy' : 'skip'}${conf}`);
}
if (e.risk_review && e.risk_review.severity) drivers.push(`risk officer ${e.risk_review.severity}`);
+ if (e.scout && e.scout.timing === 'before_entry' && e.scout.score != null) drivers.push(`Sentiment Scout flagged it at ${e.scout.score}`);
let line = `${who} ${p.paper ? 'paper-bought' : 'bought'} ${coin}. Trigger: ${r.trigger.label}.`;
if (drivers.length) line += ` ${drivers.join(', ').replace(/^./, (c) => c.toUpperCase())}.`;
if (p.status === 'closed') {
@@ -300,7 +328,7 @@ export function summarizeReceipt(r) {
* @param {object} parts
* position agent_sniper_positions row joined with agent_name / agent_image / is_public
* journal trading_journal rows for the position (any order)
- * oracleHistory, oracleCurrent, firewall, judge, riskReview, sentiment, tokenRisk, intel
+ * oracleHistory, oracleCurrent, firewall, judge, riskReview, sentiment, tokenRisk, intel, scout
* @returns {object} the receipt the API returns and both renderers read
*/
export function shapeTradeReceipt(parts) {
@@ -352,6 +380,7 @@ export function shapeTradeReceipt(parts) {
rugpull_score: 'num', risk_level: 'text', signal: 'text', confidence: 'num', rejected: 'bool',
}),
intel: shapeIntel(parts.intel, position),
+ scout: shapeScout(parts.scout, position),
};
const receipt = {
position,
@@ -411,7 +440,7 @@ export async function loadTradeReceipt(id) {
const entryCutoff = new Date(opened.getTime() + ENTRY_SKEW_MS);
const judgeModel = position.entry_trigger === 'llm_intel' ? position.trigger_ref : null;
- const [journal, oracleHistory, oracleCurrent, firewall, judge, riskReview, sentiment, tokenRisk, intel] = await Promise.all([
+ const [journal, oracleHistory, oracleCurrent, firewall, judge, riskReview, sentiment, tokenRisk, intel, scout] = await Promise.all([
all(sql`
select event, reason, rationale, sold_fraction, leg_pnl_lamports, market_cap_usd, venue, mode, ts, sig
from trading_journal where position_id = ${id}
@@ -464,9 +493,13 @@ export async function loadTradeReceipt(id) {
first_seen_at, observation_ended_at, updated_at
from pump_coin_intel where mint = ${mint} limit 1
`),
+ first(sql`
+ select first_scouted_at, first_score, first_evidence, first_caution, peak_score
+ from sentiment_scout_reads where mint = ${mint} and network = ${network} limit 1
+ `),
]);
return shapeTradeReceipt({
- position, journal, oracleHistory, oracleCurrent, firewall, judge, riskReview, sentiment, tokenRisk, intel,
+ position, journal, oracleHistory, oracleCurrent, firewall, judge, riskReview, sentiment, tokenRisk, intel, scout,
});
}
diff --git a/api/_lib/x-search.js b/api/_lib/x-search.js
new file mode 100644
index 000000000..936ded055
--- /dev/null
+++ b/api/_lib/x-search.js
@@ -0,0 +1,217 @@
+// X (Twitter) recent search, read-only, for evidence that has to be citable.
+//
+// The Sentiment Scout uses this to find posts that quote a coin's exact
+// contract address. Searching the mint (not the ticker) is deliberate: a
+// ticker like $CAT matches thousands of unrelated coins, while a 44-character
+// base58 address only matches posts about that one coin. Every post returned
+// here carries its own permalink, author and timestamp, so a claim built from
+// it can always be opened and checked by a reader.
+//
+// Auth: an app-only bearer token. X_BEARER_TOKEN is used as-is when set;
+// otherwise one is minted from the app's consumer key pair (X_API_KEY /
+// X_API_SECRET, the same app the platform posts from) with the OAuth2
+// client-credentials grant and cached in-process until X rejects it.
+//
+// Budget: X meters recent search per app per 15 minutes. Every response
+// reports what is left (x-rate-limit-remaining); once it drops under
+// RESERVE_REQUESTS this module stops searching until the window resets, so a
+// busy scout board can never exhaust the quota other X features share.
+
+import { fetchUpstream } from './upstream-fetch.js';
+
+const TOKEN_URL = 'https://api.twitter.com/oauth2/token';
+const SEARCH_URL = 'https://api.twitter.com/2/tweets/search/recent';
+const BREAKER = 'x:search';
+const TIMEOUT_MS = 6_000;
+const RESERVE_REQUESTS = 60;
+
+let _token = null;
+let _budget = { remaining: null, resetAtMs: 0 };
+
+export class XSearchUnavailable extends Error {
+ constructor(reason, message) {
+ super(message || reason);
+ this.name = 'XSearchUnavailable';
+ this.reason = reason;
+ }
+}
+
+/** True when this deployment holds credentials that can search. */
+export function xSearchConfigured(env = process.env) {
+ return !!(env.X_BEARER_TOKEN || (env.X_API_KEY && env.X_API_SECRET));
+}
+
+/**
+ * Build the search query for posts quoting one contract address. Retweets are
+ * excluded: a retweet is the same post again, and counting it would let one
+ * account's shill be amplified into many "mentions".
+ */
+export function mintQuery(mint) {
+ return `"${String(mint).trim()}" -is:retweet`;
+}
+
+// X returns post text with &amp; &lt; &gt; escaped. Decode those three (and
+// &quot; / &#39; for safety) so a quote reads as the author wrote it; the page
+// escapes again on render.
+const ENTITIES = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'" };
+export function decodeXText(text) {
+ return String(text ?? '').replace(/&(?:amp|lt|gt|quot|#39);/g, (m) => ENTITIES[m]);
+}
+
+/**
+ * Normalize a v2 search payload into post receipts. PURE.
+ *
+ * @param {object} payload the JSON body of /2/tweets/search/recent
+ * @returns {Array<{ id, url, text, created_at, author: { id, username, name, followers, verified }, likes, reposts, replies, quotes, impressions }>}
+ */
+export function parseSearchPayload(payload) {
+ const users = new Map();
+ for (const u of payload?.includes?.users || []) {
+ if (u?.id) users.set(String(u.id), u);
+ }
+ const out = [];
+ for (const t of Array.isArray(payload?.data) ? payload.data : []) {
+ if (!t?.id || typeof t.text !== 'string') continue;
+ const u = users.get(String(t.author_id)) || null;
+ const username = u?.username ? String(u.username) : null;
+ const m = t.public_metrics || {};
+ out.push({
+ id: String(t.id),
+ // Without a username X still resolves /i/status/<id> to the post.
+ url: username ? `https://x.com/${username}/status/${t.id}` : `https://x.com/i/status/${t.id}`,
+ text: decodeXText(t.text),
+ created_at: t.created_at || null,
+ author: {
+ id: t.author_id ? String(t.author_id) : null,
+ username,
+ name: u?.name || null,
+ followers: Number.isFinite(Number(u?.public_metrics?.followers_count)) ? Number(u.public_metrics.followers_count) : null,
+ verified: u?.verified === true,
+ },
+ likes: Number(m.like_count) || 0,
+ reposts: Number(m.retweet_count) || 0,
+ replies: Number(m.reply_count) || 0,
+ quotes: Number(m.quote_count) || 0,
+ impressions: Number.isFinite(Number(m.impression_count)) ? Number(m.impression_count) : null,
+ });
+ }
+ return out;
+}
+
+/**
+ * Summarize a set of posts about one coin: how many, from how many distinct
+ * accounts, the most-followed account, and how concentrated the chatter is.
+ * PURE. `posts` come from parseSearchPayload.
+ */
+export function summarizePosts(posts) {
+ const list = Array.isArray(posts) ? posts : [];
+ const byAuthor = new Map();
+ for (const p of list) {
+ const key = p.author?.id || p.author?.username || p.id;
+ const cur = byAuthor.get(key) || { author: p.author, posts: 0 };
+ cur.posts += 1;
+ byAuthor.set(key, cur);
+ }
+ const authors = [...byAuthor.values()];
+ const top = authors.slice().sort((a, b) => (b.posts - a.posts))[0] || null;
+ const mostFollowed = authors
+ .filter((a) => a.author?.followers != null)
+ .sort((a, b) => b.author.followers - a.author.followers)[0] || null;
+ const reach = authors.reduce((s, a) => s + (a.author?.followers || 0), 0);
+ const engagement = list.reduce((s, p) => s + p.likes + p.reposts + p.replies + p.quotes, 0);
+ const times = list.map((p) => Date.parse(p.created_at)).filter(Number.isFinite).sort((a, b) => a - b);
+ return {
+ posts: list.length,
+ authors: authors.length,
+ top_poster: top ? { username: top.author?.username || null, posts: top.posts } : null,
+ top_poster_share: list.length && top ? top.posts / list.length : 0,
+ most_followed: mostFollowed ? { username: mostFollowed.author.username, followers: mostFollowed.author.followers } : null,
+ reach_followers: reach,
+ engagement,
+ first_at: times.length ? new Date(times[0]).toISOString() : null,
+ last_at: times.length ? new Date(times[times.length - 1]).toISOString() : null,
+ };
+}
+
+function noteBudget(res) {
+ const remaining = Number(res.headers.get('x-rate-limit-remaining'));
+ const reset = Number(res.headers.get('x-rate-limit-reset'));
+ if (Number.isFinite(remaining)) _budget.remaining = remaining;
+ if (Number.isFinite(reset)) _budget.resetAtMs = reset * 1000;
+}
+
+function budgetExhausted(now = Date.now()) {
+ if (_budget.remaining == null) return false;
+ if (now >= _budget.resetAtMs) return false;
+ return _budget.remaining < RESERVE_REQUESTS;
+}
+
+async function bearer(env, fetchImpl) {
+ if (env.X_BEARER_TOKEN) return env.X_BEARER_TOKEN;
+ if (_token) return _token;
+ if (!env.X_API_KEY || !env.X_API_SECRET) throw new XSearchUnavailable('not_configured', 'X search credentials are not configured');
+ const basic = Buffer.from(`${encodeURIComponent(env.X_API_KEY)}:${encodeURIComponent(env.X_API_SECRET)}`).toString('base64');
+ const res = await fetchImpl(TOKEN_URL, {
+ method: 'POST',
+ headers: { authorization: `Basic ${basic}`, 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' },
+ body: 'grant_type=client_credentials',
+ }, { name: BREAKER, timeoutMs: TIMEOUT_MS, attempts: 1, okWhen: () => true });
+ if (!res.ok) throw new XSearchUnavailable('auth_failed', `X token exchange failed with HTTP ${res.status}`);
+ const body = await res.json();
+ if (!body?.access_token) throw new XSearchUnavailable('auth_failed', 'X token exchange returned no access token');
+ _token = body.access_token;
+ return _token;
+}
+
+/**
+ * Search recent posts (X keeps the last 7 days searchable) quoting a mint.
+ * Throws XSearchUnavailable when search cannot run (no credentials, auth
+ * failure, the budget reserve reached, or X down); callers list the source as
+ * unavailable rather than guessing.
+ *
+ * @param {string} mint
+ * @param {{ sinceIso?: string|null, maxResults?: number, env?: object, fetchImpl?: Function }} [opts]
+ */
+export async function searchMintPosts(mint, { sinceIso = null, maxResults = 25, env = process.env, fetchImpl = fetchUpstream } = {}) {
+ if (!xSearchConfigured(env)) throw new XSearchUnavailable('not_configured', 'X search credentials are not configured');
+ if (budgetExhausted()) throw new XSearchUnavailable('budget_reserve', 'X search budget reserve reached for this window');
+
+ const params = new URLSearchParams({
+ query: mintQuery(mint),
+ max_results: String(Math.max(10, Math.min(100, Math.round(maxResults)))),
+ 'tweet.fields': 'created_at,public_metrics,author_id',
+ expansions: 'author_id',
+ 'user.fields': 'username,name,public_metrics,verified',
+ });
+ // X rejects a start_time older than 7 days or in the future; clamp to a
+ // valid window rather than sending one it will refuse.
+ if (sinceIso) {
+ const t = Date.parse(sinceIso);
+ const floor = Date.now() - 7 * 24 * 3600 * 1000 + 60_000;
+ const ceil = Date.now() - 15_000;
+ if (Number.isFinite(t) && t < ceil) params.set('start_time', new Date(Math.max(t, floor)).toISOString());
+ }
+
+ for (let pass = 0; pass < 2; pass++) {
+ const token = await bearer(env, fetchImpl);
+ const res = await fetchImpl(`${SEARCH_URL}?${params}`, {
+ headers: { authorization: `Bearer ${token}`, accept: 'application/json' },
+ }, { name: BREAKER, timeoutMs: TIMEOUT_MS, attempts: 1, okWhen: () => true });
+ noteBudget(res);
+ if (res.status === 401 && !env.X_BEARER_TOKEN && pass === 0) {
+ // A revoked or rotated app token: mint a fresh one once.
+ _token = null;
+ continue;
+ }
+ if (res.status === 429) throw new XSearchUnavailable('rate_limited', 'X search rate limit reached');
+ if (!res.ok) throw new XSearchUnavailable('upstream_error', `X search returned HTTP ${res.status}`);
+ return parseSearchPayload(await res.json());
+ }
+ throw new XSearchUnavailable('auth_failed', 'X rejected the app token');
+}
+
+/** Test seam: forget the cached token and budget. */
+export function _resetXSearch() {
+ _token = null;
+ _budget = { remaining: null, resetAtMs: 0 };
+}
diff --git a/api/_mcp/tools/trader.js b/api/_mcp/tools/trader.js
index 45253db9b..e8441acda 100644
--- a/api/_mcp/tools/trader.js
+++ b/api/_mcp/tools/trader.js
@@ -14,6 +14,11 @@
// reasons, trade firewall, LLM judge, Risk Officer, paid
// x402 reads) plus each journal leg and its tx.
//
+// sentiment_scout unscoped. Sourced pump.fun momentum candidates: every
+// claim carries its source link, the time it was true,
+// and (for social claims) the on-chain facts it was
+// checked against. Never trades.
+//
// copy_subscribe auth-gated (agents:write). Set up copy-trading: mirror
// a leader's future entries to your own wallet with your
// own sizing and risk caps. Non-custodial: we never
@@ -31,6 +36,7 @@ import { limits } from '../../_lib/rate-limit.js';
import { getLeaderboard, getTraderStats, WINDOWS, LEADERBOARD_SORTS } from '../../_lib/trader-stats.js';
import { normalizeSubscriptionInput } from '../../_lib/copy-engine.js';
import { loadTradeReceipt } from '../../_lib/trade-receipt.js';
+import { runSentimentScout, scoutTrackRecord } from '../../_lib/sentiment-scout.js';
import { isUuid } from '../../_lib/validate.js';
const NETWORKS = new Set(['mainnet', 'devnet']);
@@ -328,6 +334,52 @@ export const toolDefs = [
},
},
+ // ── sentiment_scout ─────────────────────────────────────────────────────
+ {
+ name: 'sentiment_scout',
+ title: 'Sourced momentum candidates (Sentiment Scout)',
+ annotations: LIVE,
+ description:
+ "Surface pump.fun momentum candidates with evidence you can cite. Each candidate returns a 0-100 momentum_score (with the parts that add up to it), evidence lines of type volume_spike, fresh_buyers, smart_money, graduation_approach, social_mention (X posts quoting the coin's exact contract address, or pump.fun callouts), paid_signal (x402 market reads with their payment transaction) and news_match, and one caution line naming the main risk. Every evidence line carries source (a URL that returns the fact), at (when it was true) and, for social or paid claims, checked_against (the on-chain facts read in the same run). Sources that could not be read are listed in unavailable, never estimated. Pass mint to read one coin even if it would not make the board. Pass track_record=true to include how the coins the Scout flagged over the last 14 days actually did against the base rate. This tool never trades and is not advice; cite the evidence, not the score.",
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string', description: 'Optional pump.fun mint (base58). Omit for the board.' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ window_minutes: { type: 'integer', minimum: 15, maximum: 240, default: 60, description: 'Minutes of launches to rank against.' },
+ limit: { type: 'integer', minimum: 1, maximum: 10, default: 5 },
+ track_record: { type: 'boolean', default: false, description: 'Include the Scout\'s graded track record.' },
+ },
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ const network = NETWORKS.has(args?.network) ? args.network : 'mainnet';
+ const mint = typeof args?.mint === 'string' && args.mint.trim() ? args.mint.trim() : null;
+ if (mint && !BASE58_RE.test(mint)) return mcpErr('Invalid mint: must be a base58 Solana address.');
+
+ const rl = await limits.mcpIp(rateKeyFor(auth));
+ if (!rl.success) return mcpErr('Rate limit exceeded, try again in a moment.');
+
+ let scout;
+ let track = null;
+ try {
+ [scout, track] = await Promise.all([
+ runSentimentScout({ network, mint, windowMinutes: args?.window_minutes, limit: args?.limit }),
+ args?.track_record === true ? scoutTrackRecord(network).catch(() => null) : null,
+ ]);
+ } catch (err) {
+ return unavailable(err, 'The Sentiment Scout');
+ }
+ const payload = {
+ ...scout,
+ board_url: 'https://three.ws/coin-intel?tab=scout',
+ disclaimer: 'Evidence, not advice. Most early pump.fun momentum fades; the caution line names the main risk for each coin.',
+ };
+ if (args?.track_record === true) payload.track_record = track;
+ return mcpOk(payload);
+ },
+ },
+
// ── copy_subscribe ──────────────────────────────────────────────────────
{
name: 'copy_subscribe',
diff --git a/api/cron/db-retention.js b/api/cron/db-retention.js
index 25680a707..2490d4754 100644
--- a/api/cron/db-retention.js
+++ b/api/cron/db-retention.js
@@ -157,6 +157,9 @@ const TIME_SERIES_TABLES = [
{ table: 'sniper_coin_sentiment', tsColumn: 'checked_at', windowKind: 'firehose' },
{ table: 'token_intel_risk', tsColumn: 'checked_at', windowKind: 'firehose' },
{ table: 'x402_spent_payments', tsColumn: 'created_at', windowKind: 'spent' },
+ // One row per coin the Sentiment Scout ever put on its board. Trade receipts
+ // cite the first sighting, so it keeps the audit window, not the firehose one.
+ { table: 'sentiment_scout_reads', tsColumn: 'first_scouted_at', windowKind: 'audit' },
];
// ── Autopilot run logs ────────────────────────────────────────────────────────
diff --git a/api/pump/sentiment-scout.js b/api/pump/sentiment-scout.js
new file mode 100644
index 000000000..46f090110
--- /dev/null
+++ b/api/pump/sentiment-scout.js
@@ -0,0 +1,74 @@
+/**
+ * Sentiment Scout: sourced momentum candidates, every claim with its receipt.
+ *
+ * GET /api/pump/sentiment-scout the board: top candidates now
+ * &window=60 minutes of launches to rank against (15-240)
+ * &limit=5 candidates to return (1-10)
+ * &network=mainnet
+ * &notes=0 skip the LLM-written "Scout's read" per candidate
+ * &track=1 include the Scout's graded track record
+ * GET /api/pump/sentiment-scout?mint=<mint> one coin's Scout read, even if
+ * it would not make the board
+ *
+ * Each candidate: { mint, ticker, momentum_score, score_parts, evidence[],
+ * caution, market_check, x, posts[], note?, links, unavailable[] }. Every
+ * evidence line carries `source` (a URL a reader can open), `at` (when the fact
+ * was true) and, for social or paid claims, `checked_against` (the on-chain
+ * facts read in the same run). Sources that could not be read are named in
+ * `unavailable` rather than estimated. The Scout never trades.
+ *
+ * Public, CORS-open, IP rate-limited. Logic and honesty rules live in
+ * api/_lib/sentiment-scout.js; the note layer in api/_lib/scout-notes.js.
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { runSentimentScout, scoutTrackRecord } from '../_lib/sentiment-scout.js';
+import { writeScoutNotes } from '../_lib/scout-notes.js';
+
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const NETWORKS = new Set(['mainnet', 'devnet']);
+
+export const maxDuration = 60;
+
+/** Attach validated notes to candidates. Never throws, never blocks on a dead chain. */
+export async function withNotes(candidates, writer = writeScoutNotes) {
+ if (!candidates.length) return candidates;
+ const notes = await writer(candidates).catch(() => new Map());
+ return candidates.map((c) => {
+ const n = notes.get(c.mint);
+ return n ? { ...c, note: n.note, note_model: n.model } : { ...c, note: null, note_model: null };
+ });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
+ const network = params.get('network') || 'mainnet';
+ if (!NETWORKS.has(network)) return error(res, 400, 'invalid_network', 'network must be mainnet or devnet');
+ const mint = (params.get('mint') || '').trim() || null;
+ if (mint && !BASE58_RE.test(mint)) return error(res, 400, 'invalid_mint', 'mint must be a base58 Solana address');
+ const wantNotes = params.get('notes') !== '0';
+ const wantTrack = params.get('track') === '1';
+
+ const [scout, track] = await Promise.all([
+ runSentimentScout({
+ network,
+ mint,
+ windowMinutes: params.get('window'),
+ limit: params.get('limit'),
+ }),
+ wantTrack ? scoutTrackRecord(network).catch(() => null) : null,
+ ]);
+
+ const candidates = wantNotes ? await withNotes(scout.candidates) : scout.candidates;
+ const body = { ...scout, candidates };
+ if (wantTrack) body.track_record = track;
+
+ return json(res, 200, body, { 'cache-control': 'public, max-age=15, s-maxage=30' });
+});
diff --git a/api/sniper/experiments.js b/api/sniper/experiments.js
index 2e0e2f8fc..d27246362 100644
--- a/api/sniper/experiments.js
+++ b/api/sniper/experiments.js
@@ -67,7 +67,8 @@ function lamportsToSol(v) {
function conditionSummary(s) {
if ((s.decision_mode || 'rules') === 'llm') {
const conf = s.llm_min_confidence != null ? ` ≥${Math.round(Number(s.llm_min_confidence) * 100)}%` : '';
- return `LLM judge (${s.llm_model || 'openrouter/auto'}${conf}), no rule shields`;
+ const scout = s.llm_scout_context === true ? ', reads the Sentiment Scout' : '';
+ return `LLM judge (${s.llm_model || 'openrouter/auto'}${conf}${scout}), no rule shields`;
}
const parts = [`trigger ${s.trigger || 'new_mint'}`];
if (s.min_market_cap_usd != null || s.max_market_cap_usd != null) {
@@ -97,7 +98,7 @@ export default wrap(async (req, res) => {
select
s.id as strategy_id,
s.label, s.experiment_group, s.decision_mode, s.llm_model, s.llm_min_confidence,
- s.llm_strict_model, s.kill_switch,
+ s.llm_strict_model, s.llm_scout_context, s.kill_switch,
s.trigger, s.enabled,
s.per_trade_lamports, s.daily_budget_lamports, s.max_concurrent_positions,
s.min_market_cap_usd, s.max_market_cap_usd, s.require_socials,
@@ -161,6 +162,7 @@ export default wrap(async (req, res) => {
ledger_url: `/reasoning-ledger?agent=${encodeURIComponent(r.agent_id)}&kind=snipe`,
decision_mode: r.decision_mode || 'rules',
llm_model: r.llm_model || null,
+ llm_scout_context: r.llm_scout_context === true,
trigger: r.trigger || 'new_mint',
enabled: r.enabled === true,
conditions: conditionSummary(r),
diff --git a/api/sniper/strategy.js b/api/sniper/strategy.js
index 32e44a351..436aee730 100644
--- a/api/sniper/strategy.js
+++ b/api/sniper/strategy.js
@@ -125,6 +125,8 @@ export const STRATEGY_SCHEMA = z.object({
llm_min_confidence: z.union([z.string(), z.number()]).nullable().optional(),
llm_max_confidence: z.union([z.string(), z.number()]).nullable().optional(),
llm_strict_model: z.boolean().optional(),
+ // Hand this LLM arm's judge the Sentiment Scout's sourced read of the coin.
+ llm_scout_context: z.boolean().optional(),
moonbag_always: z.boolean().optional(),
// Laddered take-initials exit. An explicit null on initials_out_multiple opts
// back into the classic single-shot exit; moonbag_min_pct is NOT NULL in the
@@ -294,6 +296,7 @@ async function listStrategies(req, res, userId) {
llm_min_confidence: s.llm_min_confidence != null ? Number(s.llm_min_confidence) : null,
llm_max_confidence: s.llm_max_confidence != null ? Number(s.llm_max_confidence) : null,
llm_strict_model: s.llm_strict_model === true,
+ llm_scout_context: s.llm_scout_context === true,
moonbag_always: s.moonbag_always !== false,
label: s.label || null,
experiment_group: s.experiment_group || null,
@@ -360,7 +363,7 @@ async function upsertStrategy(req, res, userId) {
alpha_min_smart_money: null, alpha_min_organic_score: null, alpha_max_mcap_usd: null,
alpha_narrative_keywords: null, alpha_min_quality_score: null,
decision_mode: 'rules', llm_model: null, llm_min_confidence: null,
- llm_max_confidence: null, llm_strict_model: false, moonbag_always: true,
+ llm_max_confidence: null, llm_strict_model: false, llm_scout_context: false, moonbag_always: true,
initials_out_multiple: 2,
label: null, experiment_group: null,
};
@@ -430,6 +433,8 @@ async function upsertStrategy(req, res, userId) {
// Named-model integrity: a strict arm refuses to trade on a fallback
// model's verdict, pausing rather than polluting its own experiment.
llm_strict_model: 'llm_strict_model' in p ? Boolean(p.llm_strict_model) : (cur.llm_strict_model === true),
+ // Scout context: the Sentiment Scout's evidence lines join the judge's brief.
+ llm_scout_context: 'llm_scout_context' in p ? Boolean(p.llm_scout_context) : (cur.llm_scout_context === true),
// Fleet-wide never-sell-100%-of-a-winner rule; opt-out per strategy.
moonbag_always: 'moonbag_always' in p ? Boolean(p.moonbag_always) : (cur.moonbag_always !== false),
label: 'label' in p ? (p.label || null) : (cur.label || null),
@@ -482,7 +487,7 @@ async function upsertStrategy(req, res, userId) {
alpha_min_smart_money, alpha_min_organic_score, alpha_max_mcap_usd,
alpha_narrative_keywords, alpha_min_quality_score, auto_fund_enabled,
initials_out_multiple, moonbag_min_pct,
- decision_mode, llm_model, llm_min_confidence, llm_max_confidence, llm_strict_model, moonbag_always, label, experiment_group, updated_at)
+ decision_mode, llm_model, llm_min_confidence, llm_max_confidence, llm_strict_model, llm_scout_context, moonbag_always, label, experiment_group, updated_at)
values
(${p.agent_id}, ${userId}, ${p.network}, ${next.enabled}, ${next.kill_switch},
${next.trigger}, ${next.buy_delay_ms}, ${next.min_claim_lamports}, ${next.max_claim_lamports}, ${next.first_claim_max_age_seconds},
@@ -499,7 +504,7 @@ async function upsertStrategy(req, res, userId) {
${next.alpha_min_smart_money}, ${next.alpha_min_organic_score}, ${next.alpha_max_mcap_usd},
${next.alpha_narrative_keywords}, ${next.alpha_min_quality_score}, ${next.auto_fund_enabled},
${next.initials_out_multiple}, ${next.moonbag_min_pct},
- ${next.decision_mode}, ${next.llm_model}, ${next.llm_min_confidence}, ${next.llm_max_confidence}, ${next.llm_strict_model}, ${next.moonbag_always}, ${next.label}, ${next.experiment_group}, now())
+ ${next.decision_mode}, ${next.llm_model}, ${next.llm_min_confidence}, ${next.llm_max_confidence}, ${next.llm_strict_model}, ${next.llm_scout_context}, ${next.moonbag_always}, ${next.label}, ${next.experiment_group}, now())
on conflict (agent_id, network) do update set
enabled = excluded.enabled,
kill_switch = excluded.kill_switch,
@@ -550,6 +555,7 @@ async function upsertStrategy(req, res, userId) {
llm_min_confidence = excluded.llm_min_confidence,
llm_max_confidence = excluded.llm_max_confidence,
llm_strict_model = excluded.llm_strict_model,
+ llm_scout_context = excluded.llm_scout_context,
moonbag_always = excluded.moonbag_always,
label = excluded.label,
experiment_group = excluded.experiment_group,
@@ -611,6 +617,7 @@ async function upsertStrategy(req, res, userId) {
llm_min_confidence: row.llm_min_confidence != null ? Number(row.llm_min_confidence) : null,
llm_max_confidence: row.llm_max_confidence != null ? Number(row.llm_max_confidence) : null,
llm_strict_model: row.llm_strict_model === true,
+ llm_scout_context: row.llm_scout_context === true,
moonbag_always: row.moonbag_always !== false,
label: row.label || null,
experiment_group: row.experiment_group || null,
diff --git a/docs/mcp.md b/docs/mcp.md
index c82c826a9..b640097e1 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -726,6 +726,35 @@ Returns `{ mint, sources: [...], dexscreener?, jupiter?, solana?, skipped: [...]
---
+### `sentiment_scout`
+
+Sourced pump.fun momentum candidates from the [Sentiment Scout](./sentiment-scout.md). Each candidate carries a 0-100 `momentum_score` with its parts, evidence lines (`volume_spike`, `fresh_buyers`, `smart_money`, `graduation_approach`, `social_mention`, `paid_signal`, `news_match`) and one `caution` line. Every evidence line has a `source` URL, an `at` timestamp, and, for social or paid claims, `checked_against`: the on-chain facts read in the same run. Unreadable sources are listed in `unavailable`, never estimated. Read-only; never trades.
+
+```json
+{
+ "type": "object",
+ "properties": {
+ "mint": { "type": "string", "description": "Optional pump.fun mint (base58). Omit for the board." },
+ "network": { "type": "string", "enum": ["mainnet", "devnet"], "default": "mainnet" },
+ "window_minutes": { "type": "integer", "minimum": 15, "maximum": 240, "default": 60 },
+ "limit": { "type": "integer", "minimum": 1, "maximum": 10, "default": 5 },
+ "track_record": { "type": "boolean", "default": false }
+ },
+ "additionalProperties": false
+}
+```
+
+```bash
+curl -s https://three.ws/api/mcp -H 'content-type: application/json' -H 'authorization: Bearer <token>' -d '{
+ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": { "name": "sentiment_scout", "arguments": { "limit": 3, "track_record": true } }
+}'
+```
+
+Returns `{ network, window_minutes, observed, generated_at, candidates: [...], board_url, disclaimer, track_record? }`. `track_record` grades the coins the Scout flagged over the last 14 days against the base rate of every labeled launch.
+
+---
+
### `text_to_animation`
Generate a brand-new motion from a natural-language prompt ("waving confidently", "a slow tai-chi sweep") with a text-to-motion diffusion model (MDM, MIT), then retarget it onto a caller-supplied rigged humanoid GLB — the same retarget engine `apply_animation` uses. Unlike the curated animation library, the motion does not pre-exist: it's synthesized for the prompt, on the self-host `model-text2motion` GPU worker (`workers/model-text2motion/`).
diff --git a/docs/sentiment-scout.md b/docs/sentiment-scout.md
new file mode 100644
index 000000000..d63d5fd71
--- /dev/null
+++ b/docs/sentiment-scout.md
@@ -0,0 +1,175 @@
+# Sentiment Scout: momentum with receipts
+
+Most "alpha" is a claim with nothing behind it: a post says a coin is running,
+a bot says sentiment is bullish, and nobody can check either. The Sentiment
+Scout ranks the last hour of pump.fun launches by momentum and backs every
+single claim with its receipt: where it came from, when it was true, and, for
+anything social or paid, what the chain showed at that same moment. It never
+trades.
+
+Surfaces: the **Scout** tab on [Coin Intelligence](https://three.ws/coin-intel?tab=scout)
+(`/coin-intel?tab=scout`) · the **Sentiment Scout** section in every coin's
+detail drawer on `/coin-intel` · the Scout card on [trade receipts](./trade-receipts.md)
+· `GET /api/pump/sentiment-scout` · the `sentiment_scout` MCP tool · an opt-in
+context block for LLM-judged sniper strategies.
+Model: `api/_lib/sentiment-scout.js` · X client: `api/_lib/x-search.js` ·
+Notes: `api/_lib/scout-notes.js` · Page module: `src/coin-intel-scout.js`
+
+## What a candidate looks like
+
+```json
+{
+ "mint": "…pump",
+ "ticker": "$EXAMPLE",
+ "momentum_score": 71,
+ "score_parts": { "volume": 29.5, "buyers": 24.8, "buy_pressure": 8.4, "smart_money": 0, "curve": 9, "social": 9.7, "risk_penalty": -10 },
+ "evidence": [
+ { "type": "volume_spike", "detail": "56.5 SOL bought in its first 90s, top 2% of 1241 launches in the window (median 0.59 SOL)",
+ "source": "https://three.ws/api/pump/coin-intel?mint=…", "at": "2026-09-29T06:48:22.420Z" },
+ { "type": "social_mention", "platform": "x",
+ "detail": "19 X posts quoted this exact contract address, from 15 accounts; most-followed @… (36k followers): \"…\"",
+ "source": "https://x.com/…/status/…", "at": "2026-09-29T06:56:02.000Z",
+ "checked_against": "On-chain at 07:03 UTC: 56.5 SOL bought by 74 wallets in the first 90s; graduated to pumpswap" }
+ ],
+ "caution": "1 other coin named $EXAMPLE launched in the same window; check you have the right mint.",
+ "market_check": { "checked_at": "…", "early_buy_volume_sol": 56.5, "early_buyers": 74, "graduated": true, "bonding_progress_pct": 100 },
+ "x": { "posts": 19, "authors": 15, "top_poster_share": 0.16, "most_followed": { "username": "…", "followers": 36000 } },
+ "posts": [ { "url": "https://x.com/…/status/…", "author": "…", "followers": 36000, "at": "…", "text": "…" } ],
+ "note": "Two sentences written from the evidence above, or null",
+ "unavailable": ["callouts"]
+}
+```
+
+Every evidence line carries:
+
+- **`source`**: a URL that returns the fact (the Coin Intelligence row, the
+ pump.fun coin page, the X post, or the x402 payment transaction on Solscan).
+- **`at`**: when the fact was true. Launch-window facts are stamped at the end
+ of the coin's observation window; the curve at the moment it was read; a post
+ at the moment it was posted.
+- **`checked_against`** (social, paid and news lines): the on-chain facts read
+ in the same run, so a loud post sits right next to the chart that did or did
+ not back it up.
+
+## Where the evidence comes from
+
+| Type | Source | Notes |
+|---|---|---|
+| `volume_spike`, `fresh_buyers` | `pump_coin_intel` (the Coin Intelligence Engine, see [trading surfaces](./trading-surfaces.md)) | Ranked as percentiles against every launch in the same window. The median launch has one buyer, so "40x the median" would be noise. |
+| `smart_money` | `pump_coin_intel.smart_money_*` | Wallets with a profitable pump.fun record that bought early. |
+| `graduation_approach` | live bonding curve (pump.fun) | Read at scout time. |
+| `social_mention` (X) | X recent search for the coin's **exact contract address** | A ticker matches thousands of coins; a 44-character address matches one. Retweets are excluded so one account cannot count many times. |
+| `social_mention` (pump.fun) | pump.fun callouts | pump.fun now serves these only to signed-in sessions, so they usually appear under `unavailable`. |
+| `paid_signal` | `sniper_coin_sentiment` | A paid Crypto Intel read over x402, linked to its payment transaction. Reads older than 6 hours are ignored. |
+| `news_match` | `pump_coin_intel.signals.news_headline` | The coin's name matches a live news story. |
+
+A source that could not be read is named in `unavailable` and left out. It is
+never estimated.
+
+## How it ranks and screens
+
+1. Every coin observed in the last `window` minutes (15 to 240, default 60).
+2. A coin qualifies only with 3+ distinct buyers, top-quartile early buy volume,
+ and no `bundle_launch` or `dev_dumped` flag.
+3. The strongest shortlist is enriched (curve, X, callouts, paid reads) and
+ scored 0 to 100: volume 30, buyers 25, buy pressure 10, smart money 10,
+ curve 15, social 10, minus risk penalties. The parts are returned in
+ `score_parts` and shown behind **Why 71?** on the page.
+4. One caution line per coin, deterministic and worst-first: a dumped dev, a
+ bundled launch, a curve back near 0% after heavy early buying (the early
+ buyers already sold), a single whale, a fresh-wallet swarm, **X chatter that
+ is mostly one account** (promotion, not interest), heavy top-10
+ concentration, copycat tickers, a bearish paid read, sell pressure, snipers.
+
+Social attention counts distinct accounts, not posts. Twenty posts from one
+account score lower than three posts from three accounts, and cost a penalty.
+
+## The Scout's read (the LLM layer)
+
+Each board candidate can carry a two-sentence `note` written by the platform's
+LLM failover chain (`api/_lib/llm.js`) from that candidate's evidence lines and
+nothing else. No note is trusted as written: `validateScoutNote()` drops any
+note that contains a number the evidence does not hold (digits or spelled out),
+names a ticker other than the candidate's own or $THREE, carries a link, or
+makes a promise ("guaranteed", "buy now"). A dropped note is never repaired;
+the card simply shows its evidence. The page loads the evidence first and fills
+the notes in when the chain answers, so a slow chain never holds the board.
+
+## Graded, not claimed
+
+Every board candidate is recorded in `sentiment_scout_reads` (migration
+`20260929120000_sentiment_scout_reads.sql`): the first sighting (score,
+evidence, caution) is written once and never changes, and the latest read
+overwrites the rest. Two things read it:
+
+- **The track record** (`?track=1`, shown above the board): of the coins the
+ Scout flagged in the last 14 days that now have an outcome label, how many
+ graduated or pumped, next to the same rate for every labeled launch the
+ engine watched over the same days, and split by score band. A scout that
+ cannot beat the base rate is noise, and this is where a reader finds out.
+- **Trade receipts**: when the Scout had flagged a coin before an agent bought
+ it, the receipt shows the Scout's first flag with its sources, tagged
+ "before entry". A flag recorded after the exit is dropped.
+
+## The API
+
+```bash
+# The board: the top 5 candidates from the last hour, with the track record
+curl "https://three.ws/api/pump/sentiment-scout?limit=5&track=1"
+
+# One coin, even if it would not make the board
+curl "https://three.ws/api/pump/sentiment-scout?mint=<mint>"
+
+# Evidence only, no LLM-written notes (fastest)
+curl "https://three.ws/api/pump/sentiment-scout?notes=0"
+```
+
+| Param | Default | Meaning |
+|---|---|---|
+| `window` | `60` | Minutes of launches to rank against, 15 to 240. |
+| `limit` | `5` | Candidates, 1 to 10. |
+| `mint` | none | Read one coin. The response adds `qualifies` (would it clear the screen) and `scouted` (when it first made the board). |
+| `notes` | `1` | `0` skips the LLM-written note. |
+| `track` | `0` | `1` adds `track_record`. |
+| `network` | `mainnet` | `mainnet` or `devnet`. |
+
+Public, CORS-open, IP rate-limited, cached for 30 seconds. Errors use the
+platform shape `{ error, error_description }`: `invalid_mint`, `invalid_network`.
+
+## The MCP tool
+
+`sentiment_scout` on the main three.ws MCP server (`/api/mcp`), next to
+`trade_receipt`. Arguments: `mint`, `network`, `window_minutes`, `limit`,
+`track_record`. It returns the same board plus `board_url`. Read-only; like
+every tool there it needs an OAuth token or an x402 payment. See
+[MCP](./mcp.md).
+
+## For strategy builders: Scout context for the LLM judge
+
+An LLM-judged sniper strategy (`decision_mode: 'llm'`) can opt in with
+`llm_scout_context: true` on `POST /api/sniper/strategy`. Its judge is then
+handed the Scout's read of the coin (momentum score, every evidence line, the
+caution) alongside the launch brief, built from the coin's intel row, a cached
+one-hour window, the latest paid read and any X posts the board already
+recorded, with no network call on the hot path. The read only exists once a
+coin has been observed, so in practice it feeds `intel_confirmed` arms. It is
+off by default so every running experiment keeps asking the question it was
+asking; an arm with it on is marked **+ Scout** on
+[/sniper/experiments](https://three.ws/sniper/experiments).
+
+## X search budget
+
+X recent search is metered per app per 15 minutes. The Scout only searches
+shortlisted candidates, caches each coin's posts for 10 minutes (a failed read
+for 1 minute), and stops searching once the remaining quota drops below a
+reserve, so it can never exhaust the quota other X features share.
+Credentials: `X_BEARER_TOKEN`, or the app key pair `X_API_KEY` / `X_API_SECRET`
+from which an app token is minted. Without them X posts are listed as
+unavailable and everything else works.
+
+## Related
+
+- [Trading surfaces](./trading-surfaces.md): Coin Intelligence and the launch data
+ every volume and buyer line is measured from.
+- [Trade receipts](./trade-receipts.md): where a Scout flag shows up on a trade.
+- [Copy Coach](./copy-coach.md): the guided first copy, which links here.
diff --git a/docs/trade-receipts.md b/docs/trade-receipts.md
index 30a0485b4..16e211e7e 100644
--- a/docs/trade-receipts.md
+++ b/docs/trade-receipts.md
@@ -37,6 +37,7 @@ missing gate is left out, never guessed at.
| Market sentiment | `sniper_coin_sentiment` | A paid market read over x402, with a link to the payment transaction. |
| Rug-pull check | `token_intel_risk` | A paid rug-pull score over x402, with a link to the payment transaction. |
| Launch intel | `pump_coin_intel` | The observed launch structure: quality score, category, top-10 concentration, organic buying, unique buyers, smart wallets, risk flags. |
+| Sentiment Scout | `sentiment_scout_reads` | The [Sentiment Scout](./sentiment-scout.md)'s first flag of the coin: its momentum score and every evidence line with its source, time and on-chain check, plus its caution. Shown only when the flag came before the exit. |
| Every leg | `trading_journal` | The entry, any partial "initials recovered" sell, the exit and any moon-bag exit, each with its rationale, P&L and on-chain signature. |
The receipt opens with a one-line summary built only from the evidence it
diff --git a/packages/mcp-policy/src/table.js b/packages/mcp-policy/src/table.js
index 76eed956e..0ab2c6e9c 100644
--- a/packages/mcp-policy/src/table.js
+++ b/packages/mcp-policy/src/table.js
@@ -129,6 +129,7 @@ export const POLICY = {
update_custom_skill: w('skills'),
delete_custom_skill: f('skills', 'confirm_delete', 'get_custom_skill', ['agent_id', 'skill_id']),
trade_receipt: r('trading'),
+ sentiment_scout: r('intelligence'),
// Agent cards (api/_mcp/tools/cards.js). The service verifies its own
// quote and reveal ids, so the policy enforces enablement and the flag.
agent_card_search_merchants: r('cards'),
diff --git a/pages/coin-intel.html b/pages/coin-intel.html
index 73a028620..af0f930b9 100644
--- a/pages/coin-intel.html
+++ b/pages/coin-intel.html
@@ -408,6 +408,7 @@
<nav class="ci-tabs" id="ci-tabs" role="tablist" aria-label="Coin intelligence views">
<button class="ci-tab is-active" data-tab="radar" role="tab" data-i18n-html="coin_intel.radar">Radar<span class="count" id="cnt-radar"></span></button>
+ <button class="ci-tab" data-tab="scout" role="tab" title="Sourced momentum: every claim with its receipt">Scout<span class="count" id="cnt-scout"></span></button>
<button class="ci-tab" data-tab="leaderboard" role="tab" data-i18n="coin_intel.leaderboard">Leaderboard</button>
<button class="ci-tab" data-tab="traders" role="tab" data-i18n-html="coin_intel.smart_money">Smart Money<span class="count" id="cnt-traders"></span></button>
<button class="ci-tab" data-tab="learning" role="tab" data-i18n="coin_intel.what_it_learned">What it learned</button>
@@ -438,6 +439,9 @@
<div class="ci-grid" id="ci-grid"></div>
</section>
+ <!-- SCOUT (src/coin-intel-scout.js) -->
+ <section id="view-scout" data-view class="hide" aria-label="Sentiment Scout"></section>
+
<!-- LEADERBOARD -->
<section id="view-leaderboard" data-view class="hide">
<div class="section-title">Top quality · last 24h</div>
@@ -484,6 +488,7 @@
</aside>
<script type="module">
+ import { mountScoutBoard, scoutDrawerSection, SCOUT_CSS } from '/src/coin-intel-scout.js';
const API = '/api/pump/intel';
const REFRESH_MS = 15_000;
@@ -854,6 +859,7 @@
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeDrawer(); });
async function openDrawer(mint) {
+ drawerBody.dataset.mint = mint;
drawer.classList.add('is-open'); scrim.classList.add('is-open'); drawer.setAttribute('aria-hidden','false');
drawer.scrollTop = 0;
drawerBody.innerHTML = `<div class="sh" style="height:60px;border-radius:14px;background:linear-gradient(90deg,rgba(255,255,255,.04),rgba(255,255,255,.09),rgba(255,255,255,.04));background-size:200% 100%;animation:ciShimmer 1.4s infinite"></div>`;
@@ -863,6 +869,16 @@
drawerBody.innerHTML = renderDetail(data);
const svg = $('#bm-svg'); if (svg) drawBubbleMap(svg, data.wallets || [], data.clusters || []);
+ // Sentiment Scout read for this coin: sourced evidence, injected when ready.
+ scoutDrawerSection(mint).then((sec) => {
+ if (!sec || drawerBody.dataset.mint !== mint || drawer.getAttribute('aria-hidden') === 'true') return;
+ const sigSection = [...drawerBody.querySelectorAll('.d-section')].find(
+ s => s.querySelector('h4')?.textContent?.includes('Launch signals')
+ );
+ if (sigSection) sigSection.insertAdjacentElement('beforebegin', sec);
+ else drawerBody.appendChild(sec);
+ });
+
// inject Oracle link + watchlist button into d-links
const dlinks = drawerBody.querySelector('.d-links');
if (dlinks) {
@@ -1073,9 +1089,27 @@
}
}
+ // ── Sentiment Scout tab ────────────────────────────────────
+ {
+ const st = document.createElement('style');
+ st.textContent = SCOUT_CSS;
+ document.head.appendChild(st);
+ }
+ const scoutBoard = mountScoutBoard($('#view-scout'), {
+ onOpenCoin: (mint) => openDrawer(mint),
+ onCount: (n) => { $('#cnt-scout').textContent = n ? String(n) : ''; },
+ });
+
// ── tabs ───────────────────────────────────────────────────
function switchTab(tab) {
+ if (!document.getElementById('view-' + tab)) tab = 'radar';
state.tab = tab;
+ scoutBoard.setActive(tab === 'scout');
+ try {
+ const u = new URL(location.href);
+ if (tab === 'radar') u.searchParams.delete('tab'); else u.searchParams.set('tab', tab);
+ history.replaceState(null, '', u);
+ } catch { /* URL sync is a convenience */ }
document.querySelectorAll('.ci-tab').forEach(t => t.classList.toggle('is-active', t.dataset.tab === tab));
document.querySelectorAll('[data-view]').forEach(s => s.classList.add('hide'));
$('#view-' + tab).classList.remove('hide');
@@ -1120,6 +1154,14 @@
renderStats([]);
loadStats();
loadRadar();
+ // Deep links: ?tab=scout|leaderboard|traders|learning and ?mint=<mint>.
+ {
+ const q = new URLSearchParams(location.search);
+ const tab = q.get('tab');
+ if (tab && tab !== 'radar') switchTab(tab);
+ const deepMint = q.get('mint');
+ if (deepMint && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(deepMint)) openDrawer(deepMint);
+ }
setInterval(() => { if (state.tab === 'radar' && !document.hidden) loadRadar(); }, REFRESH_MS);
document.addEventListener('visibilitychange', () => { if (!document.hidden && state.tab === 'radar') loadRadar(); });
</script>
diff --git a/public/nav-data.js b/public/nav-data.js
index 4445aaae8..6eab37138 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -647,6 +647,13 @@ export const NAV_GROUPS = [
badgeTone: 'live',
desc: 'Every launch classified — organic vs bundle, the wallets, a learning score',
},
+ {
+ title: 'Sentiment Scout',
+ href: '/coin-intel?tab=scout',
+ badge: 'New',
+ badgeTone: 'new',
+ desc: 'Momentum with receipts: every claim linked to its post or read, timestamped, and checked on-chain',
+ },
{
title: 'Coin Radar',
href: '/radar',
diff --git a/src/coin-intel-scout.js b/src/coin-intel-scout.js
new file mode 100644
index 000000000..65b8fc765
--- /dev/null
+++ b/src/coin-intel-scout.js
@@ -0,0 +1,484 @@
+// Sentiment Scout on /coin-intel: the "Scout" tab (the live board) and the
+// Scout section inside a coin's detail drawer.
+//
+// Data: GET /api/pump/sentiment-scout (api/pump/sentiment-scout.js). The board
+// loads in two passes so it is never held hostage by the LLM chain: first the
+// evidence (fast, deterministic), then the same board with the Scout's written
+// read per candidate, patched into the cards that are already on screen.
+//
+// Honesty on the page mirrors the API: every evidence line shows its source
+// link, the time the fact was true, and (for social or paid claims) the
+// on-chain facts it was checked against. Sources that could not be read are
+// named, never filled in.
+
+const API = '/api/pump/sentiment-scout';
+const REFRESH_MS = 60_000;
+// Notes already written for a coin survive the next refresh, so a card does
+// not lose its summary (and shift under the reader) every minute.
+const noteCache = new Map();
+
+function withCachedNote(c) {
+ if (c.note) {
+ noteCache.set(c.mint, { note: c.note, note_model: c.note_model });
+ return c;
+ }
+ const hit = noteCache.get(c.mint);
+ return hit ? { ...c, ...hit } : c;
+}
+
+const TYPE_META = {
+ volume_spike: { label: 'Volume', tone: 'chain' },
+ fresh_buyers: { label: 'Buyers', tone: 'chain' },
+ smart_money: { label: 'Smart money', tone: 'chain' },
+ graduation_approach: { label: 'Curve', tone: 'chain' },
+ social_mention: { label: 'Social', tone: 'social' },
+ paid_signal: { label: 'Paid read', tone: 'paid' },
+ news_match: { label: 'News', tone: 'social' },
+};
+
+const PART_LABEL = {
+ volume: 'Volume',
+ buyers: 'Buyers',
+ buy_pressure: 'Buy pressure',
+ smart_money: 'Smart money',
+ curve: 'Curve',
+ social: 'Social',
+ risk_penalty: 'Risk',
+};
+
+const UNAVAILABLE_LABEL = {
+ callouts: 'pump.fun callouts',
+ x_posts: 'X posts',
+ bonding_curve: 'live bonding curve',
+ paid_signals: 'paid market reads',
+};
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const short = (a) => (!a ? '' : `${a.slice(0, 4)}…${a.slice(-4)}`);
+const imgSrc = (uri, seed) => {
+ if (!uri) return `https://api.dicebear.com/7.x/shapes/svg?seed=${encodeURIComponent(seed || 'x')}`;
+ if (uri.startsWith('data:') || uri.startsWith('/')) return uri;
+ return `/api/img?url=${encodeURIComponent(uri)}&seed=${encodeURIComponent(seed || 'x')}`;
+};
+
+function fmtCount(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return null;
+ if (v >= 1e6) return `${(v / 1e6).toFixed(v >= 1e7 ? 0 : 1)}M`;
+ if (v >= 1e3) return `${(v / 1e3).toFixed(v >= 1e4 ? 0 : 1)}k`;
+ return String(Math.round(v));
+}
+
+function ago(iso) {
+ const t = Date.parse(iso);
+ if (!Number.isFinite(t)) return '';
+ const d = Date.now() - t;
+ if (d < 45_000) return 'just now';
+ const m = d / 60_000;
+ if (m < 60) return `${Math.round(m)}m ago`;
+ const h = m / 60;
+ if (h < 24) return `${Math.round(h)}h ago`;
+ return `${Math.round(h / 24)}d ago`;
+}
+
+function timeTag(iso) {
+ if (!iso) return '';
+ const abs = new Date(iso).toUTCString().replace(' GMT', ' UTC');
+ return `<time datetime="${esc(iso)}" title="${esc(abs)}">${esc(ago(iso))}</time>`;
+}
+
+function srcLink(href, label = 'Source') {
+ if (!href || !/^https?:\/\//.test(href)) return '';
+ return `<a class="sc-src" href="${esc(href)}" target="_blank" rel="noopener noreferrer">${esc(label)}<span aria-hidden="true"> ↗</span><span class="sc-sr"> (opens in a new tab)</span></a>`;
+}
+
+function scoreTone(score) {
+ if (score >= 70) return 'hi';
+ if (score >= 50) return 'mid';
+ return 'lo';
+}
+
+function scoreBlock(c) {
+ const parts = Object.entries(c.score_parts || {})
+ .filter(([, v]) => v != null)
+ .map(([k, v]) => `<li><span>${esc(PART_LABEL[k] || k)}</span><b class="${v < 0 ? 'neg' : ''}">${v > 0 ? '+' : ''}${esc(v)}</b></li>`)
+ .join('');
+ return `<div class="sc-score sc-score-${scoreTone(c.momentum_score)}">
+ <span class="sc-score-n">${esc(c.momentum_score)}</span><span class="sc-score-t">/100 momentum</span>
+ ${parts ? `<details class="sc-why"><summary>Why ${esc(c.momentum_score)}?</summary><ul>${parts}</ul></details>` : ''}
+ </div>`;
+}
+
+function evidenceItem(e) {
+ const meta = TYPE_META[e.type] || { label: String(e.type || '').replace(/_/g, ' '), tone: 'chain' };
+ const label = `${meta.label}${e.platform ? ` · ${e.platform}` : ''}`;
+ const linkLabel = e.platform === 'x' ? 'Post' : e.type === 'paid_signal' ? 'Payment tx' : 'Source';
+ return `<li class="sc-ev">
+ <span class="sc-type sc-type-${meta.tone}">${esc(label)}</span>
+ <div class="sc-ev-body">
+ <p class="sc-ev-detail">${esc(e.detail)}</p>
+ <p class="sc-meta">${timeTag(e.at)}${e.at && e.source ? '<span aria-hidden="true"> · </span>' : ''}${srcLink(e.source, linkLabel)}</p>
+ ${e.checked_against ? `<p class="sc-check"><span class="sc-check-k">Checked against</span> ${esc(e.checked_against)}</p>` : ''}
+ </div>
+ </li>`;
+}
+
+function postsBlock(c) {
+ if (!c.posts?.length) return '';
+ const items = c.posts.map((p) => `<li class="sc-post">
+ <p class="sc-post-head"><b>${p.author ? `@${esc(p.author)}` : 'An account'}</b>${p.followers != null ? ` <span>${esc(fmtCount(p.followers))} followers</span>` : ''}${p.verified ? ' <span class="sc-verified">verified</span>' : ''} <span aria-hidden="true">·</span> ${timeTag(p.at)}</p>
+ <p class="sc-post-text">${esc(p.text)}</p>
+ <p class="sc-meta">${esc(p.likes)} likes · ${esc(p.reposts)} reposts · ${srcLink(p.url, 'Open post')}</p>
+ </li>`).join('');
+ const x = c.x;
+ const head = x ? `${esc(x.posts)} post${x.posts === 1 ? '' : 's'} on X quoted this exact contract address, from ${esc(x.authors)} account${x.authors === 1 ? '' : 's'}` : 'Posts quoting this contract';
+ return `<div class="sc-posts"><h4>${head}</h4><ul>${items}</ul></div>`;
+}
+
+function unavailableLine(c) {
+ const list = (c.unavailable || []).map((k) => UNAVAILABLE_LABEL[k] || k);
+ if (!list.length) return '';
+ return `<p class="sc-unavail" title="Left out, never estimated">Not readable this time: ${esc(list.join(', '))}</p>`;
+}
+
+function noteBlock(c) {
+ if (!c.note) return '';
+ return `<p class="sc-note"><span class="sc-note-k">Scout's read</span> ${esc(c.note)}<span class="sc-note-by">Written${c.note_model ? ` by ${esc(c.note_model)}` : ''} from the evidence below, and checked so it adds no number or name the evidence does not hold.</span></p>`;
+}
+
+function candidateCard(c, { compact = false } = {}) {
+ const name = c.name || c.ticker || short(c.mint);
+ const id = `sc-${c.mint.slice(0, 10)}`;
+ return `<article class="sc-card${compact ? ' sc-compact' : ''}" data-mint="${esc(c.mint)}" aria-labelledby="${id}">
+ <header class="sc-head">
+ ${compact ? '' : `<img class="sc-avatar" src="${esc(imgSrc(c.image_uri, c.mint))}" alt="" loading="lazy" referrerpolicy="no-referrer" />`}
+ <div class="sc-id">
+ ${compact ? '' : `<h3 class="sc-name" id="${id}">${esc(name)}</h3>`}
+ <div class="sc-sub">
+ ${c.ticker ? `<span class="sc-sym">${esc(c.ticker)}</span>` : ''}
+ <button type="button" class="sc-copy" data-copy="${esc(c.mint)}" aria-label="Copy mint address ${esc(c.mint)}">${esc(short(c.mint))}<span aria-hidden="true"> ⧉</span></button>
+ ${c.first_seen_at ? `<span class="sc-age">launched ${timeTag(new Date(c.first_seen_at).toISOString())}</span>` : ''}
+ </div>
+ </div>
+ ${scoreBlock(c)}
+ </header>
+ <div class="sc-note-slot">${noteBlock(c)}</div>
+ <ol class="sc-evidence" aria-label="Evidence, each line with its source">${(c.evidence || []).map(evidenceItem).join('')}</ol>
+ ${postsBlock(c)}
+ <p class="sc-caution"><strong>Main risk</strong> ${esc(c.caution)}</p>
+ <footer class="sc-foot">
+ ${unavailableLine(c)}
+ <div class="sc-actions">
+ ${compact ? '' : `<button type="button" class="sc-btn sc-btn-primary" data-open="${esc(c.mint)}">Full intel</button>`}
+ <a class="sc-btn" href="/oracle/coin/${encodeURIComponent(c.mint)}">Oracle</a>
+ <a class="sc-btn" href="${esc(c.links?.pump || `https://pump.fun/coin/${encodeURIComponent(c.mint)}`)}" target="_blank" rel="noopener noreferrer">pump.fun<span aria-hidden="true"> ↗</span></a>
+ </div>
+ </footer>
+ </article>`;
+}
+
+function trackBlock(t) {
+ if (!t) {
+ return `<p class="sc-track-empty">The Scout's track record could not be read right now. Every call it makes is recorded and graded against the coin's real outcome once one is labeled.</p>`;
+ }
+ if (!t.labeled) {
+ return `<p class="sc-track-empty"><b>Graded, not claimed.</b> ${t.scouted ? `The Scout has flagged ${esc(t.scouted)} coin${t.scouted === 1 ? '' : 's'} in the last ${esc(t.days)} days;` : 'No flags recorded yet;'} none has an outcome label yet. Coins are labeled about an hour after launch, then this shows how its calls did against every launch the engine watched.</p>`;
+ }
+ const pct = (r) => (r == null ? 'n/a' : `${(r * 100).toFixed(r < 0.1 ? 1 : 0)}%`);
+ const lift = t.lift != null ? `<span class="sc-lift ${t.lift >= 1 ? 'up' : 'down'}">${esc(t.lift)}× the base rate</span>` : '';
+ const bands = t.bands.filter((b) => b.labeled).map((b) => {
+ const lbl = b.band === '70_plus' ? 'Scored 70+' : b.band === '50_69' ? 'Scored 50 to 69' : 'Under 50';
+ return `<li><span>${lbl}</span><b>${pct(b.good_rate)}</b><small>${esc(b.good)} of ${esc(b.labeled)}</small></li>`;
+ }).join('');
+ return `<div class="sc-track-body">
+ <p><b>Graded, not claimed.</b> Of the ${esc(t.labeled)} coins the Scout flagged in the last ${esc(t.days)} days that now have an outcome, <b>${pct(t.good_rate)}</b> graduated or pumped, against <b>${pct(t.base_rate)}</b> for all ${esc(t.base_labeled)} labeled launches over the same days. ${lift}</p>
+ ${bands ? `<ul class="sc-bands">${bands}</ul>` : ''}
+ <p class="sc-track-foot">${esc(t.rugged)} of the flagged coins rugged. Past calls do not predict the next one.</p>
+ </div>`;
+}
+
+function skeletonCards(n = 3) {
+ return Array.from({ length: n }, () => `<div class="sc-card sc-skel" aria-hidden="true">
+ <span class="sc-sh" style="width:45%"></span><span class="sc-sh" style="width:92%"></span>
+ <span class="sc-sh" style="width:80%"></span><span class="sc-sh" style="width:86%"></span><span class="sc-sh" style="width:60%"></span>
+ </div>`).join('');
+}
+
+async function getJson(params) {
+ const u = new URL(API, location.origin);
+ for (const [k, v] of Object.entries(params)) if (v != null && v !== '') u.searchParams.set(k, v);
+ const r = await fetch(u, { headers: { accept: 'application/json' } });
+ if (!r.ok) {
+ let msg = `HTTP ${r.status}`;
+ try { msg = (await r.json()).error_description || msg; } catch { /* body was not JSON */ }
+ throw new Error(msg);
+ }
+ return r.json();
+}
+
+function wireCopy(root, announce) {
+ root.addEventListener('click', async (e) => {
+ const btn = e.target.closest('.sc-copy');
+ if (!btn) return;
+ try {
+ await navigator.clipboard.writeText(btn.dataset.copy);
+ btn.classList.add('is-copied');
+ announce('Mint address copied');
+ setTimeout(() => btn.classList.remove('is-copied'), 1400);
+ } catch {
+ announce('Copy failed: select the address and copy it by hand');
+ }
+ });
+}
+
+/**
+ * Mount the Scout board.
+ * @param {HTMLElement} root the #view-scout section
+ * @param {{ onOpenCoin: (mint: string) => void, onCount?: (n: number) => void }} opts
+ */
+export function mountScoutBoard(root, { onOpenCoin, onCount = () => {} }) {
+ root.innerHTML = `
+ <div class="sc-intro">
+ <p class="sc-lede">Momentum you can check. The Scout ranks the last hour of pump.fun launches, then backs every claim with its receipt: the post or read it came from, when it was true, and what the chain showed at that moment. It never trades, and it names the main risk on every coin.</p>
+ <div class="sc-controls">
+ <label class="sc-field">Window
+ <select class="ci-select" id="sc-window" aria-label="Launch window to rank against">
+ <option value="30">30 min</option>
+ <option value="60" selected>1 hour</option>
+ <option value="120">2 hours</option>
+ <option value="240">4 hours</option>
+ </select>
+ </label>
+ <button type="button" class="sc-btn" id="sc-refresh">Refresh</button>
+ <span class="sc-updated" id="sc-updated"></span>
+ </div>
+ </div>
+ <section class="sc-track" id="sc-track" aria-label="Scout track record"></section>
+ <div class="sc-list" id="sc-list" aria-live="polite" aria-busy="true"></div>
+ <p class="sc-sr" id="sc-announce" role="status" aria-live="polite"></p>`;
+
+ const list = root.querySelector('#sc-list');
+ const trackEl = root.querySelector('#sc-track');
+ const updated = root.querySelector('#sc-updated');
+ const winSel = root.querySelector('#sc-window');
+ const announceEl = root.querySelector('#sc-announce');
+ const announce = (msg) => { announceEl.textContent = msg; };
+ let active = false;
+ let seq = 0;
+ let timer = null;
+
+ wireCopy(root, announce);
+ list.addEventListener('click', (e) => {
+ const open = e.target.closest('[data-open]');
+ if (open) onOpenCoin(open.dataset.open);
+ });
+
+ function renderEmpty(data) {
+ list.innerHTML = `<div class="ci-empty">
+ <div class="icon" aria-hidden="true">🛰️</div>
+ <h3>Nothing clears the bar right now</h3>
+ <p>${esc(data.reason || 'No launch in this window has momentum the Scout can back with evidence.')}</p>
+ <p>An empty board is an honest answer, not an outage. Widen the window, or check the Radar tab for everything the engine is watching.</p>
+ <button type="button" class="ci-retry" id="sc-widen">Try the 4 hour window</button>
+ </div>`;
+ list.querySelector('#sc-widen').addEventListener('click', () => { winSel.value = '240'; load(); });
+ }
+
+ function renderError(msg) {
+ list.innerHTML = `<div class="ci-empty">
+ <div class="icon" aria-hidden="true">⚠️</div>
+ <h3>The Scout could not load</h3>
+ <p>${esc(msg)}. The evidence comes from live reads, so a hiccup upstream shows here first.</p>
+ <button type="button" class="ci-retry" id="sc-retry">Try again</button>
+ </div>`;
+ list.querySelector('#sc-retry').addEventListener('click', load);
+ }
+
+ function patchNotes(candidates) {
+ for (const c of candidates) {
+ if (!c.note) continue;
+ withCachedNote(c);
+ const slot = list.querySelector(`.sc-card[data-mint="${CSS.escape(c.mint)}"] .sc-note-slot`);
+ if (slot && !slot.firstElementChild) {
+ slot.innerHTML = noteBlock(c);
+ slot.firstElementChild?.classList.add('is-new');
+ }
+ }
+ }
+
+ async function load() {
+ const my = ++seq;
+ const win = winSel.value;
+ list.setAttribute('aria-busy', 'true');
+ if (!list.querySelector('.sc-card:not(.sc-skel)')) list.innerHTML = skeletonCards();
+ if (!trackEl.innerHTML) trackEl.innerHTML = '<span class="sc-sh" style="width:70%"></span>';
+ try {
+ const data = await getJson({ window: win, notes: 0, track: 1, limit: 6 });
+ if (my !== seq) return;
+ trackEl.innerHTML = trackBlock(data.track_record);
+ onCount(data.candidates.length);
+ updated.innerHTML = `Updated ${timeTag(data.generated_at)} · ${esc(data.observed)} launches ranked`;
+ if (!data.candidates.length) renderEmpty(data);
+ else list.innerHTML = data.candidates.map((c) => candidateCard(withCachedNote(c))).join('');
+ list.setAttribute('aria-busy', 'false');
+ // Second pass: the same board with the Scout's written read.
+ getJson({ window: win, limit: 6 })
+ .then((withNotes) => { if (my === seq) patchNotes(withNotes.candidates); })
+ .catch(() => { /* the evidence is already on screen; a missing summary is fine */ });
+ } catch (err) {
+ if (my !== seq) return;
+ list.setAttribute('aria-busy', 'false');
+ renderError(err.message || 'Network error');
+ }
+ }
+
+ winSel.addEventListener('change', load);
+ root.querySelector('#sc-refresh').addEventListener('click', load);
+ document.addEventListener('visibilitychange', () => { if (active && !document.hidden) load(); });
+
+ return {
+ setActive(on) {
+ active = on;
+ clearInterval(timer);
+ if (on) {
+ load();
+ timer = setInterval(() => { if (!document.hidden) load(); }, REFRESH_MS);
+ }
+ },
+ load,
+ };
+}
+
+/**
+ * The Scout's read of one coin, as a drawer section. Resolves to null when the
+ * coin was never observed (the drawer already says so) or the read failed.
+ */
+export async function scoutDrawerSection(mint) {
+ let data;
+ try {
+ data = await getJson({ mint, notes: 0 });
+ } catch {
+ return null;
+ }
+ const c = data.candidates?.[0];
+ if (!data.found || !c) return null;
+ const sec = document.createElement('div');
+ sec.className = 'd-section sc-drawer';
+ const status = c.scouted
+ ? `On the Scout board since ${timeTag(c.scouted.first_at)} (first score ${esc(c.scouted.first_score)}, peak ${esc(c.scouted.peak_score)}).`
+ : c.qualifies
+ ? 'Clears the Scout\'s screen, but has not appeared on the board yet.'
+ : 'Not on the Scout board: it did not clear the screen (top-quartile early buying, 3+ buyers, no bundle or dev dump). Its evidence is still shown.';
+ sec.innerHTML = `<h4>Sentiment Scout</h4><p class="sc-drawer-status">${status}</p>${candidateCard(c, { compact: true })}`;
+ wireCopy(sec, () => {});
+ // The written read follows when the LLM chain answers; the evidence never waits for it.
+ getJson({ mint })
+ .then((d) => {
+ const n = d.candidates?.[0];
+ const slot = sec.querySelector('.sc-note-slot');
+ if (n?.note && slot && !slot.firstElementChild) {
+ slot.innerHTML = noteBlock(n);
+ slot.firstElementChild?.classList.add('is-new');
+ }
+ })
+ .catch(() => { /* evidence is already shown */ });
+ return sec;
+}
+
+/** Styles for the board and the drawer section, scoped to .sc-* classes. */
+export const SCOUT_CSS = `
+.sc-intro{display:flex;flex-wrap:wrap;gap:14px 24px;align-items:flex-end;justify-content:space-between;margin-bottom:14px}
+.sc-lede{margin:0;color:var(--ci-muted);font-size:13.5px;line-height:1.55;max-width:680px}
+.sc-controls{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
+.sc-field{display:inline-flex;gap:8px;align-items:center;font-size:12px;color:var(--ci-faint)}
+.sc-updated{font-size:11.5px;color:var(--ci-faint)}
+.sc-sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
+.sc-btn{display:inline-flex;align-items:center;gap:4px;font:inherit;font-size:12px;padding:7px 12px;border-radius:8px;border:1px solid var(--ci-border);
+ background:rgba(255,255,255,.05);color:var(--ci-text);text-decoration:none;cursor:pointer;
+ transition:background var(--duration-fast),border-color var(--duration-fast),transform var(--duration-fast)}
+.sc-btn:hover{background:rgba(255,255,255,.12);border-color:var(--ci-border-strong)}
+.sc-btn:active{transform:translateY(1px)}
+.sc-btn:focus-visible,.sc-copy:focus-visible,.sc-src:focus-visible,.sc-why summary:focus-visible{outline:2px solid var(--ci-accent);outline-offset:2px}
+.sc-btn-primary{background:var(--ci-accent);border-color:var(--ci-accent);color:#fff}
+.sc-btn-primary:hover{background:#7c4ded;border-color:#7c4ded}
+.sc-track{background:var(--ci-panel);border:1px solid var(--ci-border);border-radius:14px;padding:14px 16px;margin-bottom:16px;min-height:22px}
+.sc-track p{margin:0;font-size:13px;line-height:1.55;color:var(--ci-muted)}
+.sc-track b{color:var(--ci-text)}
+.sc-track-empty{font-size:13px}
+.sc-lift{display:inline-block;margin-left:4px;font-size:11px;font-weight:700;padding:2px 8px;border-radius:999px}
+.sc-lift.up{color:var(--ci-success);background:rgba(52,211,153,.13)}
+.sc-lift.down{color:var(--ci-danger);background:rgba(248,113,113,.13)}
+.sc-bands{list-style:none;margin:10px 0 0;padding:0;display:flex;flex-wrap:wrap;gap:8px}
+.sc-bands li{display:flex;align-items:baseline;gap:8px;background:var(--ci-panel-2);border:1px solid var(--ci-border);border-radius:9px;padding:6px 10px;font-size:12px;color:var(--ci-muted)}
+.sc-bands b{font-family:var(--font-mono,monospace)}
+.sc-bands small{color:var(--ci-faint)}
+.sc-track-foot{margin-top:8px!important;font-size:11.5px!important;color:var(--ci-faint)!important}
+.sc-list{display:grid;gap:14px}
+.sc-card{background:var(--ci-panel);border:1px solid var(--ci-border);border-radius:14px;padding:16px;min-width:0;
+ animation:ciFadeIn .35s ease both;transition:border-color var(--duration-fast)}
+.sc-card:hover{border-color:var(--ci-border-strong)}
+.sc-compact{padding:12px;background:var(--ci-panel-2)}
+.sc-head{display:flex;gap:12px;align-items:flex-start}
+.sc-avatar{width:46px;height:46px;border-radius:11px;object-fit:cover;background:#15171f;border:1px solid var(--ci-border);flex-shrink:0}
+.sc-id{flex:1;min-width:0}
+.sc-name{margin:0;font-size:15.5px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.sc-sub{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:4px;font-size:11.5px;color:var(--ci-faint)}
+.sc-sym{font-family:var(--font-mono,monospace);color:var(--ci-neutral)}
+.sc-copy{font:inherit;font-family:var(--font-mono,monospace);font-size:11px;color:var(--ci-muted);background:var(--ci-panel-2);border:1px solid var(--ci-border);
+ border-radius:6px;padding:2px 7px;cursor:pointer;transition:color var(--duration-fast),border-color var(--duration-fast)}
+.sc-copy:hover{color:var(--ci-text);border-color:var(--ci-border-strong)}
+.sc-copy.is-copied{color:var(--ci-success);border-color:rgba(52,211,153,.5)}
+.sc-score{text-align:right;flex-shrink:0;min-width:92px}
+.sc-score-n{font-family:var(--font-mono,monospace);font-size:26px;font-weight:700;line-height:1;font-variant-numeric:tabular-nums}
+.sc-score-t{display:block;font-size:9.5px;letter-spacing:.08em;text-transform:uppercase;color:var(--ci-faint);margin-top:3px}
+.sc-score-hi .sc-score-n{color:var(--ci-success)} .sc-score-mid .sc-score-n{color:var(--ci-warn)} .sc-score-lo .sc-score-n{color:var(--ci-muted)}
+.sc-why{margin-top:6px;font-size:11px;color:var(--ci-muted)}
+.sc-why summary{cursor:pointer;list-style:none;color:var(--ci-neutral)}
+.sc-why summary::-webkit-details-marker{display:none}
+.sc-why ul{list-style:none;margin:6px 0 0;padding:8px 10px;background:var(--ci-panel-2);border:1px solid var(--ci-border);border-radius:8px;text-align:left;min-width:150px}
+.sc-why li{display:flex;justify-content:space-between;gap:12px;padding:1px 0}
+.sc-why b{font-family:var(--font-mono,monospace);color:var(--ci-text)} .sc-why b.neg{color:var(--ci-danger)}
+.sc-note-slot:empty{display:none}
+.sc-note{margin:12px 0 0;padding:10px 12px;border-radius:10px;background:rgba(139,92,246,.08);border:1px solid rgba(139,92,246,.22);font-size:13.5px;line-height:1.55;color:var(--ci-text)}
+.sc-note.is-new{animation:ciFadeIn .35s ease both}
+.sc-note-k{display:block;font-size:10px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#c4b5fd;margin-bottom:3px}
+.sc-note-by{display:block;font-size:11px;color:var(--ci-faint);margin-top:5px}
+.sc-evidence{list-style:none;margin:14px 0 0;padding:0;display:grid;gap:10px}
+.sc-ev{display:grid;grid-template-columns:96px 1fr;gap:10px;align-items:start}
+.sc-type{font-size:10px;font-weight:700;letter-spacing:.05em;text-transform:uppercase;padding:3px 7px;border-radius:6px;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.sc-type-chain{color:#a5b4fc;background:rgba(129,140,248,.12)}
+.sc-type-social{color:#67e8f9;background:rgba(34,211,238,.12)}
+.sc-type-paid{color:#fcd34d;background:rgba(251,191,36,.12)}
+.sc-ev-body{min-width:0}
+.sc-ev-detail{margin:0;font-size:13px;line-height:1.5;color:var(--ci-text);overflow-wrap:anywhere}
+.sc-meta{margin:3px 0 0;font-size:11.5px;color:var(--ci-faint)}
+.sc-src{color:var(--ci-neutral);text-decoration:none;border-bottom:1px dotted currentColor;transition:color var(--duration-fast)}
+.sc-src:hover{color:#c7d2fe}
+.sc-check{margin:4px 0 0;font-size:11.5px;color:var(--ci-muted);padding-left:8px;border-left:2px solid var(--ci-border-strong)}
+.sc-check-k{font-weight:600;color:var(--ci-faint);margin-right:2px}
+.sc-posts{margin-top:14px;border-top:1px solid var(--ci-border);padding-top:12px}
+.sc-posts h4{margin:0 0 8px;font-size:11px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;color:var(--ci-faint)}
+.sc-posts ul{list-style:none;margin:0;padding:0;display:grid;gap:10px}
+.sc-post{background:var(--ci-panel-2);border:1px solid var(--ci-border);border-radius:10px;padding:9px 11px}
+.sc-post-head{margin:0;font-size:12px;color:var(--ci-faint)} .sc-post-head b{color:var(--ci-text)}
+.sc-verified{color:#67e8f9}
+.sc-post-text{margin:4px 0 0;font-size:12.5px;line-height:1.5;color:var(--ci-muted);overflow-wrap:anywhere}
+.sc-caution{margin:14px 0 0;padding:9px 12px;border-radius:10px;background:rgba(251,191,36,.08);border:1px solid rgba(251,191,36,.22);font-size:12.5px;line-height:1.5;color:var(--ci-text)}
+.sc-caution strong{color:var(--ci-warn);margin-right:4px;font-size:11px;letter-spacing:.05em;text-transform:uppercase}
+.sc-foot{display:flex;flex-wrap:wrap;gap:10px;align-items:center;justify-content:space-between;margin-top:12px}
+.sc-unavail{margin:0;font-size:11px;color:var(--ci-faint)}
+.sc-actions{display:flex;gap:7px;flex-wrap:wrap;margin-left:auto}
+.sc-drawer-status{margin:0 0 10px;font-size:12.5px;line-height:1.5;color:var(--ci-muted)}
+.sc-skel{height:220px}
+.sc-sh{display:block;height:12px;border-radius:6px;margin-bottom:12px;background:linear-gradient(90deg,rgba(255,255,255,.04),rgba(255,255,255,.09),rgba(255,255,255,.04));background-size:200% 100%;animation:ciShimmer 1.4s infinite}
+@media (max-width:560px){
+ .sc-ev{grid-template-columns:1fr;gap:4px}
+ .sc-type{justify-self:start}
+ .sc-head{flex-wrap:wrap}
+ .sc-score{text-align:left;min-width:0;width:100%;display:flex;flex-wrap:wrap;align-items:baseline;gap:6px}
+ .sc-score-t{display:inline;margin:0}
+ .sc-why{width:100%}
+ .sc-actions{margin-left:0}
+}
+@media (prefers-reduced-motion:reduce){.sc-card,.sc-note.is-new,.sc-sh{animation:none}}
+`;
diff --git a/src/shared/trade-receipt-view.js b/src/shared/trade-receipt-view.js
index cf345cde2..bfec4be15 100644
--- a/src/shared/trade-receipt-view.js
+++ b/src/shared/trade-receipt-view.js
@@ -176,6 +176,31 @@ function intelCard(i, openedAt) {
return card('Launch intel', timingChip(i.timing, i.observed_at, openedAt), body);
}
+const SCOUT_TYPE_LABEL = {
+ volume_spike: 'Volume',
+ fresh_buyers: 'Buyers',
+ smart_money: 'Smart money',
+ graduation_approach: 'Curve',
+ social_mention: 'Social',
+ paid_signal: 'Paid read',
+ news_match: 'News',
+};
+
+function scoutCard(sc, openedAt) {
+ const lines = sc.evidence.map((e) => {
+ const label = SCOUT_TYPE_LABEL[e.type] || e.type.replace(/_/g, ' ');
+ const src = e.source ? ` ${link(e.source, e.platform === 'x' ? 'Post' : 'Source')}` : '';
+ const check = e.checked_against ? `<span class="rc-dim rc-check-line">${esc(e.checked_against)}</span>` : '';
+ return `<li><span class="rc-pill rc-muted">${esc(label)}${e.platform ? ` · ${esc(e.platform)}` : ''}</span><span>${esc(e.detail)}${src}${check}</span></li>`;
+ }).join('');
+ const peak = sc.peak_score != null && sc.score != null && sc.peak_score > sc.score ? ` <span class="rc-dim">peaked at ${sc.peak_score}</span>` : '';
+ const body = `${sc.score != null ? `<p class="rc-big">${sc.score}<small>/100 momentum</small>${peak}</p>` : ''}
+ ${lines ? `<ul class="rc-list rc-scout">${lines}</ul>` : ''}
+ ${sc.caution ? `<p class="rc-text rc-caution"><strong>Caution:</strong> ${esc(sc.caution)}</p>` : ''}
+ <p class="rc-foot">The Scout's first flag of this coin, with every line's source. ${link('/coin-intel?tab=scout', 'Scout board')}</p>`;
+ return card('Sentiment Scout', timingChip(sc.timing, sc.at, openedAt), body);
+}
+
function legsHTML(legs, openedAt) {
if (!legs.length) return '';
return `<ol class="rc-legs">${legs.map((l) => {
@@ -207,6 +232,7 @@ export function receiptHTML(r, { showLinks = true } = {}) {
e.sentiment && sentimentCard(e.sentiment, opened),
e.token_risk && tokenRiskCard(e.token_risk, opened),
e.intel && intelCard(e.intel, opened),
+ e.scout && scoutCard(e.scout, opened),
].filter(Boolean);
const evidence = cards.length
? `<div class="rc-grid">${cards.join('')}</div>`
@@ -294,6 +320,11 @@ export const RECEIPT_CSS = `
.rc-link:hover,.rc-link:focus-visible{color:var(--rc-ink)}
.rc-link:focus-visible{outline:2px solid var(--accent,#34d399);outline-offset:2px;border-radius:2px}
.rc-note{font-size:11px;color:var(--rc-faint);margin-top:12px!important}
+.rc-scout li{display:grid;grid-template-columns:auto 1fr;gap:8px;align-items:start}
+.rc-scout .rc-pill{font-size:10px;white-space:nowrap}
+.rc-check-line{display:block;margin-top:2px}
+.rc-caution{margin-top:8px!important}
+.rc-caution strong{color:var(--rc-warn);font-weight:700}
.rc-actions{display:flex;flex-wrap:wrap;gap:14px;margin-top:8px!important}
.rc-empty{border:1px dashed var(--rc-line);border-radius:12px;padding:12px 14px}
.rc-sk{display:block;height:14px;border-radius:6px;margin-bottom:10px;
diff --git a/src/sniper-experiments.js b/src/sniper-experiments.js
index c21cfb4b3..640db256a 100644
--- a/src/sniper-experiments.js
+++ b/src/sniper-experiments.js
@@ -134,7 +134,10 @@ function walletLine(x) {
function modeBadge(x) {
if (x.decision_mode === 'llm') {
- return `<span class="xp-badge xp-badge-llm" title="No rule shields: an LLM judges each launch">LLM · ${esc(shortModel(x.llm_model))}</span>`;
+ const scout = x.llm_scout_context
+ ? ' <span class="xp-badge xp-badge-llm" title="This judge also reads the Sentiment Scout\'s sourced evidence for each coin">+ Scout</span>'
+ : '';
+ return `<span class="xp-badge xp-badge-llm" title="No rule shields: an LLM judges each launch">LLM · ${esc(shortModel(x.llm_model))}</span>${scout}`;
}
return `<span class="xp-badge xp-badge-rules">rules</span>`;
}
diff --git a/tests/mcp-trader-tools.test.js b/tests/mcp-trader-tools.test.js
index 5221faa3f..a0c886368 100644
--- a/tests/mcp-trader-tools.test.js
+++ b/tests/mcp-trader-tools.test.js
@@ -1,7 +1,7 @@
/**
* Trader MCP tools (api/_mcp/tools/trader.js), the tools that close the
* autonomous copy-trading loop: trader_leaderboard, trader_profile,
- * trade_receipt, copy_subscribe, copy_status.
+ * trade_receipt, sentiment_scout, 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
@@ -89,6 +89,13 @@ vi.mock('../api/_lib/trade-receipt.js', () => ({
loadTradeReceipt: (...a) => loadTradeReceipt(...a),
}));
+const runSentimentScout = vi.fn();
+const scoutTrackRecord = vi.fn();
+vi.mock('../api/_lib/sentiment-scout.js', () => ({
+ runSentimentScout: (...a) => runSentimentScout(...a),
+ scoutTrackRecord: (...a) => scoutTrackRecord(...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',
@@ -159,7 +166,7 @@ beforeEach(() => {
describe('tool surface', () => {
it('exports the trader tools with handlers and input schemas', () => {
expect(Object.keys(TOOLS).sort()).toEqual(
- ['copy_status', 'copy_subscribe', 'trade_receipt', 'trader_leaderboard', 'trader_profile'],
+ ['copy_status', 'copy_subscribe', 'sentiment_scout', 'trade_receipt', 'trader_leaderboard', 'trader_profile'],
);
for (const t of toolDefs) {
expect(typeof t.handler).toBe('function');
@@ -176,6 +183,8 @@ describe('tool surface', () => {
expect(TOOLS.trader_profile.scope).toBeUndefined();
expect(TOOLS.trade_receipt.scope).toBeUndefined();
expect(TOOLS.trade_receipt.annotations.readOnlyHint).toBe(true);
+ expect(TOOLS.sentiment_scout.scope).toBeUndefined();
+ expect(TOOLS.sentiment_scout.annotations.readOnlyHint).toBe(true);
expect(TOOLS.copy_subscribe.annotations.readOnlyHint).toBe(false);
expect(TOOLS.copy_status.annotations.readOnlyHint).toBe(true);
});
@@ -372,6 +381,56 @@ describe('trade_receipt', () => {
});
});
+describe('sentiment_scout', () => {
+ const board = {
+ network: 'mainnet',
+ window_minutes: 60,
+ observed: 1200,
+ generated_at: '2026-09-29T06:00:00.000Z',
+ candidates: [{
+ mint: THREE_MINT,
+ ticker: '$THREE',
+ momentum_score: 64,
+ evidence: [{ type: 'volume_spike', detail: '12.0 SOL bought in its first 90s', source: 'https://three.ws/api/pump/coin-intel?mint=x', at: '2026-09-29T05:40:00.000Z' }],
+ caution: 'These signals cover only the first 90s of trading; most early momentum on pump.fun fades.',
+ }],
+ };
+
+ beforeEach(() => {
+ runSentimentScout.mockReset();
+ scoutTrackRecord.mockReset();
+ });
+
+ it('returns the board with its evidence and a link to the page', async () => {
+ runSentimentScout.mockResolvedValueOnce(board);
+ const out = payloadOf(await TOOLS.sentiment_scout.handler({ limit: 3 }, ANON));
+ expect(runSentimentScout).toHaveBeenCalledWith({ network: 'mainnet', mint: null, windowMinutes: undefined, limit: 3 });
+ expect(out.candidates[0].evidence[0].source).toMatch(/^https:/);
+ expect(out.board_url).toBe('https://three.ws/coin-intel?tab=scout');
+ expect(out.track_record).toBeUndefined();
+ expect(scoutTrackRecord).not.toHaveBeenCalled();
+ });
+
+ it('reads one coin and attaches the track record on request', async () => {
+ runSentimentScout.mockResolvedValueOnce({ ...board, found: true });
+ scoutTrackRecord.mockResolvedValueOnce({ days: 14, scouted: 40, labeled: 30, good_rate: 0.1, base_rate: 0.02 });
+ const out = payloadOf(await TOOLS.sentiment_scout.handler({ mint: THREE_MINT, track_record: true }, ANON));
+ expect(runSentimentScout.mock.calls[0][0].mint).toBe(THREE_MINT);
+ expect(out.track_record.scouted).toBe(40);
+ });
+
+ it('rejects a malformed mint and reports an outage as unavailable', async () => {
+ const bad = await TOOLS.sentiment_scout.handler({ mint: 'not-a-mint' }, ANON);
+ expect(bad.isError).toBe(true);
+ expect(runSentimentScout).not.toHaveBeenCalled();
+
+ runSentimentScout.mockRejectedValueOnce(new Error('Error connecting to database: fetch failed'));
+ const down = await TOOLS.sentiment_scout.handler({}, ANON);
+ expect(down.isError).toBe(true);
+ expect(textOf(down)).toMatch(/temporarily unavailable/i);
+ });
+});
+
describe('copy_subscribe', () => {
const goodArgs = {
leader_agent_id: LEADER_ID,
diff --git a/tests/sentiment-scout.test.js b/tests/sentiment-scout.test.js
new file mode 100644
index 000000000..1dc02d415
--- /dev/null
+++ b/tests/sentiment-scout.test.js
@@ -0,0 +1,328 @@
+/**
+ * Sentiment Scout: sourced momentum candidates where every claim carries its
+ * receipt. Covers the pure scoring, evidence and caution logic
+ * (api/_lib/sentiment-scout.js), the X recent-search client
+ * (api/_lib/x-search.js, driven through an injected fetch), and the LLM note
+ * layer (api/_lib/scout-notes.js, driven through an injected completion) whose
+ * whole job is refusing a note that adds a fact the evidence does not hold.
+ */
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+vi.mock('../api/_lib/db.js', () => ({ sql: () => Promise.resolve([]) }));
+
+const scout = await import('../api/_lib/sentiment-scout.js');
+const xs = await import('../api/_lib/x-search.js');
+const notes = await import('../api/_lib/scout-notes.js');
+
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const ORIGIN = 'https://three.ws';
+
+function intelRow(over = {}) {
+ return {
+ mint: MINT,
+ network: 'mainnet',
+ symbol: 'THREE',
+ name: 'three.ws',
+ first_seen_at: '2026-09-29T06:00:00.000Z',
+ observation_seconds: 90,
+ buy_count: 40,
+ sell_count: 10,
+ buy_volume_lamports: String(30e9),
+ unique_buyers: 35,
+ signals: { buy_sell_ratio: 4 },
+ concentration_top10: 0.6,
+ fresh_wallet_ratio: 0.2,
+ risk_flags: [],
+ smart_money_count: 0,
+ smart_money_notable: [],
+ is_news_meme: false,
+ twitter: null,
+ telegram: null,
+ website: null,
+ ...over,
+ };
+}
+
+function windowOf(n = 200) {
+ const rows = [];
+ for (let i = 0; i < n; i++) {
+ rows.push({ buy_volume_lamports: String(Math.round((i / n) * 5e9)), unique_buyers: i % 10, symbol: `C${i}`, concentration_top10: 0.9 });
+ }
+ rows.push(intelRow());
+ return rows;
+}
+
+function post(over = {}) {
+ return {
+ id: '1',
+ url: 'https://x.com/alice/status/1',
+ text: 'the contract is live',
+ created_at: '2026-09-29T06:05:00.000Z',
+ author: { id: 'a1', username: 'alice', name: 'Alice', followers: 1200, verified: false },
+ likes: 3, reposts: 1, replies: 0, quotes: 0, impressions: 400,
+ ...over,
+ };
+}
+
+describe('x-search parsing', () => {
+ it('decodes the entities X escapes', () => {
+ expect(xs.decodeXText('CA&gt; 1 &amp; 2 &lt;3')).toBe('CA> 1 & 2 <3');
+ });
+
+ it('quotes the mint and excludes retweets so one shill cannot count many times', () => {
+ expect(xs.mintQuery(MINT)).toBe(`"${MINT}" -is:retweet`);
+ });
+
+ it('normalizes a v2 payload into post receipts with permalinks', () => {
+ const posts = xs.parseSearchPayload({
+ data: [
+ { id: '10', author_id: 'u1', text: 'up only &gt; ok', created_at: '2026-09-29T06:10:00.000Z', public_metrics: { like_count: 4, retweet_count: 2 } },
+ { id: '11', author_id: 'u9', text: 'no user expansion', created_at: '2026-09-29T06:11:00.000Z' },
+ { id: null, text: 'dropped' },
+ ],
+ includes: { users: [{ id: 'u1', username: 'bob', name: 'Bob', public_metrics: { followers_count: 5400 }, verified: true }] },
+ });
+ expect(posts).toHaveLength(2);
+ expect(posts[0]).toMatchObject({ url: 'https://x.com/bob/status/10', text: 'up only > ok', likes: 4, reposts: 2 });
+ expect(posts[0].author).toMatchObject({ username: 'bob', followers: 5400, verified: true });
+ expect(posts[1].url).toBe('https://x.com/i/status/11');
+ expect(posts[1].author.followers).toBeNull();
+ });
+
+ it('summarizes breadth, reach, and how much of the chatter is one voice', () => {
+ const s = xs.summarizePosts([
+ post(),
+ post({ id: '2', author: { id: 'a1', username: 'alice', followers: 1200 } }),
+ post({ id: '3', author: { id: 'b2', username: 'bob', followers: 9000 } }),
+ ]);
+ expect(s).toMatchObject({ posts: 3, authors: 2, reach_followers: 10200 });
+ expect(s.top_poster).toEqual({ username: 'alice', posts: 2 });
+ expect(s.most_followed).toEqual({ username: 'bob', followers: 9000 });
+ expect(s.top_poster_share).toBeCloseTo(2 / 3);
+ expect(s.first_at).toBe('2026-09-29T06:05:00.000Z');
+ });
+});
+
+describe('x-search client', () => {
+ beforeEach(() => xs._resetXSearch());
+
+ function res(status, body, headers = {}) {
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ headers: { get: (k) => headers[k.toLowerCase()] ?? null },
+ json: async () => body,
+ };
+ }
+
+ it('mints an app token from the key pair, then searches with it', async () => {
+ const calls = [];
+ const fetchImpl = vi.fn(async (url, init) => {
+ calls.push({ url, init });
+ if (url.includes('oauth2/token')) return res(200, { access_token: 'app-token' });
+ return res(200, { data: [{ id: '5', author_id: 'u', text: 'hi' }], includes: { users: [{ id: 'u', username: 'u1' }] } }, { 'x-rate-limit-remaining': '400', 'x-rate-limit-reset': String(Math.floor(Date.now() / 1000) + 600) });
+ });
+ const posts = await xs.searchMintPosts(MINT, { env: { X_API_KEY: 'k', X_API_SECRET: 's' }, fetchImpl });
+ expect(posts[0].url).toBe('https://x.com/u1/status/5');
+ expect(calls[0].init.body).toBe('grant_type=client_credentials');
+ expect(calls[1].url).toContain(encodeURIComponent(`"${MINT}"`));
+ expect(calls[1].init.headers.authorization).toBe('Bearer app-token');
+ });
+
+ it('re-mints once on a 401 and stops searching when the budget reserve is reached', async () => {
+ let tokens = 0;
+ let searches = 0;
+ const reset = String(Math.floor(Date.now() / 1000) + 600);
+ const fetchImpl = vi.fn(async (url) => {
+ if (url.includes('oauth2/token')) return res(200, { access_token: `t${++tokens}` });
+ searches++;
+ if (searches === 1) return res(401, {});
+ return res(200, { data: [] }, { 'x-rate-limit-remaining': '10', 'x-rate-limit-reset': reset });
+ });
+ const env = { X_API_KEY: 'k', X_API_SECRET: 's' };
+ await expect(xs.searchMintPosts(MINT, { env, fetchImpl })).resolves.toEqual([]);
+ expect(tokens).toBe(2);
+ await expect(xs.searchMintPosts(MINT, { env, fetchImpl })).rejects.toMatchObject({ reason: 'budget_reserve' });
+ });
+
+ it('refuses to run without credentials rather than guessing', async () => {
+ expect(xs.xSearchConfigured({})).toBe(false);
+ await expect(xs.searchMintPosts(MINT, { env: {}, fetchImpl: vi.fn() })).rejects.toMatchObject({ reason: 'not_configured' });
+ });
+});
+
+describe('social scoring', () => {
+ it('treats one account posting on repeat as promotion, not attention', () => {
+ const single = { posts: 6, authors: 1, top_poster_share: 1, reach_followers: 50000 };
+ const broad = { posts: 6, authors: 6, top_poster_share: 1 / 6, reach_followers: 50000 };
+ expect(scout.isSingleVoice(single)).toBe(true);
+ expect(scout.isSingleVoice(broad)).toBe(false);
+ expect(scout.xAttention(single)).toBeLessThan(scout.xAttention(broad) / 3);
+ expect(scout.xAttention(null)).toBe(0);
+ });
+
+ it('raises the score for broad chatter and docks it for a single voice', () => {
+ const stats = scout.windowStats(windowOf());
+ const pre = scout.measure(intelRow(), stats);
+ const base = { curve: null, calloutCount: 0, newsMatch: false, paidSignal: null, flags: [], copycats: 0 };
+ const none = scout.momentumScore(pre, base).score;
+ const broad = scout.momentumScore(pre, { ...base, xSummary: { posts: 8, authors: 6, top_poster_share: 0.2, reach_followers: 20000 } }).score;
+ const shill = scout.momentumScore(pre, { ...base, xSummary: { posts: 8, authors: 1, top_poster_share: 1, reach_followers: 20000 } }).score;
+ expect(broad).toBeGreaterThan(none);
+ expect(shill).toBeLessThan(none);
+ });
+});
+
+describe('evidence receipts', () => {
+ const stats = scout.windowStats(windowOf());
+ const r = intelRow();
+ const pre = scout.measure(r, stats);
+ const curve = { graduated: false, bondingProgressPct: 46, solInCurve: 15.3 };
+ const xPosts = [post(), post({ id: '9', url: 'https://x.com/bob/status/9', text: 'look https://t.co/abc here', author: { id: 'b', username: 'bob', followers: 9000 } })];
+ const ev = scout.buildEvidence(r, pre, stats, {
+ curve, callouts: [], paidSignal: null, origin: ORIGIN,
+ xSummary: xs.summarizePosts(xPosts), xPosts, checkedAt: '2026-09-29T06:30:00.000Z',
+ });
+
+ it('stamps every line with a source and the time the fact was true', () => {
+ for (const e of ev) {
+ expect(e.source).toMatch(/^https:\/\//);
+ expect(Date.parse(e.at)).not.toBeNaN();
+ }
+ expect(ev.find((e) => e.type === 'volume_spike').at).toBe('2026-09-29T06:01:30.000Z');
+ expect(ev.find((e) => e.type === 'graduation_approach').at).toBe('2026-09-29T06:30:00.000Z');
+ });
+
+ it('quotes the most-followed post, links it, and checks it against the chain', () => {
+ const x = ev.find((e) => e.type === 'social_mention');
+ expect(x.platform).toBe('x');
+ expect(x.source).toBe('https://x.com/bob/status/9');
+ expect(x.detail).toContain('2 X posts quoted this exact contract address, from 2 accounts');
+ expect(x.detail).toContain('@bob (9.0k followers)');
+ expect(x.detail).not.toContain('t.co');
+ expect(x.checked_against).toBe('On-chain at 06:30 UTC: 30.0 SOL bought by 35 wallets in the first 90s; bonding curve at 46%');
+ });
+
+ it('leaves out a source it could not read instead of estimating one', () => {
+ const bare = scout.buildEvidence(r, pre, stats, { curve: null, callouts: [], paidSignal: null, origin: ORIGIN });
+ expect(bare.map((e) => e.type)).toEqual(['volume_spike', 'fresh_buyers']);
+ });
+});
+
+describe('caution line', () => {
+ it('names a curve back at the start after heavy early buying', () => {
+ const c = scout.cautionFor(intelRow(), { curve: { graduated: false, bondingProgressPct: 0.4 }, earlyVolSol: 26.4 });
+ expect(c).toBe('The bonding curve is back at 0% after 26.4 SOL of early buying: the early buyers have already sold.');
+ });
+
+ it('calls out chatter that is all one account', () => {
+ const c = scout.cautionFor(intelRow(), { xSummary: { posts: 12, authors: 1, top_poster_share: 1, top_poster: { username: 'shill', posts: 12 } } });
+ expect(c).toBe('All 12 X posts quoting this contract came from @shill: that is promotion, not independent interest.');
+ });
+
+ it('does not claim nothing outside the chart when X posts exist', () => {
+ const c = scout.cautionFor(intelRow(), { xSummary: { posts: 4, authors: 4, top_poster_share: 0.25 } });
+ expect(c).toMatch(/first 90s of trading/);
+ });
+
+ it('keeps the dev-dump warning above everything else', () => {
+ const c = scout.cautionFor(intelRow({ risk_flags: ['dev_dumped'] }), { curve: { graduated: false, bondingProgressPct: 0 }, earlyVolSol: 50 });
+ expect(c).toMatch(/creator already sold/);
+ });
+});
+
+describe('track record', () => {
+ it('grades the Scout against the base rate, band by band', () => {
+ const t = scout.shapeTrackRecord(
+ { scouted: '50', labeled: '40', graduated: '3', pumped: '5', rugged: '9', good: '8', labeled_70_plus: '10', good_70_plus: '4', labeled_50_69: '20', good_50_69: '3', labeled_under_50: '10', good_under_50: '1' },
+ { labeled: '10000', good: '200' },
+ 14,
+ );
+ expect(t.good_rate).toBe(0.2);
+ expect(t.base_rate).toBe(0.02);
+ expect(t.lift).toBe(10);
+ expect(t.bands[0]).toEqual({ band: '70_plus', labeled: 10, good: 4, good_rate: 0.4 });
+ });
+
+ it('reports no rate rather than zero when nothing is labeled yet', () => {
+ const t = scout.shapeTrackRecord({ scouted: '5', labeled: '0', good: '0' }, { labeled: '0', good: '0' }, 14);
+ expect(t.good_rate).toBeNull();
+ expect(t.base_rate).toBeNull();
+ expect(t.lift).toBeNull();
+ });
+});
+
+describe('judge block', () => {
+ it('hands the judge the same evidence lines a human sees, with the caution', () => {
+ const block = scout.formatJudgeBlock({
+ momentum_score: 61,
+ evidence: [{ type: 'volume_spike', detail: '30.00 SOL bought in its first 90s' }, { type: 'social_mention', platform: 'x', detail: '3 X posts quoted this exact contract address' }],
+ caution: 'Most early momentum fades.',
+ });
+ expect(block).toContain('momentum_score: 61/100');
+ expect(block).toContain('- social_mention (x): 3 X posts quoted this exact contract address');
+ expect(block).toContain('caution: Most early momentum fades.');
+ expect(scout.formatJudgeBlock(null)).toBe('');
+ });
+});
+
+describe('scout notes', () => {
+ const candidate = {
+ mint: MINT,
+ ticker: '$THREE',
+ momentum_score: 61,
+ evidence: [
+ { type: 'volume_spike', detail: '30.00 SOL bought in its first 90s, top 2% of 1288 launches' },
+ { type: 'fresh_buyers', detail: '35 distinct buyers in its first 90s' },
+ ],
+ caution: '4 other coins named $THREE launched in the same window; check you have the right mint.',
+ };
+
+ beforeEach(() => notes._resetScoutNotes());
+
+ it('accepts a note built only from the evidence', () => {
+ expect(notes.validateScoutNote('35 wallets bought 30.00 SOL of $THREE in its first 90s. Four copycats launched too, so check the mint on pump.fun.', candidate)).toEqual({ ok: true });
+ });
+
+ it('rejects invented numbers, in digits or in words', () => {
+ expect(notes.validateScoutNote('35 wallets bought 30.00 SOL; expect a 10x from here on this one.', candidate).reason).toBe('ungrounded_number:10');
+ expect(notes.validateScoutNote('35 wallets bought 30.00 SOL. Five copycats launched in the same window.', candidate).reason).toBe('ungrounded_number:5');
+ });
+
+ it('rejects links, promises, and other tickers', () => {
+ expect(notes.validateScoutNote('35 wallets bought 30.00 SOL, see dexscreener.com for more detail.', candidate).reason).toBe('link');
+ expect(notes.validateScoutNote('35 wallets bought 30.00 SOL, a guaranteed winner for anyone early.', candidate).reason).toBe('promise');
+ expect(notes.validateScoutNote('35 wallets bought 30.00 SOL, more than $OTHER did in its first 90s.', candidate).reason).toBe('foreign_ticker');
+ });
+
+ it('builds one prompt for the batch and parses fenced JSON back', () => {
+ const prompt = notes.buildScoutNotePrompt([candidate]);
+ expect(prompt).toContain(`mint: ${MINT}`);
+ expect(prompt).toContain('- volume_spike: 30.00 SOL bought');
+ expect(notes.parseScoutNotes('```json\n{"notes":[{"mint":" m ","note":"a b"}]}\n```')).toEqual([{ mint: 'm', note: 'a b' }]);
+ expect(notes.parseScoutNotes('no json here')).toEqual([]);
+ });
+
+ it('keeps valid notes, drops invalid ones, and caches by evidence', async () => {
+ const other = { ...candidate, mint: 'THREEsynthetic111111111111111111111111111111', ticker: '$SYNTH' };
+ const complete = vi.fn(async () => ({
+ text: JSON.stringify({ notes: [
+ { mint: MINT, note: '35 wallets bought 30.00 SOL in its first 90s. Four copycats share the name, so verify the mint.' },
+ { mint: other.mint, note: 'This one will moon, 1000 buyers are coming for sure.' },
+ ] }),
+ model: 'test-model',
+ provider: 'test',
+ }));
+ const out = await notes.writeScoutNotes([candidate, other], { complete });
+ expect(out.get(MINT)).toMatchObject({ model: 'test-model' });
+ expect(out.has(other.mint)).toBe(false);
+ await notes.writeScoutNotes([candidate, other], { complete });
+ expect(complete).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns no notes, and throws nothing, when the chain is down', async () => {
+ const out = await notes.writeScoutNotes([candidate], { complete: async () => { throw new Error('chain exhausted'); } });
+ expect(out.size).toBe(0);
+ });
+});
diff --git a/tests/trade-receipt.test.js b/tests/trade-receipt.test.js
index 92345842f..6b6725e25 100644
--- a/tests/trade-receipt.test.js
+++ b/tests/trade-receipt.test.js
@@ -137,6 +137,28 @@ describe('shapeTradeReceipt', () => {
expect(r.evidence.sentiment.receipt_url).toContain(SOL_SIG);
});
+ it('shows what the Sentiment Scout flagged before the entry, with sources, and nothing it said after the exit', () => {
+ const scout = {
+ first_scouted_at: at(-600), first_score: 64, peak_score: 71,
+ first_caution: 'Most early momentum on pump.fun fades.',
+ first_evidence: [
+ { type: 'volume_spike', detail: '30.0 SOL bought in its first 90s', source: 'https://three.ws/api/pump/coin-intel?mint=x', at: at(-700) },
+ { type: 'social_mention', platform: 'x', detail: '3 X posts quoted this exact contract address', source: 'https://x.com/a/status/1', at: at(-650), checked_against: 'On-chain at 05:40 UTC: 30.0 SOL bought' },
+ { type: 'paid_signal', detail: 'no link', source: 'javascript:alert(1)' },
+ { type: '', detail: 'dropped' },
+ ],
+ };
+ const r = shapeTradeReceipt({ position: position(), journal: [], scout });
+ expect(r.evidence.scout).toMatchObject({ score: 64, peak_score: 71, timing: 'before_entry' });
+ expect(r.evidence.scout.evidence).toHaveLength(3);
+ expect(r.evidence.scout.evidence[1]).toMatchObject({ platform: 'x', source: 'https://x.com/a/status/1' });
+ expect(r.evidence.scout.evidence[2].source).toBeNull();
+ expect(r.summary).toContain('Sentiment Scout flagged it at 64');
+
+ const late = shapeTradeReceipt({ position: position(), journal: [], scout: { ...scout, first_scouted_at: '2026-09-24T09:00:00.000Z' } });
+ expect(late.evidence.scout).toBeNull();
+ });
+
it('only admits an LLM verdict that existed before the entry', () => {
const before = shapeTradeReceipt({
position: position(), journal: [],
diff --git a/workers/agent-sniper/llm-judge.js b/workers/agent-sniper/llm-judge.js
index 8ef16e6a4..d9dbd8d5e 100644
--- a/workers/agent-sniper/llm-judge.js
+++ b/workers/agent-sniper/llm-judge.js
@@ -15,6 +15,12 @@
// calibration). See judge-knowledge.js. An arm that has not earned it sees
// exactly the prompt this file has always sent.
//
+// Scout context (opt-in, strategy.llm_scout_context): the Sentiment Scout's
+// sourced read of the coin (evidence lines with their sources, momentum score,
+// caution; api/_lib/sentiment-scout.js scoutJudgeBlock) is appended to the
+// brief. It only exists once the coin has been observed, so in practice it
+// feeds intel_confirmed arms; a fresh new_mint launch gets an empty block.
+//
// Cost + latency control:
// • One verdict per (mint, model, knowledge depth). Arms at base depth still
// share a single call across a same-model fleet exactly as before; an arm
@@ -31,6 +37,7 @@ import { sql } from '../../api/_lib/db.js';
import { llmComplete } from '../../api/_lib/llm.js';
import { assessMarketRealness } from '../../api/_lib/market-realness.js';
import { buildKnowledgePack } from './judge-knowledge.js';
+import { scoutJudgeBlock } from '../../api/_lib/sentiment-scout.js';
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions';
@@ -197,9 +204,10 @@ export async function judgeLaunch(mint, strat) {
});
// Arms at base depth share one call per (mint, model) exactly as before. An arm
- // with earned context is asking a materially different question, so it keys on
- // its own strategy and pays for its own call.
- const scope = pack.block ? `${pack.depth}:${strat.id}` : 'base';
+ // with earned context (or Scout context) is asking a materially different
+ // question, so it keys on its own strategy and pays for its own call.
+ const scoutOn = strat.llm_scout_context === true;
+ const scope = pack.block || scoutOn ? `${pack.depth}${scoutOn ? '+scout' : ''}:${strat.id}` : 'base';
const key = `${mint.mint}:${model}:${scope}`;
const cached = _verdicts.get(key);
if (cached && Date.now() - cached.ts < VERDICT_TTL_MS) return cached.promise;
@@ -209,7 +217,14 @@ export async function judgeLaunch(mint, strat) {
return null;
}
_active++;
- const promise = judge(mint, model, pack.block)
+ const scoutRead = scoutOn
+ ? scoutJudgeBlock(mint.mint, network).catch((err) => {
+ log.warn('scout context unavailable, judging without it', { mint: mint.mint, model, err: err?.message });
+ return '';
+ })
+ : Promise.resolve('');
+ const promise = scoutRead
+ .then((scoutBlock) => judge(mint, model, pack.block + scoutBlock))
.then((verdict) => {
if (verdict) {
recordVerdict({ mint: mint.mint, network, requestedModel: model, verdict });