SPB Git

Repository Public MIT

projects.test.ts 39.5 KB 683 lines typescript

1// @vitest-environment node2/**3 * =============================================================================4 *                  SP BOUCHER | SOFTWARE & RESEARCH5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : VQuant9 * File             : server/next/projects.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 * Research projects (contract §5.1): bundle, run, exports and their audit trail, plus the export formats.48 * The chat endpoint is replaced by a stand-in that uses the real generation jobs and the real project hooks but49 * no model; everything else is the real code.50 */51import { afterAll, beforeAll, describe, expect, it } from "vitest";52import fs from "node:fs";53import path from "node:path";54import { inflateRawSync } from "node:zlib";55import type { Request, Response } from "express";56import { bootTestApp, openStream, type TestApp } from "./testkit";5758let t: TestApp;59let projects: typeof import("./projects");60let objects: typeof import("./objects");61let formats: typeof import("./exportFormats");62const written: string[] = [];63let lastChat: { owner: string; body: any; context: string | null } | null = null;6465const SESSION_A = "11111111-aaaa-4aaa-8aaa-111111111111";66const SESSION_B = "22222222-bbbb-4bbb-8bbb-222222222222";67const JOB_A = "job-alice-lab";68const JOB_LEGACY = "job-alice-legacy";69const JOB_B = "job-bob";7071const ANSWER = [72  "# Apple: valuation",73  "",74  "Revenue grew **12 %** and the margin is *stable* at 30 % & rising; cost is $45 to $60 per unit.",75  "",76  "## Data",77  "",78  "| Metric | 2024 | 2025 |",79  "|:---|---:|---:|",80  "| Revenue (G$) | 391.0 | 416.2 |",81  "| EPS | 6.08 | 7.26 |",82  "",83  "The discount rate is $r = r_f + \\beta (r_m - r_f)$ and",84  "",85  "$$",86  "P_0 = \\sum_{t=1}^{T} \\frac{CF_t}{(1+r)^t}",87  "$$",88  "",89  "![Figure 1 — Price and 200-day average](/plots/aapl_200d.png)",90  "",91  "1. First point",92  "2. Second point",93  "   - nested detail",94  "",95  "See [the 10-K](https://www.sec.gov/ixviewer?doc=/Archives/aapl_10k.htm#part2&x=1) and `get_quote`.",96].join("\n");9798const LAB_RESULT = {99  success: true,100  schema: "lab/1",101  engine: "volatility_lab",102  engineVersion: "1.0.0",103  title: "GARCH(1,1) on SPY",104  headline: "Conditional volatility is persistent (0.97).",105  summary: [{ label: "Persistence", value: 0.9712345678, unit: "ratio", kind: "calculated" }, { label: "Observations", value: 2516, unit: "count", kind: "observed" }],106  tables: [{ id: "params", title: "Parameters", columns: [{ key: "name", label: "Parameter" }, { key: "est", label: "Estimate" }], rows: [{ name: "alpha", est: 0.08 }, { name: "beta", est: 0.89 }] }],107  diagnostics: [{ name: "Ljung-Box (10)", statistic: 8.4, pvalue: 0.59, conclusion: "No residual autocorrelation", passed: true }],108  assumptions: ["Returns are close-to-close log returns."],109  warnings: ["Sample includes the 2020 volatility spike."],110  methodology: "## Model\n\nThe variance follows $\\sigma_t^2 = \\omega + \\alpha \\epsilon_{t-1}^2 + \\beta \\sigma_{t-1}^2$.",111  provenance: {112    data: [{ symbol: "SPY", provider: "fmp", retrievedAt: "2026-11-20T14:00:00Z", start: "2016-11-21", end: "2026-11-19", observations: 2516, frequency: "1d", adjusted: true, currency: "USD" }],113    spec: { p: 1, q: 1 },114    seed: 12345,115    software: { python: "3.13.1", arch: "8.0.0" },116    computedAt: "2026-11-20T14:00:03Z",117    durationMs: 2140,118    reproduce: "from arch import arch_model\nres = arch_model(r, p=1, q=1).fit()",119  },120};121122function seed(): void {123  const session = (id: string, owner: string, title: string, messages: unknown[], updatedAtSec: number) =>124    t.db.prepare("INSERT INTO conversation_sessions (id, session_id, title, messages, owner, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(`row-${id}`, id, title, JSON.stringify(messages), owner, updatedAtSec, updatedAtSec);125  session(126    SESSION_A,127    "alice",128    "Apple valuation",129    [130      { question: "Value Apple with a DCF", answer: ANSWER, sources: [{ url: "https://www.sec.gov/aapl-10k", title: "10-K" }], provenance: { sources: [{ tool: "get_income_statement", provider: "fmp", symbols: ["AAPL"], retrievedAt: 1_763_000_000_000, ok: true }] } },131      { question: "And the downside case?", answer: "The downside case assumes 2 % growth.", sources: [] },132    ],133    1_763_000_100,134  );135  session(SESSION_B, "bob", "Bob secret thesis", [{ question: "BOB-SECRET-QUESTION", answer: "BOB-SECRET-CONTENT" }], 1_763_000_200);136  const job = (id: string, owner: string, tool: string, result: unknown, code: string | null) =>137    t.db.prepare("INSERT INTO vq_quant_jobs (id, owner, tool, params, status, started_at, finished_at, result, code) VALUES (?, ?, ?, ?, 'done', ?, ?, ?, ?)").run(id, owner, tool, JSON.stringify({ symbol: "SPY", p: 1, q: 1 }), 1_763_000_000_000, 1_763_000_003_000, JSON.stringify(result), code);138  job(JOB_A, "alice", "volatility_lab", LAB_RESULT, null);139  job(JOB_LEGACY, "alice", "garch", { success: true, persistence: 0.95, forecast: [0.011, 0.012] }, "import numpy as np\nprint('garch')");140  job(JOB_B, "bob", "risk_lab", { ...LAB_RESULT, title: "BOB-SECRET-JOB", headline: "BOB-SECRET-HEADLINE" }, null);141  t.db.prepare("INSERT INTO shared_reports (id, share_id, question, answer, created_at) VALUES ('sr-1', 'abc12345', 'Is Apple overvalued?', 'It depends.', 1763000300)").run();142}143144const put = (user: string, kind: string, id: string, data: unknown, baseRev = 0) => t.api(user, "PUT", `/api/v2/objects/${kind}/${id}`, { data, baseRev });145const exportProject = async (user: string, id: string, body: unknown) => {146  const r = await t.api(user, "POST", `/api/v2/projects/${id}/export`, body);147  if (r.status === 200) written.push(r.body.filename);148  return r;149};150const fileOf = (filename: string) => fs.readFileSync(path.join(path.resolve("downloads"), filename));151152/** Entries of a ZIP archive, read from its central directory and inflated: an independent check of the writer. */153function unzip(buf: Buffer): Record<string, Buffer> {154  const eocd = buf.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]));155  expect(eocd).toBeGreaterThanOrEqual(0);156  const count = buf.readUInt16LE(eocd + 10);157  let at = buf.readUInt32LE(eocd + 16);158  const out: Record<string, Buffer> = {};159  for (let i = 0; i < count; i++) {160    expect(buf.readUInt32LE(at)).toBe(0x02014b50);161    const method = buf.readUInt16LE(at + 10);162    const crc = buf.readUInt32LE(at + 16);163    const size = buf.readUInt32LE(at + 20);164    const rawSize = buf.readUInt32LE(at + 24);165    const nameLen = buf.readUInt16LE(at + 28);166    const local = buf.readUInt32LE(at + 42);167    const name = buf.subarray(at + 46, at + 46 + nameLen).toString("utf8");168    expect(buf.readUInt32LE(local)).toBe(0x04034b50);169    const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);170    const body = buf.subarray(start, start + size);171    const data = method === 8 ? inflateRawSync(body) : Buffer.from(body);172    expect(data.length).toBe(rawSize);173    expect(formats.crc32(data)).toBe(crc);174    out[name] = data;175    at += 46 + nameLen + buf.readUInt16LE(at + 30) + buf.readUInt16LE(at + 32);176  }177  return out;178}179180beforeAll(async () => {181  t = await bootTestApp(async (app) => {182    const { chatBodySchema } = await import("../routes/validation");183    const { startGeneration, attachViewer } = await import("../routes/generations");184    const { registerReportRoutes } = await import("../routes/reports");185    const p = await import("./projects");186    registerReportRoutes(app);187    // Stand-in for POST /api/chat: same body schema, same generation job, same project hooks as server/routes.ts;188    // the "analysis" is a fixed answer saved after a short delay.189    app.post("/api/chat", (req: Request, res: Response) => {190      const parsed = chatBodySchema.safeParse(req.body);191      if (!parsed.success) return res.status(400).json({ error: parsed.error.issues[0].message });192      const me = (req as Request & { vqUser: { id: string } }).vqUser;193      if (parsed.data.query === "REFUSE") return res.status(429).json({ error: "4 analyses tournent déjà." });194      const sessionId = parsed.data.sessionId ?? "generated";195      const projectId = p.resolveProjectId(me.id, parsed.data.projectId, sessionId);196      lastChat = { owner: me.id, body: parsed.data, context: p.projectContextFor(me.id, projectId) };197      const job = startGeneration({ owner: me.id, sessionId, query: parsed.data.query, mode: parsed.data.mode });198      attachViewer(job, res, 0);199      setTimeout(() => {200        t.db.prepare("INSERT INTO conversation_sessions (id, session_id, title, messages, owner, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(`row-${sessionId}`, sessionId, parsed.data.query.slice(0, 60), JSON.stringify([{ question: parsed.data.query, answer: "Stand-in answer." }]), me.id, 1_763_100_000, 1_763_100_000);201        p.linkConversationToProject(me.id, projectId, sessionId, parsed.data.query);202        job.sink.write(`data: ${JSON.stringify({ type: "done", sessionId })}\n\n`);203        job.close();204      }, 600);205    });206  });207  projects = await import("./projects");208  objects = await import("./objects");209  formats = await import("./exportFormats");210  seed();211212  await put("alice", "note", "n1", { title: "Method notes", body: "## Returns\n\nWe use **daily** log returns.\n\n- adjusted for splits\n- adjusted for dividends", projectId: "p1" });213  await put("alice", "note", "n2", { title: "Loose note about the project", body: "Not listed as an item.", projectId: "p1" });214  await put("alice", "note", "n3", { title: "Unrelated note", body: "Other topic." });215  await put("alice", "watchlist", "w1", { name: "Mega caps", symbols: ["AAPL", "MSFT", "NVDA"] });216  await put("alice", "chart", "c1", { symbol: "AAPL", interval: "1d", chartType: "candles", indicators: [{ id: "i1", type: "sma", params: { length: 200 } }] });217  await put("alice", "portfolio", "pf1", { name: "Core", baseCurrency: "USD", positions: [{ symbol: "AAPL", quantity: 10, costBasis: 150 }] });218  objects.writeObject("alice", "review", "rv1", () => ({ status: "done", automated: true, verdict: "Numbers match the stored results.", checks: [{ id: "k1", category: "math", severity: "info", finding: "EPS matches", evidence: "7.26" }] }));219  await put("bob", "note", "bn1", { title: "Bob note", body: "BOB-SECRET-NOTE" });220  await put("alice", "project", "p1", {221    title: "Étude Apple & co. (2026)",222    question: "Is Apple fairly valued at 30x earnings?",223    status: "active",224    hypotheses: [{ id: "h1", text: "Services growth justifies the multiple", status: "open" }, { id: "h2", text: "Hardware margins are peaking", status: "supported" }],225    dataSources: [{ id: "d1", provider: "FMP", description: "Statements and daily prices" }],226    summary: "Work in progress.",227    items: [228      { id: "i-conv", type: "conversation", ref: SESSION_A, title: "DCF conversation", addedAt: 1 },229      { id: "i-job", type: "quant_job", ref: JOB_A, addedAt: 2 },230      { id: "i-legacy", type: "quant_job", ref: JOB_LEGACY },231      { id: "i-note", type: "note", ref: "n1" },232      { id: "i-wl", type: "watchlist", ref: "w1" },233      { id: "i-chart", type: "chart", ref: "c1" },234      { id: "i-pf", type: "portfolio", ref: "pf1" },235      { id: "i-review", type: "review", ref: "rv1" },236      { id: "i-report", type: "report", ref: "abc12345" },237      { id: "i-bob-conv", type: "conversation", ref: SESSION_B, title: "not mine" },238      { id: "i-bob-job", type: "quant_job", ref: JOB_B },239      { id: "i-bob-note", type: "note", ref: "bn1" },240      { id: "i-missing", type: "note", ref: "does-not-exist" },241      { id: "i-notebook", type: "notebook", ref: "nb-1" },242      { id: "i-dataset", type: "dataset", ref: "ds-1", customField: { kept: true } },243    ],244  });245});246247afterAll(async () => {248  for (const f of written) fs.rmSync(path.join(path.resolve("downloads"), f), { force: true });249  await t.close();250});251252describe("bundle", () => {253  it("resolves each item against what it points to", async () => {254    const r = await t.api("alice", "GET", "/api/v2/projects/p1/bundle");255    expect(r.status).toBe(200);256    expect(r.body.project).toMatchObject({ kind: "project", id: "p1", rev: 1, data: { title: "Étude Apple & co. (2026)" } });257    const by = Object.fromEntries(r.body.items.map((i: any) => [i.id, i]));258    expect(r.body.items.map((i: any) => i.id)).toEqual(r.body.project.data.items.map((i: any) => i.id));259    expect(by["i-conv"]).toMatchObject({ type: "conversation", ref: SESSION_A, title: "DCF conversation", addedAt: 1 });260    expect(by["i-conv"].resolved).toEqual({ title: "Apple valuation", status: "done", updatedAt: 1_763_000_100_000, summary: "2 exchanges" });261    expect(by["i-job"].resolved).toEqual({ title: "GARCH(1,1) on SPY", status: "done", updatedAt: 1_763_000_003_000, summary: "Conditional volatility is persistent (0.97)." });262    expect(by["i-legacy"].resolved).toEqual({ title: "garch", status: "done", updatedAt: 1_763_000_003_000, summary: null });263    expect(by["i-note"].resolved).toMatchObject({ title: "Method notes", status: null });264    expect(by["i-note"].resolved.summary).toContain("daily");265    expect(by["i-wl"].resolved).toMatchObject({ title: "Mega caps", summary: "AAPL, MSFT, NVDA" });266    expect(by["i-chart"].resolved).toMatchObject({ title: "AAPL", summary: "1d · candles" });267    expect(by["i-pf"].resolved).toMatchObject({ title: "Core", summary: "1 position" });268    expect(by["i-review"].resolved).toMatchObject({ title: "Automated review", status: "done", summary: "Numbers match the stored results." });269    expect(by["i-report"].resolved).toMatchObject({ title: "Is Apple overvalued?", status: "shared", updatedAt: 1_763_000_300_000 });270    // unknown fields of an item come back untouched271    expect(by["i-dataset"].customField).toEqual({ kept: true });272  });273274  it("answers resolved: null for what does not exist, has no store, or belongs to someone else", async () => {275    const r = await t.api("alice", "GET", "/api/v2/projects/p1/bundle");276    const by = Object.fromEntries(r.body.items.map((i: any) => [i.id, i]));277    for (const id of ["i-bob-conv", "i-bob-job", "i-bob-note", "i-missing", "i-notebook", "i-dataset"]) expect(by[id].resolved).toBeNull();278    expect(JSON.stringify(r.body)).not.toContain("BOB-SECRET");279    expect(JSON.stringify(r.body)).not.toContain("Bob secret thesis");280  });281282  it("is the owner's only", async () => {283    expect((await t.api("bob", "GET", "/api/v2/projects/p1/bundle")).status).toBe(404);284    expect((await t.api("alice", "GET", "/api/v2/projects/nope/bundle")).status).toBe(404);285    expect((await t.api("alice", "GET", "/api/v2/projects/bad.id/bundle")).status).toBe(404);286    expect((await t.api(null, "GET", "/api/v2/projects/p1/bundle")).status).toBe(401);287  });288});289290describe("project context of a conversation", () => {291  it("carries the question, hypotheses, data sources and note titles", () => {292    const ctx = projects.projectContextFor("alice", "p1")!;293    expect(ctx).toContain('research project "Étude Apple & co. (2026)" (status: active)');294    expect(ctx).toContain("Research question: Is Apple fairly valued at 30x earnings?");295    expect(ctx).toContain("- [open] Services growth justifies the multiple");296    expect(ctx).toContain("- [supported] Hardware margins are peaking");297    expect(ctx).toContain("- FMP: Statements and daily prices");298    expect(ctx).toContain("- Method notes");299    expect(ctx).toContain("- Loose note about the project"); // names the project without being an item300    expect(ctx).not.toContain("Unrelated note");301    expect(ctx).toContain("Summary so far: Work in progress.");302    // titles only, never the bodies; nothing of another person303    expect(ctx).not.toContain("log returns");304    expect(ctx).not.toContain("BOB-SECRET");305    expect(ctx).not.toContain("Bob note");306  });307308  it("is null for a project that is not the person's, and for no project", () => {309    expect(projects.projectContextFor("bob", "p1")).toBeNull();310    expect(projects.projectContextFor("alice", "nope")).toBeNull();311    expect(projects.projectContextFor("alice", null)).toBeNull();312    expect(projects.projectContextFor("alice", "../etc")).toBeNull();313  });314315  it("resolveProjectId accepts the person's project, or finds the project that lists the conversation", () => {316    expect(projects.resolveProjectId("alice", "p1", null)).toBe("p1");317    expect(projects.resolveProjectId("bob", "p1", null)).toBeNull();318    expect(projects.resolveProjectId("alice", undefined, SESSION_A)).toBe("p1");319    expect(projects.resolveProjectId("alice", undefined, "unknown-session")).toBeNull();320    // Bob's conversation is listed in Alice's project: that gives Bob nothing321    expect(projects.resolveProjectId("bob", undefined, SESSION_B)).toBeNull();322  });323324  it("linkConversationToProject files a conversation once, and only in the person's own project", () => {325    const before = objects.getObject<any>("alice", "project", "p1")!;326    projects.linkConversationToProject("bob", "p1", "bob-session", "x");327    projects.linkConversationToProject("alice", "p1", SESSION_A, "already there");328    projects.linkConversationToProject("alice", null, "s", "no project");329    expect(objects.getObject("alice", "project", "p1")!.rev).toBe(before.rev);330    expect(objects.getObject("bob", "project", "p1")).toBeNull();331  });332});333334describe("run", () => {335  it("starts a generation with the project's context and files the conversation in the project", async () => {336    const stream = openStream(t.base, "alice");337    const other = openStream(t.base, "bob");338    try {339      await Promise.all([stream, other].map((s) => s.waitFor((e) => e.event === "hello")));340      const r = await t.api("alice", "POST", "/api/v2/projects/p1/run", { prompt: "Stress-test hypothesis H2", mode: "deep", budget: { maxCostUsd: 3 } });341      expect(r.status).toBe(202);342      expect(Object.keys(r.body).sort()).toEqual(["generationId", "sessionId"]);343      expect(r.body.generationId).toMatch(/^[0-9a-f-]{36}$/);344      expect(r.body.sessionId).toMatch(/^[0-9a-f-]{36}$/);345346      // what the chat endpoint received347      expect(lastChat).toMatchObject({ owner: "alice", body: { query: "Stress-test hypothesis H2", mode: "deep", projectId: "p1", sessionId: r.body.sessionId, budget: { maxCostUsd: 3 } } });348      expect(lastChat!.context).toContain("Is Apple fairly valued at 30x earnings?");349350      // filed at once, shown as running while the analysis goes on351      const during = (await t.api("alice", "GET", "/api/v2/projects/p1/bundle")).body.items.filter((i: any) => i.ref === r.body.sessionId);352      expect(during).toHaveLength(1);353      expect(during[0]).toMatchObject({ type: "conversation", title: "Stress-test hypothesis H2" });354      expect(during[0].resolved).toMatchObject({ status: "running", title: "Stress-test hypothesis H2" });355356      // the person's devices hear about it; nobody else does357      await stream.waitFor((e) => e.event === "hint" && e.data.topic === "generations" && e.data.id === r.body.generationId);358      await stream.waitFor((e) => e.event === "change" && e.data.kind === "project" && e.data.id === "p1");359      await stream.waitFor((e) => e.event === "hint" && e.data.topic === "sessions" && e.data.id === r.body.sessionId);360      expect(other.events.filter((e) => e.event !== "hello")).toEqual([]);361362      // the job went on after the wrapper left its stream, and the conversation is filed exactly once363      const after = (await t.api("alice", "GET", "/api/v2/projects/p1/bundle")).body.items.filter((i: any) => i.ref === r.body.sessionId);364      expect(after).toHaveLength(1);365      expect(after[0].resolved).toMatchObject({ status: "done", summary: "1 exchange" });366      // a follow-up in that conversation is recognised as part of the project367      expect(projects.resolveProjectId("alice", undefined, r.body.sessionId)).toBe("p1");368    } finally {369      stream.close();370      other.close();371    }372  });373374  it("passes on the chat endpoint's refusal", async () => {375    const r = await t.api("alice", "POST", "/api/v2/projects/p1/run", { prompt: "REFUSE" });376    expect(r.status).toBe(429);377    expect(r.body).toEqual({ error: "4 analyses tournent déjà." });378  });379380  it("validates its body and is the owner's only", async () => {381    lastChat = null;382    for (const body of [{}, { prompt: "" }, { prompt: "x", mode: "turbo" }, { prompt: "x", budget: { maxCostUsd: -1 } }, { prompt: "x".repeat(10001) }]) {383      expect((await t.api("alice", "POST", "/api/v2/projects/p1/run", body)).status).toBe(400);384    }385    expect((await t.api("bob", "POST", "/api/v2/projects/p1/run", { prompt: "Read Alice's project" })).status).toBe(404);386    expect((await t.api("alice", "POST", "/api/v2/projects/nope/run", { prompt: "x" })).status).toBe(404);387    expect(lastChat).toBeNull();388  });389});390391describe("export", () => {392  it("writes Markdown where /api/download serves it, under an unguessable name", async () => {393    const r = await exportProject("alice", "p1", { format: "md" });394    expect(r.status).toBe(200);395    expect(r.body.filename).toMatch(/^vquant-etude-apple-co-2026-[0-9a-f]{36}\.md$/);396    expect(r.body).toMatchObject({ url: `/api/download/${r.body.filename}`, format: "md" });397    expect(r.body).not.toHaveProperty("compiled");398    const md = fileOf(r.body.filename).toString("utf8");399    expect(r.body.bytes).toBe(Buffer.byteLength(md));400    const served = await fetch(`${t.base}/api/download/${r.body.filename}`, { headers: { "x-test-user": "alice" } });401    expect(served.status).toBe(200);402    expect(await served.text()).toBe(md);403404    // the project405    expect(md.startsWith("# Étude Apple & co. (2026)\n")).toBe(true);406    expect(md).toContain("**Research question.** Is Apple fairly valued at 30x earnings?");407    expect(md).toContain("| H2 | Hardware margins are peaking | supported |");408    expect(md).toContain("- **FMP**: Statements and daily prices");409    // the conversation, its headings pushed below the item's410    expect(md).toContain("## 1. Apple valuation");411    expect(md).toContain("### Question 1\n\nValue Apple with a DCF");412    expect(md).toContain("#### Apple: valuation");413    expect(md).toContain("| Revenue (G$) | 391.0 | 416.2 |");414    expect(md).toContain("### Question 2\n\nAnd the downside case?");415    // the lab job416    expect(md).toContain("## 2. GARCH(1,1) on SPY");417    expect(md).toContain("Conditional volatility is persistent (0.97).");418    expect(md).toContain("| Persistence | 0.97123457 | ratio | calculated |");419    expect(md).toContain("| alpha | 0.08 |");420    expect(md).toContain("| Ljung-Box (10) | 8.4 | 0.59 | No residual autocorrelation |");421    // the legacy job, the note, the other objects422    expect(md).toContain("Result as stored (legacy engine, no structured schema):");423    expect(md).toContain("## 4. Method notes");424    expect(md).toContain("#### Returns");425    expect(md).toContain("_Watchlist._ AAPL, MSFT, NVDA");426    expect(md).toContain("| AAPL | 10 | 150 |");427    expect(md).toContain("_Automated review — not a human peer review._");428    expect(md).toContain("_notebook `nb-1`: not stored on the server");429    expect(md).not.toContain("undefined");430  });431432  it("carries a methodology and provenance appendix made of what was stored, and says what was not", async () => {433    const r = await exportProject("alice", "p1", { format: "md" });434    const md = fileOf(r.body.filename).toString("utf8");435    const a = md.indexOf("## Appendix A — Methodology");436    const b = md.indexOf("## Appendix B — Provenance");437    expect(a).toBeGreaterThan(0);438    expect(b).toBeGreaterThan(a);439    const methodology = md.slice(a, b);440    expect(methodology).toContain("### 2. GARCH(1,1) on SPY");441    expect(methodology).toContain("\\sigma_t^2 = \\omega");442    expect(methodology).toContain("- Returns are close-to-close log returns.");443    const prov = md.slice(b);444    expect(prov).toContain("| get_income_statement | fmp | AAPL | 2025-11-13T02:13:20.000Z | yes |");445    expect(prov).toContain("- <https://www.sec.gov/aapl-10k>");446    expect(prov).toContain("Question 2 — no provenance record is stored with this answer");447    expect(prov).toContain("Engine `volatility_lab` version 1.0.0");448    expect(prov).toContain("| SPY | fmp | 1d | 2016-11-21 | 2026-11-19 | 2516 | true | USD | 2026-11-20T14:00:00Z |");449    expect(prov).toContain("random seed 12345");450    expect(prov).toContain("Software: python 3.13.1, arch 8.0.0.");451    expect(prov).toContain("res = arch_model(r, p=1, q=1).fit()");452    expect(prov).toContain("No provenance record is stored with this computation; the code that ran is in the ZIP export.");453    expect(prov).toMatch(/project `p1`, revision \d+, \d+ of \d+ items/);454  });455456  it("never exports another person's material, even when the project points at it", async () => {457    for (const format of ["md", "tex", "zip"]) {458      const r = await exportProject("alice", "p1", { format });459      const raw = fileOf(r.body.filename);460      const text = format === "zip" ? Object.values(unzip(raw)).map((b) => b.toString("utf8")).join("\n") : raw.toString("utf8");461      expect(text).not.toContain("BOB-SECRET");462      expect(text).not.toContain("Bob secret thesis");463      expect(text).toContain("no longer available");464    }465  });466467  it("exports only the items asked for with include", async () => {468    const r = await exportProject("alice", "p1", { format: "md", include: ["i-note", "i-wl", "not-an-item"] });469    expect(r.body.items).toBe(2);470    const md = fileOf(r.body.filename).toString("utf8");471    expect(md).toContain("## 1. Method notes");472    expect(md).toContain("## 2. Mega caps");473    expect(md).not.toContain("Apple valuation");474    expect(md).not.toContain("GARCH");475    expect(md).toContain("No item of this export carries a stored methodology.");476    expect(md).toContain("No item of this export carries a stored provenance record.");477  });478479  it("writes LaTeX with its own converter and says it was not compiled", async () => {480    const r = await exportProject("alice", "p1", { format: "tex" });481    expect(r.status).toBe(200);482    expect(r.body).toMatchObject({ format: "tex", compiled: false });483    expect(r.body.filename).toMatch(/\.tex$/);484    const tex = fileOf(r.body.filename).toString("utf8");485    expect(tex).toContain("\\documentclass[11pt,a4paper]{article}");486    expect(tex).toContain("\\title{Étude Apple \\& co. (2026)}");487    expect(tex).toContain("\\begin{document}");488    expect(tex.trimEnd().endsWith("\\end{document}")).toBe(true);489    expect(tex).toContain("\\section{1. Apple valuation}");490    expect(tex).toContain("\\subsection{Question 1}");491    expect(tex).toContain("\\emph{Conversation, last updated 2025-11-13T02:15:00.000Z.}");492    expect(tex).toContain("\\section{Appendix A --- Methodology}");493    expect(tex).toContain("\\section{Appendix B --- Provenance}");494    expect(tex).toContain("\\caption{Figure 1 --- Price and 200-day average}");495    expect(tex).toContain("P_0 = \\sum_{t=1}^{T} \\frac{CF_t}{(1+r)^t}");496    expect(tex).toContain("\\begin{longtable}");497    // every environment that opens closes498    for (const env of ["itemize", "enumerate", "longtable", "figure", "verbatim", "quote"]) {499      expect(tex.split(`\\begin{${env}}`).length, env).toBe(tex.split(`\\end{${env}}`).length);500    }501  });502503  it("writes a ZIP with the report, the LaTeX source and the raw items", async () => {504    const r = await exportProject("alice", "p1", { format: "zip" });505    expect(r.status).toBe(200);506    expect(r.body).toMatchObject({ format: "zip", compiled: false });507    const raw = fileOf(r.body.filename);508    expect(raw.subarray(0, 4)).toEqual(Buffer.from([0x50, 0x4b, 0x03, 0x04]));509    const files = unzip(raw);510    const names = Object.keys(files);511    expect(names).toContain("report.md");512    expect(names).toContain("report.tex");513    expect(names).toContain("project.json");514    expect(names).toContain("items/01-conversation.json");515    expect(names).toContain("items/02-quant-job.json");516    expect(names).toContain("items/03-quant-job-code.py");517    expect(names).toContain("items/04-note.json");518    expect(files["report.md"].toString("utf8")).toContain("# Étude Apple & co. (2026)");519    expect(JSON.parse(files["project.json"].toString("utf8"))).toMatchObject({ kind: "project", id: "p1" });520    expect(JSON.parse(files["items/02-quant-job.json"].toString("utf8")).result.provenance.seed).toBe(12345);521    expect(files["items/03-quant-job-code.py"].toString("utf8")).toBe("import numpy as np\nprint('garch')");522    expect(JSON.parse(files["items/01-conversation.json"].toString("utf8")).messages).toHaveLength(2);523  });524525  it("removes its own export files after a week, and nothing else", async () => {526    const dir = path.resolve("downloads");527    const old = (await exportProject("alice", "p1", { format: "md", include: ["i-wl"] })).body.filename;528    const recent = (await exportProject("alice", "p1", { format: "md", include: ["i-wl"] })).body.filename;529    const foreign = `agent-data-${Date.now()}.csv`;530    fs.writeFileSync(path.join(dir, foreign), "a,b\n");531    written.push(foreign);532    const eightDaysAgo = new Date(Date.now() - 8 * 86_400_000);533    fs.utimesSync(path.join(dir, old), eightDaysAgo, eightDaysAgo);534    fs.utimesSync(path.join(dir, foreign), eightDaysAgo, eightDaysAgo);535    expect(projects.sweepExports()).toBe(1);536    expect(fs.existsSync(path.join(dir, old))).toBe(false);537    expect(fs.existsSync(path.join(dir, recent))).toBe(true);538    expect(fs.existsSync(path.join(dir, foreign))).toBe(true);539  });540541  // Needs Chromium: run with VQ_TEST_PDF=1 (it is the existing PDF service; the route only hands it the Markdown).542  it.runIf(process.env.VQ_TEST_PDF === "1")("renders a PDF through the research-note service", async () => {543    const r = await exportProject("alice", "p1", { format: "pdf", include: ["i-conv", "i-job", "i-note"] });544    expect(r.status).toBe(200);545    expect(r.body.filename).toMatch(/\.pdf$/);546    expect(r.body).not.toHaveProperty("compiled");547    const pdf = fileOf(r.body.filename);548    expect(pdf.subarray(0, 5).toString("latin1")).toBe("%PDF-");549    expect(pdf.length).toBeGreaterThan(20_000);550  }, 120_000);551552  it("validates its body and is the owner's only", async () => {553    for (const body of [{}, { format: "docx" }, { format: "md", include: "all" }, { format: "md", include: [1] }]) {554      expect((await t.api("alice", "POST", "/api/v2/projects/p1/export", body)).status).toBe(400);555    }556    const before = fs.readdirSync(path.resolve("downloads")).length;557    expect((await t.api("bob", "POST", "/api/v2/projects/p1/export", { format: "md" })).status).toBe(404);558    expect((await t.api("alice", "POST", "/api/v2/projects/nope/export", { format: "md" })).status).toBe(404);559    expect(fs.readdirSync(path.resolve("downloads")).length).toBe(before);560  });561562  it("is audited, without the file name, for the person who exported", async () => {563    const events = (await t.api("alice", "GET", "/api/v2/audit")).body.events.filter((e: any) => e.action === "project.export");564    expect(events.length).toBeGreaterThanOrEqual(6);565    expect(events.every((e: any) => e.target === "project/p1")).toBe(true);566    expect(events.map((e: any) => e.detail.format)).toContain("zip");567    expect(events[0].detail).toHaveProperty("bytes");568    for (const f of written) expect(JSON.stringify(events)).not.toContain(f);569    expect((await t.api("bob", "GET", "/api/v2/audit")).body.events.filter((e: any) => e.action === "project.export")).toEqual([]);570  });571});572573describe("audit of shares and conversation deletions (server/routes/reports.ts)", () => {574  it("records a shared report", async () => {575    const r = await t.api("alice", "POST", "/api/share", { question: "Is NVDA expensive?", answer: "Relative to what?" });576    expect(r.status).toBe(200);577    const e = (await t.api("alice", "GET", "/api/v2/audit")).body.events.find((x: any) => x.action === "report.share");578    expect(e).toMatchObject({ target: `share/${r.body.shareId}`, detail: { question: "Is NVDA expensive?" }, device: "web" });579  });580581  it("records a deleted conversation, for its owner only", async () => {582    t.db.prepare("INSERT INTO conversation_sessions (id, session_id, title, messages, owner, created_at, updated_at) VALUES ('row-del', 'to-delete', 'Scratch', '[]', 'alice', 1, 1)").run();583    expect((await t.api("bob", "DELETE", "/api/sessions/to-delete")).status).toBe(404);584    expect((await t.api("alice", "DELETE", "/api/sessions/to-delete")).status).toBe(200);585    const alice = (await t.api("alice", "GET", "/api/v2/audit")).body.events;586    expect(alice.filter((x: any) => x.action === "session.delete").map((x: any) => x.target)).toEqual(["session/to-delete"]);587    const bob = (await t.api("bob", "GET", "/api/v2/audit")).body.events;588    expect(bob.some((x: any) => x.action === "session.delete" || x.action === "report.share")).toBe(false);589  });590});591592describe("Markdown → LaTeX", () => {593  it("converts headings, emphasis, links and escapes the special characters", () => {594    const tex = formats.markdownBodyToLatex("# One\n\n## Two\n\n### Three\n\n#### Four\n\n50% of R&D_costs are #1 {fixed} ~ approx, a\\b, x^2.\n\n**bold** and *italic* and `code_span & more`, [link](https://example.com/a_b?x=1&y=2#frag).");595    expect(tex).toContain("\\section{One}");596    expect(tex).toContain("\\subsection{Two}");597    expect(tex).toContain("\\subsubsection{Three}");598    expect(tex).toContain("\\paragraph{Four}");599    expect(tex).toContain("50\\% of R\\&D\\_costs are \\#1 \\{fixed\\} \\textasciitilde{} approx, a\\textbackslash{}b, x\\textasciicircum{}2.");600    expect(tex).toContain("\\textbf{bold} and \\emph{italic} and \\texttt{code\\_span \\& more}");601    expect(tex).toContain("\\href{https://example.com/a\\_b?x=1\\&y=2\\#frag}{link}");602  });603604  it("keeps formulas as math and dollar amounts as text", () => {605    const tex = formats.markdownBodyToLatex("The CAPM gives $r = r_f + \\beta (r_m - r_f)$ and $x$ is small.\n\nIt costs $45 to $60 and the fee is $5.\n\nInline \\(a_1\\) too.\n\n$$\nE = mc^2\n\n$$\n\n\\[ a^2 + b^2 = c^2 \\]\n\n$$ y = \\alpha + \\beta x $$");606    expect(tex).toContain("$r = r_f + \\beta (r_m - r_f)$");607    expect(tex).toContain("$x$ is small");608    expect(tex).toContain("It costs \\$45 to \\$60 and the fee is \\$5.");609    expect(tex).toContain("Inline $a_1$ too.");610    expect(tex).toContain("\\[\nE = mc^2\n\\]");611    expect(tex).toContain("\\[\n a^2 + b^2 = c^2 \n\\]");612    expect(tex).toContain("\\[\n y = \\alpha + \\beta x \n\\]");613  });614615  it("converts lists, nested and mixed, and closes them", () => {616    const tex = formats.markdownBodyToLatex("- one\n- two\n  - two.a\n  - two.b\n    1. deep\n- three\n\n1. first\n2. second\n\n- [ ] todo\n- [x] done\n\nAfter.");617    const flat = tex.replace(/\n+/g, " ");618    expect(flat).toContain("\\begin{itemize} \\item{} one \\item{} two \\begin{itemize} \\item{} two.a \\item{} two.b \\begin{enumerate} \\item{} deep \\end{enumerate} \\end{itemize} \\item{} three \\end{itemize}");619    expect(flat).toContain("\\begin{enumerate} \\item{} first \\item{} second \\end{enumerate}");620    expect(flat).toContain("\\item{} [ ] todo \\item{} [x] done \\end{itemize} After.");621  });622623  it("converts pipe tables with their alignment, and a cell's own formatting", () => {624    const tex = formats.markdownBodyToLatex("| Name | Value | Note |\n|:---|---:|:---:|\n| **Rev** | 1,234 | 5% |\n| a_b | $x^2$ | |\n\nNot a table: a | b");625    expect(tex).toContain("\\begin{longtable}{@{}lrc@{}}");626    expect(tex).toContain("\\textbf{Name} & \\textbf{Value} & \\textbf{Note} \\\\");627    expect(tex).toContain("\\textbf{Rev} & 1,234 & 5\\% \\\\");628    expect(tex).toContain("a\\_b & $x^2$ &  \\\\");629    expect(formats.markdownBodyToLatex("| a | b |\n|---|---|\n| $p < 0.05$ | _note_ on snake_case_name |")).toContain("$p < 0.05$ & \\emph{note} on snake\\_case\\_name \\\\");630    expect(tex).toContain("\\bottomrule\n\\end{longtable}");631    expect(tex).toContain("Not a table: a | b");632  });633634  it("turns images into captioned figure placeholders, code into verbatim, quotes into quote", () => {635    const tex = formats.markdownBodyToLatex("![Figure 2 — Drawdown & recovery](/plots/dd_1.png)\n\n![](data:image/png;base64,AAAA)\n\nSee ![inline](x.png) here.\n\n```python\nx = {'a': 1}  # 100%\n```\n\n> Quoted *text*\n> second line\n\n---\n\nEnd.");636    expect(tex).toContain("\\begin{figure}[htbp]");637    expect(tex).toContain("\\texttt{/plots/dd\\_1.png}");638    expect(tex).toContain("\\caption{Figure 2 --- Drawdown \\& recovery}");639    expect(tex).toContain("\\texttt{embedded image}");640    expect(tex).toContain("\\caption{Figure}");641    expect(tex).not.toContain("AAAA");642    expect(tex).toContain("See \\emph{[figure: inline]} here.");643    expect(tex).toContain("\\begin{verbatim}\nx = {'a': 1}  # 100%\n\\end{verbatim}");644    expect(tex).toContain("\\begin{quote}\nQuoted \\emph{text} second line\n\\end{quote}");645    expect(tex).toContain("\\hrule");646    expect(tex.trimEnd().endsWith("End.")).toBe(true);647  });648649  it("maps the symbols the reports use and drops emoji", () => {650    expect(formats.texEscape("A → B ≥ 3 × 2 ± 1 € 5 — ok … “q” 🚀✅")).toBe("A $\\rightarrow$ B $\\geq$ 3 $\\times$ 2 $\\pm$ 1 \\texteuro{} 5 --- ok \\ldots{} ``q'' ");651  });652653  it("wraps the body in a complete document", () => {654    const tex = formats.markdownToLatex("Hello *world*.", { title: "R&D 100%", author: "VQuant", date: "2026-11-20" });655    expect(tex).toContain("\\title{R\\&D 100\\%}");656    expect(tex).toContain("\\date{2026-11-20}");657    expect(tex.indexOf("\\begin{document}")).toBeLessThan(tex.indexOf("Hello \\emph{world}."));658    expect(tex.indexOf("Hello \\emph{world}.")).toBeLessThan(tex.indexOf("\\end{document}"));659    // the top heading level in use becomes \section, whatever it is; headings inside code are not counted660    const shifted = formats.markdownToLatex("```\n# not a heading\n```\n\n### Top\n\n#### Below", { title: "T" });661    expect(shifted).toContain("\\section{Top}");662    expect(shifted).toContain("\\subsection{Below}");663    expect(shifted).toContain("# not a heading");664    expect(formats.markdownToLatex("# A\n\n## B", { title: "T" })).toContain("\\subsection{B}");665  });666});667668describe("ZIP writer", () => {669  it("computes the standard CRC-32", () => {670    expect(formats.crc32(Buffer.from("123456789"))).toBe(0xcbf43926);671    expect(formats.crc32(Buffer.alloc(0))).toBe(0);672  });673674  it("round-trips text, binary, empty and UTF-8 named entries", () => {675    const binary = Buffer.from(Array.from({ length: 5000 }, (_x, i) => (i * 7919) % 256));676    const files = unzip(formats.zipArchive([{ name: "a.txt", data: "hello ".repeat(1000) }, { name: "dir/é.bin", data: binary }, { name: "empty", data: "" }]));677    expect(Object.keys(files)).toEqual(["a.txt", "dir/é.bin", "empty"]);678    expect(files["a.txt"].toString("utf8")).toBe("hello ".repeat(1000));679    expect(files["dir/é.bin"].equals(binary)).toBe(true);680    expect(files.empty.length).toBe(0);681  });682});683
Files main
Menu

Theme