signaltrail / tree / test/agent.test.js ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { extract } from '../src/extract.js';
import { narratives } from '../src/narrative.js';
import { run, review, replay, portfolioFrom, validateConfig } from '../src/agent.js';
import { verifyChain, verifyReceipt } from '../src/receipt.js';
import { deps, posts, config, registry, NOW } from './helpers.js';
const R = registry.tokens;
const bySym = (out) => Object.fromEntries(out.decisions.map((r) => [r.decision.symbol, r]));

test('extract: cashtag, contract address, name, sentiment with negation, conviction, urgency', () => {
  const e = extract({ id: 'x', author: '@a', ts: NOW.toISOString(), text: 'Aerodrome is not weak. High conviction, adding more on 0x0b3e328455c4059eeb9e3f84b5543f74e24e7e1b now!!!' }, R);
  assert.deepEqual(e.tokens.map((t) => t.symbol).sort(), ['AERO', 'VIRTUAL']);
  assert.equal(e.sentiment.label, 'bullish');
  assert.ok(e.sentiment.bull_terms.includes('not weak'));
  assert.ok(e.conviction.score >= 0.7 && e.urgency.score >= 0.5);
  const b = extract({ id: 'y', author: '@a', ts: NOW.toISOString(), text: 'Careful with $DEGEN, bearish, weak.' }, R);
  assert.equal(b.sentiment.label, 'bearish');
});
test('extract is deterministic', () => {
  const p = posts()[6];
  assert.deepEqual(extract(p, R), extract(p, R));
});
test('narratives: AERO converges, DEGEN split, BRETT single voice (old post outside window), untracked TOSHI ignored', () => {
  const ex = posts().map((p) => extract(p, R));
  const n = Object.fromEntries(narratives(ex, config.creators, config.signal, NOW.toISOString()).map((x) => [x.symbol, x]));
  assert.equal(n.AERO.converged, true); assert.equal(n.AERO.voices.bullish.length, 4); assert.equal(n.AERO.narrative, 'base-defi');
  assert.equal(n.DEGEN.converged, false); assert.equal(n.DEGEN.voices.bearish.length, 2);
  assert.equal(n.BRETT.converged, false); assert.equal(n.BRETT.voices.bullish.length, 1);
  assert.equal(n.TOSHI, undefined);
  assert.equal(n.VIRTUAL.narrative, 'ai-agents');
});
test('run: injection post excluded; AERO + VIRTUAL practice longs; AYB honeypot vetoed; DEGEN/BRETT skipped', async () => {
  const { d } = await deps();
  const out = await run(d, { posts: posts(), config, registry: R });
  assert.deepEqual(out.excluded_posts.map((x) => x.post_id), ['p16']);
  const s = bySym(out);
  assert.equal(s.AERO.decision.action, 'OPEN_PRACTICE_LONG');
  assert.equal(s.VIRTUAL.decision.action, 'OPEN_PRACTICE_LONG');
  assert.equal(s.AYB.decision.action, 'SKIP');
  assert.ok(s.AYB.decision.vetoes.some((v) => v.startsWith('token_unsafe')) && s.AYB.decision.vetoes.some((v) => v.startsWith('not_sellable')));
  assert.equal(s.AYB.evidence.narrative.converged, true, 'the hype did converge; the safety screen is what stopped it');
  assert.equal(s.DEGEN.decision.action, 'SKIP'); assert.ok(s.DEGEN.decision.vetoes[0].startsWith('no_convergence'));
  assert.equal(s.BRETT.decision.action, 'SKIP');
  const p = s.AERO.decision.position;
  assert.ok(p.size_usd <= 1000 && p.size_usd > 0); assert.equal(p.entry_price_usd, 1.25);
  assert.equal(p.stop_price_usd, 1.1); assert.equal(p.take_profit_price_usd, 1.5625);
  assert.equal(s.AERO.evidence.price.price_usd, 1.25, 'Base pair chosen, not the deeper Ethereum pair');
  assert.ok(s.AERO.decision.position.size_usd <= s.AERO.evidence.portfolio.cash_usd);
});
test('every decision is signed, chained and replays to the same result (signals, narrative, decision)', async () => {
  const { d } = await deps();
  const out = await run(d, { posts: posts(), config, registry: R });
  assert.deepEqual(await verifyChain(d.store.list(), d.signer.publicJwk), { valid: true, count: out.decisions.length });
  for (const r of out.decisions) {
    const x = await replay(r, d.signer.publicJwk);
    assert.equal(x.signature_valid, true); assert.equal(x.reproducible, true, r.decision.symbol + JSON.stringify(x.steps));
  }
});
test('tampering: editing the AYB screen to SAFE breaks the signature, and the replayed decision differs from the recorded one', async () => {
  const { d } = await deps();
  const r = bySym(await run(d, { posts: posts(), config, registry: R })).AYB;
  const forged = structuredClone(r); forged.evidence.screen.result.verdict = 'SAFE';
  assert.equal((await verifyReceipt(forged, d.signer.publicJwk)).valid, false);
  const x = await replay(forged, d.signer.publicJwk);
  assert.equal(x.signature_valid, false); assert.equal(x.reproducible, false);
});
test('fail-closed: TokenVerdict down => no practice trade', async () => {
  const { d } = await deps({ tokenverdict: 'throw' });
  const out = await run(d, { posts: posts(), config, registry: R });
  assert.ok(out.decisions.every((r) => r.decision.action === 'SKIP'));
  assert.ok(bySym(out).AERO.decision.vetoes.some((v) => v.startsWith('screen_unavailable')));
});
test('fail-closed: TokenVerdict 500 / price feed down => SKIP', async () => {
  let { d } = await deps({ tokenverdict: 500 });
  assert.ok((await run(d, { posts: posts(), config, registry: R })).decisions.every((r) => r.decision.action === 'SKIP'));
  ({ d } = await deps({ dex: 'throw', gecko: 503 }));
  const s = bySym(await run(d, { posts: posts(), config, registry: R }));
  assert.ok(s.AERO.decision.vetoes.some((v) => v.startsWith('no_price')));
});
test('price fallback: DexScreener 429 => GeckoTerminal price, fallback recorded in evidence', async () => {
  const { d } = await deps({ dex: 429 });
  const s = bySym(await run(d, { posts: posts(), config, registry: R }));
  assert.equal(s.AERO.decision.action, 'OPEN_PRACTICE_LONG');
  assert.equal(s.AERO.evidence.price.source, 'GeckoTerminal');
  assert.match(s.AERO.evidence.price.fallback_from.error, /429/);
});
test('InjectScan free-tier limit respected: stop calling after 429, exclude the rest (fail-closed), then cache', async () => {
  const { d, calls } = await deps({ injectscanFlaky: { n: 1 } }, { scanConcurrency: 1 });
  const out = await run(d, { posts: posts(), config, registry: R });
  assert.equal(calls.filter((c) => c.startsWith('/injectscan/')).length, 1, 'no calls after the 429');
  assert.equal(out.excluded_posts.length, posts().length);
  assert.ok(out.decisions.every((r) => r.decision.action === 'SKIP'));
  // limit clears: next run scans everything once, the one after is served from the cache
  const before = calls.length; d.now = () => new Date(Date.parse('2026-10-22T18:00:00Z') + 0);
  const out2 = await run(d, { posts: posts(), config, registry: R });
  assert.equal(out2.excluded_posts.length, 1);
  const n2 = calls.slice(before).filter((c) => c.startsWith('/injectscan/')).length; assert.equal(n2, posts().length);
  const before3 = calls.length; await run(d, { posts: posts(), config, registry: R });
  assert.equal(calls.slice(before3).filter((c) => c.startsWith('/injectscan/')).length, 0, 'served from cache');
});
test('fail-closed: InjectScan unreachable => every post excluded, nothing traded', async () => {
  const { d } = await deps({ injectscan: 'throw' });
  const out = await run(d, { posts: posts(), config, registry: R });
  assert.equal(out.excluded_posts.length, posts().length);
  assert.equal(out.decisions.length, 0);
});
test('risk limits: second run does not double up (already_open); max_open_positions respected', async () => {
  const { d } = await deps();
  await run(d, { posts: posts(), config, registry: R });
  const s = bySym(await run(d, { posts: posts(), config, registry: R }));
  assert.ok(s.AERO.decision.vetoes.some((v) => v.startsWith('already_open')));
  const { d: d2 } = await deps();
  const one = { ...config, risk: { ...config.risk, max_open_positions: 1 } };
  const out = await run(d2, { posts: posts(), config: one, registry: R });
  assert.equal(out.decisions.filter((r) => r.decision.action === 'OPEN_PRACTICE_LONG').length, 1);
  assert.ok(bySym(out).VIRTUAL.decision.vetoes.some((v) => v.startsWith('max_open_positions')));
});
test('FOMO rule: high average urgency halves the size', async () => {
  const { d } = await deps();
  const hype = posts().map((p) => (['p01', 'p02', 'p03', 'p04'].includes(p.id) ? { ...p, text: p.text + ' NOW!!! last chance, hurry, today!!!' } : p));
  const a = bySym(await run(d, { posts: hype, config, registry: R })).AERO;
  assert.ok(a.decision.bear_case.some((x) => x.includes('hype pattern')));
  const { d: d2 } = await deps();
  const b = bySym(await run(d2, { posts: posts(), config, registry: R })).AERO;
  assert.ok(a.decision.position.size_usd < b.decision.position.size_usd);
});
test('review: stop-loss closes the practice position and writes an exit receipt', async () => {
  const { d } = await deps();
  await run(d, { posts: posts(), config, registry: R });
  d.fetch = (await deps({ price: (a) => (a.startsWith('0x9401') ? 1.0 : 0.82) })).d.fetch;
  const out = await review(d, config);
  const aero = out.positions.find((p) => p.symbol === 'AERO');
  assert.equal(aero.status, 'closed'); assert.ok(aero.rule.startsWith('stop')); assert.ok(aero.pnl_usd < 0);
  assert.equal(out.positions.find((p) => p.symbol === 'VIRTUAL').status, 'open');
  const pf = portfolioFrom(d.store.list(), 10000);
  assert.deepEqual(pf.open_symbols, ['VIRTUAL']);
  assert.ok((await verifyChain(d.store.list(), d.signer.publicJwk)).valid);
});
test('config validation: max 20 creators, position pct cap', () => {
  const many = Array.from({ length: 21 }, (_, i) => ({ handle: '@c' + i, weight: 1 }));
  assert.ok(validateConfig({ ...config, creators: many }).some((e) => e.includes('at most 20')));
  assert.ok(validateConfig({ ...config, risk: { ...config.risk, max_position_pct: 50 } }).length);
  assert.deepEqual(validateConfig(config), []);
});
test('receipts carry the practice-only disclaimer and no wallet/exchange fields', async () => {
  const { d } = await deps();
  const out = await run(d, { posts: posts(), config, registry: R });
  for (const r of out.decisions) { assert.equal(r.mode, 'practice'); assert.match(r.disclaimer, /Not financial advice/); assert.doesNotMatch(JSON.stringify(r), /private_key|wallet_key|exchange_api/i); }
});
test('books: separate practice portfolios; price quotes cached within TTL', async () => {
  const { d, calls } = await deps({}, { priceTtlMs: 60000 });
  const a = bySym(await run(d, { posts: posts(), config, registry: R, book: 'demo' }));
  assert.equal(a.AERO.decision.action, 'OPEN_PRACTICE_LONG'); assert.equal(a.AERO.book, 'demo');
  const b = bySym(await run(d, { posts: posts(), config, registry: R, book: 'judge-1' }));
  assert.equal(b.AERO.decision.action, 'OPEN_PRACTICE_LONG', 'fresh book is not blocked by demo positions');
  assert.equal(b.AERO.evidence.price.cached, true);
  assert.equal(calls.filter((c) => c.startsWith('/latest/dex/tokens/0x9401')).length, 1, 'one live quote served both runs');
  const c = bySym(await run(d, { posts: posts(), config, registry: R, book: 'demo' }));
  assert.ok(c.AERO.decision.vetoes.some((v) => v.startsWith('already_open')));
  await assert.rejects(run(d, { posts: posts(), config, registry: R, book: 'Bad Book!' }), /book/);
});

agentgate-source: code mirror on Cloudflare Pages. All repos