Files

299 lines
25 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Report writer + fact gate. One OpenRouter call per report (one retry when the fact check fails).
// Free check: DeepSeek v4.1 Flash, short scorecard. Deep report: Opus 5.5, the full shape from the cost test (D:/tmp/wwi-cost/run.py).
// HARD RULE (Marty): nothing invented. Every address, tx hash and number in the written report must be in the evidence (or plain
// arithmetic of evidence numbers). A report that fails twice is not shown: the deterministic facts are shown instead, with a note.
// Scores, grade and verdict are OPINION (our rubric applied to the public facts); findings are facts with tags and sources.
'use strict';
const fs = require('fs');
const path = require('path');
const RUBRIC = fs.readFileSync(path.join(__dirname, 'chain', 'rubric.md'), 'utf8');
const MODELS = { free: process.env.FREE_MODEL || 'deepseek/deepseek-v4.1-flash', deep: process.env.DEEP_MODEL || 'anthropic/claude-opus-5.5' };
const CATS = [
['control', 'Control and upgradeability', 25], ['custody', 'Custody and exit paths', 25], ['economics', 'Economic design', 20],
['insiders', 'Insider flows', 15], ['disclosure', 'Disclosure vs code', 10], ['trajectory', 'Trajectory', 5]];
const BANNED = [[/\bscam(s|med|mer|mers)?\b/gi, 'high-risk scheme'], [/\bponzi\b/gi, 'recruitment-funded'], [/\brug[ -]?pull(s|ed|ing)?\b/gi, 'drain of funds'],
[/\bfraud(ulent|ster|sters|s)?\b/gi, 'misleading'], [/\bguaranteed\b/gi, 'promised'], [/\bget rich\b/gi, 'earn'], [/\bfree money\b/gi, 'unearned payouts'],
[/\bpassive income\b/gi, 'payouts'], [/\b100% safe\b/gi, 'without risk'], [/\bdouble your\b/gi, 'grow your']];
const ADVICE = /(\bget out\b|\bpull (your|all) (money|funds)\b|\bwithdraw (now|immediately|everything)\b|\bdo not (invest|join|deposit|buy)\b|\bdon'?t (invest|join|deposit|buy)\b|\bstay away\b|\bavoid (this|it|the project)\b|\byou should (not )?(invest|join|buy|deposit|sell|exit)\b|\brun\b(?= away))/i;
function clean(s) {
if (typeof s !== 'string') return s;
let t = s.replace(/\s*\u2014\s*/g, ', ').replace(/(\d)\s*\u2013\s*(\d)/g, '$1 to $2').replace(/\s*\u2013\s*/g, ', ').replace(/\u2012|\u2015/g, '-');
for (const [re, rep] of BANNED) t = t.replace(re, rep);
// strip advice sentences ("get out", "do not invest" ...): a report gives facts and our opinion of risk, never instructions
t = t.split(/(?<=[.!?])\s+/).filter(x => !ADVICE.test(x)).join(' ');
return t.replace(/,\s*,/g, ',').replace(/\s{2,}/g, ' ').trim();
}
function deepClean(o) {
if (typeof o === 'string') return clean(o);
if (Array.isArray(o)) return o.map(deepClean);
if (o && typeof o === 'object') { const r = {}; for (const [k, v] of Object.entries(o)) r[k] = deepClean(v); return r; }
return o;
}
const hasBanned = s => BANNED.some(([re]) => { re.lastIndex = 0; return re.test(s); }) || /[\u2014\u2013]/.test(s);
const SYSTEM = `You are a smart-contract risk analyst for WebWorthIt, writing for a non-technical crypto buyer.
You get an evidence pack produced by read-only chain tools, and sometimes the text of the project's public website.
Rules you must follow:
- Use only the evidence. Never invent an address, a transaction, a number, a name or a date. If something is not in the evidence, say it is UNKNOWN.
- Copy numbers exactly as the pack shows them. Use the "Precomputed counts" section for every count: never recount events or upgrades yourself. An Upgraded event inside the deployment transaction is not an upgrade.
- If you compute a number (a sum, a difference, a share), show the arithmetic with the pack numbers, e.g. "3,632.30 of 32,690.00".
- Tag every claim VERIFIED (read on chain: storage, eth_call, logs, transactions), INFERRED (from code names, decompiled or simulated behaviour, or the website text) or UNKNOWN.
- Neutral, factual wording about code and records. You judge code and on-chain records, never people. No advice to act (never tell anyone to join, leave, buy, sell or withdraw).
- Never use these words or phrases: scam, ponzi, rug pull, fraud, guaranteed, get rich, free money, passive income, 100% safe, double your. Never use em dashes or en dashes.
- Wallet wording if needed: "SafePal or any other crypto wallet".
- Scores follow the rubric: 0 = safest, 10 = worst. Anything hidden or unreadable counts against the project, and you say so.
- Red flag 4 (returns funded by later entrants) applies ONLY when an earlier buyer or position holder is paid from a later buyer's payment
(matrix, cycler, pot, "previous N spots" paid from new entries, refunds funded by new entries). Read the "Who gets paid when someone buys"
section: it classifies every payout the chain shows. A commission paid to the buyer's sponsor or the sponsors above them on a sale where the
buyer receives a delivered product (ad credits, views, a report) is NOT red flag 4: disclose it (for example "X% of each sale goes to the
buyer's sponsors") and score it under economic design and disclosure on its merits. If a contract does both, red flag 4 applies.
The same test applies to every contract, whoever runs it.`;
const SCORE_SHAPE = `"scores": {"control": {"score": 0-10, "why": "...", "tag": "VERIFIED|INFERRED|UNKNOWN"}, "custody": {...}, "economics": {...}, "insiders": {...}, "disclosure": {...}, "trajectory": {...}},
"critical_flags": [{"rule": 1-5 (the rubric red flag number), "text": "one short sentence", "evidence": "the tx hash, address, event or pack line it rests on"}] (only red flags the evidence supports; [] when none)`;
function taskFree(pack, site) {
return `RUBRIC:\n${RUBRIC}\n\nEVIDENCE PACK:\n${pack}\n\n${site ? 'PROJECT WEBSITE (public page text, read by our browser):\n' + site + '\n\n' : ''}Write the FREE CHECK scorecard as JSON with exactly these keys:
- "verdict": one plain sentence about what the code and records show (no advice)
- ${SCORE_SHAPE}
- "top_findings": [{"tag": "VERIFIED|INFERRED|UNKNOWN", "text": "one or two plain sentences, with the evidence address or tx where it helps"}] (3 to 5 items, most important first)
- "site_vs_code": one or two sentences comparing what the website says with what the code does, or "" when there is no website text
Return only the JSON.`;
}
function taskDeep(pack, site) {
return `RUBRIC:\n${RUBRIC}\n\nEVIDENCE PACK:\n${pack}\n\n${site ? 'PROJECT WEBSITE (public page text, read by our browser):\n' + site + '\n\n' : ''}Write the DEEP REPORT as JSON with these keys:
- "verdict": one plain sentence (no advice)
- ${SCORE_SHAPE}
- "top_findings": [{"tag", "text"}] (4 to 6 items)
- "drain_capability": can any wallet move the money or change the rules in one transaction? who, how, evidence (object: {"answer", "who", "how", "evidence", "tag"})
- "exit_paths_ranked": [{"path", "who", "possible_now", "happened", "tag"}]
- "money": {"summary", "balances_now", "total_in", "total_out", "where_out_went": [{"address", "amount", "note", "tag"}]}
- "insiders": [{"address", "role", "received", "owns", "tag"}] (operator-controlled or deployment-set wallets the evidence names)
- "refund_or_promise_math": if the website or code makes a refund or payout promise, can it be met? show the arithmetic from the pack, else say UNKNOWN
- "approvals": what wallet approvals to this contract put holders at risk right now
- "site_vs_code": what the website says vs what the code does
- "unknowns": [what the evidence cannot answer]
- "plain_summary": 150 to 250 words a member could read
Return only the JSON.`;
}
async function callModel(kind, messages, key) {
const body = { model: MODELS[kind], messages, max_tokens: kind === 'deep' ? 16000 : 3000, usage: { include: true }, temperature: 0.1 };
if (/deepseek/.test(MODELS[kind])) body.reasoning = { enabled: false };
let last;
for (let attempt = 0; attempt < 3; attempt++) {
try {
const r = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', signal: AbortSignal.timeout(600000),
headers: { Authorization: 'Bearer ' + key, 'Content-Type': 'application/json', 'X-Title': 'WebWorthIt staging', 'HTTP-Referer': 'https://wwi.saasy.top' }, body: JSON.stringify(body) });
const j = await r.json();
if (r.status >= 500 || r.status === 429) { last = new Error('openrouter ' + r.status); await new Promise(z => setTimeout(z, 4000 * (attempt + 1))); continue; }
if (!r.ok || !j.choices) throw new Error('openrouter ' + r.status + ': ' + JSON.stringify(j.error || j).slice(0, 200));
const u = j.usage || {};
return { text: j.choices[0].message.content || '', cost: Number(u.cost) || 0, tin: u.prompt_tokens || 0, tout: u.completion_tokens || 0, model: j.model || MODELS[kind], finish: j.choices[0].finish_reason };
} catch (e) { last = e; if (/openrouter 4\d\d/.test(e.message)) throw e; await new Promise(z => setTimeout(z, 4000 * (attempt + 1))); }
}
throw last;
}
function parseJson(t) {
t = String(t || '').trim().replace(/^```(?:json)?\s*/i, '').replace(/```\s*$/, '');
const a = t.indexOf('{'), b = t.lastIndexOf('}'); if (a < 0 || b < a) throw new Error('no JSON object in the model reply');
return JSON.parse(t.slice(a, b + 1));
}
// ---- fact check (port of D:/tmp/wwi-cost/factcheck.py, stricter: blocks instead of listing) ----
function numbersIn(s) {
const out = []; const re = /(?<![0-9a-zA-Z_.])(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+\.\d+|\d+)(?![0-9a-zA-Z_])/g; let m;
while ((m = re.exec(s))) out.push({ raw: m[1], v: Number(m[1].replace(/,/g, '')), at: m.index });
return out;
}
function allowedSet(src, keyNums) {
const set = new Set();
const add = v => { if (!isFinite(v)) return; for (const d of [0, 1, 2, 3, 4, 5, 6]) set.add(Number(v.toFixed(d))); };
for (const n of numbersIn(src)) { add(n.v); if (!n.raw.includes('.') && n.raw.replace(/,/g, '').length >= 7) { add(Number(n.raw.replace(/,/g, '')) / 1e18); add(Number(n.raw.replace(/,/g, '')) / 1e6); } }
const k = [...new Set(keyNums.filter(x => isFinite(x) && x !== 0))].slice(0, 350);
for (let i = 0; i < k.length; i++) for (let j = 0; j < k.length; j++) {
const a = k[i], b = k[j];
add(a + b); add(Math.abs(a - b)); if (b) { add(a / b); add(a / b * 100); } if (i <= j) add(a * b);
}
return set;
}
function stringsOf(o, skipKeys) {
const out = [];
const walk = (x, k) => { if (skipKeys.has(k)) return; if (typeof x === 'string') out.push(x); else if (Array.isArray(x)) x.forEach(y => walk(y, k)); else if (x && typeof x === 'object') for (const [kk, v] of Object.entries(x)) walk(v, kk); };
walk(o, ''); return out;
}
function factcheck(report, evidenceText, keyNums) {
const src = evidenceText.toLowerCase() + '\n' + RUBRIC.toLowerCase();
const allowed = allowedSet(src, keyNums);
const texts = stringsOf(report, new Set(['tag'])); const all = texts.join('\n');
const low = all.toLowerCase();
const bad = [];
for (const a of new Set(low.match(/0x[0-9a-f]{64}(?![0-9a-f])/g) || [])) if (!src.includes(a)) bad.push({ kind: 'tx', item: a });
for (const a of new Set((low.replace(/0x[0-9a-f]{64}/g, '').match(/0x[0-9a-f]{40}(?![0-9a-f])/g) || []))) if (!src.includes(a)) bad.push({ kind: 'address', item: a });
for (const s of new Set(low.match(/0x[0-9a-f]{3,10}(?:\u2026|\.\.\.?)[0-9a-f]{3,10}/g) || [])) {
const [a, b] = s.split(/\u2026|\.\.\.?/);
if (!new RegExp(a + '[0-9a-f]*' + b + '(?![0-9a-f])').test(src)) bad.push({ kind: 'short address', item: s });
}
const strip = t => t.replace(/0x[0-9a-fA-F]+/g, ' ').replace(/\b\d{4}-\d{2}-\d{2}\b/g, ' ').replace(/\b\d{1,2}:\d{2}\b/g, ' ');
const stripped = strip(all);
const okNum = v => allowed.has(v) || [2, 3, 4, 5, 6].some(d => allowed.has(Number(v.toFixed(d))));
// shown arithmetic, checked per sentence (Marty's rule: evidence numbers or plain arithmetic of them, written out):
// (1) an explicit expression "A x B + C = R" (or "... = R1 = R2") whose inputs are all allowed is evaluated, and R is
// accepted when it matches to the decimals written; (2) a number that is the sum or difference of 2 to 4 allowed
// numbers in the sentence, or a ratio / percentage of two of them (to the decimals written). Numbers proven in a
// sentence count as allowed for the rest of that sentence only.
const tol = raw => { const d = raw.includes('.') ? raw.split('.')[1].length : 0; return 0.5 * Math.pow(10, -d) + 1e-9; };
const evalExpr = e => {
const t = e.replace(/(\d),(?=\d{3}\b)/g, '$1').replace(/[$%]/g, '').replace(/[x\u00d7]/gi, '*').trim();
if (!/^[\d.\s+\-*/()]+$/.test(t) || !/\d/.test(t) || !/[+\-*/]/.test(t)) return null;
let i = 0; const S = t.replace(/\s+/g, '');
const num = () => { const m = /^\d+(?:\.\d+)?/.exec(S.slice(i)); if (!m) throw 0; i += m[0].length; return Number(m[0]); };
const atom = () => { if (S[i] === '(') { i++; const v = sum(); if (S[i] !== ')') throw 0; i++; return v; } if (S[i] === '-') { i++; return -atom(); } return num(); };
const prod = () => { let v = atom(); while (S[i] === '*' || S[i] === '/') { const o = S[i++]; const w = atom(); v = o === '*' ? v * w : v / w; } return v; };
const sum = () => { let v = prod(); while (S[i] === '+' || S[i] === '-') { const o = S[i++]; const w = prod(); v = o === '+' ? v + w : v - w; } return v; };
try { const v = sum(); return i === S.length && isFinite(v) ? v : null; } catch (x) { return null; }
};
const proveSentence = (se, carry) => {
const ok = new Set(carry || []);
const isOk = n => okNum(n.v) || ok.has(n.raw) || (!n.raw.includes('.') && !n.raw.includes(',') && n.v < 10)
|| (n.v > 0 && n.v < 1 && okNum(Math.round(n.v * 10000) / 100)); // 0.30 for an allowed 30%
for (let pass = 0; pass < 3; pass++) {
// (1) explicit expressions
const parts = se.split('=');
for (let k = 1; k < parts.length; k++) {
const rm = /^\s*\$?\s*(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)/.exec(parts[k]);
const em = /[\d.,\s+\-x\u00d7*/()%$]*$/i.exec(parts[k - 1].replace(/\s*\b(wei|pol|usdt|usdc|bnb|usd|cents|raw units|units)\s*$/i, ' ')); if (!em) continue; // a unit word before '=' is not part of the sum
let expr = em[0].replace(/^[\s,.)]+/, ''); // trim to a balanced start
while ((expr.match(/\)/g) || []).length > (expr.match(/\(/g) || []).length && expr.includes(')')) expr = expr.slice(expr.indexOf(')') + 1);
while ((expr.match(/\(/g) || []).length > (expr.match(/\)/g) || []).length) expr = expr.slice(expr.indexOf('(') + 1);
const ins = (expr.match(/\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?/g) || []).map(r => ({ raw: r, v: Number(r.replace(/,/g, '')) })); // '4x25' holds two inputs
if (!ins.length || !ins.every(isOk)) continue;
for (const q of ins) if (q.v > 0 && q.v < 1) ok.add(q.raw); // an allowed percent written as a fraction
const v = evalExpr(expr); const r = rm ? Number(rm[1].replace(/,/g, '')) : NaN;
if (rm && v != null && [1, 1e18, 1e6].some(u => Math.abs(v / u - r) <= tol(rm[1]))) ok.add(rm[1]); // raw on-chain units written as coin amounts
else if (v != null) { // the right side is itself an expression ("... = 355 / 10 = 35.5"): equal values prove its numbers
const rx = /^[\d.,\s+\-x×*/()%$]*/i.exec(parts[k])[0].replace(/[\s,.]+$/, ''); const rv = evalExpr(rx);
if (rv != null && Math.abs(rv - v) <= Math.max(1e-9, Math.abs(v) * 1e-9)) for (const q of numbersIn(rx)) ok.add(q.raw);
}
}
// (2) sums, differences, ratios of allowed numbers in the sentence
const all = numbersIn(se); const xs = all.filter(x => okNum(x.v) || ok.has(x.raw)).map(x => x.v).slice(0, 12); // small skipped counts never feed sums
for (const n of all) {
if (isOk(n)) continue;
const v = n.v, tl = tol(n.raw), near = t => Math.abs(t - v) <= Math.max(0.011, Math.abs(v) * 1e-9);
let hit = false; const m = xs.length;
for (let a = 0; a < m && !hit; a++) for (let b = 0; b < m && !hit; b++) {
if (a === b) continue;
if (b > a && (near(xs[a] + xs[b]) || near(Math.abs(xs[a] - xs[b])))) hit = true;
else if (xs[b] && (Math.abs(xs[a] / xs[b] * 100 - v) <= tl || Math.abs(xs[a] / xs[b] - v) <= tl)) hit = true;
for (let c = b + 1; c < m && !hit && b > a; c++) { if (near(xs[a] + xs[b] + xs[c])) hit = true; for (let d = c + 1; d < m && !hit; d++) if (near(xs[a] + xs[b] + xs[c] + xs[d])) hit = true; }
}
if (hit) ok.add(n.raw);
}
}
return ok;
};
// a number proven in one sentence can be used in the next sentences of the SAME text field (a worked calculation)
const provenIn = [];
for (const t of texts) { let carry = new Set(); for (const se of strip(t).split(/(?<=[.;!?])\s+/)) { const ok = proveSentence(se, carry); provenIn.push({ se, ok }); carry = ok; } }
for (const n of numbersIn(stripped)) {
const v = n.v;
if (!n.raw.includes('.') && !n.raw.includes(',') && v < 10) continue; // small counts and scores
if (!n.raw.includes('.') && !n.raw.includes(',') && v >= 1990 && v <= 2035) continue; // years
if (okNum(v)) continue;
if (provenIn.some(x => x.ok.has(n.raw) && x.se.includes(n.raw))) continue;
// a rounded form of an allowed value (3,632 for 3,632.30, 29.06k style excluded)
let near = false; // integers: allowed already holds every allowed value rounded to 0 decimals (3,632 for 3,632.30)
if (n.raw.includes('.')) { const d = n.raw.split('.')[1].length; for (const x of [v - Math.pow(10, -d), v + Math.pow(10, -d)]) if (allowed.has(Number(x.toFixed(d)))) near = true; }
if (near) continue;
const i = stripped.indexOf(n.raw); bad.push({ kind: 'number', item: n.raw, context: stripped.slice(Math.max(0, i - 60), i + 40).replace(/\s+/g, ' ') });
}
const banned = texts.filter(hasBanned).length;
return { ok: bad.length === 0 && banned === 0, problems: bad.slice(0, 40), problem_count: bad.length, banned_strings: banned, checked_strings: texts.length };
}
// ---- opinion: overall from the six category scores (weights from the rubric) + forced High on any critical flag ----
function grade(report, E) {
let total = 0, have = 0;
for (const [k, , w] of CATS) { const s = report.scores && report.scores[k]; const v = s && Number(s.score); if (isFinite(v)) { total += Math.max(0, Math.min(10, v)) * w / 10; have += w; } }
const overall = have ? Math.round(total * 100 / have) : null;
const flags = [];
const ctl = (E && E.controllers) || {};
const eoaUp = (E && E.can_upgrade || []).filter(a => /^EOA/.test((ctl[a] || {}).type || ''));
if (eoaUp.length) flags.push({ text: 'One personal wallet can replace the code in a single transaction (' + eoaUp.join(', ') + ').', tag: 'VERIFIED', source: 'rubric red flag 1' });
const v = (E && E.verification) || {};
if (E && E.proxy && E.proxy.upgradeable && !(v.implementation && v.implementation.match)) flags.push({ text: 'The implementation behind the upgradeable proxy has no verified source on Sourcify.', tag: 'VERIFIED', source: 'rubric red flag 2' });
// red flag 4 (2026-11-16 wording): VERIFIED when the chain shows payouts to earlier buyers outside the buyer's referral line
const pr = (E && E.payout_relations) || null, bc = (pr && pr.by_class) || {};
if (bc.earlier_buyer > 0) {
const x = ((pr.examples || {}).earlier_buyer || [])[0] || {};
flags.push({ text: bc.earlier_buyer + ' payouts went to earlier buyers or position holders outside the buyer\'s referral line, paid inside a later buyer\'s purchase' + (x.tx ? ' (example tx ' + x.tx + ')' : '') + '.', tag: 'VERIFIED', source: 'rubric red flag 4' });
}
// the chain shows only operator and referral-line payouts: a model red flag 4 is not applied (sponsor commissions are disclosed, not flagged).
// Gaps in the history only block this when the code can change (an upgradeable proxy); fixed code pays the same way in every block.
const gapsMatter = !!(E && E.proxy && E.proxy.upgradeable) && (E.gaps || []).some(g => g.what === 'contract events');
const rf4Clear = !!(pr && pr.payouts_seen > 0 && pr.readable && !bc.earlier_buyer && !bc.earlier_buyer_line_unknown && !gapsMatter);
const notApplied = [];
// the model often restates the deterministic red flags: keep one per issue, the deterministic VERIFIED one
const has1 = flags.some(f => f.source === 'rubric red flag 1'), has2 = flags.some(f => f.source === 'rubric red flag 2'), has4 = flags.some(f => f.source === 'rubric red flag 4');
const words = t => new Set(String(t).toLowerCase().match(/[a-z]{4,}/g) || []);
const similar = (a, b) => { const A = words(a), B = words(b); let n = 0; for (const w of A) if (B.has(w)) n++; return n / Math.max(1, Math.min(A.size, B.size)) >= 0.5; };
const RF4 = /(red flag 4|later (entrants|buyers|entries|purchases)|new (money|entries|entrants|purchases|buyers)|previous \d* ?spots|matrix|cycler|recruit|only (when|inside|from) .{0,40}(purchase|entr|buy)|funded by (new|later))/i;
for (const f of report.critical_flags || []) {
const o = typeof f === 'string' ? { text: f } : (f && typeof f === 'object' ? f : null);
if (!o || typeof o.text !== 'string' || !o.text.trim()) continue;
const t = o.text.trim(), ev = typeof o.evidence === 'string' ? o.evidence.trim() : '';
const rule = Number(o.rule) || (RF4.test(t) ? 4 : 0);
if (has1 && (rule === 1 || /(upgrad|replace (the )?code|single[- ](eoa|wallet|key)|one (personal )?wallet|\beoa\b|owner key)/i.test(t))) continue;
if (has2 && (rule === 2 || /(unverified|not verified|no verified|source)/i.test(t))) continue;
if (rule === 4) {
if (has4) continue;
if (rf4Clear) { notApplied.push({ text: t, reason: 'Red flag 4 not applied: of ' + pr.payouts_seen + ' payouts read, ' + (bc.operator || 0) + ' went to wallets the contract names and ' + (bc.referral_line || 0) + ' to the buyer\'s referral line, and none to an earlier buyer outside that line. Sponsor commissions are disclosed and scored under economic design (rubric 2026-11-16).' }); continue; }
if (typeof f === 'object' && !ev) { notApplied.push({ text: t, reason: 'Red flag 4 not applied: the model cited no evidence.' }); continue; }
}
if (flags.some(x => similar(x.text, t))) continue;
flags.push({ text: t + (ev && !t.includes(ev) ? ' (evidence: ' + ev + ')' : ''), tag: 'INFERRED', source: 'model, from the rubric list' + (rule ? ' (red flag ' + rule + ')' : '') });
}
let band = overall == null ? null : overall <= 25 ? 'Low risk' : overall <= 50 ? 'Moderate risk' : overall <= 75 ? 'Elevated risk' : 'High risk';
const forced = flags.length > 0 && band !== 'High risk';
if (flags.length) band = 'High risk';
return { overall, grade: band, forced_by_flag: forced, flags, not_applied: notApplied };
}
const TAGS = new Set(['VERIFIED', 'INFERRED', 'UNKNOWN']);
function normalize(report) {
const fixTag = o => { if (o && typeof o === 'object') { if ('tag' in o) { const t = String(o.tag || '').toUpperCase().split(/[^A-Z]/)[0]; o.tag = TAGS.has(t) ? t : 'UNKNOWN'; } for (const v of Object.values(o)) if (v && typeof v === 'object') fixTag(v); } };
fixTag(report);
if (!Array.isArray(report.top_findings)) report.top_findings = [];
return report;
}
async function write({ kind, pack, siteText, facts, evidence, key }) {
const keyNums = [];
const walk = x => { if (typeof x === 'number') keyNums.push(x); else if (Array.isArray(x)) x.forEach(walk); else if (x && typeof x === 'object') Object.values(x).forEach(walk); };
for (const d of Object.values(evidence.decoded_events || {})) for (const x of Object.values(d.uint_field_sums_raw || {})) { const nx = Number(x); if (isFinite(nx)) { keyNums.push(nx); if (nx >= 1e6) keyNums.push(nx / 1e18, nx / 1e6); } }
walk({ money: evidence.money, approvals: evidence.approvals, positions: evidence.positions, counts: evidence.counts, txs: evidence.txs, values: evidence.values, age: evidence.age_days, wallets: evidence.wallets, native: evidence.native_balance });
const site = siteText ? siteText.slice(0, kind === 'deep' ? 12000 : 6000) : '';
const evidenceText = pack + '\n' + site + '\n' + JSON.stringify(facts);
const messages = [{ role: 'system', content: SYSTEM }, { role: 'user', content: (kind === 'deep' ? taskDeep : taskFree)(pack, site) }];
const runs = []; let cost = 0, tin = 0, tout = 0, model = MODELS[kind];
for (let attempt = 0; attempt < 2; attempt++) {
let rep, fc, raw;
try {
const r = await callModel(kind, messages, key); cost += r.cost; tin += r.tin; tout += r.tout; model = r.model; raw = r.text;
rep = normalize(deepClean(parseJson(r.text)));
fc = factcheck(rep, evidenceText, keyNums);
} catch (e) { fc = { ok: false, error: String(e.message).slice(0, 300), problems: [] }; }
runs.push({ attempt: attempt + 1, ok: fc.ok, problems: fc.problems, error: fc.error, banned: fc.banned_strings });
if (fc.ok) return { ok: true, report: rep, grade: grade(rep, evidence), factcheck: { passed: true, runs }, cost, tin, tout, model };
if (attempt === 0 && raw) {
messages.push({ role: 'assistant', content: raw });
messages.push({ role: 'user', content: 'Our fact check could not find these items in the evidence: ' + JSON.stringify((fc.problems || []).slice(0, 25)) +
(fc.banned_strings ? ' Some text also used a banned word or a dash.' : '') + ' Rewrite the whole JSON. Use only addresses, transaction hashes and numbers that appear in the evidence pack, or show the arithmetic from pack numbers. Return only the JSON.' });
}
}
return { ok: false, report: null, grade: null, factcheck: { passed: false, runs, note: 'The written report did not pass our fact check twice, so it is not shown. Only facts read directly from the chain are shown below.' }, cost, tin, tout, model };
}
module.exports = { write, factcheck, clean, deepClean, grade, CATS, MODELS, hasBanned };