SPB Git

Repository Public MIT

review.ts 35.8 KB 590 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : server/next/review.ts9 * Module           : server10 * Repository       : https://git.spboucher.ai/vquant11 * Project Website  : https://vquant.spboucher.ai12 * Created          : 2026-11-2013 * Last Modified    : 2026-11-2014 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier  : MIT34 * License          : MIT License35 * License File     : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Automated review (contract: docs/next/CONTRACT.md §5.3).47 *48 * POST /api/v2/reviews { target: { type: "session"|"quant_job"|"note", id }, projectId? } → 202 { reviewId }49 *50 * Two stages. First, deterministic checks computed here from what is stored (no model involved): figures quoted51 * in the text against the figures present in the stored tool and Quant Lab results, sample size and period,52 * look-ahead flags reported by a backtest, missing provenance, significance wording against p-values. Then a53 * reviewer model — the auditor machinery of services/agents.ts, with the data tools — reads the material and the54 * findings and re-queries data. The result is the object `review/<id>`, written through the object store's55 * server-side API and read through the generic object routes. It is always labelled as automated.56 */57import type { Express, Request, Response } from "express";58import type Database from "better-sqlite3";59import { randomUUID } from "node:crypto";60import { z } from "zod";61import { currentUser } from "../access";62import { isSqlite, pool } from "../db";63import { logger } from "../utils/logger";64import { storage } from "../storage";65import { allowWrite, getObject, writeObject } from "./objects";66import { UsageMeter } from "./usage";67import { providerOf } from "./providers";6869export const REVIEW_DISCLAIMER = "Automated review — not a human peer review.";7071export type ReviewCategory = "math" | "statistics" | "leakage" | "interpretation" | "citations" | "reproducibility";72export type ReviewSeverity = "info" | "warning" | "error";73export interface ReviewCheck {74  id: string;75  category: ReviewCategory;76  severity: ReviewSeverity;77  finding: string;78  evidence: string;79}8081export interface ReviewMaterial {82  kind: "session" | "quant_job" | "note";83  /** the text under review (the answer, the note, or the headline and conclusions of a job) */84  text: string;85  /** everything stored that a figure of the text can be checked against (tool results, job results) */86  results: unknown[];87  /** Quant Lab results (schema lab/1) among them */88  labResults: any[];89  /** the provenance stored with a conversation answer; null when the target has no such field */90  provenance: Array<{ tool?: string; provider?: string; ok?: boolean }> | null;91}9293// ─── Numbers ─────────────────────────────────────────────────────────────────94export interface QuotedNumber {95  raw: string;96  value: number;97  percent: boolean;98  /** half a unit of the last digit shown, in the units of `value` */99  resolution: number;100  context: string;101}102103const SCALES: Array<[RegExp, number]> = [104  [/^(k|K)\b/, 1e3],105  [/^(M|mn|MM|millions?)\b/, 1e6],106  [/^(B|bn|Bn|Md|Mds|Mrd|billions?|milliards?)\b/, 1e9],107  [/^(tn|trillions?)\b/, 1e12],108];109110/** "1,234.5", "1 234,5", "12,5", "1.234.567" → number; null when the token is not a plain number. */111export function parseLocaleNumber(token: string): { value: number; decimals: number } | null {112  let t = token.replace(/[\s\u00a0\u202f]/g, "");113  if (!/^\d[\d.,]*$/.test(t)) return null;114  t = t.replace(/[.,]+$/, "");115  const lastDot = t.lastIndexOf(".");116  const lastComma = t.lastIndexOf(",");117  let decimalSep = "";118  if (lastDot >= 0 && lastComma >= 0) decimalSep = lastDot > lastComma ? "." : ",";119  else if (lastComma >= 0) decimalSep = /^\d{1,3}(,\d{3})+$/.test(t) ? "" : ",";120  else if (lastDot >= 0) decimalSep = /^\d{1,3}(\.\d{3}){2,}$/.test(t) ? "" : ".";121  let intPart = t;122  let frac = "";123  if (decimalSep) {124    const i = t.lastIndexOf(decimalSep);125    intPart = t.slice(0, i);126    frac = t.slice(i + 1);127    if (/[.,]/.test(frac)) return null;128  }129  intPart = intPart.replace(/[.,]/g, "");130  const value = Number(`${intPart || "0"}${frac ? `.${frac}` : ""}`);131  return Number.isFinite(value) ? { value, decimals: frac.length } : null;132}133134/** Text with what is not prose removed: code, links, image paths, ISO dates and clock times. */135function proseOnly(text: string): string {136  return text137    .replace(/```[\s\S]*?```/g, " ")138    .replace(/`[^`\n]*`/g, " ")139    .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")140    .replace(/https?:\/\/\S+/g, " ")141    .replace(/\b\d{4}-\d{2}-\d{2}(T[\d:.]+Z?)?\b/g, " ")142    .replace(/\b\d{1,2}[:h]\d{2}(:\d{2})?\b/g, " ");143}144145/**146 * The figures a text states: numbers with a decimal part, a percent sign or a scale word, and integers of three147 * digits or more. Years, small counts ("3 scenarios") and list numbering are left out: they are not data.148 */149export function extractQuotedNumbers(text: string, max = 400): QuotedNumber[] {150  const prose = proseOnly(text);151  const out: QuotedNumber[] = [];152  const re = /(?<![\w.,])(\d(?:(?:[\d.,]|[ \u00a0\u202f](?=\d{3}(?!\d)))*\d)?)(?:\s?(%|k\b|K\b|M\b|mn\b|MM\b|B\b|bn\b|Bn\b|Mds?\b|Mrd\b|tn\b|millions?\b|milliards?\b|billions?\b|trillions?\b))?/g;153  let m: RegExpExecArray | null;154  while ((m = re.exec(prose)) && out.length < max) {155    const parsed = parseLocaleNumber(m[1]);156    if (!parsed) continue;157    const suffix = m[2] ?? "";158    const percent = suffix === "%";159    const scale = percent || !suffix ? 1 : SCALES.find(([s]) => s.test(suffix))?.[1] ?? 1;160    const plainInteger = parsed.decimals === 0 && !percent && scale === 1;161    if (plainInteger && (parsed.value < 100 || (parsed.value >= 1900 && parsed.value <= 2100))) continue;162    out.push({163      raw: m[0].trim(),164      value: parsed.value * scale,165      percent,166      resolution: 0.5 * 10 ** -parsed.decimals * scale,167      context: prose.slice(Math.max(0, m.index - 40), Math.min(prose.length, m.index + m[0].length + 30)).replace(/\s+/g, " ").trim(),168    });169  }170  return out;171}172173/** Every finite number in stored results: JSON numbers, and the figures written inside strings (notebook output, sub-analyst reports). Sorted absolute values. */174export function collectResultNumbers(results: unknown[], maxNodes = 300_000): number[] {175  const out: number[] = [];176  let nodes = 0;177  const walk = (v: unknown): void => {178    if (++nodes > maxNodes) return;179    if (typeof v === "number") {180      if (Number.isFinite(v)) out.push(Math.abs(v));181    } else if (typeof v === "string") {182      if (v.length > 2 && v.length < 400_000 && /\d/.test(v)) for (const q of extractQuotedNumbers(v, 5000)) out.push(Math.abs(q.value));183    } else if (Array.isArray(v)) {184      for (const x of v) walk(x);185    } else if (v && typeof v === "object") {186      for (const x of Object.values(v)) walk(x);187    }188  };189  walk(results);190  return Float64Array.from(out).sort() as unknown as number[];191}192193function hasNear(sorted: ArrayLike<number>, target: number, tol: number): boolean {194  let lo = 0;195  let hi = sorted.length - 1;196  const min = target - tol;197  while (lo <= hi) {198    const mid = (lo + hi) >> 1;199    if (sorted[mid] < min) lo = mid + 1;200    else hi = mid - 1;201  }202  return lo < sorted.length && sorted[lo] <= target + tol;203}204205/**206 * Whether a quoted figure is present in the results, allowing for the rounding the text shows (half a unit of its207 * last digit), 0.5 % of slack for vendor rounding, and the usual changes of unit: a percentage stored as a ratio208 * (12.5 % ↔ 0.125) and an amount stored in thousands, millions or billions.209 */210export function numberIsSupported(q: QuotedNumber, sorted: ArrayLike<number>): boolean {211  const v = Math.abs(q.value);212  const forms = q.percent ? [1, 0.01] : [1, 1e-3, 1e-6, 1e-9, 1e3, 1e6, 1e9, 100, 0.01];213  for (const f of forms) {214    const target = v * f;215    if (hasNear(sorted, target, q.resolution * f + target * 0.005)) return true;216  }217  return false;218}219220// ─── Deterministic checks ────────────────────────────────────────────────────221const STAT_CLAIM = /\b(corr[eé]lation|r[eé]gression|volatilit[yé]|sharpe|sortino|backtest|p-?value|valeur[- ]p|significati|significan|t-?stat|r²|r-squared|\bbeta\b|b[eê]ta|\bVaR\b|value at risk|drawdown|cointegr|coint[eé]gr|garch|monte carlo|[eé]cart[- ]type|standard deviation)/i;222const SAMPLE_SIZE = /\b(n\s*=\s*\d+|\d[\d\s,.]*\s*(observations?|obs\b|s[eé]ances|sessions|trading days|jours de bourse|data points|points de donn[eé]es|trades|transactions|simulations?|paths|trajectoires|échantillons?|samples?|firms|soci[eé]t[eé]s|mois\b|months\b|weeks\b|semaines\b|quarters\b|trimestres\b))/i;223const PERIOD = /((19|20)\d{2}\s*(–|-|—|to|à|au|through)\s*(19|20)\d{2}|\b(since|depuis|from|de|entre|between)\s+((janv|f[eé]v|mars|avr|mai|juin|juil|ao[uû]t|sept|oct|nov|d[eé]c|jan|feb|mar|apr|may|jun|jul|aug|sep|dec)\w*\.?\s+)?(19|20)\d{2}|\b\d{4}-\d{2}-\d{2}\b|\b(last|past|derni[eè]res?|derniers?|sur|over)\s+(the\s+)?(\d+|deux|trois|cinq|dix|two|three|five|ten)\s+(years?|ans|ann[eé]es|months?|mois|days?|jours|s[eé]ances|sessions|weeks?|semaines|quarters?|trimestres)|\b(YTD|TTM|1Y|3Y|5Y|10Y)\b|\bas of\b|\ben date du\b|\bau \d{1,2} )/i;224const SIGNIFICANT = /\b(statistically significant|significant at|highly significant|is significant|are significant|statistiquement significati\w+|significati\w+ au seuil|est significati\w+|sont significati\w+)\b/i;225const NOT_SIGNIFICANT = /\b(not (statistically )?significant|insignificant|no significant|non significati\w+|pas (statistiquement )?significati\w+|n'est pas significati\w+)\b/i;226227interface PValue {228  where: string;229  p: number;230  conclusion?: string;231}232233/** p-values found in Quant Lab results: diagnostics, summary rows and table cells whose key names a p-value. */234export function collectPValues(labResults: any[]): PValue[] {235  const out: PValue[] = [];236  const isP = (k: string) => /^(p|p[_-]?val(ue)?s?|pvalue|p>\|t\||p>\|z\||prob|p_value_.*)$/i.test(k) || /p[_-]?value/i.test(k);237  const ok = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;238  for (const r of labResults) {239    const engine = String(r?.engine ?? "result");240    for (const d of Array.isArray(r?.diagnostics) ? r.diagnostics : []) if (ok(d?.pvalue)) out.push({ where: `${engine} · ${d.name ?? "diagnostic"}`, p: d.pvalue, conclusion: typeof d.conclusion === "string" ? d.conclusion : undefined });241    for (const t of Array.isArray(r?.tables) ? r.tables : []) {242      for (const row of Array.isArray(t?.rows) ? t.rows : []) {243        if (!row || typeof row !== "object") continue;244        for (const [k, v] of Object.entries(row)) if (isP(k) && ok(v)) out.push({ where: `${engine} · ${t.title ?? t.id ?? "table"} · ${String((row as any).term ?? (row as any).name ?? (row as any).variable ?? (row as any).label ?? k)}`, p: v });245      }246    }247    for (const s of Array.isArray(r?.summary) ? r.summary : []) if (typeof s?.label === "string" && /p[- ]?value|valeur[- ]p/i.test(s.label) && ok(s.value)) out.push({ where: `${engine} · ${s.label}`, p: s.value });248  }249  return out.slice(0, 500);250}251252/** Look-ahead and leakage signals a Quant Lab result reports about itself (flags, lags, warnings). */253export function collectLeakageFlags(labResults: any[]): Array<{ where: string; severity: ReviewSeverity; detail: string }> {254  const out: Array<{ where: string; severity: ReviewSeverity; detail: string }> = [];255  const KEY = /look[_-]?ahead|lookahead|leak|future[_-]?data|survivorship/i;256  const LAG = /^(signal[_-]?lag|lag[_-]?bars|execution[_-]?lag|lag)$/i;257  for (const r of labResults) {258    const engine = String(r?.engine ?? "result");259    let nodes = 0;260    const walk = (v: unknown, path: string, depth: number): void => {261      if (++nodes > 20_000 || depth > 6 || !v || typeof v !== "object") return;262      if (Array.isArray(v)) {263        if (v.length <= 50) v.forEach((x, i) => walk(x, `${path}[${i}]`, depth + 1));264        return;265      }266      for (const [k, x] of Object.entries(v)) {267        if (k === "charts" || k === "reproduce" || k === "methodology") continue;268        const p = path ? `${path}.${k}` : k;269        if (KEY.test(k)) {270          // A flag named "no_lookahead" / "lookahead_free" states the opposite of a problem when true.271          // Same for "lookAheadChecked" / "lookAheadPassed" (the backtest engine's own flags): true is the good news.272          const negated = /^(no|not|without)[_-]|[_-]?(free|safe|checked|passed|ok)$/i.test(k);273          // Bookkeeping of the check itself (which dates were tested, how many) is not a signal.274          if (/(dates|tested|count|method|unit)$/i.test(k)) continue;275          if (typeof x === "boolean") {276            // Survivorship is a caveat about the universe, not evidence that the computation used future data.277            if (x !== negated) out.push({ where: `${engine} · ${p}`, severity: /survivorship/i.test(k) ? "warning" : "error", detail: `${p} = ${x}` });278          } else if (typeof x === "string" && x.trim()) out.push({ where: `${engine} · ${p}`, severity: "warning", detail: `${p}: ${x.slice(0, 200)}` });279          else if (Array.isArray(x) && x.length > 0) out.push({ where: `${engine} · ${p}`, severity: "warning", detail: `${p}: ${JSON.stringify(x).slice(0, 200)}` });280          else if (x && typeof x === "object") walk(x, p, depth + 1);281        } else if (LAG.test(k) && typeof x === "number" && x <= 0 && engine === "backtest") {282          out.push({ where: `${engine} · ${p}`, severity: "error", detail: `${p} = ${x}: signals are traded on the bar that produced them` });283        } else walk(x, p, depth + 1);284      }285    };286    walk({ summary: r?.summary, diagnostics: r?.diagnostics, provenance: { spec: r?.provenance?.spec }, flags: r?.flags, checks: r?.checks, leakage: r?.leakage, look_ahead: r?.look_ahead, lookahead: r?.lookahead }, "", 0);287    for (const w of Array.isArray(r?.warnings) ? r.warnings : []) if (typeof w === "string" && KEY.test(w)) out.push({ where: `${engine} · warnings`, severity: "warning", detail: w.slice(0, 240) });288  }289  return out;290}291292const clip = (s: string, n = 600) => (s.length > n ? `${s.slice(0, n)}…` : s);293294/** The deterministic stage of a review. Pure: same material, same checks. */295export function runDeterministicChecks(m: ReviewMaterial): ReviewCheck[] {296  const checks: ReviewCheck[] = [];297  const quoted = extractQuotedNumbers(m.text);298299  // 1. Figures quoted in the text against the figures stored with it.300  if (quoted.length === 0) {301    checks.push({ id: "numbers", category: "math", severity: "info", finding: "The text quotes no figure that can be compared with stored results.", evidence: "No decimal, percentage, scaled amount or large integer found in the prose." });302  } else if (m.results.length === 0) {303    checks.push({ id: "numbers", category: "math", severity: m.kind === "note" ? "info" : "warning", finding: `The text quotes ${quoted.length} figure(s) but nothing is stored with it to compare them with.`, evidence: m.kind === "note" ? "A note carries no tool or computation results." : "No tool or Quant Lab result is saved with this target." });304  } else {305    const pool = collectResultNumbers(m.results);306    const missing = quoted.filter((q) => !numberIsSupported(q, pool));307    const share = missing.length / quoted.length;308    checks.push(309      missing.length === 0310        ? { id: "numbers", category: "math", severity: "info", finding: `All ${quoted.length} figures quoted in the text are present in the stored results (within rounding).`, evidence: `${pool.length} numbers in the stored results.` }311        : {312            id: "numbers",313            category: "math",314            severity: share > 0.5 && quoted.length >= 6 ? "error" : "warning",315            finding: `${missing.length} of ${quoted.length} figures quoted in the text are not found in the stored results (within rounding and unit changes). They may be derived in the prose, come from a source that was not saved, or be wrong.`,316            evidence: clip(missing.slice(0, 12).map((q) => `"${q.raw}" in «${q.context}»`).join(" | "), 1800),317          },318    );319  }320321  // 2. Sample size and period behind statistical statements.322  const observations: Array<{ symbol: string; n: number }> = [];323  for (const r of m.labResults) for (const d of Array.isArray(r?.provenance?.data) ? r.provenance.data : []) if (typeof d?.observations === "number") observations.push({ symbol: String(d.symbol ?? "?"), n: d.observations });324  const statistical = STAT_CLAIM.test(m.text) || m.labResults.length > 0;325  if (statistical) {326    const hasN = SAMPLE_SIZE.test(m.text) || observations.length > 0;327    const hasPeriod = PERIOD.test(m.text) || m.labResults.some((r) => (Array.isArray(r?.provenance?.data) ? r.provenance.data : []).some((d: any) => d?.start && d?.end));328    if (!hasN || !hasPeriod) {329      checks.push({ id: "sample", category: "statistics", severity: "warning", finding: `Statistical statements are made without ${[!hasN ? "a sample size" : "", !hasPeriod ? "the period covered" : ""].filter(Boolean).join(" or ")}.`, evidence: clip(STAT_CLAIM.exec(m.text)?.[0] ? `First statistical term: "${STAT_CLAIM.exec(m.text)![0]}".` : "Quant Lab result without sample information.") });330    } else {331      checks.push({ id: "sample", category: "statistics", severity: "info", finding: "Sample size and period are stated for the statistical statements.", evidence: observations.length > 0 ? clip(observations.slice(0, 8).map((o) => `${o.symbol}: ${o.n} observations`).join("; ")) : "Stated in the text." });332    }333    const small = observations.filter((o) => o.n < 30);334    if (small.length > 0) checks.push({ id: "sample-small", category: "statistics", severity: "warning", finding: "At least one series has fewer than 30 observations: estimates on it are fragile.", evidence: clip(small.map((o) => `${o.symbol}: ${o.n}`).join("; ")) });335  }336337  // 3. Look-ahead and leakage, as reported by the engines themselves.338  const flags = collectLeakageFlags(m.labResults);339  const backtests = m.labResults.filter((r) => r?.engine === "backtest");340  if (flags.length > 0) {341    const worst: ReviewSeverity = flags.some((f) => f.severity === "error") ? "error" : "warning";342    checks.push({ id: "leakage", category: "leakage", severity: worst, finding: `${flags.length} look-ahead or leakage signal(s) reported by the computation.`, evidence: clip(flags.slice(0, 8).map((f) => `${f.where} — ${f.detail}`).join(" | "), 1500) });343  } else if (backtests.length > 0) {344    checks.push({ id: "leakage", category: "leakage", severity: "info", finding: "The backtest engine reports no look-ahead or leakage flag.", evidence: `${backtests.length} backtest result(s) inspected.` });345  } else if (/\bbacktest|back-test|strat[eé]gie test[eé]e|historical simulation of (a|the) strategy/i.test(m.text)) {346    checks.push({ id: "leakage", category: "leakage", severity: "warning", finding: "A backtest is described, but it was not run through the backtest engine: look-ahead and leakage cannot be checked automatically.", evidence: "No Quant Lab backtest result is stored with this target." });347  }348349  // 4. Provenance.350  if (m.kind === "session") {351    if (m.provenance === null) checks.push({ id: "provenance", category: "reproducibility", severity: "warning", finding: "No provenance is stored with this answer (it predates provenance recording, or no data tool ran).", evidence: "Field `provenance` absent from the stored message." });352    else if (m.provenance.length === 0) checks.push({ id: "provenance", category: "citations", severity: quoted.length > 0 ? "warning" : "info", finding: "No data tool ran for this answer: its figures do not come from a recorded source.", evidence: "Stored provenance is empty." });353    else {354      const failed = m.provenance.filter((p) => p.ok === false);355      checks.push({ id: "provenance", category: "citations", severity: failed.length > 0 ? "warning" : "info", finding: failed.length > 0 ? `${failed.length} of ${m.provenance.length} recorded sources failed when called.` : `${m.provenance.length} recorded source(s), all answered.`, evidence: clip((failed.length > 0 ? failed : m.provenance).slice(0, 12).map((p) => `${p.tool} (${p.provider})`).join(", ")) });356    }357  }358  for (const r of m.labResults) {359    const data = r?.provenance?.data;360    if (!Array.isArray(data) || data.length === 0) checks.push({ id: `provenance-${r?.engine ?? "lab"}`, category: "reproducibility", severity: "warning", finding: `The ${r?.engine ?? "Quant Lab"} result carries no data provenance.`, evidence: "provenance.data is missing or empty." });361  }362363  // 5. Significance wording against the p-values shown.364  const pvalues = collectPValues(m.labResults);365  // A denial ("not statistically significant") is not a claim: only what remains once denials are set aside counts.366  const affirmed = m.text.replace(new RegExp(NOT_SIGNIFICANT.source, "gi"), " ");367  const claims = SIGNIFICANT.test(affirmed);368  for (const p of pvalues) {369    if (!p.conclusion) continue;370    const saysNot = NOT_SIGNIFICANT.test(p.conclusion) || /fail(s|ed)? to reject|cannot reject|ne (permet|peut) pas (de )?rejeter/i.test(p.conclusion);371    const saysYes = !saysNot && (/\bsignifican|significati|\breject(s|ed)?\b|rejet/i.test(p.conclusion));372    if (saysYes && p.p > 0.1) checks.push({ id: `significance-${checks.length}`, category: "statistics", severity: "error", finding: `A conclusion claims significance (or a rejection) with a p-value of ${p.p}.`, evidence: clip(`${p.where}: "${p.conclusion}"`) });373    else if (saysNot && p.p < 0.01) checks.push({ id: `significance-${checks.length}`, category: "statistics", severity: "warning", finding: `A conclusion denies significance with a p-value of ${p.p}.`, evidence: clip(`${p.where}: "${p.conclusion}"`) });374  }375  if (claims) {376    if (pvalues.length === 0) checks.push({ id: "significance", category: "interpretation", severity: "warning", finding: "The text speaks of statistical significance, but no p-value is stored to support it.", evidence: clip(`"${SIGNIFICANT.exec(affirmed)![0]}"`) });377    else {378      const min = Math.min(...pvalues.map((p) => p.p));379      if (min > 0.05) checks.push({ id: "significance", category: "interpretation", severity: "warning", finding: `The text speaks of statistical significance, but the smallest stored p-value is ${min}.`, evidence: clip(pvalues.slice(0, 6).map((p) => `${p.where}: p = ${p.p}`).join("; ")) });380    }381  }382  return checks;383}384385// ─── Reviewer report ─────────────────────────────────────────────────────────386const CATEGORIES: ReviewCategory[] = ["math", "statistics", "leakage", "interpretation", "citations", "reproducibility"];387const SEVERITIES: ReviewSeverity[] = ["info", "warning", "error"];388389/** Splits the reviewer's report into its verdict and its findings ("[category|severity] finding — evidence"). Pure. */390export function parseReviewerReport(report: string): { verdict: string; checks: ReviewCheck[] } {391  const checks: ReviewCheck[] = [];392  const verdict: string[] = [];393  let inFindings = false;394  for (const line of report.split("\n")) {395    const t = line.trim();396    if (/^\**FINDINGS\**:?$/i.test(t)) {397      inFindings = true;398      continue;399    }400    const m = /^[-*\d.\s]*\[\s*([a-z]+)\s*\|\s*([a-z]+)\s*\]\s*(.+)$/i.exec(t);401    if (m && CATEGORIES.includes(m[1].toLowerCase() as ReviewCategory) && SEVERITIES.includes(m[2].toLowerCase() as ReviewSeverity)) {402      const [finding, ...rest] = m[3].split(/\s+[—–]\s+|\s+--\s+/);403      checks.push({ id: `reviewer-${checks.length + 1}`, category: m[1].toLowerCase() as ReviewCategory, severity: m[2].toLowerCase() as ReviewSeverity, finding: finding.trim().slice(0, 600), evidence: rest.join(" — ").trim().slice(0, 1200) });404    } else if (!inFindings && t) verdict.push(t);405  }406  return { verdict: verdict.join("\n").slice(0, 4000), checks: checks.slice(0, 40) };407}408409// ─── Material ────────────────────────────────────────────────────────────────410type Db = Database.Database;411const isLab = (r: any) => r && typeof r === "object" && r.schema === "lab/1";412413function quantJob(owner: string, id: string): { tool: string; status: string; result: any } | null {414  if (!isSqlite) return null;415  try {416    const row = (pool as Db).prepare("SELECT tool, status, result FROM vq_quant_jobs WHERE id = ? AND owner = ?").get(id, owner) as { tool: string; status: string; result: string | null } | undefined;417    return row ? { tool: row.tool, status: row.status, result: row.result ? JSON.parse(row.result) : null } : null;418  } catch {419    return null;420  }421}422423/** Text of a Quant Lab result that states something: headline, conclusions, notes, warnings. */424function labText(r: any): string {425  return [r?.title, r?.headline, ...(Array.isArray(r?.summary) ? r.summary.map((s: any) => `${s?.label ?? ""}: ${s?.value ?? ""}${s?.note ? ` (${s.note})` : ""}`) : []), ...(Array.isArray(r?.diagnostics) ? r.diagnostics.map((d: any) => `${d?.name ?? ""}: ${d?.conclusion ?? ""}`) : []), ...(Array.isArray(r?.warnings) ? r.warnings : [])].filter((x) => typeof x === "string" && x).join("\n");426}427428/** Loads what a review needs about its target; null when the target does not exist for this person. */429export async function loadMaterial(owner: string, target: { type: "session" | "quant_job" | "note"; id: string }): Promise<{ material: ReviewMaterial; subject: string } | null> {430  if (target.type === "session") {431    const session = await storage.getConversationSession(target.id);432    if (!session || session.owner !== owner) return null;433    let turns: any[] = [];434    try {435      turns = JSON.parse(session.messages);436    } catch {437      /* an unreadable conversation has nothing to review */438    }439    const last = turns[turns.length - 1];440    if (!last || typeof last.answer !== "string") return null;441    const toolResults: Array<{ tool?: string; result?: any }> = Array.isArray(last.toolResults) ? last.toolResults : [];442    const results: unknown[] = toolResults.map((t) => t?.result);443    const labResults: any[] = [];444    for (const t of toolResults) {445      if (t?.tool !== "run_quant_engine") continue;446      // The conversation keeps a compact copy; the job has the full result (diagnostics, flags, provenance).447      const full = typeof t.result?.jobId === "string" ? quantJob(owner, t.result.jobId)?.result : null;448      const r = isLab(full) ? full : t.result?.result;449      if (isLab(r)) {450        labResults.push(r);451        if (isLab(full)) results.push(full);452      }453    }454    return {455      subject: `The last answer of the conversation "${session.title}". Question asked: ${String(last.question ?? "").slice(0, 1500)}`,456      material: { kind: "session", text: last.answer, results, labResults, provenance: Array.isArray(last.provenance) ? last.provenance : null },457    };458  }459  if (target.type === "quant_job") {460    const job = quantJob(owner, target.id);461    if (!job || job.result === null) return null;462    const lab = isLab(job.result);463    // The statements of a job are its headline and conclusions; they are checked against its own tables and summary.464    const { headline, title, methodology, ...numbersOnly } = (lab ? job.result : {}) as Record<string, unknown>;465    return {466      subject: `The Quant Lab job ${target.id} (engine ${job.tool}, status ${job.status}).`,467      material: { kind: "quant_job", text: lab ? labText(job.result) : "", results: [lab ? numbersOnly : job.result], labResults: lab ? [job.result] : [], provenance: null },468    };469  }470  const note = getObject<{ title?: string; body?: string }>(owner, "note", target.id);471  if (!note) return null;472  return { subject: `The note "${String(note.data.title ?? "").slice(0, 200)}".`, material: { kind: "note", text: String(note.data.body ?? ""), results: [], labResults: [], provenance: null } };473}474475// ─── Run ─────────────────────────────────────────────────────────────────────476const bodySchema = z.object({477  target: z.object({ type: z.enum(["session", "quant_job", "note"]), id: z.string().min(1).max(100) }),478  projectId: z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).nullish(),479});480481const running = new Map<string, number>();482const MAX_RUNNING_PER_OWNER = 2;483484function materialForReviewer(m: ReviewMaterial, checks: ReviewCheck[]): string {485  const lab = m.labResults.map((r) => JSON.stringify({ engine: r.engine, headline: r.headline, summary: r.summary, diagnostics: r.diagnostics, assumptions: r.assumptions, warnings: r.warnings, data: r.provenance?.data, spec: r.provenance?.spec })).join("\n");486  return [487    "TEXT UNDER REVIEW",488    m.text.length > 24_000 ? `${m.text.slice(0, 24_000)}\n[text cut for length]` : m.text || "(no prose: the target is a computation result)",489    lab ? `\nQUANT LAB RESULTS STORED WITH IT\n${lab.slice(0, 16_000)}` : "",490    m.provenance ? `\nRECORDED SOURCES\n${JSON.stringify(m.provenance).slice(0, 4000)}` : "",491    `\nDETERMINISTIC CHECKS ALREADY RUN\n${checks.map((c) => `[${c.category}|${c.severity}] ${c.finding} — ${c.evidence}`).join("\n").slice(0, 8000)}`,492  ].filter(Boolean).join("\n");493}494495async function runReview(owner: string, reviewId: string, loaded: { material: ReviewMaterial; subject: string }, deterministic: ReviewCheck[]): Promise<void> {496  const sessionId = `review-${reviewId}`;497  const meter = new UsageMeter({ owner, sessionId, generationId: `review:${reviewId}` });498  let patch: Record<string, unknown>;499  try {500    // Imported here: routes.ts registers this module, and the agent runtime pulls the model services.501    const [{ createToolRunner }, { runReviewer }, { releaseKernel }] = await Promise.all([import("../routes"), import("../services/agents"), import("../services/python/kernel")]);502    const runTool = createToolRunner({ res: { write: () => true }, sessionId, owner, sources: [], customPythonFiguresData: [], pythonCodeUsed: "", monteCarloData: null, figureCount: 0 });503    const out = await runReviewer(504      { id: reviewId, subject: loaded.subject, material: materialForReviewer(loaded.material, deterministic) },505      {506        emit: () => undefined,507        runTool,508        addUsage: (usage, meta) => meter.add({ model: meta?.model ?? "unknown", provider: meta ? providerOf(meta.model) : "anthropic", role: "reviewer", inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, costUsd: usage.costUsd ?? null }),509        isCancelled: () => false,510        leadModel: "",511        owner,512        sessionId,513        generationId: `review:${reviewId}`,514        releaseKernel: (id) => releaseKernel(`${sessionId}:${id}`),515      },516    );517    if (!out.ok) throw new Error(out.report.slice(0, 300));518    const parsed = parseReviewerReport(out.report);519    patch = { status: "done", checks: [...deterministic, ...parsed.checks], verdict: parsed.verdict || out.report.slice(0, 4000), model: out.model, usage: meter.summary(), finishedAt: Date.now() };520  } catch (e) {521    logger.error(`[review] ${reviewId} failed: ${(e as Error).message}`);522    // The deterministic checks stand on their own: they stay in the object, with the reason the reviewer did not finish.523    patch = { status: "error", error: `The reviewer model did not finish: ${String((e as Error).message).slice(0, 300)}`, usage: meter.summary(), finishedAt: Date.now() };524  }525  try {526    writeObject(owner, "review", reviewId, (cur) => (cur ? { ...cur, ...patch } : null));527  } catch (e) {528    logger.error(`[review] ${reviewId} could not be saved: ${(e as Error).message}`);529  }530}531532/** A review that was running when the server stopped will never finish: say so instead of leaving it "running". */533export function closeOrphanedReviews(): number {534  let n = 0;535  try {536    const rows = (pool as Database.Database).prepare("SELECT owner, id FROM vq_objects WHERE kind = 'review' AND deleted = 0 AND data LIKE '%\"status\":\"running\"%'").all() as { owner: string; id: string }[];537    for (const r of rows) {538      writeObject(r.owner, "review", r.id, (cur) =>539        cur && (cur as { status?: string }).status === "running" ? { ...cur, status: "error", error: "The server restarted while this review was running. Its deterministic checks are kept; start it again for the reviewer's verdict.", finishedAt: Date.now() } : null,540      );541      n++;542    }543  } catch (e) {544    logger.warn(`[review] could not close orphaned reviews: ${(e as Error).message}`);545  }546  return n;547}548549export function registerReviewRoutes(app: Express): void {550  closeOrphanedReviews();551  app.post("/api/v2/reviews", async (req: Request, res: Response) => {552    const parsed = bodySchema.safeParse(req.body);553    if (!parsed.success) return res.status(400).json({ error: parsed.error.issues[0].message });554    const me = currentUser(req).id;555    const { target, projectId } = parsed.data;556    if (!allowWrite(me)) return res.status(429).json({ error: "Too many requests. Try again in a moment." });557    if ((running.get(me) ?? 0) >= MAX_RUNNING_PER_OWNER) return res.status(429).json({ error: `${MAX_RUNNING_PER_OWNER} reviews are already running. Wait for one to finish.` });558559    let loaded: Awaited<ReturnType<typeof loadMaterial>>;560    try {561      loaded = await loadMaterial(me, target);562    } catch (e) {563      logger.error(`[review] could not load ${target.type} ${target.id}: ${(e as Error).message}`);564      return res.status(500).json({ error: "The target could not be read." });565    }566    if (!loaded) return res.status(404).json({ error: "Nothing to review: the target was not found, or it has no result yet." });567568    const reviewId = randomUUID();569    const deterministic = runDeterministicChecks(loaded.material);570    try {571      writeObject(me, "review", reviewId, () => ({ target, projectId: projectId ?? null, status: "running", automated: true, checks: deterministic, verdict: null, model: null, usage: null, disclaimer: REVIEW_DISCLAIMER, startedAt: Date.now() }));572    } catch (e) {573      logger.error(`[review] could not create ${reviewId}: ${(e as Error).message}`);574      return res.status(500).json({ error: "The review could not be created." });575    }576    // A review asked from a project is filed in it (the review exists either way).577    if (projectId) {578      try {579        writeObject<Record<string, any>>(me, "project", projectId, (cur) => (cur && Array.isArray(cur.items) ? { ...cur, items: [...cur.items, { id: randomUUID(), type: "review", ref: reviewId, title: `Review — ${target.type}`, addedAt: Date.now() }] } : null));580      } catch (e) {581        logger.warn(`[review] ${reviewId} could not be filed in project ${projectId}: ${(e as Error).message}`);582      }583    }584585    running.set(me, (running.get(me) ?? 0) + 1);586    void runReview(me, reviewId, loaded, deterministic).finally(() => running.set(me, Math.max(0, (running.get(me) ?? 1) - 1)));587    res.status(202).json({ reviewId });588  });589}590
Files main
Menu

Theme