Repository Public MIT
1// @vitest-environment node2/**3 * =============================================================================4 * SP BOUCHER | SOFTWARE & RESEARCH5 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project : VQuant9 * File : server/next/review.test.ts10 * Module : server11 * Repository : https://git.spboucher.ai/vquant12 * Project Website : https://vquant.spboucher.ai13 * Created : 2026-11-2014 * Last Modified : 2026-11-2015 *16 * Author : Simon-Pierre Boucher17 * Position : Professor of Finance18 * Institution : Université du Québec en Outaouais (UQO)19 * Organization : SP Boucher20 * Website : https://spboucher.ai21 * Git : https://git.spboucher.ai22 *23 * Preferred Contact: contact@spboucher.ai24 * Development : dev@spboucher.ai25 * Support : support@spboucher.ai26 * Security/Admin : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * SPDX Identifier : MIT35 * License : MIT License36 * License File : LICENSE37 *38 * Do not embed credentials, private keys, access tokens,39 * certificates or confidential personal information.40 *41 * =============================================================================42 * END OF SP BOUCHER SOURCE HEADER43 * =============================================================================44 */4546/**47 * Automated review (contract §5.3): the deterministic checks on fixtures, the reviewer-report parser, and the48 * route on a temporary database with the reviewer model replaced by a canned report (no model is called).49 */50import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";51import { bootTestApp, sleep, type TestApp } from "./testkit";5253const reviewer = vi.hoisted(() => ({ report: "", ok: true, calls: [] as any[] }));54vi.mock("../services/agents", () => ({55 runReviewer: async (o: any, ctx: any) => {56 reviewer.calls.push(o);57 ctx.addUsage({ inputTokens: 1000, outputTokens: 100, cost: 0.003, costUsd: 0.003 }, { model: "claude-sonnet-5-5", role: "reviewer" });58 return { report: reviewer.report, tools: 2, ok: reviewer.ok, model: "claude-sonnet-5-5" };59 },60}));61vi.mock("../routes", () => ({ createToolRunner: () => async () => ({}) }));62vi.mock("../services/python/kernel", () => ({ releaseKernel: () => undefined }));6364let t: TestApp;65let review: typeof import("./review");6667beforeAll(async () => {68 t = await bootTestApp(async (app) => (await import("./review")).registerReviewRoutes(app));69 review = await import("./review");70});71afterAll(async () => {72 await t.close();73});7475const check = (checks: Array<{ id: string }>, id: string): any => checks.find((c) => c.id === id);7677const BACKTEST = {78 schema: "lab/1", engine: "backtest", headline: "Sharpe 1.42 over 2015–2024",79 summary: [{ label: "Sharpe", value: 1.4213 }, { label: "CAGR", value: 0.1234, unit: "percent" }, { label: "Max drawdown", value: -0.2371 }],80 diagnostics: [{ name: "Alpha t-test", statistic: 2.9, pvalue: 0.004, conclusion: "Alpha is significant at the 1% level", passed: true }],81 tables: [{ id: "coef", title: "Regression", rows: [{ term: "alpha", coef: 0.0031, p_value: 0.004 }, { term: "beta", coef: 0.92, p_value: 0.0001 }] }],82 warnings: [],83 provenance: { data: [{ symbol: "SPY", provider: "fmp", start: "2015-01-02", end: "2024-12-31", observations: 2516 }], spec: { signal_lag: 1 }, seed: null },84};8586describe("numbers", () => {87 it("parses English and French number formats", () => {88 const p = (s: string) => review.parseLocaleNumber(s)?.value;89 expect(p("1,234.5")).toBe(1234.5);90 expect(p("1 234,5")).toBe(1234.5);91 expect(p("12,5")).toBe(12.5);92 expect(p("1,234")).toBe(1234);93 expect(p("1.234.567")).toBe(1234567);94 expect(p("0.125")).toBe(0.125);95 expect(p("215.9")).toBe(215.9);96 expect(p("abc")).toBeUndefined();97 });9899 it("extracts the figures of a text and leaves out years, small counts, dates, code and links", () => {100 const text = "En 2024, le chiffre d'affaires atteint 215,9 Md$ (+12,5 %), soit 3 segments. Cours : 1 234,50 $ au 2026-11-20 à 16:00. Voir  et `x = 99.9`.\n```python\nprint(123.456)\n```\nVolume 1,250,000 titres; ratio 0.87; 5 M d'actions; 450 employés.";101 const got = review.extractQuotedNumbers(text).map((q) => [q.value, q.percent]);102 expect(got).toEqual([[215.9e9, false], [12.5, true], [1234.5, false], [41.2, false], [1_250_000, false], [0.87, false], [5e6, false], [450, false]]);103 });104105 it("finds a quoted figure in results across rounding and units, and not when it is absent", () => {106 const pool = review.collectResultNumbers([{ revenue: 215_938_000_000, growth: 0.1249, price: 1234.4967, note: "Volatility 23.47% annualised over 504 sessions" }, [{ pe: 31.26 }]]);107 const q = (s: string) => review.extractQuotedNumbers(s)[0];108 expect(review.numberIsSupported(q("215.9 B"), pool)).toBe(true); // scaled amount, rounded109 expect(review.numberIsSupported(q("215,9 milliards"), pool)).toBe(true);110 expect(review.numberIsSupported(q("12.5 %"), pool)).toBe(true); // stored as a ratio111 expect(review.numberIsSupported(q("1,234.50"), pool)).toBe(true);112 expect(review.numberIsSupported(q("23.5%"), pool)).toBe(true); // figure written inside a string result113 expect(review.numberIsSupported(q("31.3"), pool)).toBe(true);114 expect(review.numberIsSupported(q("14.2 %"), pool)).toBe(false);115 expect(review.numberIsSupported(q("219.4 B"), pool)).toBe(false);116 expect(review.numberIsSupported(q("35.9"), pool)).toBe(false);117 });118});119120describe("deterministic checks", () => {121 it("passes a consistent answer", () => {122 const checks = review.runDeterministicChecks({123 kind: "session",124 text: "Sur 2015–2024 (2 516 séances), la stratégie affiche un Sharpe de 1.42 et un rendement annualisé de 12.3 %, avec un alpha statistiquement significatif (p = 0.004). Drawdown maximal : 23.7 %.",125 results: [{ jobId: "j", result: BACKTEST }],126 labResults: [BACKTEST],127 provenance: [{ tool: "run_quant_engine", provider: "quant-engine", ok: true }],128 });129 expect(check(checks, "numbers")).toMatchObject({ category: "math", severity: "info" });130 expect(check(checks, "sample")).toMatchObject({ category: "statistics", severity: "info" });131 expect(check(checks, "leakage")).toMatchObject({ severity: "info" });132 expect(check(checks, "provenance")).toMatchObject({ severity: "info" });133 expect(checks.filter((c) => c.severity !== "info")).toEqual([]);134 });135136 it("flags figures that are not in the stored results, with where they are quoted", () => {137 const checks = review.runDeterministicChecks({138 kind: "session",139 text: "Revenue reached 219.4 B (+14.2 %) and the P/E is 31.3. Net margin 26.9 %.",140 results: [{ revenue: 215_938_000_000, growth: 0.1249, pe: 31.26 }],141 labResults: [],142 provenance: [{ tool: "get_income_statement", provider: "fmp", ok: true }],143 });144 const n = check(checks, "numbers");145 expect(n.severity).toBe("warning");146 expect(n.finding).toMatch(/^3 of 4 figures/);147 expect(n.evidence).toContain('"219.4 B"');148 expect(n.evidence).toContain('"14.2 %"');149 expect(n.evidence).toContain('"26.9 %"');150 expect(n.evidence).not.toContain('"31.3"');151 });152153 it("escalates when most of many figures are unsupported, and warns when nothing is stored", () => {154 const text = "Values: 11.1, 22.2, 33.3, 44.4, 55.5, 66.6 and 77.7.";155 expect(check(review.runDeterministicChecks({ kind: "session", text, results: [{ a: 11.1 }], labResults: [], provenance: [] }), "numbers").severity).toBe("error");156 expect(check(review.runDeterministicChecks({ kind: "session", text, results: [], labResults: [], provenance: [] }), "numbers")).toMatchObject({ severity: "warning" });157 expect(check(review.runDeterministicChecks({ kind: "note", text, results: [], labResults: [], provenance: null }), "numbers")).toMatchObject({ severity: "info" });158 expect(check(review.runDeterministicChecks({ kind: "note", text: "Just words.", results: [], labResults: [], provenance: null }), "numbers").finding).toMatch(/quotes no figure/);159 });160161 it("asks for sample size and period behind statistical statements", () => {162 const run = (text: string) => check(review.runDeterministicChecks({ kind: "note", text, results: [], labResults: [], provenance: null }), "sample");163 expect(run("The correlation between the two is 0.82 and volatility is high.")).toMatchObject({ severity: "warning", finding: expect.stringMatching(/a sample size or the period covered/) });164 expect(run("Over 2019-2024 the correlation is 0.82.")).toMatchObject({ severity: "warning", finding: expect.stringMatching(/without a sample size\.$/) });165 expect(run("Correlation of 0.82 on 1 258 sessions since 2020.")).toMatchObject({ severity: "info" });166 expect(run("The company sells phones.")).toBeUndefined();167 });168169 it("warns about small samples reported by an engine", () => {170 const small = { ...BACKTEST, engine: "regression", provenance: { data: [{ symbol: "XYZ", start: "2026-01-01", end: "2026-01-31", observations: 21 }] } };171 const checks = review.runDeterministicChecks({ kind: "quant_job", text: "", results: [small], labResults: [small], provenance: null });172 expect(check(checks, "sample-small")).toMatchObject({ severity: "warning", evidence: "XYZ: 21" });173 });174175 it("reads look-ahead and leakage flags from a backtest result", () => {176 const flagged = (extra: Record<string, unknown>) => review.collectLeakageFlags([{ ...BACKTEST, ...extra }]);177 // The backtest engine's own flags: a check that ran and passed is good news, not a leakage signal.178 expect(flagged({ provenance: { spec: { lookAheadChecked: true, lookAheadPassed: true, lookAheadDates: 5, look_ahead: { checked: true, passed: true, method: "truncation", datesTested: 5 }, leakage: false, signal_lag: 1 } } })).toEqual([]);179 expect(flagged({ provenance: { spec: { lookAheadPassed: false } } })[0]).toMatchObject({ severity: "error" });180 expect(flagged({ provenance: { spec: { survivorship_warning: true } } })[0]).toMatchObject({ severity: "warning" });181 expect(flagged({})).toEqual([]);182 expect(flagged({ flags: { look_ahead: true } })).toMatchObject([{ severity: "error", detail: "flags.look_ahead = true" }]);183 expect(flagged({ flags: { look_ahead: false, no_lookahead: true, lookahead_free: true } })).toEqual([]);184 expect(flagged({ flags: { no_lookahead: false } })).toMatchObject([{ severity: "error" }]);185 expect(flagged({ provenance: { spec: { signal_lag: 0 } } })).toMatchObject([{ severity: "error", detail: expect.stringContaining("signal_lag = 0") }]);186 expect(flagged({ warnings: ["Possible look-ahead: fundamentals are not point-in-time"] })).toMatchObject([{ severity: "warning", where: "backtest · warnings" }]);187 expect(flagged({ checks: { leakage: ["feature 'next_close' uses future data"] } })).toMatchObject([{ severity: "warning" }]);188189 const bad = { ...BACKTEST, flags: { look_ahead: true } };190 expect(check(review.runDeterministicChecks({ kind: "quant_job", text: "", results: [bad], labResults: [bad], provenance: null }), "leakage")).toMatchObject({ category: "leakage", severity: "error" });191 // A backtest told in prose only cannot be checked.192 expect(check(review.runDeterministicChecks({ kind: "session", text: "Our backtest of the strategy over 2010-2020 (2 500 sessions) returns 14.5 %.", results: [{ x: 14.5 }], labResults: [], provenance: [] }), "leakage")).toMatchObject({ severity: "warning", finding: expect.stringMatching(/not run through the backtest engine/) });193 });194195 it("reports missing and failed provenance", () => {196 const base = { kind: "session" as const, text: "Price 123.45.", results: [{ p: 123.45 }], labResults: [] };197 expect(check(review.runDeterministicChecks({ ...base, provenance: null }), "provenance")).toMatchObject({ category: "reproducibility", severity: "warning" });198 expect(check(review.runDeterministicChecks({ ...base, provenance: [] }), "provenance")).toMatchObject({ category: "citations", severity: "warning" });199 expect(check(review.runDeterministicChecks({ ...base, provenance: [{ tool: "get_stock_quote", provider: "fmp", ok: true }, { tool: "findata_get_bars", provider: "findata", ok: false }] }), "provenance")).toMatchObject({ severity: "warning", finding: "1 of 2 recorded sources failed when called.", evidence: "findata_get_bars (findata)" });200 const noData = { ...BACKTEST, provenance: { data: [] } };201 expect(check(review.runDeterministicChecks({ kind: "quant_job", text: "", results: [noData], labResults: [noData], provenance: null }), "provenance-backtest")).toMatchObject({ category: "reproducibility", severity: "warning" });202 });203204 it("confronts significance wording with the p-values of a lab result", () => {205 expect(review.collectPValues([BACKTEST]).map((p) => p.p)).toEqual([0.004, 0.004, 0.0001]);206207 const weak = { ...BACKTEST, diagnostics: [{ name: "Alpha t-test", pvalue: 0.31, conclusion: "Alpha is significant" }, { name: "ADF", pvalue: 0.002, conclusion: "Fail to reject the unit root: not significant" }], tables: [] };208 const checks = review.runDeterministicChecks({ kind: "quant_job", text: "Alpha is significant", results: [weak], labResults: [weak], provenance: null });209 const sig = checks.filter((c) => c.id.startsWith("significance"));210 expect(sig.map((c) => [c.severity, c.category])).toEqual([["error", "statistics"], ["warning", "statistics"]]);211 expect(sig[0].finding).toContain("0.31");212213 const none = { ...BACKTEST, diagnostics: [{ name: "t", pvalue: 0.2, conclusion: "weak evidence" }], tables: [] };214 expect(check(review.runDeterministicChecks({ kind: "session", text: "The effect is statistically significant over 2015–2024 (n = 2516).", results: [none], labResults: [none], provenance: [{ ok: true }] }), "significance")).toMatchObject({ category: "interpretation", severity: "warning", finding: expect.stringContaining("smallest stored p-value is 0.2") });215 expect(check(review.runDeterministicChecks({ kind: "note", text: "L'effet est statistiquement significatif.", results: [], labResults: [], provenance: null }), "significance")).toMatchObject({ severity: "warning", finding: expect.stringMatching(/no p-value is stored/) });216 expect(check(review.runDeterministicChecks({ kind: "note", text: "The effect is not statistically significant.", results: [], labResults: [], provenance: null }), "significance")).toBeUndefined();217 });218});219220describe("reviewer report", () => {221 it("splits the verdict from well-formed findings and ignores the rest", () => {222 const out = review.parseReviewerReport(223 "The valuation holds.\nThe growth claim does not.\n\nFINDINGS\n[math|error] Revenue growth is 12.5 %, not 14.2 % — FMP income statement FY2025 vs FY2024, as of 2026-11-20\n- [statistics|warning] Sample of 21 days is too short\n[style|info] not a category\nstray line\n[citations|INFO] Source named -- 10-K",224 );225 expect(out.verdict).toBe("The valuation holds.\nThe growth claim does not.");226 expect(out.checks).toEqual([227 { id: "reviewer-1", category: "math", severity: "error", finding: "Revenue growth is 12.5 %, not 14.2 %", evidence: "FMP income statement FY2025 vs FY2024, as of 2026-11-20" },228 { id: "reviewer-2", category: "statistics", severity: "warning", finding: "Sample of 21 days is too short", evidence: "" },229 { id: "reviewer-3", category: "citations", severity: "info", finding: "Source named", evidence: "10-K" },230 ]);231 });232});233234describe("POST /api/v2/reviews", () => {235 const waitDone = async (user: string, id: string) => {236 for (let i = 0; i < 100; i++) {237 const r = await t.api(user, "GET", `/api/v2/objects/review/${id}`);238 if (r.body?.object?.data?.status && r.body.object.data.status !== "running") return r.body.object.data;239 await sleep(20);240 }241 throw new Error("review did not finish");242 };243244 it("validates the body and answers 404 for what is not the person's", async () => {245 expect((await t.api("alice", "POST", "/api/v2/reviews", {})).status).toBe(400);246 expect((await t.api("alice", "POST", "/api/v2/reviews", { target: { type: "report", id: "x" } })).status).toBe(400);247 expect((await t.api("alice", "POST", "/api/v2/reviews", { target: { type: "note", id: "missing" } })).status).toBe(404);248 expect((await t.api("alice", "POST", "/api/v2/reviews", { target: { type: "quant_job", id: "missing" } })).status).toBe(404);249 expect((await t.api("alice", "POST", "/api/v2/reviews", { target: { type: "session", id: "missing" } })).status).toBe(404);250 expect((await t.api(null, "POST", "/api/v2/reviews", { target: { type: "note", id: "n1" } })).status).toBe(401);251 expect(reviewer.calls).toHaveLength(0);252 });253254 it("reviews a quant job: deterministic checks, then the reviewer, stored as a review object with usage and the disclaimer", async () => {255 const bad = { ...BACKTEST, flags: { look_ahead: true } };256 t.db.prepare("INSERT INTO vq_quant_jobs (id, owner, tool, params, status, started_at, finished_at, result) VALUES ('job1', 'bob', 'backtest', '{}', 'done', 1, 2, ?)").run(JSON.stringify(bad));257 expect((await t.api("alice", "POST", "/api/v2/reviews", { target: { type: "quant_job", id: "job1" } })).status).toBe(404); // not Alice's job258259 reviewer.report = "The backtest is not usable as it stands.\n\nFINDINGS\n[leakage|error] Signals use same-bar closes — spec and flags of the job";260 const r = await t.api("bob", "POST", "/api/v2/reviews", { target: { type: "quant_job", id: "job1" } });261 expect(r.status).toBe(202);262 expect(r.body.reviewId).toMatch(/^[0-9a-f-]{36}$/);263264 const data = await waitDone("bob", r.body.reviewId);265 expect(data).toMatchObject({ target: { type: "quant_job", id: "job1" }, status: "done", automated: true, model: "claude-sonnet-5-5", disclaimer: "Automated review — not a human peer review.", verdict: "The backtest is not usable as it stands." });266 expect(check(data.checks, "leakage")).toMatchObject({ severity: "error" });267 expect(check(data.checks, "reviewer-1")).toMatchObject({ category: "leakage", severity: "error" });268 expect(data.usage).toMatchObject({ inputTokens: 1000, outputTokens: 100, costUsd: 0.003, byModel: [{ model: "claude-sonnet-5-5", role: "reviewer", calls: 1 }] });269 expect(t.db.prepare("SELECT role, generation_id FROM vq_usage WHERE owner = 'bob' AND role = 'reviewer'").all()).toEqual([{ role: "reviewer", generation_id: `review:${r.body.reviewId}` }]);270271 // The reviewer was given the material and the deterministic findings.272 const sent = reviewer.calls.at(-1);273 expect(sent.subject).toContain("job1");274 expect(sent.material).toContain("DETERMINISTIC CHECKS ALREADY RUN");275 expect(sent.material).toContain("[leakage|error]");276 // Another person cannot read it.277 expect((await t.api("alice", "GET", `/api/v2/objects/review/${r.body.reviewId}`)).status).toBe(404);278 });279280 it("reviews the last answer of a conversation against its stored tool results and provenance", async () => {281 const turns = [282 { question: "old", answer: "old answer 999.9" },283 { question: "Valorisation de ACME ?", answer: "Le chiffre d'affaires atteint 215,9 Md$ et le P/E est de 35.9.", toolResults: [{ tool: "get_income_statement", result: [{ revenue: 215_938_000_000 }] }, { tool: "get_key_metrics", result: [{ peRatio: 31.26 }] }], provenance: [{ tool: "get_income_statement", provider: "fmp", symbols: ["ACME"], ok: true }] },284 ];285 t.db.prepare("INSERT INTO conversation_sessions (id, session_id, title, messages, owner, created_at, updated_at) VALUES ('c1', 'sess-1', 'ACME', ?, 'carol', 1, 1)").run(JSON.stringify(turns));286 reviewer.report = "Mostly fine.\nFINDINGS\n[math|warning] P/E is 31.3 — FMP key metrics";287 const r = await t.api("carol", "POST", "/api/v2/reviews", { target: { type: "session", id: "sess-1" } });288 expect(r.status).toBe(202);289 const data = await waitDone("carol", r.body.reviewId);290 const numbers = check(data.checks, "numbers");291 expect(numbers.finding).toMatch(/^1 of 2 figures/);292 expect(numbers.evidence).toContain('"35.9"');293 expect(check(data.checks, "provenance")).toMatchObject({ severity: "info" });294 expect(data.checks.at(-1)).toMatchObject({ id: "reviewer-1", category: "math" });295 expect((await t.api("dave", "POST", "/api/v2/reviews", { target: { type: "session", id: "sess-1" } })).status).toBe(404);296 });297298 it("keeps the deterministic checks when the reviewer does not finish", async () => {299 await t.api("erin", "PUT", "/api/v2/objects/note/n1", { data: { title: "Idée", body: "La corrélation est de 0.82." }, baseRev: 0 });300 reviewer.ok = false;301 reviewer.report = "This sub-analyst failed before finishing: Claude API (529): overloaded";302 const r = await t.api("erin", "POST", "/api/v2/reviews", { target: { type: "note", id: "n1" } });303 reviewer.ok = true;304 expect(r.status).toBe(202);305 const data = await waitDone("erin", r.body.reviewId);306 expect(data.status).toBe("error");307 expect(data.error).toMatch(/reviewer model did not finish/);308 expect(data.verdict).toBeNull();309 expect(check(data.checks, "sample")).toMatchObject({ severity: "warning" });310 expect(data.disclaimer).toBe(review.REVIEW_DISCLAIMER);311 });312});313