signaltrail / tree / src/app.js ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
import { run, review, replay, portfolioFrom, bookOf, checkBook, VERSION, DISCLAIMER } from './agent.js';
import { verifyReceipt, verifyChain } from './receipt.js';
import { price } from './screens.js';
import { DASHBOARD } from './dashboard.js';
const CORS = { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS', 'access-control-allow-headers': 'content-type' };
const json = (o, status = 200) => new Response(JSON.stringify(o, null, 2), { status, headers: { 'content-type': 'application/json; charset=utf-8', ...CORS } });

export function materialize(dataset, now) {
  return dataset.posts.map((p) => ({ id: p.id, author: p.author, source: p.source || 'x', url: p.url || null, text: p.text, ts: p.ts || new Date(now.getTime() - p.ago_hours * 3600e3).toISOString() }));
}

// d: {fetch, signer, store, base, now, issuer, dataset, config, registry, runThrottleMs}
export async function handle(req, d) {
  const url = new URL(req.url); const path = url.pathname.replace(/\/+$/, '') || '/';
  if (req.method === 'OPTIONS') return new Response(null, { headers: CORS });
  try {
    if (path === '/' && req.method === 'GET') return new Response(DASHBOARD, { headers: { 'content-type': 'text/html; charset=utf-8' } });
    if (path === '/v1' || path === '/v1/info') return json({ service: 'SignalTrail', version: VERSION, what: 'Multi-KOL narrative agent: reads posts from up to 20 user-selected creators, screens them for prompt injection, detects when trusted voices converge on a token, screens the token for honeypot / owner-power risk, and records the PRACTICE trade it would make in a signed, hash-chained, replayable reasoning trail.', practice_only: true, endpoints: { 'POST /v1/run': 'run the agent on {posts?, config?, book?} (default: the recorded demo dataset, book "demo"); a book is a separate practice portfolio', 'GET /v1/trail?limit=': 'recent receipts', 'GET /v1/receipt/{seq}': 'one receipt', 'GET /v1/replay/{seq}': 're-run a decision from its recorded evidence', 'POST /v1/replay': 'same, body: receipt', 'GET /v1/portfolio?book=': 'practice portfolio marked to market', 'POST /v1/review': 'apply stop / target / max-hold exits', 'POST /v1/verify': 'verify a receipt', 'GET /v1/ledger/verify': 'verify the whole chain', 'GET /v1/config': 'default creators + signal rules + risk limits', 'GET /v1/dataset': 'demo dataset', 'GET /v1/pubkey': 'public key' }, disclaimer: DISCLAIMER });
    if (path === '/v1/pubkey') return json(d.signer.publicJwk);
    if (path === '/v1/config') return json(d.config);
    if (path === '/v1/dataset') return json(d.dataset);
    if (path === '/v1/run' && req.method === 'POST') {
      const body = await req.json().catch(() => ({}));
      if (d.store.claimRun && !(await d.store.claimRun(d.runThrottleMs ?? 30000))) return json({ error: 'busy', detail: 'one run per 30 seconds on the public demo' }, 429);
      const now = d.now();
      const custom = Array.isArray(body.posts);
      const posts = custom ? body.posts.map((p, i) => ({ id: String(p.id || `u${i + 1}`), author: String(p.author || ''), source: p.source || 'manual', url: p.url || null, text: String(p.text || '').slice(0, 1500), ts: p.ts || now.toISOString() })) : materialize(d.dataset, now);
      const config = body.config ? { ...d.config, ...body.config, signal: { ...d.config.signal, ...(body.config.signal || {}) }, risk: { ...d.config.risk, ...(body.config.risk || {}) } } : d.config;
      const out = await run(d, { posts, config, registry: d.registry.tokens, source_note: custom ? 'user-supplied posts (POST /v1/run)' : d.dataset.source_note, book: body.book ?? 'demo' });
      return json({ ...out, decisions: out.decisions.map((r) => ({ seq: r.chain.seq, receipt_id: r.receipt_id, symbol: r.decision.symbol, action: r.decision.action, verdict: r.decision.verdict, narrative: r.evidence.narrative.narrative, voices: r.evidence.narrative.voices, bull_case: r.decision.bull_case, bear_case: r.decision.bear_case, vetoes: r.decision.vetoes, position: r.decision.position, hash: r.integrity.hash })) });
    }
    if (path === '/v1/trail') { const all = await d.store.list(); const n = Math.min(100, Number(url.searchParams.get('limit')) || 20); return json({ count: all.length, receipts: all.slice(-n).reverse() }); }
    let m;
    if ((m = path.match(/^\/v1\/receipt\/(\d+)$/))) { const r = (await d.store.list()).find((x) => x.chain.seq === Number(m[1])); return r ? json(r) : json({ error: 'not_found' }, 404); }
    if ((m = path.match(/^\/v1\/replay\/(\d+)$/))) { const r = (await d.store.list()).find((x) => x.chain.seq === Number(m[1])); return r ? json({ seq: r.chain.seq, ...(await replay(r, d.signer.publicJwk)) }) : json({ error: 'not_found' }, 404); }
    if (path === '/v1/replay' && req.method === 'POST') return json(await replay(await req.json(), d.signer.publicJwk));
    if (path === '/v1/verify' && req.method === 'POST') return json(await verifyReceipt(await req.json(), d.signer.publicJwk));
    if (path === '/v1/ledger/verify') return json(await verifyChain(await d.store.list(), d.signer.publicJwk));
    if (path === '/v1/portfolio') {
      const book = checkBook(url.searchParams.get('book') || 'demo');
      const pf = portfolioFrom((await d.store.list()).filter((r) => bookOf(r) === book), d.config.risk.paper_start_usd);
      const marks = await Promise.all(pf.open.map(async (p) => { const px = await price(d, p.address); const v = px.status === 'ok' ? Math.round(p.qty * px.price_usd * 100) / 100 : null; return { symbol: p.symbol, size_usd: p.size_usd, entry_price_usd: p.entry_price_usd, mark_price_usd: px.price_usd ?? null, value_usd: v, unrealized_pnl_usd: v == null ? null : Math.round((v - p.size_usd) * 100) / 100, stop_price_usd: p.stop_price_usd, take_profit_price_usd: p.take_profit_price_usd, opened_at: p.opened_at }; }));
      const mtm = marks.reduce((s, x) => s + (x.value_usd ?? x.size_usd), 0);
      return json({ practice_only: true, book, start_usd: pf.start_usd, cash_usd: pf.cash_usd, realized_pnl_usd: pf.realized_pnl_usd, positions: marks, equity_marked_usd: Math.round((pf.cash_usd + mtm) * 100) / 100, price_source: 'DexScreener public API (deepest Base pair), GeckoTerminal fallback; quotes cached 60 s', disclaimer: DISCLAIMER });
    }
    if (path === '/v1/review' && req.method === 'POST') { const b = await req.json().catch(() => ({})); return json(await review(d, d.config, b.book ?? 'demo')); }
    return json({ error: 'not_found' }, 404);
  } catch (e) { return json({ error: e.status ? e.message : 'internal_error', detail: e.status ? undefined : String(e.message || e) }, e.status || 500); }
}

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