signaltrail / tree / src/agent.js · raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
// SignalTrail agent: posts -> InjectScan -> extraction -> narrative convergence -> TokenVerdict + price -> bull/bear/judge -> signed receipt.
// Practice (paper) trading only: there is no wallet, key, exchange or swap code anywhere in this project.
import { canonicalize, seal, sha256hex, verifyReceipt } from './receipt.js';
import { extract, RULES_VERSION } from './extract.js';
import { narratives } from './narrative.js';
import { judge, exitCheck } from './judge.js';
import { injectScan, tokenVerdict, price } from './screens.js';
const SCAN_TTL_MS = 7 * 24 * 3600 * 1000;
// InjectScan every post. Results are cached by sha256(text). After a 429 we stop calling (free tier: 10 requests/min per IP)
// and exclude the remaining posts, fail-closed, instead of hammering the API or routing around the limit.
async function screenPosts(d, posts) {
  let limited = null;
  return mapLimit(posts, d.scanConcurrency ?? 3, async (p) => {
    const key = 'injectscan:' + (await sha256hex(p.text.slice(0, 1500)));
    const hit = d.store.cacheGet ? await d.store.cacheGet(key) : null;
    if (hit && Date.parse(d.now()) - Date.parse(hit.scanned_at) < SCAN_TTL_MS) return { p, scan: { ...hit, cached: true } };
    if (limited) return { p, scan: { tool: 'InjectScan', status: 'error', error: `free-tier rate limit hit earlier in this run (HTTP ${limited}); not called`, flagged: null, skipped: true } };
    const scan = await injectScan({ ...d, retries: 1 }, p.text);
    if (scan.status === 'ok') { scan.scanned_at = d.now().toISOString(); if (d.store.cachePut) await d.store.cachePut(key, scan); }
    else if (scan.http_status === 429) limited = 429;
    return { p, scan };
  });
}
async function mapLimit(items, n, fn) { const out = new Array(items.length); let i = 0; await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => { while (i < items.length) { const k = i++; out[k] = await fn(items[k]); } })); return out; }
export const VERSION = 'signaltrail-0.1.0';
export const DISCLAIMER = 'Practice (paper) trading record for research and education. Not financial advice, not a recommendation to buy or sell anything, and no real funds are traded. Creator posts in the demo dataset are fictional personas.';

export function validateConfig(c) {
  const e = [];
  if (!Array.isArray(c.creators) || !c.creators.length) e.push('creators: at least one');
  if (c.creators?.length > 20) e.push('creators: at most 20 user-selected voices');
  for (const k of ['max_position_usd', 'max_position_pct', 'max_open_positions', 'stop_loss_pct', 'take_profit_pct', 'min_liquidity_usd', 'max_hold_hours']) if (!(Number(c.risk?.[k]) >= 0)) e.push(`risk.${k} must be a number ≥ 0`);
  if (c.risk?.max_position_pct > 25) e.push('risk.max_position_pct must be ≤ 25');
  return e;
}

async function appendSealed(d, body) {
  for (let i = 0; i < 5; i++) {
    const head = (await d.store.head()) || { seq: 0, hash: null };
    const r = await seal({ ...body, chain: { seq: head.seq + 1, prev_hash: head.hash } }, d.signer);
    if (await d.store.append(r)) return r;
  }
  throw Object.assign(new Error('ledger_busy'), { status: 503 });
}

export function portfolioFrom(receipts, startUsd) {
  const open = new Map(); let cash = startUsd, realized = 0;
  for (const r of receipts) {
    if (r.type === 'decision' && r.decision.action === 'OPEN_PRACTICE_LONG') { open.set(r.decision.symbol, { ...r.decision.position, symbol: r.decision.symbol, address: r.evidence.narrative.address, opened_at: r.issued_at, open_receipt: r.receipt_id }); cash -= r.decision.position.size_usd; }
    if (r.type === 'exit' && open.has(r.symbol)) { const p = open.get(r.symbol); cash += r.exit.proceeds_usd; realized += r.exit.pnl_usd; open.delete(r.symbol); }
  }
  const pos = [...open.values()];
  const cost = pos.reduce((s, p) => s + p.size_usd, 0);
  return { start_usd: startUsd, cash_usd: Math.round(cash * 100) / 100, realized_pnl_usd: Math.round(realized * 100) / 100, open: pos, open_symbols: pos.map((p) => p.symbol), open_count: pos.length, equity_usd: Math.round((cash + cost) * 100) / 100 };
}

const BOOK_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
export const bookOf = (r) => r.book || 'demo';
export function checkBook(book) { if (!BOOK_RE.test(book)) throw Object.assign(new Error('book: 1-40 chars of a-z, 0-9, -'), { status: 400 }); return book; }
export async function run(d, { posts, config, registry, source_note, book = 'demo' }) {
  checkBook(book);
  const errs = validateConfig(config); if (errs.length) throw Object.assign(new Error(errs.join('; ')), { status: 400 });
  if (!Array.isArray(posts) || !posts.length || posts.length > 60) throw Object.assign(new Error('posts: 1 to 60 required'), { status: 400 });
  const now = d.now().toISOString();
  const run_id = crypto.randomUUID();
  // 1. every post is screened for prompt injection before the agent reads it
  const scanned = await screenPosts(d, posts);
  const excluded = scanned.filter((x) => x.scan.status !== 'ok' || x.scan.flagged).map((x) => ({ post_id: x.p.id, author: x.p.author, mentions: extract(x.p, registry).tokens.map((t) => t.symbol), reason: x.scan.status !== 'ok' ? `InjectScan unavailable (${x.scan.error}): excluded, fail-closed` : `InjectScan ${x.scan.verdict} (risk ${x.scan.risk_score}; ${x.scan.categories.join(', ')})`, text_excerpt: x.p.text.slice(0, 140) }));
  const clean = scanned.filter((x) => x.scan.status === 'ok' && !x.scan.flagged).map((x) => x.p);
  // 2. deterministic extraction + convergence
  const extracted = clean.map((p) => extract(p, registry));
  const cands = narratives(extracted, config.creators, config.signal, now);
  const config_sha256 = await sha256hex(canonicalize(config));
  const results = [];
  let receipts = await d.store.list();
  for (const n of cands) {
    if (results.length >= (config.max_candidates || 8)) break;
    const portfolio = portfolioFrom(receipts.filter((r) => bookOf(r) === book), config.risk.paper_start_usd);
    // 3. screens only for candidates that could trade (saves calls); others are recorded as skipped without a screen
    const screen = n.converged ? await tokenVerdict(d, n.address) : { status: 'not_run', error: 'not needed: no convergence' };
    const px = n.converged && screen.status === 'ok' ? await price(d, n.address) : { status: 'not_run', error: 'not needed' };
    const relPosts = posts.filter((p) => n.post_ids.includes(p.id)).map((p) => ({ id: p.id, author: p.author, source: p.source || 'x', ts: p.ts, url: p.url || null, text: p.text }));
    const relExtract = extracted.filter((e) => n.post_ids.includes(e.post_id));
    const registry_entries = registry.filter((x) => relExtract.some((e) => e.tokens.some((t) => t.symbol === x.symbol)));
    const evidence = { narrative: n, posts: relPosts, registry_entries, signals: relExtract, screen, price: px, portfolio: { equity_usd: portfolio.equity_usd, cash_usd: portfolio.cash_usd, open_symbols: portfolio.open_symbols, open_count: portfolio.open_count }, excluded_posts: excluded };
    const decision = judge(evidence, config.risk);
    const r = await appendSealed(d, {
      receipt_version: '1', type: 'decision', receipt_id: crypto.randomUUID(), run_id, issued_at: now,
      issuer: { service: 'SignalTrail', version: VERSION, url: d.issuer?.url || null },
      mode: 'practice', book, rules_version: RULES_VERSION, data_source: source_note || 'user-supplied posts',
      config: { sha256: config_sha256, risk: config.risk, signal: config.signal, creators: config.creators },
      evidence, decision, disclaimer: DISCLAIMER,
    });
    receipts.push(r);
    results.push(r);
  }
  return { run_id, book, at: now, posts: posts.length, excluded_posts: excluded, candidates: cands.length, decisions: results };
}

// Mark open practice positions to market and close any that hit stop / target / max hold (writes exit receipts).
export async function review(d, config, book = 'demo') {
  checkBook(book);
  const receipts = (await d.store.list()).filter((r) => bookOf(r) === book);
  const pf = portfolioFrom(receipts, config.risk.paper_start_usd);
  const now = d.now().toISOString(); const out = [];
  for (const p of pf.open) {
    const px = await price(d, p.address);
    if (px.status !== 'ok') { out.push({ symbol: p.symbol, status: 'no_price', note: 'kept open; no exit without a price' }); continue; }
    const x = exitCheck(p, px.price_usd, now);
    const value = Math.round(p.qty * px.price_usd * 100) / 100;
    if (!x.exit) { out.push({ symbol: p.symbol, status: 'open', mark_usd: px.price_usd, value_usd: value, pnl_usd: Math.round((value - p.size_usd) * 100) / 100, rule: x.reason }); continue; }
    const r = await appendSealed(d, { receipt_version: '1', type: 'exit', receipt_id: crypto.randomUUID(), issued_at: now, issuer: { service: 'SignalTrail', version: VERSION, url: d.issuer?.url || null }, mode: 'practice', book, symbol: p.symbol, open_receipt: p.open_receipt, price: px, exit: { rule: x.reason, exit_price_usd: px.price_usd, proceeds_usd: value, pnl_usd: Math.round((value - p.size_usd) * 100) / 100 }, disclaimer: DISCLAIMER });
    out.push({ symbol: p.symbol, status: 'closed', receipt: r.receipt_id, ...r.exit });
  }
  return { at: now, book, positions: out };
}

// Replay: re-run the judge on the receipt's own recorded evidence and check it reproduces the recorded decision.
export async function replay(receipt, publicJwk) {
  const v = await verifyReceipt(receipt, publicJwk);
  if (receipt?.type !== 'decision') return { ...v, reproducible: null, reason: v.reason || 'only decision receipts can be replayed' };
  const ev = receipt.evidence, cfg = receipt.config;
  // 1. signals: re-extract every recorded post with the recorded registry entries
  const signals = ev.posts.map((p) => extract(p, ev.registry_entries || []));
  const signalsSame = canonicalize(signals) === canonicalize(ev.signals);
  // 2. convergence: recompute the narrative for this token at the receipt's time
  const n = narratives(signals, cfg.creators, cfg.signal, receipt.issued_at).find((x) => x.symbol === ev.narrative.symbol);
  const narrativeSame = canonicalize(n) === canonicalize(ev.narrative);
  // 3. decision: bull / bear / judge on the recorded screens, price and portfolio
  const again = judge({ ...ev, narrative: n || ev.narrative }, cfg.risk);
  const decisionSame = canonicalize(again) === canonicalize(receipt.decision);
  return { signature_valid: v.valid, signature_reason: v.reason, reproducible: signalsSame && narrativeSame && decisionSame, steps: { signals: signalsSame, narrative: narrativeSame, decision: decisionSame }, recorded: receipt.decision.verdict, replayed: again.verdict, rules_version: receipt.rules_version };
}

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