Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(news): match the crypto lexicon and tickers as whole words so equities headlines stop leading the feed
nirholasc71feb002e3c
diff --git a/api/_lib/news-curation.js b/api/_lib/news-curation.jsindex a65fe7cf6..921332db3 100644--- a/api/_lib/news-curation.js+++ b/api/_lib/news-curation.js@@ -57,18 +57,25 @@ const CRYPTO_NATIVE_CATEGORIES = new Set([// developer — is a mixed source: its article must prove it is about crypto.// Crypto topical lexicon for the per-article relevance gate. Kept lowercase and-// matched as substrings against `${title} ${description}`. Deliberately broad-// on the crypto side (better to admit a borderline crypto story than drop a-// real one), while excluding the generic finance words that a non-crypto-// markets story would trip ("stocks", "inflation", "GDP" are NOT here).+// matched as WHOLE WORDS against `${title} ${description}` (see CRYPTO_TERM_RE+// below). Deliberately broad on the crypto side (better to admit a borderline+// crypto story than drop a real one), while excluding the generic finance words+// that a non-crypto markets story would trip ("stocks", "inflation", "GDP" are+// NOT here).const CRYPTO_TERMS = ['crypto','bitcoin','btc','ethereum',- 'ether ',+ 'ether','blockchain','stablecoin',+ // The major stablecoins by name and symbol. "Tether" used to squeak through+ // only because the old substring test found "ether" inside it; a mainstream+ // outlet's Tether story is squarely on topic and now says so explicitly.+ 'tether',+ 'usdt',+ 'usdc','defi','web3','altcoin',@@ -96,11 +103,35 @@ const CRYPTO_TERMS = ['staking','metamask','ledger',- 'defi',- 'dao ',+ 'dao','wallet',];+// Terms that are deliberately a PREFIX, not a word, because they head a family+// of endings the whole-word matcher would otherwise reject: cryptocurrency /+// cryptoassets, tokenize / tokenization / tokenized.+const CRYPTO_PREFIX_TERMS = new Set(['crypto', 'tokeniz']);++// Whole-word matcher for the lexicon.+//+// This was a plain `includes()` substring test, and short terms quietly matched+// inside ordinary English: "defi" fired on "defied", which put three Indian+// equities headlines ("FIIs dumped … but 8 defied the selloff") at the top of+// the crypto news feed and the daily digest. "deficit", "definition", and+// "defiance" were the same story waiting to happen, and "ether" matched inside+// "tether". A leading \b plus a trailing "not another letter" guard keeps every+// real hit (matching is case-insensitive, so DeFi/BTC/DAO all land, and the+// guard still admits the hyphenated compounds crypto writing is full of:+// blockchain-based, wallet-to-wallet) while refusing the mid-word ones. An+// optional plural "s" keeps DAOs, NFTs, and wallets matching.+const CRYPTO_TERM_RE = new RegExp(+ CRYPTO_TERMS.map((term) => {+ const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ return CRYPTO_PREFIX_TERMS.has(term) ? `\\b${escaped}` : `\\b${escaped}s?(?![a-z])`;+ }).join('|'),+ 'i',+);+/** Runtime-tunable credibility floor (0–1). */export const DEFAULT_MIN_CREDIBILITY = (() => {const raw = Number(env.NEWS_MIN_CREDIBILITY);@@ -127,8 +158,7 @@ export function isCryptoRelevant(a) {// assuming either way.if (Array.isArray(a.tickers) && a.tickers.length) return true;- const hay = ` ${String(a.title || '')} ${String(a.description || '')} `.toLowerCase();- return CRYPTO_TERMS.some((t) => hay.includes(t));+ return CRYPTO_TERM_RE.test(`${String(a.title || '')} ${String(a.description || '')}`);}/**diff --git a/api/_lib/news.js b/api/_lib/news.jsindex 72d66eaea..d6a9f389b 100644--- a/api/_lib/news.js+++ b/api/_lib/news.js@@ -161,21 +161,41 @@ const TICKER_WORDS = new Map([['tether', 'USDT'], ['usdt', 'USDT'], ['usdc', 'USDC'], ['avalanche', 'AVAX'],['avax', 'AVAX'], ['polkadot', 'DOT'], ['chainlink', 'LINK'], ['litecoin', 'LTC'],['polygon', 'MATIC'], ['tron', 'TRX'], ['shiba inu', 'SHIB'], ['shib', 'SHIB'],- ['sui', 'SUI'], ['aptos', 'APT'], ['near', 'NEAR'], ['arbitrum', 'ARB'], ['optimism', 'OP'],- ['pepe', 'PEPE'], ['bonk', 'BONK'], ['aave', 'AAVE'], ['uniswap', 'UNI'], ['maker', 'MKR'],+ ['sui', 'SUI'], ['aptos', 'APT'], ['arbitrum', 'ARB'],+ ['pepe', 'PEPE'], ['bonk', 'BONK'], ['aave', 'AAVE'], ['uniswap', 'UNI'],['stellar', 'XLM'], ['monero', 'XMR'], ['cosmos', 'ATOM'], ['filecoin', 'FIL'],['hedera', 'HBAR'], ['injective', 'INJ'], ['celestia', 'TIA'], ['jito', 'JTO'],['jupiter', 'JUP'], ['worldcoin', 'WLD'], ['toncoin', 'TON'], ['hyperliquid', 'HYPE'],]);+// Projects whose bare name is ALSO an ordinary English or finance word. They+// were in the wordlist above and tagged the language, not the coin: "near"+// turned every "near-term profit booking" note into NEAR Protocol (the archive's+// trending strip ranked NEAR third on the strength of it), "optimism" tagged+// every hopeful Fed headline as OP, and "maker" tagged every market maker as+// MKR. A false ticker is expensive here — it pins a price widget to an unrelated+// story, skews trending, and lets a non-crypto article through the display gate+// on the strength of a detected ticker — so these count only when the text names+// the project rather than uses the word. A cashtag ($NEAR) still matches via the+// pass above, and crypto-native coverage of these three reliably qualifies them.+const QUALIFIED_TICKER_PHRASES = new Map([+ ['near protocol', 'NEAR'], ['near foundation', 'NEAR'],+ ['optimism network', 'OP'], ['optimism mainnet', 'OP'], ['op mainnet', 'OP'],+ ['op token', 'OP'], ['optimism collective', 'OP'],+ ['makerdao', 'MKR'], ['maker dao', 'MKR'], ['maker protocol', 'MKR'], ['mkr', 'MKR'],+]);+export function extractTickers(text) {const found = new Set();const t = String(text || '');for (const m of t.matchAll(/\$([A-Z][A-Z0-9]{1,9})\b/g)) found.add(m[1]);- const lower = ` ${t.toLowerCase().replace(/[^a-z0-9$ ]/g, ' ')} `;+ const lower = ` ${t.toLowerCase().replace(/[^a-z0-9$ ]/g, ' ').replace(/\s+/g, ' ')} `;for (const [word, sym] of TICKER_WORDS) {if (lower.includes(` ${word} `)) found.add(sym);}+ for (const [phrase, sym] of QUALIFIED_TICKER_PHRASES) {+ if (lower.includes(` ${phrase} `)) found.add(sym);+ }return [...found].slice(0, 8);}diff --git a/api/news/article.js b/api/news/article.jsindex fe76e1a7b..e4876b23b 100644--- a/api/news/article.js+++ b/api/news/article.js@@ -139,12 +139,21 @@ export default wrap(async (req, res) => {const params = new URL(req.url, 'http://x').searchParams;const rawUrl = (params.get('url') || '').replace(/^<!\[CDATA\[/, '').replace(/\]\]>$/, '').trim();if (!rawUrl) return error(res, 400, 'bad_url', 'url is required');- let target;+ let parsed;try {- target = new URL(rawUrl).toString();+ parsed = new URL(rawUrl);} catch {return error(res, 400, 'bad_url', 'url is not a valid absolute URL');}+ // An article link is a web link. `new URL()` happily parses javascript:,+ // file:, and data: URLs, and every rung of the extraction ladder then+ // refuses them one by one — which used to end in a 200 carrying an empty+ // "Untitled" record. Reject the scheme here instead: a non-web URL is bad+ // input, not an article we failed to read.+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {+ return error(res, 400, 'bad_url', 'url must be an http(s) article link');+ }+ const target = parsed.toString();// Withdrawn publisher (or a taken-down story reached by its link) — refuse// before fetching anything. 410: the resource is permanently gone from here.@@ -255,7 +264,16 @@ export default wrap(async (req, res) => {// Record into the durable knowledge base the 3D agents read from. Fire-and-// forget: a persistence hiccup must never fail the reader response.- recordExtraction(value).catch(() => {});+ //+ // Only rows carrying real body text are worth recording. A zero-content+ // preview (every rung of the ladder refused the URL) grounds no agent and+ // is never reused as the cross-instance cache above, which requires a+ // page/reader row over 400 chars — so writing it only adds noise to the+ // corpus. It also closes the corpus to drive-by writes: this endpoint is+ // public and unauthenticated, and the caller controls `url`, `title`, and+ // `source`, so an arbitrary link used to mint a permanent knowledge row+ // with an attacker-chosen headline behind a single GET.+ if (value.content_chars > 0) recordExtraction(value).catch(() => {});return json(res, 200, publicView(value), cacheHeaders);});diff --git a/api/news/feed.js b/api/news/feed.jsindex e9485fc6e..936a69129 100644--- a/api/news/feed.js+++ b/api/news/feed.js@@ -19,6 +19,9 @@// limit 1–50 (default 30)// offset pagination offset// meta=1 include the source registry + category + language lists+// raw=1 bypass the editorial display gate (crypto-relevant + above the+// quality floor) and return the unfiltered aggregate. Debugging and+// parity checks only; the human-facing feeds never set it.//// Aggregation results are cached per source for 5 minutes inside// api/_lib/news.js, so this endpoint is cheap under load; CDN caches 120s.diff --git a/api/news/knowledge.js b/api/news/knowledge.jsindex d478a2b2b..24fbbdf8d 100644--- a/api/news/knowledge.js+++ b/api/news/knowledge.js@@ -14,6 +14,10 @@// (none) → the latest recorded stories + corpus stats//// Lightweight rows by default; add &full=1 for the extracted body + coins.+//+// Every row this endpoint serves carries real extracted body text. A story the+// extraction ladder could not read is not knowledge, so it never appears here+// and its id answers 404 rather than a headline-only shell.import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -25,6 +29,16 @@ import { suppression, isSuppressed, excerptParagraphs } from '../_lib/news-right// same rights boundary the reader uses applies on the way out: withdrawn// stories are dropped entirely, and `paragraphs` is capped to a lead excerpt.// Callers wanting the whole article follow `url` to the publisher.+// A row only belongs in the grounding corpus if it actually carries extracted+// body text. Zero-content rows are the residue of a story every extraction+// rung refused (a paywall, a bot wall, or a link that was never an article):+// they hold a headline and nothing an agent can reason over, and they are the+// shape a drive-by write to /api/news/article leaves behind. Filtered here so+// the corpus already on disk is clean on the way out, not just from now on.+function hasBody(record) {+ return Number(record?.content_chars) > 0;+}+function publicRecord(record) {if (!record) return record;if (!Array.isArray(record.paragraphs)) return record;@@ -53,7 +67,7 @@ export default wrap(async (req, res) => {const sup = suppression({ id });if (sup) return error(res, 410, 'removed', 'this story was withdrawn at the rightsholder’s request');const record = await getExtraction(id);- if (!record) return error(res, 404, 'not_found', 'no knowledge recorded for this story yet');+ if (!record || !hasBody(record)) return error(res, 404, 'not_found', 'no knowledge recorded for this story yet');if (isSuppressed(record)) return error(res, 410, 'removed', 'this story was withdrawn at the rightsholder’s request');return json(res, 200, publicRecord(record), headers);}@@ -67,6 +81,6 @@ export default wrap(async (req, res) => {queryKnowledge({ ticker: ticker || null, q: q || null, limit, full }),knowledgeStats(),]);- const visible = articles.filter((a) => !isSuppressed(a)).map(publicRecord);+ const visible = articles.filter((a) => hasBody(a) && !isSuppressed(a)).map(publicRecord);return json(res, 200, { articles: visible, stats, query: { ticker: ticker || null, q: q || null, full } }, headers);});diff --git a/public/locales/localized-pages.json b/public/locales/localized-pages.jsonindex d86bb1da1..c02195352 100644--- a/public/locales/localized-pages.json+++ b/public/locales/localized-pages.json@@ -1,6 +1,6 @@{"generated": true,- "count": 355,+ "count": 243,"paths": ["/","/3d",@@ -157,118 +157,6 @@"/mocap-studio","/motion-swap","/my-agents",- "/news",- "/news/",- "/news/2045242891350814835",- "/news/2049397875935989970",- "/news/2049406826719137937",- "/news/2049412062837928202",- "/news/2049447738434339171",- "/news/2049458671139336613",- "/news/2049476546285740512",- "/news/2049557523330638269",- "/news/2049573582247022869",- "/news/2049576603324411933",- "/news/2049576641127682430",- "/news/2049577291957899336",- "/news/2049762836881301865",- "/news/2049765915575914834",- "/news/2049997615421649363",- "/news/2050016695897706885",- "/news/2050049239301165535",- "/news/2050221269732425928",- "/news/2050226678321102975",- "/news/2050229144676675999",- "/news/2050284562069266616",- "/news/2050585585191186781",- "/news/2050627547394916768",- "/news/2050753406109880576",- "/news/2050758788186353723",- "/news/2050800140295049308",- "/news/2050886334261391686",- "/news/2051140736201175323",- "/news/2051261108506558901",- "/news/2051616708482498843",- "/news/2051689230997618690",- "/news/2051690803203105230",- "/news/2051774915876098063",- "/news/2051858035862335505",- "/news/2051858503523066283",- "/news/2051893054584553680",- "/news/2052037977556287723",- "/news/2052167399399735476",- "/news/2052181307002929363",- "/news/2052189491801284690",- "/news/2052402481024667887",- "/news/2052402580266098813",- "/news/2052418108837781511",- "/news/2052418482269254040",- "/news/2052426446073983267",- "/news/2052588973466484922",- "/news/2052603250524967045",- "/news/2052685648377913671",- "/news/2052790746256920583",- "/news/2052791935585407403",- "/news/2053025259645981078",- "/news/2053698115203743922",- "/news/2053698387263008827",- "/news/2053730856339144932",- "/news/2053801703355629587",- "/news/2053804700609458214",- "/news/2053832201176027583",- "/news/2054404663802483072",- "/news/2054675701132132736",- "/news/2055140064070717618",- "/news/2055307440921702738",- "/news/2055309846556401735",- "/news/2055310365588922872",- "/news/2055517252964024561",- "/news/2055967730495586477",- "/news/2055985494606106821",- "/news/2056556899403997450",- "/news/2057721370310775223",- "/news/2057780453709648200",- "/news/2057782522994684413",- "/news/2057786164862730704",- "/news/2058076885805085111",- "/news/2058287578227577039",- "/news/2059456289789657537",- "/news/2059456294189498830",- "/news/2059456295825223723",- "/news/2059457822941978723",- "/news/2059675892981633179",- "/news/2059712761622675776",- "/news/2059821472156446844",- "/news/2059894004771418220",- "/news/2060178868305326413",- "/news/2060186881636422038",- "/news/2061418285896269952",- "/news/2061488909264040194",- "/news/2061523804405616642",- "/news/2061713039624405062",- "/news/aws-agentic-economy-three-ws",- "/news/aws-builder-center-3d-agents-onchain-payments",- "/news/aws-builder-center-blog",- "/news/aws-marketplace-live-may29",- "/news/bybit-alpha-listing",- "/news/cmc-mcp-registry-article",- "/news/cmc-memecoin-3d-world",- "/news/ibm-collaboration-showcase",- "/news/ibm-showcase-may31",- "/news/joined-aws-partner-network",- "/news/listed-on-bnb-chain-dappbay",- "/news/live-on-alibaba-cloud-marketplace",- "/news/live-on-aws-marketplace",- "/news/mcp-servers-x402-bazaar-coinbase",- "/news/monetize-mcp-server-x402-paid-tools",- "/news/moonshot-verified",- "/news/partnered-with-hackernoon",- "/news/quicknode-startup-program",- "/news/text-to-3d-is-live",- "/news/three-ws-dextools-social-boost-buyback",- "/news/three-ws-featured-on-alibaba-cloud-marketplace-blog",- "/news/three-ws-first-month-3d-agent-layer",- "/news/threews-play-coin-communities","/nim-forge","/notifications","/nvidia",diff --git a/tests/news-article-api.test.js b/tests/news-article-api.test.jsnew file mode 100644index 000000000..db626b1ab--- /dev/null+++ b/tests/news-article-api.test.js@@ -0,0 +1,149 @@+// Coverage for api/news/article.js — the reader endpoint's input boundary and+// its write into the durable knowledge base.+//+// Two guarantees are load-bearing and both were previously unenforced:+// 1. `url` must be a web link. `new URL()` parses javascript:/file:/data:+// URLs happily, and the extraction ladder then refuses them rung by rung,+// which used to surface as a 200 carrying an empty "Untitled" article.+// 2. Only a story with real extracted body text is recorded to the corpus the+// 3D agents ground on. The endpoint is public and unauthenticated and the+// caller supplies url/title/source, so recording every request turned a+// single GET into a permanent knowledge row with an attacker-chosen+// headline.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('../api/_lib/http.js', () => ({+ wrap: (fn) => fn,+ cors: () => false,+ method: () => true,+ rateLimited: (res) => {+ res._json = { status: 429, body: { error: 'rate_limited' } };+ return res;+ },+ json: (res, status, body, headers = {}) => {+ res._json = { status, body, headers };+ return res;+ },+ error: (res, status, code, message) => {+ res._json = { status, body: { error: code, message } };+ return res;+ },+}));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { marketFeedIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '1.2.3.4',+}));+vi.mock('../api/_lib/llm.js', () => ({+ llmComplete: vi.fn(),+ llmConfigured: vi.fn(() => false),+}));++const extractArticle = vi.fn();+vi.mock('../api/_lib/article-extract.js', () => ({ extractArticle: (...a) => extractArticle(...a) }));++const recordExtraction = vi.fn(async () => {});+const getExtraction = vi.fn(async () => null);+vi.mock('../api/_lib/news-knowledge-store.js', () => ({+ recordExtraction: (...a) => recordExtraction(...a),+ getExtraction: (...a) => getExtraction(...a),+}));++vi.mock('../api/_lib/news-coins.js', () => ({ enrichTickers: vi.fn(async () => []) }));++const findArticle = vi.fn(async () => null);+const getNews = vi.fn(async () => ({ articles: [], total: 0, sources_ok: 1, sources_total: 1 }));+vi.mock('../api/_lib/news.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ findArticle: (...a) => findArticle(...a),+ getNews: (...a) => getNews(...a),+ };+});++const { default: handler } = await import('../api/news/article.js');++function call(url) {+ const res = { setHeader() {}, end() {}, statusCode: 200 };+ return handler({ method: 'GET', url, headers: {} }, res).then(() => res._json);+}++const PARAS = [+ 'Regulated venues took share as oversight tightened across the region this quarter.',+ 'The regulator published its final rulebook on Tuesday after a year of consultation.',+ 'Exchanges that registered early reported the largest inflows of the period.',+];++beforeEach(() => {+ extractArticle.mockReset();+ recordExtraction.mockReset();+ getExtraction.mockReset().mockResolvedValue(null);+ findArticle.mockReset().mockResolvedValue(null);+ getNews.mockReset().mockResolvedValue({ articles: [], total: 0, sources_ok: 1, sources_total: 1 });+});+afterEach(() => vi.clearAllMocks());++describe('url validation', () => {+ it('rejects a missing url', async () => {+ const out = await call('/api/news/article');+ expect(out.status).toBe(400);+ expect(out.body.error).toBe('bad_url');+ });++ it('rejects a relative or unparseable url', async () => {+ const out = await call('/api/news/article?url=notaurl');+ expect(out.status).toBe(400);+ expect(out.body.error).toBe('bad_url');+ });++ for (const scheme of ['javascript:alert(1)', 'file:///etc/passwd', 'data:text/html,hi']) {+ it(`rejects the non-web scheme in ${scheme.split(':')[0]}:`, async () => {+ const out = await call(`/api/news/article?url=${encodeURIComponent(scheme)}`);+ expect(out.status).toBe(400);+ expect(out.body.error).toBe('bad_url');+ // The refusal happens at the boundary — nothing is fetched, nothing+ // reaches the corpus.+ expect(extractArticle).not.toHaveBeenCalled();+ expect(recordExtraction).not.toHaveBeenCalled();+ });+ }++ it('accepts an https article link', async () => {+ extractArticle.mockResolvedValue({ paragraphs: PARAS, extraction: 'page', blocked_reason: null, html: null });+ const out = await call('/api/news/article?url=https%3A%2F%2Fpublisher.example%2Fstory');+ expect(out.status).toBe(200);+ expect(out.body.extraction).toBe('page');+ expect(out.body.paragraphs.length).toBeGreaterThan(0);+ });+});++describe('knowledge-base write gate', () => {+ // A distinct URL per case: the handler keeps a 30-minute in-process cache+ // keyed by URL, and a cache hit short-circuits before the write.+ it('records a story that yielded real body text', async () => {+ extractArticle.mockResolvedValue({ paragraphs: PARAS, extraction: 'page', blocked_reason: null, html: null });+ await call('/api/news/article?url=https%3A%2F%2Fpublisher.example%2Fstory-recorded');+ expect(recordExtraction).toHaveBeenCalledTimes(1);+ expect(recordExtraction.mock.calls[0][0].content_chars).toBeGreaterThan(0);+ });++ it('does not record a zero-content preview, however the caller labels it', async () => {+ extractArticle.mockResolvedValue({+ paragraphs: [],+ extraction: 'preview',+ blocked_reason: 'publisher blocked the fetch',+ html: null,+ });+ const out = await call(+ '/api/news/article?url=https%3A%2F%2Fpublisher.example%2Fblocked&title=Attacker%20chosen%20headline&source=Reuters',+ );+ // The reader still gets an honest preview response...+ expect(out.status).toBe(200);+ expect(out.body.extraction).toBe('preview');+ expect(out.body.blocked_reason).toBe('publisher blocked the fetch');+ expect(out.body.content_chars).toBe(0);+ // ...but nothing enters the corpus the agents ground on.+ expect(recordExtraction).not.toHaveBeenCalled();+ });+});diff --git a/tests/news-curation.test.js b/tests/news-curation.test.jsindex 965e7d370..8978667bc 100644--- a/tests/news-curation.test.js+++ b/tests/news-curation.test.js@@ -57,6 +57,45 @@ describe('isCryptoRelevant', () => {expect(isCryptoRelevant({ source_key: BROAD_KEY, title: 'Inflation cools, stocks rally, GDP revised up' })).toBe(false);});+ // Regression: the lexicon was matched as raw substrings, so "defi" fired+ // inside "defied" and three Economic Times equities headlines led the crypto+ // feed and the daily digest. Every entry here is an ordinary English word+ // that contains a lexicon term but is not about crypto.+ it('does not match a lexicon term buried inside an ordinary word', () => {+ const notCrypto = [+ 'FIIs dumped nearly Rs 1 lakh crore worth of these 10 stocks but 8 defied the selloff',+ 'Budget deficit widens as spending climbs',+ 'The definition of a recession is contested',+ 'Protesters show defiance outside parliament',+ 'Whether the Fed cuts in September is still unclear',+ 'Together, the two firms employ 40,000 people',+ ];+ for (const title of notCrypto) {+ expect(isCryptoRelevant({ source_key: BROAD_KEY, title, tickers: [] })).toBe(false);+ }+ });++ // The other half of the same change: whole-word matching must not start+ // dropping real crypto coverage, including the prefix families and the+ // hyphenated compounds the beat is written in.+ it('still matches whole words, prefix families, plurals, and hyphenated compounds', () => {+ const crypto = [+ 'Cryptocurrency exchange volumes surge',+ 'Cryptoassets draw institutional flows',+ 'Tokenized treasuries pass $5B',+ 'Blockchain-based settlement goes live',+ 'Wallet-to-wallet transfers are now instant',+ 'DAOs vote on a treasury policy',+ 'NFTs return to volume growth',+ 'On-chain volume hits a record',+ 'Tether clears its first KPMG audit',+ 'USDC supply hits a record high',+ ];+ for (const title of crypto) {+ expect(isCryptoRelevant({ source_key: BROAD_KEY, title, tickers: [] })).toBe(true);+ }+ });+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);diff --git a/tests/news-knowledge-api.test.js b/tests/news-knowledge-api.test.jsnew file mode 100644index 000000000..08de86a89--- /dev/null+++ b/tests/news-knowledge-api.test.js@@ -0,0 +1,132 @@+// Coverage for api/news/knowledge.js — the read side of the crypto knowledge+// base the 3D agents ground on.+//+// The guarantee under test: every row served carries real extracted body text.+// The corpus already holds headline-only rows from stories no extraction rung+// could read (paywalls, bot walls, links that were never articles), and those+// are exactly the shape a drive-by write leaves behind. They ground nothing, so+// the endpoint filters them out on the way out rather than waiting for the+// corpus to be rewritten.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('../api/_lib/http.js', () => ({+ wrap: (fn) => fn,+ cors: () => false,+ method: () => true,+ rateLimited: (res) => {+ res._json = { status: 429, body: { error: 'rate_limited' } };+ return res;+ },+ json: (res, status, body, headers = {}) => {+ res._json = { status, body, headers };+ return res;+ },+ error: (res, status, code, message) => {+ res._json = { status, body: { error: code, message } };+ return res;+ },+}));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { marketFeedIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '1.2.3.4',+}));++const getExtraction = vi.fn(async () => null);+const queryKnowledge = vi.fn(async () => []);+const knowledgeStats = vi.fn(async () => ({ total: 2, full_text: 1, enabled: true }));+vi.mock('../api/_lib/news-knowledge-store.js', () => ({+ getExtraction: (...a) => getExtraction(...a),+ queryKnowledge: (...a) => queryKnowledge(...a),+ knowledgeStats: (...a) => knowledgeStats(...a),+}));++const { default: handler } = await import('../api/news/knowledge.js');++function call(url = '/api/news/knowledge') {+ const res = { setHeader() {}, end() {}, statusCode: 200 };+ return handler({ method: 'GET', url, headers: {} }, res).then(() => res._json);+}++const SUBSTANTIVE = {+ id: '1111111111111111',+ url: 'https://publisher.example/real-story',+ title: 'Regulated exchanges gain ground as oversight tightens',+ source: 'The Block',+ extraction: 'page',+ content_chars: 4200,+ summary: 'Oversight tightened and regulated venues took share.',+ tickers: ['BTC'],+ paragraphs: ['Regulated venues took share as oversight tightened across the region.'],+};++const HOLLOW = {+ id: '2222222222222222',+ url: 'https://publisher.example/blocked-story',+ title: 'Three Airports Plan to Ditch T.S.A.',+ source: 'Some Wire',+ extraction: 'preview',+ content_chars: 0,+ summary: 'Three Airports Plan to Ditch T.S.A.',+ tickers: [],+};++beforeEach(() => {+ getExtraction.mockReset().mockResolvedValue(null);+ queryKnowledge.mockReset().mockResolvedValue([]);+ knowledgeStats.mockReset().mockResolvedValue({ total: 2, full_text: 1, enabled: true });+});+afterEach(() => vi.clearAllMocks());++describe('input validation', () => {+ it('rejects an id that is not a 16-hex article id', async () => {+ const out = await call('/api/news/knowledge?id=zzz');+ expect(out.status).toBe(400);+ expect(out.body.error).toBe('bad_id');+ expect(getExtraction).not.toHaveBeenCalled();+ });++ it('rejects a ticker that is not a symbol', async () => {+ const out = await call('/api/news/knowledge?ticker=not%20a%20symbol');+ expect(out.status).toBe(400);+ expect(out.body.error).toBe('bad_ticker');+ });++ it('rejects an over-long free-text query', async () => {+ const out = await call(`/api/news/knowledge?q=${'a'.repeat(200)}`);+ expect(out.status).toBe(400);+ expect(out.body.error).toBe('bad_query');+ });+});++describe('body-text guarantee', () => {+ it('serves a record that carries extracted body text', async () => {+ getExtraction.mockResolvedValue(SUBSTANTIVE);+ const out = await call(`/api/news/knowledge?id=${SUBSTANTIVE.id}`);+ expect(out.status).toBe(200);+ expect(out.body.id).toBe(SUBSTANTIVE.id);+ expect(out.body.full_text_url).toBe(SUBSTANTIVE.url);+ });++ it('answers 404 for a stored row with no extracted body', async () => {+ getExtraction.mockResolvedValue(HOLLOW);+ const out = await call(`/api/news/knowledge?id=${HOLLOW.id}`);+ expect(out.status).toBe(404);+ expect(out.body.error).toBe('not_found');+ });++ it('drops zero-content rows from the listing', async () => {+ queryKnowledge.mockResolvedValue([SUBSTANTIVE, HOLLOW]);+ const out = await call('/api/news/knowledge?limit=10');+ expect(out.status).toBe(200);+ expect(out.body.articles.map((a) => a.id)).toEqual([SUBSTANTIVE.id]);+ });++ it('drops zero-content rows from a ticker query too', async () => {+ queryKnowledge.mockResolvedValue([HOLLOW, HOLLOW]);+ const out = await call('/api/news/knowledge?ticker=BTC');+ expect(out.status).toBe(200);+ expect(out.body.articles).toEqual([]);+ expect(out.body.query.ticker).toBe('BTC');+ });+});diff --git a/tests/news-lib.test.js b/tests/news-lib.test.jsindex 0dd6c013b..1be618d91 100644--- a/tests/news-lib.test.js+++ b/tests/news-lib.test.js@@ -117,6 +117,34 @@ describe('enrichment', () => {);});+ // Regression: three project names are also ordinary English words, and the+ // bare wordlist tagged the word rather than the coin. "near-term profit+ // booking" became NEAR Protocol (enough hits to rank NEAR third in the+ // archive's trending strip), "cautious optimism" became OP, and a market+ // maker became MKR. A false ticker pins a price widget to an unrelated story+ // and lets it through the crypto display gate, so these three now need the+ // project named.+ it('does not read the English words near, optimism, and maker as tickers', () => {+ for (const text of [+ 'Gold falls as analysts expect near-term profit booking',+ 'Shares near a record high on Wall Street',+ 'Cautious optimism returns to markets before the Fed',+ 'Market maker liquidity thinned overnight',+ 'Policy makers weigh a rate cut',+ ]) {+ expect(extractTickers(text)).toEqual([]);+ }+ });++ it('still detects those three when the project is actually named', () => {+ expect(extractTickers('NEAR Protocol rallies 12% on new validators')).toContain('NEAR');+ expect(extractTickers('MakerDAO votes to raise the stability fee')).toContain('MKR');+ expect(extractTickers('OP Mainnet sequencer revenue climbs')).toContain('OP');+ expect(extractTickers('$NEAR and $OP lead layer-1 gains')).toEqual(+ expect.arrayContaining(['NEAR', 'OP']),+ );+ });+it('scores clearly positive and negative headlines apart', () => {const pos = lexiconSentiment('Bitcoin surges to all-time high after ETF approval');const neg = lexiconSentiment('Exchange hacked, funds stolen in $40M exploit');