Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
News curation hardening + oracle realized-label cron and sniper test coverage
nirholas21084a2385e9
diff --git a/api/cron/oracle-realized-labels.js b/api/cron/oracle-realized-labels.jsnew file mode 100644index 000000000..afc2e1f43--- /dev/null+++ b/api/cron/oracle-realized-labels.js@@ -0,0 +1,56 @@+// GET/POST /api/cron/oracle-realized-labels — Bridge 1: give the Oracle real+// money to learn from.+//+// The Oracle/intel learner (workers/agent-sniper/intel/learn.js) trains its+// signal weights on coarse chart labels: a coin "won" if it hit ATH >= 3x at any+// point (pump_coin_outcomes). But a coin can spike 3x and the sniper still LOSE+// (bought late, timed-out exit). The fleet's REALIZED entry->exit PnL is scarcer+// but far higher-fidelity ground truth.+//+// This cron derives, per mint the fleet actually traded, the realized result+// (net win/loss + avg PnL%) from agent_sniper_positions and upserts it into+// oracle_realized_outcomes. trainWeights LEFT JOINs that table and PREFERS the+// realized label when present, so Oracle learns what actually makes money. A+// closed trade's PnL never changes, so re-deriving is cheap and idempotent.++import { error, json, method, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }+ return true;+}++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const network = 'mainnet';+ const rows = await sql`+ insert into oracle_realized_outcomes (mint, network, realized_win, realized_pnl_pct, samples, updated_at)+ select p.mint, p.network,+ case when sum(p.realized_pnl_lamports) > 0 then 1 else 0 end,+ round(avg(p.realized_pnl_pct)::numeric, 4),+ count(*)+ from agent_sniper_positions p+ where p.network = ${network}+ and p.status = 'closed' and p.buy_sig <> 'SIMULATED'+ and p.realized_pnl_lamports is not null+ group by p.mint, p.network+ on conflict (mint, network) do update set+ realized_win = excluded.realized_win,+ realized_pnl_pct = excluded.realized_pnl_pct,+ samples = excluded.samples,+ updated_at = now()+ returning mint, realized_win+ `;++ const wins = rows.filter((r) => Number(r.realized_win) === 1).length;+ return json(res, 200, { ok: true, labeled: rows.length, wins, losses: rows.length - wins });+});diff --git a/api/news/article.js b/api/news/article.jsindex 31b4fa06a..fe76e1a7b 100644--- a/api/news/article.js+++ b/api/news/article.js@@ -205,10 +205,10 @@ export default wrap(async (req, res) => {(async () => {try {const relatedQuery = tickers[0] || title.split(/\s+/).slice(0, 3).join(' ');- const rel = await getNews({ q: relatedQuery, limit: 7 });+ const rel = await getNews({ q: relatedQuery, limit: 7, curated: true });let out = rel.articles.filter((a) => a.link !== target).slice(0, 6);if (!out.length) {- const fallback = await getNews({ category: feedCopy?.category, limit: 7 });+ const fallback = await getNews({ category: feedCopy?.category, limit: 7, curated: true });out = fallback.articles.filter((a) => a.link !== target).slice(0, 6);}return out;diff --git a/api/news/digest.js b/api/news/digest.jsindex 27c8b618d..65ed21bd8 100644--- a/api/news/digest.js+++ b/api/news/digest.js@@ -198,7 +198,7 @@ export default wrap(async (req, res) => {});}- const { articles: all, sources_ok, sources_total } = await getNews({ limit: 400 });+ const { articles: all, sources_ok, sources_total } = await getNews({ limit: 400, curated: true });const cutoff = Date.now() - hours * 3600_000;const windowed = all.filter((a) => a.pub_date && new Date(a.pub_date).getTime() >= cutoff)diff --git a/api/news/feed.js b/api/news/feed.jsindex 2ab21456e..f02590dcc 100644--- a/api/news/feed.js+++ b/api/news/feed.js@@ -60,7 +60,10 @@ export default wrap(async (req, res) => {});}- const result = await getNews({ category, source, lang, q, limit, offset, featured });+ // Human-facing feed: apply the editorial display gate (crypto-relevant ++ // above the quality floor). raw=1 bypasses it for debugging / parity checks.+ const curated = params.get('raw') !== '1';+ const result = await getNews({ category, source, lang, q, limit, offset, featured, curated });const body = {articles: result.articles,diff --git a/api/news/rss.js b/api/news/rss.jsindex 944de968d..fc6440599 100644--- a/api/news/rss.js+++ b/api/news/rss.js@@ -38,7 +38,7 @@ export default wrap(async (req, res) => {return error(res, 400, 'bad_category', `unknown category "${category}"`);}- const { articles } = await getNews({ category, limit });+ const { articles } = await getNews({ category, limit, curated: true });const feedUrl = `https://three.ws/api/news/rss${category ? `?category=${category}` : ''}`;const pageUrl = `https://three.ws/markets/news${category ? `?category=${category}` : ''}`;const title = `three.ws Crypto News${category ? ` — ${category}` : ''}`;diff --git a/scripts/rug-signature.mjs b/scripts/rug-signature.mjsindex e4b562bf5..f8eb2be68 100644--- a/scripts/rug-signature.mjs+++ b/scripts/rug-signature.mjs@@ -29,6 +29,14 @@ const args = process.argv.slice(2);const asJson = args.includes('--json');const minMcIdx = args.indexOf('--min-mc');const minMc = minMcIdx >= 0 ? Number(args[minMcIdx + 1]) : 0;+// --active isolates the cohort a momentum bot would actually consider: a coin+// that had a real formed market in the observation window, not a stillborn mint.+// Without this, 50k dead-on-arrival "rugs" (unique_buyers=1) swamp every median+// and the honeypot signature (which lives among the LIVE-LOOKING coins) is+// invisible. Floor is generous so we keep the whole "looked alive" population.+const activeIdx = args.indexOf('--active');+const activeBuyers = activeIdx >= 0 ? Number(args[activeIdx + 1] || 10) : 0;+const ACTIVE = activeBuyers ? `and i.unique_buyers >= ${activeBuyers}` : '';function resolveDatabaseUrl() {if (process.env.DATABASE_URL) return process.env.DATABASE_URL;@@ -78,6 +86,7 @@ async function distribution(pool, expr, bucketPred) {join pump_coin_outcomes o on o.mint = i.mintwhere i.network = 'mainnet'and ${bucketPred}+ ${ACTIVE}and (${expr}) is not null${minMc ? `and coalesce(o.ath_market_cap_usd, 0) >= ${minMc}` : ''}) s`;@@ -101,6 +110,7 @@ async function main() {`select count(*)::int as n from pump_coin_intel ijoin pump_coin_outcomes o on o.mint = i.mintwhere i.network='mainnet' and ${pred}+ ${ACTIVE}${minMc ? `and coalesce(o.ath_market_cap_usd,0) >= ${minMc}` : ''}`,);counts[name] = rows[0].n;diff --git a/tests/news-curation.test.js b/tests/news-curation.test.jsnew file mode 100644index 000000000..965e7d370--- /dev/null+++ b/tests/news-curation.test.js@@ -0,0 +1,112 @@+// Coverage for api/_lib/news-curation.js — the editorial display gate.+//+// The contract this protects: a crypto-native source always shows; a broad /+// mixed source (WSJ, Seeking Alpha, a world-news desk) shows an article ONLY if+// that article is itself about crypto; and a scored source below the credibility+// floor is dropped. It is a DISPLAY filter — ingestion is unaffected, which is+// asserted separately against getNews.++import { describe, it, expect } from 'vitest';++const { isCryptoRelevant, passesQualityFloor, isDisplayable, DEFAULT_MIN_CREDIBILITY } =+ await import('../api/_lib/news-curation.js');+const { NEWS_SOURCES } = await import('../api/_lib/news-sources.js');++// Anchor the tests to real registry keys so a category rename can't silently+// make them vacuous.+const NATIVE_KEY = 'coindesk'; // general, crypto-native+const BROAD_KEY = 'seekingalpha'; // mainstream, mixed content+const REG_KEY = 'sec_press'; // geopolitical, mixed content (regulator)++describe('registry assumptions', () => {+ it('the anchor sources exist and are the categories the tests assume', () => {+ expect(NEWS_SOURCES[NATIVE_KEY]?.category).toBe('general');+ expect(NEWS_SOURCES[BROAD_KEY]).toBeTruthy();+ expect(NEWS_SOURCES[BROAD_KEY].category).not.toBe('general');+ });+});++describe('isCryptoRelevant', () => {+ it('passes any article from a crypto-native source, even an off-topic-looking title', () => {+ expect(isCryptoRelevant({ source_key: NATIVE_KEY, title: 'Governance drama at a foundation' })).toBe(true);+ });++ it('passes a broad-source article that is about crypto (by keyword)', () => {+ expect(isCryptoRelevant({ source_key: BROAD_KEY, title: 'Ethereum staking yields climb after upgrade' })).toBe(true);+ });++ it('passes a broad-source article that carries a detected ticker', () => {+ expect(isCryptoRelevant({ source_key: BROAD_KEY, title: 'A quiet week', tickers: ['BTC'] })).toBe(true);+ });++ it('drops a broad-source article with no crypto signal', () => {+ expect(isCryptoRelevant({ source_key: BROAD_KEY, title: '3M stock jumps on raised outlook', tickers: [] })).toBe(false);+ expect(isCryptoRelevant({ source_key: BROAD_KEY, title: 'Ryanair broken window may have been caused by foreign object' })).toBe(false);+ });++ it('passes a regulator story about crypto, drops its non-crypto business', () => {+ expect(isCryptoRelevant({ source_key: REG_KEY, title: 'SEC charges firm over unregistered token sale' })).toBe(true);+ expect(isCryptoRelevant({ source_key: REG_KEY, title: 'Commission adopts new proxy voting rule' })).toBe(false);+ });++ it('matches on the description when the title is neutral', () => {+ expect(isCryptoRelevant({ source_key: BROAD_KEY, title: 'Markets today', description: 'Bitcoin led gains as the DeFi sector rebounded.' })).toBe(true);+ });++ it('does not misfire on generic finance words', () => {+ expect(isCryptoRelevant({ source_key: BROAD_KEY, title: 'Inflation cools, stocks rally, GDP revised up' })).toBe(false);+ });++ it('falls back to the content test for an unknown source key', () => {+ expect(isCryptoRelevant({ source_key: 'not_in_registry', title: 'Bitcoin surges' })).toBe(true);+ expect(isCryptoRelevant({ source_key: 'not_in_registry', title: 'A weather report' })).toBe(false);+ });++ it('is null-safe', () => {+ expect(isCryptoRelevant(null)).toBe(false);+ expect(isCryptoRelevant({})).toBe(false);+ });+});++describe('passesQualityFloor', () => {+ it('drops a scored source below the floor', () => {+ // Fabricate a below-floor article by pointing at a real low-cred source+ // only if one exists; otherwise assert the mechanism directly.+ const belowKey = Object.keys(NEWS_SOURCES).find((k) => typeof NEWS_SOURCES[k].credibility === 'number' && NEWS_SOURCES[k].credibility < DEFAULT_MIN_CREDIBILITY);+ if (belowKey) {+ expect(passesQualityFloor({ source_key: belowKey })).toBe(false);+ }+ // And with an explicit high floor, a mid-cred source fails.+ expect(passesQualityFloor({ source_key: 'coindesk' }, 0.99)).toBe(false);+ });++ it('passes a scored source at or above the floor', () => {+ expect(passesQualityFloor({ source_key: 'coindesk' })).toBe(true); // 0.95+ });++ it('presumes an unscored registry source is acceptable', () => {+ const unscored = Object.keys(NEWS_SOURCES).find((k) => NEWS_SOURCES[k].credibility == null);+ expect(passesQualityFloor({ source_key: unscored })).toBe(true);+ });++ it('never drops an article whose source is not in the registry', () => {+ expect(passesQualityFloor({ source_key: 'legacy_archive_row' })).toBe(true);+ });+});++describe('isDisplayable (combined gate)', () => {+ it('needs BOTH relevance and quality', () => {+ // Crypto but below an aggressive floor → dropped.+ expect(isDisplayable({ source_key: 'coindesk', title: 'Bitcoin news' }, { minCredibility: 0.99 })).toBe(false);+ // Above floor but off-topic from a broad source → dropped.+ expect(isDisplayable({ source_key: BROAD_KEY, title: '3M stock jumps' })).toBe(false);+ // Crypto-native + scored fine → shown.+ expect(isDisplayable({ source_key: 'coindesk', title: 'anything' })).toBe(true);+ });++ it('honours a runtime floor override', () => {+ const a = { source_key: 'coindesk', title: 'Bitcoin' }; // cred 0.95+ expect(isDisplayable(a, { minCredibility: 0.9 })).toBe(true);+ expect(isDisplayable(a, { minCredibility: 0.96 })).toBe(false);+ });+});diff --git a/tests/sniper-optimizer.test.js b/tests/sniper-optimizer.test.jsindex cc147d703..a9356a32f 100644--- a/tests/sniper-optimizer.test.js+++ b/tests/sniper-optimizer.test.js@@ -105,3 +105,59 @@ describe('proposeAdjustments', () => {for (const p of r.proposals) expect(p.to).not.toBe(p.from);});});++describe('bestOracleThreshold (Bridge 2)', () => {+ it('finds the conviction floor where wins concentrate', () => {+ // Low-conviction coins mostly lose; >=70 mostly win.+ const buckets = [+ { lo: 30, closed: 6, wins: 1 },+ { lo: 50, closed: 4, wins: 1 },+ { lo: 70, closed: 5, wins: 4 },+ { lo: 85, closed: 3, wins: 3 },+ ];+ expect(bestOracleThreshold(buckets)).toBe(70);+ });++ it('returns null when conviction does not separate outcomes', () => {+ const buckets = [+ { lo: 30, closed: 5, wins: 3 },+ { lo: 70, closed: 5, wins: 3 },+ ];+ expect(bestOracleThreshold(buckets)).toBeNull();+ });++ it('returns null on too little data', () => {+ expect(bestOracleThreshold([{ lo: 70, closed: 3, wins: 3 }])).toBeNull();+ expect(bestOracleThreshold([])).toBeNull();+ expect(bestOracleThreshold(null)).toBeNull();+ });+});++describe('Rule O: optimizer uses Oracle conviction', () => {+ it('sets min_oracle_score toward the winning conviction band', () => {+ const r = proposeAdjustments(+ stats({+ closed: 18, wins: 8, winRate: 44, avgPnlPct: 5,+ exitReasons: { stop_loss: 6, trailing_stop: 6, timeout: 6 },+ oracleBuckets: [+ { lo: 30, closed: 8, wins: 1 },+ { lo: 50, closed: 4, wins: 1 },+ { lo: 70, closed: 6, wins: 5 },+ ],+ }),+ { ...baseConfig, min_oracle_score: null },+ );+ const o = r.proposals.find((p) => p.field === 'min_oracle_score');+ expect(o).toBeTruthy();+ expect(o.from).toBe(null);+ expect(o.to).toBe(70);+ });++ it('does nothing when the arm has no oracle-scored trades', () => {+ const r = proposeAdjustments(+ stats({ closed: 12, wins: 7, oracleBuckets: [] }),+ { ...baseConfig, min_oracle_score: null },+ );+ expect(r.proposals.find((p) => p.field === 'min_oracle_score')).toBeFalsy();+ });+});