SPB Git

Repository Public MIT

research.test.ts 47.1 KB 631 lines typescript

1// @vitest-environment node2/**3 * =============================================================================4 *                  SP BOUCHER | SOFTWARE & RESEARCH5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : VQuant9 * File             : server/services/research/research.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 workspace, ledger, memory, library, uploads, runs, approvals and the research API (contract §9), on a48 * temporary database and a temporary research root. Runs are real sandboxed Python processes; no model is called.49 */50import { afterAll, beforeAll, describe, expect, it } from "vitest";51import fs from "node:fs";52import os from "node:os";53import path from "node:path";54import { bootTestApp, sleep, type TestApp } from "../../next/testkit";5556let t: TestApp;57let root: string;58let store: typeof import("./store");59let runtime: typeof import("./runtime");60let tools: typeof import("./tools");6162beforeAll(async () => {63  root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "vq-research-")));64  process.env.VQ_RESEARCH_DIR = root;65  process.env.VQ_RESEARCH_APPROVAL_WAIT_SECONDS = "2";66  t = await bootTestApp(async (app) => (await import("../../next/research")).registerResearchRoutes(app));67  store = await import("./store");68  runtime = await import("./runtime");69  tools = await import("./tools");70});71afterAll(async () => {72  await t.close();73  fs.rmSync(root, { recursive: true, force: true });74});7576const ctx = (owner: string, sessionId: string, events: any[] = [], extra: Record<string, unknown> = {}) => ({ owner, sessionId, generationId: `gen-${sessionId}`, emit: (e: Record<string, unknown>) => void events.push(e), ...extra });77const call = (name: string, input: unknown, c: ReturnType<typeof ctx>) => tools.executeResearchTool({ id: "t1", name, input }, c) as Promise<any>;7879describe("workspaces and paths", () => {80  it("gives each conversation its own directory, and the conversations of a project a shared one", () => {81    const a = store.ensureWorkspace("alice", { sessionId: "sess-a1", title: "Étude" });82    expect(a).toMatchObject({ id: "s-sess-a1", kind: "session", title: "Étude", dir: path.join(root, "alice", "s-sess-a1") });83    for (const d of ["code", "data", "artifacts", "runs", "logs"]) expect(fs.statSync(path.join(a.dir, d)).isDirectory()).toBe(true);84    const p1 = store.ensureWorkspace("alice", { sessionId: "sess-a2", projectId: "proj1" });85    const p2 = store.ensureWorkspace("alice", { sessionId: "sess-a3", projectId: "proj1" });86    expect(p1.id).toBe("p-proj1");87    expect(p2.dir).toBe(p1.dir);88    expect(store.sessionsOfWorkspace("alice", "p-proj1").sort()).toEqual(["sess-a2", "sess-a3"]);89    // A conversation keeps the workspace it started with.90    expect(store.ensureWorkspace("alice", { sessionId: "sess-a1", projectId: "proj1" }).id).toBe("s-sess-a1");91    expect(store.workspaceOfSession("alice", "sess-a2")!.id).toBe("p-proj1");92    expect(store.workspaceOfSession("bob", "sess-a2")).toBeNull();93    expect(store.getWorkspace("bob", "s-sess-a1")).toBeNull();94  });9596  it("refuses every path that leaves the workspace", () => {97    const ws = store.ensureWorkspace("alice", { sessionId: "sess-a1" });98    fs.writeFileSync(path.join(root, "outside.txt"), "secret");99    fs.symlinkSync(path.join(root, "outside.txt"), path.join(ws.dir, "data", "link.txt"));100    fs.symlinkSync(root, path.join(ws.dir, "data", "linkdir"));101    for (const p of ["../outside.txt", "/etc/passwd", "data/../../outside.txt", "~/x", "data/link.txt", "data/linkdir/outside.txt", "", "a\0b", "..", "code/../../../x"]) expect(() => store.resolveInside(ws.dir, p), JSON.stringify(p)).toThrow(store.ResearchError);102    expect(() => store.resolveInside(ws.dir, ".site/evil.py", { userVisible: true })).toThrow(/internal/);103    expect(store.resolveInside(ws.dir, "code/new/deep/file.py")).toBe(path.join(ws.dir, "code/new/deep/file.py"));104    expect(() => store.readTextFile(ws, "data/link.txt")).toThrow(store.ResearchError);105    expect(() => store.writeTextFile(ws, "data/linkdir/planted.txt", "x")).toThrow(store.ResearchError);106    expect(fs.existsSync(path.join(root, "planted.txt"))).toBe(false);107    // Links are not listed either.108    expect(store.listFiles(ws, "data").map((f) => f.path)).toEqual([]);109    // A file path reported by sandboxed code is only trusted inside the workspace.110    fs.writeFileSync(path.join(ws.dir, "artifacts", "ok.xlsx"), "x");111    expect(tools.trustedOutputFile(ws, path.join(ws.dir, "artifacts", "ok.xlsx"))).toBe(path.join(ws.dir, "artifacts", "ok.xlsx"));112    expect(tools.trustedOutputFile(ws, path.join(root, "outside.txt"))).toBeNull();113    expect(tools.trustedOutputFile(ws, path.join(ws.dir, "data", "link.txt"))).toBeNull();114    expect(tools.trustedOutputFile(ws, path.join(ws.dir, "data", "linkdir", "outside.txt"))).toBeNull();115    expect(tools.trustedOutputFile(ws, path.join(ws.dir, "artifacts", "missing.xlsx"))).toBeNull();116  });117118  it("writes, reads, patches and deletes text files through the tool", async () => {119    const events: any[] = [];120    const c = ctx("alice", "sess-a1", events);121    expect(await call("workspace_files", { action: "write", path: "code/model.py", content: "A = 1\nB = 2\nA = 1\n" }, c)).toMatchObject({ written: "code/model.py", bytes: 18 });122    await expect(call("workspace_files", { action: "patch", path: "code/model.py", old_text: "A = 1", new_text: "A = 3" }, c)).rejects.toThrow(/occurs 2 times/);123    await expect(call("workspace_files", { action: "patch", path: "code/model.py", old_text: "C = 9", new_text: "" }, c)).rejects.toThrow(/not found/);124    await call("workspace_files", { action: "patch", path: "code/model.py", old_text: "B = 2", new_text: "B = 20" }, c);125    expect((await call("workspace_files", { action: "read", path: "code/model.py" }, c)).text).toBe("A = 1\nB = 20\nA = 1\n");126    expect((await call("workspace_files", { action: "read", path: "code/model.py", offset: 2, limit: 1 }, c))).toMatchObject({ text: "B = 20", from: 2, to: 2, truncated: true });127    expect((await call("workspace_files", { action: "list", path: "code" }, c)).files).toEqual(["code/model.py  (19 bytes)"]);128    await expect(call("workspace_files", { action: "write", path: "../x.py", content: "x" }, c)).rejects.toThrow(/Invalid path/);129    await expect(call("workspace_files", { action: "delete", path: "code" }, c)).rejects.toThrow(/layout/);130    await call("workspace_files", { action: "delete", path: "code/model.py" }, c);131    expect(events.map((e) => [e.type, e.action, e.path])).toEqual([["research_file", "write", "code/model.py"], ["research_file", "patch", "code/model.py"], ["research_file", "delete", "code/model.py"]]);132  });133});134135describe("dataset uploads", () => {136  const parquet = Buffer.concat([Buffer.from("PAR1"), Buffer.alloc(20), Buffer.from("PAR1")]);137  it("accepts datasets by type and content, and nothing else", () => {138    expect(store.validateUpload("My data (final).csv", Buffer.from("a,b\n1,2\n"))).toBe("My_data_final_.csv");139    expect(store.validateUpload("../../etc/passwd.csv", Buffer.from("a\n"))).toBe("passwd.csv");140    expect(store.validateUpload("p.parquet", parquet)).toBe("p.parquet");141    expect(store.validateUpload("w.xlsx", Buffer.from("PK\x03\x04rest", "latin1"))).toBe("w.xlsx");142    const bad: Array<[string, Buffer, RegExp]> = [143      ["script.py", Buffer.from("print(1)"), /Unsupported dataset type/],144      ["run.sh", Buffer.from("#!/bin/sh"), /Unsupported/],145      ["noext", Buffer.from("a,b"), /Unsupported/],146      ["page.html", Buffer.from("<html>"), /Unsupported/],147      ["empty.csv", Buffer.alloc(0), /empty/],148      ["fake.parquet", Buffer.from("a,b\n1,2\n"), /not a Parquet/],149      ["fake.xlsx", Buffer.from("a,b\n1,2\n"), /not an \.xlsx/],150      ["binary.csv", Buffer.from([0x61, 0x2c, 0x00, 0x62]), /binary data/],151      ["zip.csv", Buffer.from("PK\x03\x04payload", "latin1"), /not text/],152      ["exe.txt", Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 1, 2, 3, 4]), /not text/],153    ];154    for (const [name, data, re] of bad) expect(() => store.validateUpload(name, data), name).toThrow(re);155    expect(() => store.validateUpload("big.csv", { length: store.UPLOAD_MAX_BYTES + 1, subarray: () => Buffer.from("a,b") } as unknown as Buffer)).toThrow(/larger than/);156  });157158  it("uploads through the API into data/, profiles the dataset in the sandbox, and keeps people apart", async () => {159    const created = await t.api("alice", "POST", "/api/v2/research/sessions", { title: "Panel study" });160    expect(created.status).toBe(201);161    const id = created.body.session.id as string;162    expect(id).toBe(`s-${created.body.sessionId}`);163164    const rows = ["date,firm,ret,size", ...Array.from({ length: 50 }, (_, i) => `2026-01-${String((i % 28) + 1).padStart(2, "0")},F${i % 5},${(i * 0.37) % 1 - 0.5},${i % 7 === 0 ? "" : 100 + i}`)].join("\n");165    const form = new FormData();166    form.append("file", new Blob([rows], { type: "text/csv" }), "panel.csv");167    const up = await fetch(`${t.base}/api/v2/research/sessions/${id}/upload`, { method: "POST", headers: { "x-test-user": "alice" }, body: form });168    expect(up.status).toBe(201);169    expect((await up.json()).file).toMatchObject({ path: "data/panel.csv", bytes: rows.length });170171    const bad = new FormData();172    bad.append("file", new Blob(["print(1)"]), "evil.py");173    expect((await fetch(`${t.base}/api/v2/research/sessions/${id}/upload`, { method: "POST", headers: { "x-test-user": "alice" }, body: bad })).status).toBe(415);174    expect((await fetch(`${t.base}/api/v2/research/sessions/${id}/upload`, { method: "POST", headers: { "x-test-user": "bob" }, body: form })).status).toBe(404);175176    const inspected = await t.api("alice", "GET", `/api/v2/research/sessions/${id}/inspect?path=data/panel.csv`);177    expect(inspected.status).toBe(200);178    const d = inspected.body.dataset;179    expect(d).toMatchObject({ path: "data/panel.csv", format: "csv", rows: 50, columnCount: 4, timeColumns: ["date"] });180    expect(d.columns.map((c: any) => c.name)).toEqual(["date", "firm", "ret", "size"]);181    expect(d.columns.find((c: any) => c.name === "size")).toMatchObject({ missing: 8, missingShare: 0.16 });182    expect(d.columns.find((c: any) => c.name === "firm").distinct).toBe(5);183    expect(d.head).toHaveLength(8);184    expect((await t.api("alice", "GET", `/api/v2/research/sessions/${id}/inspect?path=../x.csv`)).status).toBe(400);185186    const file = await t.api("alice", "GET", `/api/v2/research/sessions/${id}/file?path=data/panel.csv&limit=2`);187    expect(file.body.text).toBe(rows.split("\n").slice(0, 2).join("\n"));188    expect((await t.api("bob", "GET", `/api/v2/research/sessions/${id}/file?path=data/panel.csv`)).status).toBe(404);189    expect((await t.api("bob", "GET", `/api/v2/research/sessions/${id}`)).status).toBe(404);190    expect((await t.api("alice", "GET", `/api/v2/research/sessions/${id}/file?path=../../outside.txt`)).status).toBe(400);191    expect((await t.api(null, "GET", "/api/v2/research/sessions")).status).toBe(401);192    expect((await t.api("alice", "GET", "/api/v2/research/sessions")).body.sessions.map((s: any) => s.id)).toContain(id);193    expect((await t.api("bob", "GET", "/api/v2/research/sessions")).body.sessions).toEqual([]);194    expect((await t.api("alice", "GET", `/api/v2/research/sessions/session:${created.body.sessionId}`)).body.session.id).toBe(id);195  }, 120_000);196});197198describe("experiment ledger", () => {199  it("records declared experiments, their updates, and failures as first-class entries", async () => {200    const events: any[] = [];201    const c = ctx("carol", "sess-c1", events);202    const first = await call("log_experiment", { title: "GARCH(1,1) normal", hypothesis: "Volatility clusters", method: "arch, SPY daily 2015–2024", status: "running" }, c);203    expect(first).toMatchObject({ number: 1, status: "running", recorded: true });204    await call("log_experiment", { experiment_id: first.experiment_id, title: "GARCH(1,1) normal", status: "ok", metrics: { aic: 5123.4, n_obs: 2516 }, diagnostics: { ljung_box_p: 0.31 }, artifacts: ["artifacts/garch.png"] }, c);205    await call("log_experiment", { title: "EGARCH(2,2) skew-t", status: "failed", notes: "Optimizer did not converge (singular Hessian) after 3 restarts." }, c);206    await call("log_experiment", { title: "HAR-RV on 5-min data", status: "abandoned", notes: "No intraday data for 2015–2017 in the sample." }, c);207    await expect(call("log_experiment", { title: "x", status: "great" }, c)).rejects.toThrow(/status must be one of/);208    await expect(call("log_experiment", { status: "ok" }, c)).rejects.toThrow(/needs a title/);209    await expect(call("log_experiment", { experiment_id: "nope", title: "x", status: "ok" }, c)).rejects.toThrow(/No experiment/);210    await expect(call("log_experiment", { title: "huge", status: "ok", metrics: { blob: "x".repeat(30_000) } }, c)).rejects.toThrow(/too large for the ledger/);211212    const listed = await call("list_experiments", {}, c);213    expect(listed.experiments.map((e: any) => [e.number, e.title, e.status])).toEqual([[1, "GARCH(1,1) normal", "ok"], [2, "EGARCH(2,2) skew-t", "failed"], [3, "HAR-RV on 5-min data", "abandoned"]]);214    expect(listed.experiments[0]).toMatchObject({ metrics: { aic: 5123.4, n_obs: 2516 }, diagnostics: { ljung_box_p: 0.31 }, artifacts: ["artifacts/garch.png"] });215    expect(events.filter((e) => e.type === "experiment").map((e) => e.experiment.status)).toEqual(["running", "ok", "failed", "abandoned"]);216    // Another person's ledger is not reachable, even with the id.217    await expect(call("log_experiment", { experiment_id: first.experiment_id, title: "x", status: "ok" }, ctx("dave", "sess-d1"))).rejects.toThrow(/No experiment/);218    expect(store.getExperiment("dave", first.experiment_id)).toBeNull();219  });220221  it("logs every notebook execution with the hash of its code, failures included", () => {222    const events: any[] = [];223    const c = ctx("carol", "sess-c1", events);224    const ws = tools.workspaceFor(c);225    const code = "import arch\nprint(1/0)\n";226    tools.recordNotebookExecution(c, ws, { code, description: "Fit", startedAt: Date.now() - 1200, ok: false, error: "ZeroDivisionError: division by zero", result: null });227    // A cell is announced before it runs, and its end names the same tool call.228    const cell: any[] = [];229    const cc = ctx("carol", "sess-cell", cell);230    tools.announceNotebookExecution(cc, { code: "x = 1\ny = 2", description: "Setup", toolId: "toolu_1" });231    tools.recordNotebookExecution(cc, tools.workspaceFor(cc), { code: "x = 1\ny = 2", description: "Setup", toolId: "toolu_1", startedAt: Date.now(), ok: true, result: { success: true } });232    expect(cell.map((e) => [e.type, e.toolId, e.codeHash === cell[0].codeHash])).toEqual([["code_execution_start", "toolu_1", true], ["code_execution", "toolu_1", true]]);233    expect(cell[0]).toMatchObject({ agent: "lead", description: "Setup", lines: 2 });234    const note = tools.recordNotebookExecution(c, ws, {235      code: "plot()", description: "Chart", startedAt: Date.now() - 300, ok: true,236      result: { success: true, installs: [{ spec: "linearmodels", ok: true }], figure_reports: [237        { title: "Vol", ok: true, issues: [{ code: "tick_overlap", severity: "warning", message: "Tick labels overlap (rotated).", fixed: true }], files: { png: "artifacts/figures/a.png", svg: "artifacts/figures/a.svg", pdf: "artifacts/figures/a.pdf" } },238        { title: "Bare", ok: false, issues: [{ code: "title", severity: "warning", message: "The figure has no title.", fixed: false }] },239      ] },240    });241    expect(note).toContain("Figure 1 — repaired automatically: tick_overlap.");242    expect(note).toContain("Figure 2 (“Bare”) — to fix in your code: The figure has no title.");243    expect(note).toContain("Redraw the figures that still have defects");244    const execs = store.listExperiments("carol", ws.id, { kind: "execution" });245    expect(execs.map((e) => [e.title, e.status, e.codeHash?.length, e.error])).toEqual([["Fit", "failed", 16, "ZeroDivisionError: division by zero"], ["Chart", "ok", 16, null]]);246    expect(execs[1].artifacts).toEqual(["artifacts/figures/a.png", "artifacts/figures/a.svg", "artifacts/figures/a.pdf"]);247    expect(fs.readFileSync(path.join(ws.dir, "logs", "cells", `${execs[0].codeHash}.py`), "utf8")).toBe(code);248    const lines = fs.readFileSync(path.join(ws.dir, "logs", "executions.jsonl"), "utf8").trim().split("\n").map((l) => JSON.parse(l));249    expect(lines.map((l) => [l.type, l.ok, l.codeHash])).toEqual([["notebook", false, execs[0].codeHash], ["notebook", true, execs[1].codeHash]]);250    expect(events.map((e) => e.type)).toEqual(["code_execution", "code_execution", "package_install"]);251    expect(events[0]).toMatchObject({ ok: false, error: "ZeroDivisionError: division by zero", lines: 3, toolId: null });252    expect(events[2]).toEqual({ type: "package_install", spec: "linearmodels", ok: true });253  });254255  it("holds the quality gate against undisclosed failures, figure defects and untraceable numbers", () => {256    const ws = store.workspaceOfSession("carol", "sess-c1")!;257    const numbers = [{ id: "numbers", severity: "warning" as const, finding: "2 of 9 figures quoted in the text are not found", evidence: '"14.2 %"' }, { id: "provenance", severity: "info" as const, finding: "x", evidence: "y" }];258    const silent = tools.researchGate({ owner: "carol", ws, generationId: "gen-sess-c1", numberChecks: numbers, figureIssues: [{ title: "Bare", messages: ["The figure has no title."] }], answer: "The GARCH model fits well with AIC 5123.4." });259    expect(silent.map((f) => [f.id, f.severity])).toEqual([["numbers", "warning"], ["figures", "warning"], ["failed_experiments", "warning"]]);260    expect(silent[2].finding).toMatch(/^2 declared experiment\(s\) and 0 run\(s\)/);261    expect(silent[2].evidence).toContain("EGARCH(2,2) skew-t [failed]");262    expect(silent[2].evidence).toContain("HAR-RV on 5-min data [abandoned]");263    const honest = tools.researchGate({ owner: "carol", ws, generationId: "gen-sess-c1", numberChecks: [], figureIssues: [], answer: "L'EGARCH(2,2) n'a pas convergé et le HAR-RV a été abandonné faute de données." });264    expect(honest.map((f) => [f.id, f.severity])).toEqual([["failed_experiments", "info"]]);265    expect(tools.researchGate({ owner: "carol", ws, generationId: "another-generation", numberChecks: [], figureIssues: [], answer: "x" })).toEqual([]);266  });267});268269describe("what a reopened study shows", () => {270  it("keeps every figure with its caption, files and linter verdict, and the plan and budget of each analysis", async () => {271    const events: any[] = [];272    const c = ctx("dave", "sess-reopen", events);273    const ws = tools.workspaceFor(c);274    const issue = (code: string, severity: "warning" | "info", fixed: boolean) => ({ code, severity, message: `${code} message`, fixed });275    const figs = tools.recordFigures(c, ws, {276      toolId: "toolu_fig", code: "plot()", urls: ["/figures/fig-1-0.png", "/figures/fig-1-1.png", "/figures/fig-1-2.png"],277      reports: [278        { title: "Volatilité réalisée, SPY, 2015–2024", ok: true, issues: [], files: { png: "artifacts/figures/a.png", svg: "artifacts/figures/a.svg", pdf: "artifacts/figures/a.pdf" } },279        { title: "Rendements", ok: true, issues: [issue("tick_overlap", "warning", true), issue("off_palette", "info", false)], files: { png: "artifacts/figures/b.png", errors: { pdf: "x" } as any } },280        { title: "", ok: false, issues: [issue("contrast", "warning", true), issue("title", "warning", false)] },281      ],282    });283    expect(figs.map((f) => [f.status, f.fixes.map((i) => i.code), f.findings.map((i) => i.code)])).toEqual([["passed", [], []], ["fixed", ["tick_overlap"], ["off_palette"]], ["issues", ["contrast"], ["title"]]]);284    expect(events.map((e) => [e.type, e.toolId, e.index, e.status, e.url])).toEqual([["figure_lint", "toolu_fig", 0, "passed", "/figures/fig-1-0.png"], ["figure_lint", "toolu_fig", 1, "fixed", "/figures/fig-1-1.png"], ["figure_lint", "toolu_fig", 2, "issues", "/figures/fig-1-2.png"]]);285    expect(events[0]).toMatchObject({ figureId: figs[0].id, title: "Volatilité réalisée, SPY, 2015–2024", caption: "Volatilité réalisée, SPY, 2015–2024", files: { png: "artifacts/figures/a.png", svg: "artifacts/figures/a.svg", pdf: "artifacts/figures/a.pdf" } });286    expect(figs[1].files).toEqual({ png: "artifacts/figures/b.png" }); // only real file paths are kept287    expect(store.figureVerdict([issue("off_palette", "info", false)]).status).toBe("passed");288289    // The analysis itself: its plan as last shown and the budget it ran under are in its trace.290    const { GenerationTrace } = await import("../../next/trace");291    const first = new GenerationTrace({ owner: "dave", sessionId: "sess-reopen", generationId: "gen-sess-reopen", mode: "research", model: "m" });292    first.observe({ type: "budget_applied", maxCostUsd: 5, maxMinutes: null, source: "request" });293    first.observe({ type: "plan", steps: [{ title: "Explorer", status: "in_progress" }, { title: "Estimer", status: "pending" }] });294    first.observe({ type: "plan", steps: [{ title: "Explorer", status: "done" }, { title: "Estimer", status: "done" }] });295    first.finish("done");296    await call("log_experiment", { title: "AR(1)", status: "ok", notes: "Baseline", metrics: { rmse: 1.2 } }, c);297298    const r = await t.api("dave", "GET", "/api/v2/research/sessions/session:sess-reopen");299    expect(r.status).toBe(200);300    expect(r.body.plan).toEqual([{ title: "Explorer", status: "done" }, { title: "Estimer", status: "done" }]);301    expect(r.body.generations).toHaveLength(1);302    expect(r.body.generations[0]).toMatchObject({ generationId: "gen-sess-reopen", sessionId: "sess-reopen", status: "done", mode: "research", plan: [{ title: "Explorer", status: "done" }, { title: "Estimer", status: "done" }], budgetApplied: { maxCostUsd: 5, maxMinutes: null, source: "request" } });303    expect(r.body.figures.map((f: any) => [f.title, f.caption, f.status, f.toolId, f.generationId])).toEqual([304      ["Volatilité réalisée, SPY, 2015–2024", "Volatilité réalisée, SPY, 2015–2024", "passed", "toolu_fig", "gen-sess-reopen"],305      ["Rendements", "Rendements", "fixed", "toolu_fig", "gen-sess-reopen"],306      [null, null, "issues", "toolu_fig", "gen-sess-reopen"],307    ]);308    expect(r.body.figures[1]).toMatchObject({ url: "/figures/fig-1-1.png", files: { png: "artifacts/figures/b.png" }, fixes: [{ code: "tick_overlap", fixed: true }], findings: [{ code: "off_palette", severity: "info" }] });309    // The experiment event now carries the notes and the hashes.310    expect(events.at(-1)).toMatchObject({ type: "experiment", experiment: { title: "AR(1)", notes: "Baseline", envHash: null, codeHash: null } });311    expect((await t.api("erin", "GET", "/api/v2/research/sessions/session:sess-reopen")).status).toBe(404);312  });313314  it("deletes a workspace file for its owner only, inside the workspace only, and records it", async () => {315    const c = ctx("dave", "sess-reopen");316    const ws = tools.workspaceFor(c);317    fs.writeFileSync(path.join(ws.dir, "data", "attachment.csv"), "a,b\n1,2\n");318    fs.mkdirSync(path.join(ws.dir, "artifacts", "old"), { recursive: true });319    fs.writeFileSync(path.join(ws.dir, "artifacts", "old", "x.txt"), "x");320    fs.writeFileSync(path.join(root, "keep.txt"), "must stay");321    const del = (user: string, p: string) => t.api(user, "DELETE", `/api/v2/research/sessions/${ws.id}/files?path=${encodeURIComponent(p)}`);322    expect((await del("erin", "data/attachment.csv")).status).toBe(404);323    expect(fs.existsSync(path.join(ws.dir, "data", "attachment.csv"))).toBe(true);324    for (const p of ["../../keep.txt", "/etc/hosts", "data/../../../keep.txt", ".site", ""]) expect((await del("dave", p)).status, p).toBe(400);325    expect((await del("dave", "data")).status).toBe(400); // part of the layout326    expect((await del("dave", "data/missing.csv")).status).toBe(404);327    expect(await del("dave", "data/attachment.csv")).toMatchObject({ status: 200, body: { ok: true, path: "data/attachment.csv" } });328    expect((await del("dave", "artifacts/old")).status).toBe(200);329    expect(fs.existsSync(path.join(ws.dir, "data", "attachment.csv"))).toBe(false);330    expect(fs.existsSync(path.join(ws.dir, "artifacts", "old"))).toBe(false);331    expect(fs.readFileSync(path.join(root, "keep.txt"), "utf8")).toBe("must stay");332    expect((t.db.prepare("SELECT target FROM vq_audit WHERE owner = 'dave' AND action = 'research.file.delete' ORDER BY id").all() as any[]).map((a) => a.target)).toEqual([`${ws.id}:data/attachment.csv`, `${ws.id}:artifacts/old`]);333  });334});335336describe("research memory and code library", () => {337  it("keeps notes per workspace, replaces a note of the same kind and title, and feeds the digest of a resumed project", async () => {338    const events: any[] = [];339    const c1 = ctx("erin", "sess-e1", events, { projectId: "macro" });340    await call("research_memory", { action: "save", kind: "dataset", title: "panel.csv", body: "50 rows, firm × day, `size` missing 16%." }, c1);341    await call("research_memory", { action: "save", kind: "decision", title: "Clustering", body: "Cluster by firm: residuals are serially correlated within firm." }, c1);342    await call("research_memory", { action: "save", kind: "failure", title: "Random effects", body: "Hausman rejects RE (p < 0.001): do not use." }, c1);343    await call("research_memory", { action: "save", kind: "decision", title: "clustering", body: "Cluster by firm and day (two-way) after the Thompson check." }, c1);344    await expect(call("research_memory", { action: "save", kind: "gossip", title: "x", body: "y" }, c1)).rejects.toThrow(/kind must be one of/);345    await call("log_experiment", { title: "FE with two-way clustering", status: "ok", metrics: { beta: 0.42 } }, c1);346347    // A new conversation of the same project sees it all; another project and another person see nothing.348    const c2 = ctx("erin", "sess-e2", [], { projectId: "macro" });349    const notes = (await call("research_memory", { action: "list" }, c2)).notes;350    expect(notes.map((n: any) => `${n.kind}:${n.title}`).sort()).toEqual(["dataset:panel.csv", "decision:Clustering", "failure:Random effects"]);351    expect(notes.find((n: any) => n.kind === "decision").body).toMatch(/two-way/);352    const digest = store.workspaceDigest(tools.workspaceFor(c2));353    expect(digest).toContain("shared by the conversations of this project");354    expect(digest).toContain("[dataset] panel.csv: 50 rows");355    expect(digest).toContain("[failure] Random effects: Hausman rejects RE");356    expect(digest).toContain("#1 [ok] FE with two-way clustering");357    expect((await call("research_memory", { action: "list" }, ctx("erin", "sess-e3", [], { projectId: "other" }))).notes).toEqual([]);358    expect((await call("research_memory", { action: "list" }, ctx("frank", "sess-f1", [], { projectId: "macro" }))).notes).toEqual([]);359    expect(store.workspaceDigest(store.ensureWorkspace("frank", { sessionId: "sess-f9" }))).toBe("");360    expect((await call("research_memory", { action: "delete", id: notes.find((n: any) => n.kind === "failure").id }, c2)).deleted).toBe(true);361    expect(events.filter((e) => e.type === "research_note")).toHaveLength(4);362  });363364  it("saves reusable modules per person, importable later, and refuses unsafe names", async () => {365    const c = ctx("erin", "sess-e1", [], { projectId: "macro" });366    await call("workspace_files", { action: "write", path: "code/panel_tools.py", content: "def within(df, key):\n    return df - df.groupby(key).transform('mean')\n\ndef _private():\n    pass\n\nclass Estimator:\n    pass\n" }, c);367    const saved = await call("code_library", { action: "save", name: "panel_tools", path: "code/panel_tools.py", description: "Within transformation and estimator" }, c);368    expect(saved).toMatchObject({ saved: "panel_tools", exports: ["within", "Estimator"], import: "from vqlib.panel_tools import within, Estimator" });369    await expect(call("code_library", { action: "save", name: "../evil", code: "x=1" }, c)).rejects.toThrow(/lowercase Python identifier/);370    await expect(call("code_library", { action: "save", name: "ok_name", code: "  " }, c)).rejects.toThrow(/No code/);371    const other = ctx("erin", "sess-e9");372    expect((await call("code_library", { action: "list" }, other)).modules.map((m: any) => m.name)).toEqual(["panel_tools"]);373    expect((await call("code_library", { action: "read", name: "panel_tools" }, other)).code).toContain("def within");374    expect((await call("code_library", { action: "list" }, ctx("frank", "sess-f1"))).modules).toEqual([]);375    expect(store.workspaceDigest(tools.workspaceFor(other))).toContain("panel_tools [within, Estimator]");376  });377});378379describe("runs", () => {380  it("runs a program of the workspace in the sandbox, with its library, and logs it in the ledger", async () => {381    const events: any[] = [];382    const c = ctx("erin", "sess-e1", events, { projectId: "macro" });383    await call("workspace_files", { action: "write", path: "code/job.py", content: [384      "import os, sys, json",385      "import pandas as pd",386      "from vqlib.panel_tools import within",387      "df = pd.DataFrame({'k': ['a', 'a', 'b', 'b'], 'v': [1.0, 3.0, 10.0, 20.0]})",388      "out = within(df[['v']], df['k'])",389      "os.makedirs('artifacts', exist_ok=True)",390      "out.to_csv('artifacts/within.csv', index=False)",391      "print('ARGS', sys.argv[1:]); print('SUM', float(out['v'].abs().sum()))",392      "print('KEYS', sorted(k for k in os.environ if 'ANTHROPIC' in k or 'ACCESS' in k))",393      "print('@@progress 1.0', file=sys.stderr)",394    ].join("\n") }, c);395    const r = await call("research_run", { path: "code/job.py", args: ["--alpha", "0.05"], label: "Within transform" }, c);396    expect(r).toMatchObject({ status: "done", exit_code: 0, label: "Within transform", code: "code/job.py" });397    expect(r.stdout_tail).toContain("ARGS ['--alpha', '0.05']");398    expect(r.stdout_tail).toContain("SUM 12.0");399    expect(r.stdout_tail).toContain("KEYS []");400    expect(r.files_written).toContain("artifacts/within.csv");401    const ws = tools.workspaceFor(c);402    const exec = store.listExperiments("erin", ws.id, { kind: "execution" }).at(-1)!;403    expect(exec).toMatchObject({ status: "ok", codeRef: "code/job.py", runId: r.run_id, title: "Within transform" });404    expect(exec.codeHash).toHaveLength(16);405    expect(events.filter((e) => e.type === "research_run").map((e) => e.run.status)).toEqual(["running"]);406    expect(runtime.getRun("erin", r.run_id)).toMatchObject({ status: "done", progress: 1 });407    expect(runtime.getRun("frank", r.run_id)).toBeNull();408    expect((await t.api("erin", "GET", `/api/v2/research/runs/${r.run_id}`)).body.stdout).toContain("SUM 12.0");409    expect((await t.api("frank", "GET", `/api/v2/research/runs/${r.run_id}`)).status).toBe(404);410  }, 120_000);411412  it("reports a failing program with its traceback, as a failed execution", async () => {413    const c = ctx("erin", "sess-e1", [], { projectId: "macro" });414    const r = await call("research_run", { code: "import numpy as np\nraise ValueError('matrix is singular')\n", label: "Bad fit" }, c);415    expect(r.status).toBe("failed");416    expect(r.exit_code).toBe(1);417    expect(r.error).toContain("ValueError: matrix is singular");418    expect(r.stderr_tail).toContain("Traceback");419    expect(r.code).toMatch(/^code\/_runs\/\d{14}_[0-9a-f]{8}\.py$/);420    const exec = store.listExperiments("erin", tools.workspaceFor(c).id, { kind: "execution" }).at(-1)!;421    expect(exec).toMatchObject({ status: "failed", title: "Bad fit" });422    expect(exec.error).toContain("matrix is singular");423    await expect(call("research_run", { path: "code/missing.py" }, c)).rejects.toThrow(/No such file/);424    await expect(call("research_run", { path: "data/x.sh" }, c)).rejects.toThrow(/No such file|Only Python/);425    await expect(call("research_run", {}, c)).rejects.toThrow(/needs `path`/);426  }, 120_000);427428  it("runs programs in parallel in the background, collects them, cancels one, and enforces the time limit", async () => {429    const c = ctx("erin", "sess-e1", [], { projectId: "macro" });430    const quick = (n: number) => call("research_run", { code: `import time\ntime.sleep(1.5)\nprint("worker ${n} done")\n`, label: `worker ${n}`, background: true }, c);431    const started = Date.now();432    const [a, b, d] = await Promise.all([quick(1), quick(2), quick(3)]);433    expect([a.status, b.status, d.status]).toEqual(["running", "running", "running"]);434    const slow = await call("research_run", { code: "import time\ntime.sleep(120)\n", label: "slow", background: true }, c);435    const capped = await call("research_run", { code: "import time\ntime.sleep(120)\n", label: "capped", background: true, timeout_seconds: 5 }, c);436    const waited = await call("research_runs", { action: "wait", run_ids: [a.run_id, b.run_id, d.run_id], timeout_seconds: 60 }, c);437    expect(waited.all_finished).toBe(true);438    expect(waited.runs.map((r: any) => r.status)).toEqual(["done", "done", "done"]);439    expect(waited.runs.map((r: any) => r.stdout_tail.trim())).toEqual(["worker 1 done", "worker 2 done", "worker 3 done"]);440    expect(Date.now() - started).toBeLessThan(25_000); // side by side, not one after the other on a busy node441    expect((await call("research_runs", { action: "status", run_ids: [slow.run_id] }, c)).runs[0].status).toBe("running");442    await call("research_runs", { action: "cancel", run_ids: [slow.run_id] }, c);443    await sleep(1500);444    expect(runtime.getRun("erin", slow.run_id)).toMatchObject({ status: "cancelled" });445    const timedOut = (await call("research_runs", { action: "wait", run_ids: [capped.run_id], timeout_seconds: 30 }, c)).runs[0];446    expect(timedOut.status).toBe("timeout");447    expect(timedOut.error).toMatch(/time limit: 5 s/);448    await expect(call("research_runs", { action: "status", run_ids: [a.run_id] }, ctx("frank", "sess-f1"))).rejects.toThrow(/No run/);449    const listed = (await call("research_runs", { action: "list" }, c)).runs;450    expect(listed.length).toBeGreaterThanOrEqual(5);451  }, 120_000);452453  it("finds its runs again after a restart: finished, still running, or interrupted", async () => {454    const c = ctx("erin", "sess-e1", [], { projectId: "macro" });455    const ws = tools.workspaceFor(c);456    const insert = (id: string, pid: number | null) => {457      fs.mkdirSync(path.join(ws.dir, "runs", id), { recursive: true });458      t.db.prepare("INSERT INTO vq_research_runs (id, owner, workspace_id, code_ref, status, pid, started_at) VALUES (?, 'erin', ?, 'code/job.py', 'running', ?, ?)").run(id, ws.id, pid, Date.now() - 5000);459      store.addExperiment(ws, { kind: "execution", title: id, runId: id, status: "running" });460    };461    // 1. finished while the server was away: its status file is there.462    insert("aaaaaaaa-0000-0000-0000-000000000001", 999_999);463    fs.writeFileSync(path.join(ws.dir, "runs", "aaaaaaaa-0000-0000-0000-000000000001", "status.json"), JSON.stringify({ exitCode: 0, signal: null, finishedAt: Date.now() / 1000 }));464    // 2. gone without a trace.465    insert("aaaaaaaa-0000-0000-0000-000000000002", 999_998);466    // 3. still alive (this very process stands in for it).467    insert("aaaaaaaa-0000-0000-0000-000000000003", process.pid);468    expect(runtime.adoptRuns()).toEqual({ adopted: 1, finished: 1, interrupted: 1 });469    expect(runtime.getRun("erin", "aaaaaaaa-0000-0000-0000-000000000001")).toMatchObject({ status: "done", exitCode: 0 });470    expect(runtime.getRun("erin", "aaaaaaaa-0000-0000-0000-000000000002")).toMatchObject({ status: "interrupted" });471    expect(runtime.getRun("erin", "aaaaaaaa-0000-0000-0000-000000000002")!.error).toMatch(/start it again/);472    expect(runtime.getRun("erin", "aaaaaaaa-0000-0000-0000-000000000003")).toMatchObject({ status: "running" });473    const ledger = store.listExperiments("erin", ws.id, { kind: "execution" });474    expect(ledger.find((e) => e.runId === "aaaaaaaa-0000-0000-0000-000000000001")!.status).toBe("ok");475    expect(ledger.find((e) => e.runId === "aaaaaaaa-0000-0000-0000-000000000002")!.status).toBe("interrupted");476    // The stand-in "finishes": the watcher picks its status file up.477    fs.writeFileSync(path.join(ws.dir, "runs", "aaaaaaaa-0000-0000-0000-000000000003", "status.json"), JSON.stringify({ exitCode: 3, signal: null, finishedAt: Date.now() / 1000 }));478    await sleep(1600);479    expect(runtime.getRun("erin", "aaaaaaaa-0000-0000-0000-000000000003")).toMatchObject({ status: "failed", exitCode: 3 });480    expect(runtime.adoptRuns()).toEqual({ adopted: 0, finished: 0, interrupted: 0 });481  }, 60_000);482});483484describe("notebook kernel", () => {485  it("runs in the sandbox with the workspace as working directory, holds no key, keeps its state, and delivers linted figures as PNG + SVG + PDF", async () => {486    process.env.ANTHROPIC_API_KEY = "sk-test-SUPERSECRET-kernel";487    process.env.ACCESS_KEY = "SUPERSECRET-access";488    const { runInKernel, releaseKernel } = await import("../python/kernel");489    const ws = store.ensureWorkspace("alice", { sessionId: "sess-kernel" });490    const first = await runInKernel("sess-kernel:lead", [491      "import os, json",492      "print('CWD', os.getcwd())",493      "print('SECRETS', sorted(k for k in os.environ if 'ANTHROPIC' in k or 'ACCESS' in k or 'DATABASE' in k), 'SUPERSECRET' in json.dumps(dict(os.environ)))",494      "try:",495      "    open(os.path.join(os.path.dirname(os.getcwd()), '..', 'outside.txt')).read(); print('READ outside')",496      "except Exception as e:",497      "    print('DENIED', type(e).__name__)",498      "x = 41",499      "open('data/kept.txt', 'w').write('persisted')",500    ].join("\n"), undefined, 120_000, ws);501    expect(first.error ?? null).toBeNull();502    expect(first.output).toContain(`CWD ${ws.dir}`);503    expect(first.output).toContain("SECRETS [] False");504    expect(first.output).toMatch(/DENIED (PermissionError|FileNotFoundError)/);505    expect(fs.readFileSync(path.join(ws.dir, "data", "kept.txt"), "utf8")).toBe("persisted");506    expect(fs.existsSync(path.join(ws.dir, "environment.lock.txt"))).toBe(true);507508    const second = await runInKernel("sess-kernel:lead", [509      "import numpy as np",510      "fig, ax = plt.subplots()",511      "ax.plot(np.arange(30), np.cumsum(np.ones(30)) * (x + 1), label='series')",512      "ax.set_title('State kept between cells'); ax.set_xlabel('t'); ax.set_ylabel('level')",513      "print('X', x + 1)",514    ].join("\n"), undefined, 120_000, ws);515    expect(second.success).toBe(true);516    expect(second.output).toContain("X 42");517    expect(second.figures).toHaveLength(1);518    const rep = second.figure_reports![0];519    expect(rep.title).toBe("State kept between cells");520    expect(rep.ok).toBe(true);521    for (const fmt of ["png", "svg", "pdf"]) {522      expect(rep.files![fmt]).toMatch(new RegExp(`^artifacts/figures/.*state-kept-between-cells\\.${fmt}$`));523      expect(fs.statSync(path.join(ws.dir, rep.files![fmt])).size).toBeGreaterThan(1000);524    }525    releaseKernel("sess-kernel:lead");526  }, 180_000);527});528529describe("research mode and model choice outside the chat body", () => {530  it("is accepted by a project run and by a scheduled watch", async () => {531    // Project run: the body is validated before the project is looked up, so an unknown project tells them apart.532    expect((await t.api("alice", "POST", "/api/v2/projects/nope/run", { prompt: "x", mode: "research" })).status).toBe(404);533    expect((await t.api("alice", "POST", "/api/v2/projects/nope/run", { prompt: "x", mode: "bogus" })).status).toBe(400);534    // Watches: "auto" and any selectable model are kept; an unknown id falls back to the default.535    const watch = async (model: unknown) => (await t.api("alice", "POST", "/api/workspace/watches", { title: `W ${String(model)}`, prompt: "Brief me on SPY", time: "08:30", model })).body;536    expect((await watch("auto")).model).toBe("auto");537    expect((await watch("claude-sonnet-5-5")).model).toBe("claude-sonnet-5-5");538    expect((await watch("not-a-model")).model).toBe("claude-fable-5-2");539  });540});541542describe("recorded approval stream (tests/fixtures/research/approval_stream.json)", () => {543  it("is a real stream the clients can replay: ask, answer, then continue or adapt", () => {544    const fx = JSON.parse(fs.readFileSync(path.join(process.cwd(), "tests", "fixtures", "research", "approval_stream.json"), "utf8"));545    for (const [name, decision, finalStatus] of [["approved", "approve", "approved"], ["denied", "deny", "denied"]] as const) {546      const events: any[] = fx[name].events;547      const types = events.map((e) => e.type);548      expect(fx[name].eventTypes).toEqual(types);549      expect(types[0]).toBe("job");550      expect(types.at(-1)).toBe("done");551      expect(types.indexOf("budget_applied")).toBe(1);552      const ask = events.find((e) => e.type === "approval_request");553      const answer = events.find((e) => e.type === "approval_resolved");554      expect(ask.approval).toMatchObject({ action: "open_network", status: "pending" });555      expect(answer.approval).toMatchObject({ id: ask.approval.id, status: finalStatus });556      expect(types.indexOf("approval_request")).toBeLessThan(types.indexOf("approval_resolved"));557      expect(fx[name].clientAction).toMatchObject({ method: "POST", path: `/api/v2/research/approvals/${ask.approval.id}`, body: { decision } });558      // Every event written by the generation is time-stamped, in order.559      const stamped = events.filter((e) => e.type !== "job");560      for (const e of stamped) expect(typeof e.at, e.type).toBe("number");561      expect(stamped.map((e) => e.at)).toEqual([...stamped.map((e) => e.at)].sort((a, b) => a - b));562      expect(JSON.stringify(events)).not.toMatch(/sk-[A-Za-z0-9]{8}|apikey=/);563    }564    const ok = fx.approved.events;565    expect(ok.filter((e: any) => e.type === "research_run").map((e: any) => [e.run.status, e.run.network])).toEqual([["running", "open"], ["done", "open"]]);566    expect(ok.find((e: any) => e.type === "tool_result")).toMatchObject({ tool: "research_run", toolId: ok.find((e: any) => e.type === "tool_start").toolId });567    const no = fx.denied.events;568    expect(no.some((e: any) => e.type === "research_run")).toBe(false);569    expect(no.find((e: any) => e.type === "tool_error").error).toMatch(/did not authorize open network/);570  });571});572573describe("authorization boundary", () => {574  it("runs with open network only after an explicit approval, which is audited", async () => {575    const events: any[] = [];576    const c = ctx("alice", "sess-net", events);577    // Nobody answers: the request expires and the run does not start.578    await expect(call("research_run", { code: "print('x')", network: "open", reason: "Download a public dataset from data.gov" }, c)).rejects.toThrow(/did not authorize open network/);579    const pending = events.find((e) => e.type === "approval_request");580    expect(pending.approval).toMatchObject({ action: "open_network", status: "pending", reason: "Download a public dataset from data.gov" });581    expect(runtime.listRuns("alice", tools.workspaceFor(c).id)).toEqual([]);582    expect(runtime.listApprovals("alice")[0].status).toBe("expired");583584    // Denied by the person.585    const denied = call("research_run", { code: "print('x')", network: "open", reason: "r" }, c).catch((e) => e as Error);586    await sleep(150);587    const req1 = (await t.api("alice", "GET", "/api/v2/research/approvals?status=pending")).body.approvals[0];588    expect((await t.api("bob", "POST", `/api/v2/research/approvals/${req1.id}`, { decision: "approve" })).status).toBe(404); // not theirs to answer589    expect((await t.api("alice", "POST", `/api/v2/research/approvals/${req1.id}`, { decision: "maybe" })).status).toBe(400);590    expect((await t.api("alice", "POST", `/api/v2/research/approvals/${req1.id}`, { decision: "deny" })).body.approval.status).toBe("denied");591    expect(((await denied) as Error).message).toMatch(/did not authorize/);592    expect((await t.api("alice", "POST", `/api/v2/research/approvals/${req1.id}`, { decision: "approve" })).status).toBe(404); // already answered593594    // Approved: the run starts with the open grant and the decision is in the audit trail.595    const approved = call("research_run", { code: "import os\nprint('ran', bool(os.environ.get('VQ_BROKER_TOKEN')))", network: "open", reason: "r2", label: "open run" }, c);596    await sleep(150);597    const req2 = (await t.api("alice", "GET", "/api/v2/research/approvals?status=pending")).body.approvals[0];598    expect((await t.api("alice", "POST", `/api/v2/research/approvals/${req2.id}`, { decision: "approve" })).status).toBe(200);599    const ran = await approved;600    expect(ran).toMatchObject({ status: "done" });601    expect(ran.stdout_tail).toContain("ran True");602    expect(runtime.getRun("alice", ran.run_id)!.network).toBe("open");603    const trail = t.db.prepare("SELECT action, target FROM vq_audit WHERE owner = 'alice' AND action LIKE 'research.%' ORDER BY id").all() as Array<{ action: string; target: string }>;604    expect(trail.map((a) => a.action)).toEqual(expect.arrayContaining(["research.approval", "research.approval.answer", "research.network.open"]));605    expect(trail.filter((a) => a.action === "research.network.open").map((a) => a.target)).toEqual([ran.run_id]);606  }, 60_000);607608  it("raises the budget only on approval, and tells the agent when the answer is no", async () => {609    const raised: unknown[] = [];610    const c = ctx("alice", "sess-net", [], { raiseBudget: (l: unknown) => raised.push(l) });611    const no = await call("request_approval", { action: "raise_budget", reason: "Bootstrap needs more runs", max_cost_usd: 20 }, c);612    expect(no).toMatchObject({ approved: false, status: "expired" });613    expect(raised).toEqual([]);614    const yes = call("request_approval", { action: "raise_budget", reason: "Bootstrap needs more runs", max_cost_usd: 20, max_minutes: 90 }, c);615    await sleep(150);616    const req = (await t.api("alice", "GET", "/api/v2/research/approvals?status=pending")).body.approvals[0];617    expect(req.detail).toEqual({ maxCostUsd: 20, maxMinutes: 90 });618    await t.api("alice", "POST", `/api/v2/research/approvals/${req.id}`, { decision: "approve" });619    expect(await yes).toMatchObject({ approved: true });620    expect(raised).toEqual([{ maxCostUsd: 20, maxMinutes: 90 }]);621  }, 30_000);622623  it("describes the sandbox and its limits to the clients", async () => {624    const r = await t.api("alice", "GET", "/api/v2/research/sandbox");625    expect(r.status).toBe(200);626    expect(r.body.sandbox).toHaveProperty("enforced");627    expect(r.body.limits).toMatchObject({ memoryMb: expect.any(Number), maxProcesses: expect.any(Number), diskMb: expect.any(Number) });628    expect(r.body.network.default).toEqual(expect.arrayContaining(["pypi.org", "files.pythonhosted.org"]));629  });630});631
Files main
Menu

Theme