Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/services/research/tools.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Execution of the research tools (definitions: services/claude/researchTools.ts; contract §9), and what the47 * runtime records by itself around the notebook: every execution in the ledger with the hash of its code, the48 * figure-linter reports, the package installations — each also sent to the clients as an activity event.49 */50import fs from "node:fs";51import path from "node:path";52import { audit } from "../../next/audit";53import { redactSecrets } from "../python/lab";54import type { CustomPythonResult } from "../python/var";55import {56 APPROVAL_ACTIONS, approvalEvents, cancelRun, getRun, inspectDataset, listRuns, requestApproval, runEvents, startRun, tailLog, waitRun, type Approval, type ApprovalAction, type Run,57} from "./runtime";58import {59 NOTE_KINDS, ResearchError, addExperiment, addFigure, appendExecutionLog, deleteFile, deleteNote, ensureWorkspace, getExperiment, listExperiments, listFiles, listLibrary, listNotes, patchTextFile, readLibraryModule, readTextFile,60 resolveInside, saveLibraryModule, saveNote, sha256, updateExperiment, writeTextFile, type Experiment, type FigureIssue, type ResearchFigure, type Workspace,61} from "./store";6263export interface ResearchContext {64 owner: string;65 sessionId: string;66 projectId?: string | null;67 generationId?: string | null;68 /** sends one activity event to the clients of the generation */69 emit: (event: Record<string, unknown>) => void;70 signal?: AbortSignal;71 /** raises the budget of the generation once the person approved it */72 raiseBudget?: (limits: { maxCostUsd?: number; maxMinutes?: number }) => void;73 /** title for a workspace created by this conversation */74 title?: string | null;75}7677/** The workspace of the conversation (created on first use). */78export function workspaceFor(ctx: Pick<ResearchContext, "owner" | "sessionId" | "projectId" | "title">): Workspace {79 return ensureWorkspace(ctx.owner, { sessionId: ctx.sessionId, projectId: ctx.projectId, title: ctx.title });80}8182/** An open-network authorization obtained with request_approval, usable once by the next run of the workspace within ten minutes. */83const openGrants = new Map<string, number>();8485const experimentEvent = (e: Experiment) => ({ type: "experiment", experiment: { id: e.id, seq: e.seq, kind: e.kind, title: e.title, hypothesis: e.hypothesis, method: e.method, status: e.status, metrics: e.metrics, diagnostics: e.diagnostics, artifacts: e.artifacts, notes: e.notes, codeRef: e.codeRef, codeHash: e.codeHash, envHash: e.envHash, runId: e.runId, error: e.error, startedAt: e.startedAt, finishedAt: e.finishedAt, durationMs: e.durationMs } });86const runEvent = (r: Run) => ({ type: "research_run", run: { id: r.id, label: r.label, code: r.codeRef, status: r.status, progress: r.progress, exitCode: r.exitCode, error: r.error, network: r.network, startedAt: r.startedAt, finishedAt: r.finishedAt } });87const approvalEvent = (a: Approval) => ({ type: a.status === "pending" ? "approval_request" : "approval_resolved", approval: { id: a.id, action: a.action, reason: a.reason, detail: a.detail, status: a.status, createdAt: a.createdAt, resolvedAt: a.resolvedAt } });8889/** Forwards the progress and the end of this generation's runs, and the answers to its approval requests, to its stream. Returns the detach function. */90export function attachResearchEvents(ctx: Pick<ResearchContext, "owner" | "generationId" | "emit">): () => void {91 const onRun = (e: { owner: string; run: Run }) => {92 if (e.owner === ctx.owner && ctx.generationId && e.run.generationId === ctx.generationId) ctx.emit(runEvent(e.run));93 };94 const onApproval = (e: { owner: string; approval: Approval }) => {95 if (e.owner === ctx.owner && ctx.generationId && e.approval.generationId === ctx.generationId && e.approval.status !== "pending") ctx.emit(approvalEvent(e.approval));96 };97 runEvents.on("run", onRun);98 approvalEvents.on("approval", onApproval);99 return () => {100 runEvents.off("run", onRun);101 approvalEvents.off("approval", onApproval);102 };103}104105function describeRun(ws: Workspace, r: Run, withLogs: boolean): Record<string, unknown> {106 const out: Record<string, unknown> = { run_id: r.id, label: r.label, code: r.codeRef, status: r.status, exit_code: r.exitCode, seconds: Math.round(((r.finishedAt ?? Date.now()) - r.startedAt) / 1000), progress: r.progress, error: r.error, logs: `runs/${r.id}/stdout.log, runs/${r.id}/stderr.log` };107 if (withLogs) {108 out.stdout_tail = tailLog(ws, r.id, "stdout", 9000);109 const err = tailLog(ws, r.id, "stderr", 5000).trim();110 if (err) out.stderr_tail = err;111 }112 if (r.status === "running") out.note = "Still running: it continues on the server. Collect it later with research_runs (wait or status).";113 if (r.status === "interrupted") out.note = "Interrupted by a restart of the server: its partial output is in the logs; run it again.";114 return out;115}116117function filesChangedSince(ws: Workspace, since: number): string[] {118 return listFiles(ws, "", { recursive: true, max: 2000 })119 .filter((f) => f.type === "file" && f.modifiedAt >= since - 1000 && !f.path.startsWith("runs/") && !f.path.startsWith("logs/") && !f.path.startsWith("code/_runs/"))120 .map((f) => f.path)121 .slice(0, 60);122}123124/** Asks for open network for one run; resolves to true only on an explicit approval, which is audited. */125async function approveOpenNetwork(ctx: ResearchContext, ws: Workspace, reason: string, detail: Record<string, unknown>): Promise<boolean> {126 const a = await requestApproval(ctx.owner, { workspaceId: ws.id, sessionId: ctx.sessionId, generationId: ctx.generationId, action: "open_network", reason: reason || "A run asks for network access beyond the package index and market data.", detail, signal: ctx.signal }, (pending) => ctx.emit(approvalEvent(pending)));127 audit(null, "research.approval", `${a.action}:${a.id}`, { status: a.status, workspace: ws.id, ...detail }, { owner: ctx.owner });128 return a.status === "approved";129}130131/** Executes one research tool. Throws ResearchError (a message the agent can act on) on bad input. */132export async function executeResearchTool(toolCall: { id: string; name: string; input: any; agent?: string }, ctx: ResearchContext): Promise<unknown> {133 const input = toolCall.input ?? {};134 const ws = workspaceFor(ctx);135 try {136 switch (toolCall.name) {137 case "workspace_files": {138 const action = String(input.action ?? "");139 if (action === "list") {140 const files = listFiles(ws, input.path ? String(input.path) : "", { recursive: input.recursive === true, max: 400 });141 return { workspace: ws.id, files: files.map((f) => (f.type === "dir" ? `${f.path}/` : `${f.path} (${f.bytes} bytes)`)) };142 }143 if (action === "read") return readTextFile(ws, String(input.path ?? ""), { offset: input.offset, limit: input.limit });144 if (action === "write") {145 const r = writeTextFile(ws, String(input.path ?? ""), input.content);146 ctx.emit({ type: "research_file", action: "write", path: r.path, bytes: r.bytes, agent: toolCall.agent ?? "lead" });147 return { written: r.path, bytes: r.bytes, sha256: r.sha256.slice(0, 16) };148 }149 if (action === "patch") {150 const r = patchTextFile(ws, String(input.path ?? ""), String(input.old_text ?? ""), String(input.new_text ?? ""));151 ctx.emit({ type: "research_file", action: "patch", path: r.path, bytes: r.bytes, agent: toolCall.agent ?? "lead" });152 return { patched: r.path, bytes: r.bytes, sha256: r.sha256.slice(0, 16) };153 }154 if (action === "delete") {155 deleteFile(ws, String(input.path ?? ""));156 ctx.emit({ type: "research_file", action: "delete", path: String(input.path), bytes: 0, agent: toolCall.agent ?? "lead" });157 return { deleted: String(input.path) };158 }159 throw new ResearchError("action must be list, read, write, patch or delete.");160 }161162 case "inspect_dataset": {163 const profile = await inspectDataset(ws, String(input.path ?? ""));164 ctx.emit({ type: "dataset", path: profile.path, rows: profile.rows, columns: profile.columnCount, bytes: profile.bytes });165 return profile;166 }167168 case "research_run": {169 let network: "default" | "open" = "default";170 const grantKey = `${ctx.owner}:${ws.id}`;171 if (input.network === "open" && (openGrants.get(grantKey) ?? 0) > Date.now()) {172 openGrants.delete(grantKey);173 network = "open";174 } else if (input.network === "open") {175 const ok = await approveOpenNetwork(ctx, ws, String(input.reason ?? ""), { code: input.path ?? "(inline code)", label: input.label ?? null });176 if (!ok) throw new ResearchError("The user did not authorize open network access for this run. Run it without network (market data and the package index stay available), or explain in your answer what could not be done.");177 network = "open";178 }179 const started = Date.now();180 const run = await startRun({ ws, path: input.path, code: input.code, args: Array.isArray(input.args) ? input.args : undefined, label: input.label, timeoutSeconds: input.timeout_seconds, network, sessionId: ctx.sessionId, generationId: ctx.generationId });181 if (network === "open") audit(null, "research.network.open", run.id, { workspace: ws.id, code: run.codeRef }, { owner: ctx.owner });182 ctx.emit(runEvent(run));183 if (input.background === true) return { ...describeRun(ws, run, false), note: "Started in the background. Use research_runs (wait / status / logs) to follow it; start other runs meanwhile if they are independent." };184 const ended = await waitRun(ctx.owner, run.id, 9 * 60_000, ctx.signal);185 return { ...describeRun(ws, ended, true), files_written: ended.status === "running" ? undefined : filesChangedSince(ws, started) };186 }187188 case "research_runs": {189 const action = String(input.action ?? "");190 if (action === "list") return { runs: listRuns(ctx.owner, ws.id, 40).map((r) => describeRun(ws, r, false)) };191 const ids: string[] = (Array.isArray(input.run_ids) ? input.run_ids : []).map(String).slice(0, 16);192 if (ids.length === 0) throw new ResearchError("run_ids is required for this action.");193 const mine = (id: string): Run => {194 const r = getRun(ctx.owner, id);195 if (!r || r.workspaceId !== ws.id) throw new ResearchError(`No run ${id} in this workspace.`, 404);196 return r;197 };198 if (action === "status") return { runs: ids.map((id) => describeRun(ws, mine(id), false)) };199 if (action === "logs") return { runs: ids.map((id) => describeRun(ws, mine(id), true)) };200 if (action === "cancel") return { runs: ids.map((id) => (mine(id), describeRun(ws, cancelRun(ctx.owner, id), false))) };201 if (action === "wait") {202 ids.forEach(mine);203 const timeout = Math.min(540, Math.max(1, Number(input.timeout_seconds) || 300)) * 1000;204 const deadline = Date.now() + timeout;205 const ended = await Promise.all(ids.map((id) => waitRun(ctx.owner, id, Math.max(0, deadline - Date.now()), ctx.signal)));206 return { runs: ended.map((r) => describeRun(ws, r, r.status !== "running")), all_finished: ended.every((r) => r.status !== "running") };207 }208 throw new ResearchError("action must be list, status, wait, logs or cancel.");209 }210211 case "log_experiment": {212 const fields = {213 title: input.title, hypothesis: input.hypothesis, method: input.method, status: input.status, metrics: input.metrics && typeof input.metrics === "object" ? input.metrics : undefined,214 diagnostics: input.diagnostics && typeof input.diagnostics === "object" ? input.diagnostics : undefined, artifacts: Array.isArray(input.artifacts) ? input.artifacts.map(String).slice(0, 40) : undefined,215 codeRef: input.code_path, runId: input.run_id, notes: input.notes,216 };217 let codeHash: string | undefined;218 if (typeof input.code_path === "string" && input.code_path) {219 try {220 codeHash = sha256(fs.readFileSync(resolveInside(ws.dir, input.code_path, { userVisible: true }))).slice(0, 16);221 } catch {222 /* the path is kept as given; no hash for a file that is not there */223 }224 }225 let e: Experiment;226 if (input.experiment_id) {227 const cur = getExperiment(ctx.owner, String(input.experiment_id));228 if (!cur || cur.workspaceId !== ws.id || cur.kind !== "experiment") throw new ResearchError("No experiment with this id in this workspace.", 404);229 e = updateExperiment(ctx.owner, cur.id, { ...fields, codeHash });230 } else {231 if (!String(input.title ?? "").trim()) throw new ResearchError("An experiment needs a title.");232 e = addExperiment(ws, { kind: "experiment", sessionId: ctx.sessionId, generationId: ctx.generationId, ...fields, codeHash, status: input.status });233 }234 ctx.emit(experimentEvent(e));235 return { experiment_id: e.id, number: e.seq, status: e.status, recorded: true };236 }237238 case "list_experiments": {239 const kind = input.kind === "execution" ? "execution" : "experiment";240 const rows = listExperiments(ctx.owner, ws.id, { kind, limit: Math.min(300, Math.max(1, Number(input.limit) || 60)) });241 return {242 kind,243 count: rows.length,244 experiments: rows.map((e) => ({ id: e.id, number: e.seq, title: e.title, status: e.status, hypothesis: e.hypothesis, method: e.method, metrics: e.metrics, diagnostics: e.diagnostics, artifacts: e.artifacts, code: e.codeRef, code_hash: e.codeHash, environment: e.envHash, run_id: e.runId, error: e.error, seconds: e.durationMs !== null ? Math.round(e.durationMs / 1000) : null, notes: e.notes })),245 };246 }247248 case "research_memory": {249 const action = String(input.action ?? "");250 if (action === "save") {251 const n = saveNote(ws, { kind: String(input.kind ?? ""), title: String(input.title ?? ""), body: String(input.body ?? ""), sessionId: ctx.sessionId });252 ctx.emit({ type: "research_note", note: { id: n.id, kind: n.kind, title: n.title, body: n.body.slice(0, 600) } });253 return { saved: n.id, kind: n.kind, title: n.title };254 }255 if (action === "list") return { notes: listNotes(ctx.owner, ws.id, input.kind ? String(input.kind) : undefined).map((n) => ({ id: n.id, kind: n.kind, title: n.title, body: n.body, updated: new Date(n.updatedAt).toISOString().slice(0, 10) })), kinds: NOTE_KINDS };256 if (action === "delete") return { deleted: deleteNote(ctx.owner, ws.id, String(input.id ?? "")) };257 throw new ResearchError("action must be save, list or delete.");258 }259260 case "code_library": {261 const action = String(input.action ?? "");262 if (action === "list") return { modules: listLibrary(ctx.owner).map((m) => ({ name: m.name, import: `from vqlib.${m.name} import ${m.exports.slice(0, 4).join(", ") || "…"}`, exports: m.exports, description: m.description, saved: new Date(m.savedAt).toISOString().slice(0, 10) })) };263 if (action === "read") return { name: String(input.name), code: readLibraryModule(ctx.owner, String(input.name ?? "")) };264 if (action === "save") {265 const code = typeof input.code === "string" && input.code.trim() ? input.code : input.path ? fs.readFileSync(resolveInside(ws.dir, String(input.path), { userVisible: true }), "utf8") : "";266 const m = saveLibraryModule(ctx.owner, String(input.name ?? ""), code, String(input.description ?? ""));267 ctx.emit({ type: "research_file", action: "library", path: `vqlib/${m.name}.py`, bytes: m.bytes, agent: toolCall.agent ?? "lead" });268 return { saved: m.name, import: `from vqlib.${m.name} import ${m.exports.slice(0, 4).join(", ") || "…"}`, exports: m.exports, note: "Importable in new notebook sessions and runs; a notebook session already running must importlib.reload it." };269 }270 throw new ResearchError("action must be save, list or read.");271 }272273 case "request_approval": {274 const action = (APPROVAL_ACTIONS as readonly string[]).includes(input.action) ? (input.action as ApprovalAction) : "other";275 const detail: Record<string, unknown> = {};276 if (typeof input.max_cost_usd === "number") detail.maxCostUsd = input.max_cost_usd;277 if (typeof input.max_minutes === "number") detail.maxMinutes = input.max_minutes;278 const a = await requestApproval(ctx.owner, { workspaceId: ws.id, sessionId: ctx.sessionId, generationId: ctx.generationId, action, reason: String(input.reason ?? ""), detail, signal: ctx.signal }, (pending) => ctx.emit(approvalEvent(pending)));279 audit(null, "research.approval", `${a.action}:${a.id}`, { status: a.status, workspace: ws.id, ...detail }, { owner: ctx.owner });280 if (a.status === "approved" && action === "open_network") openGrants.set(`${ctx.owner}:${ws.id}`, Date.now() + 10 * 60_000);281 if (a.status === "approved" && action === "raise_budget") ctx.raiseBudget?.({ maxCostUsd: detail.maxCostUsd as number | undefined, maxMinutes: detail.maxMinutes as number | undefined });282 return a.status === "approved"283 ? { approved: true, approval_id: a.id, note: action === "open_network" ? "Authorized for one run started within ten minutes: pass network=\"open\" to that research_run." : "Authorized by the user." }284 : { approved: false, status: a.status, note: a.status === "expired" ? "No answer from the user in time: treat it as a refusal, continue without it and say what could not be done." : "The user refused. Continue without it and say what could not be done." };285 }286 default:287 throw new ResearchError(`Unknown research tool: ${toolCall.name}`);288 }289 } catch (e) {290 if (e instanceof ResearchError) throw new Error(e.message);291 throw new Error(redactSecrets((e as Error).message));292 }293}294295// ─── Around the notebook ─────────────────────────────────────────────────────296/**297 * Called after every notebook execution, successful or not: writes it to the ledger and to logs/executions.jsonl298 * with the hash of its code, emits the activity events, and returns the text the agent must read about its figures299 * (what the linter repaired, what is left for it to fix) and its installations.300 */301export function recordNotebookExecution(ctx: ResearchContext, ws: Workspace, o: { code: string; description?: string; agent?: string; toolId?: string; startedAt: number; ok: boolean; error?: string; result?: CustomPythonResult | null }): string {302 const codeHash = sha256(o.code ?? "").slice(0, 16);303 const durationMs = Date.now() - o.startedAt;304 const figures = o.result?.figure_reports ?? [];305 const artifacts = figures.flatMap((f) => Object.values(f.files ?? {}).filter((v): v is string => typeof v === "string"));306 let experiment: Experiment | null = null;307 try {308 experiment = addExperiment(ws, { kind: "execution", sessionId: ctx.sessionId, generationId: ctx.generationId, title: (o.description || "Notebook cell").slice(0, 200), codeRef: `notebook:${o.agent ?? "lead"}`, codeHash, status: o.ok ? "ok" : /time limit|Execution stopped after/.test(o.error ?? "") ? "timeout" : /stopped by the sandbox/.test(o.error ?? "") ? "killed" : "failed", error: o.ok ? null : redactSecrets(o.error ?? "").slice(0, 3000), artifacts: artifacts.length ? artifacts.slice(0, 40) : null, startedAt: o.startedAt, finishedAt: Date.now(), durationMs });309 } catch {310 /* a ledger problem must not fail the analysis */311 }312 // The code itself is kept beside the log, addressed by its hash: an execution can always be traced to what ran.313 try {314 const dir = path.join(ws.dir, "logs", "cells");315 fs.mkdirSync(dir, { recursive: true });316 const file = path.join(dir, `${codeHash}.py`);317 if (!fs.existsSync(file)) fs.writeFileSync(file, o.code ?? "");318 } catch {319 /* best effort */320 }321 appendExecutionLog(ws, { type: "notebook", agent: o.agent ?? "lead", description: o.description ?? null, codeHash, code: `logs/cells/${codeHash}.py`, ok: o.ok, durationMs, error: o.ok ? null : redactSecrets(o.error ?? "").slice(0, 1500), figures: figures.length, installs: o.result?.installs ?? [] });322 ctx.emit({ type: "code_execution", toolId: o.toolId ?? null, agent: o.agent ?? "lead", description: o.description ?? null, codeHash, code: `logs/cells/${codeHash}.py`, lines: (o.code ?? "").split("\n").length, ok: o.ok, durationMs, error: o.ok ? null : redactSecrets(o.error ?? "").slice(0, 400), experimentId: experiment?.id ?? null });323 for (const i of o.result?.installs ?? []) ctx.emit({ type: "package_install", spec: i.spec, ok: i.ok });324325 const notes: string[] = [];326 figures.forEach((f, idx) => {327 const fixed = f.issues.filter((i) => i.fixed);328 const open = f.issues.filter((i) => !i.fixed && i.severity !== "info");329 if (open.length) notes.push(`Figure ${idx + 1}${f.title ? ` (“${f.title.slice(0, 60)}”)` : ""} — to fix in your code: ${open.map((i) => i.message).join(" ")}`);330 else if (fixed.length) notes.push(`Figure ${idx + 1} — repaired automatically: ${fixed.map((i) => i.code).join(", ")}.`);331 });332 let text = "";333 if (notes.length) text += `\n\n[Figure check — VQuant visualization standard]\n${notes.join("\n")}${figures.some((f) => !f.ok) ? "\nRedraw the figures that still have defects before using them in the report." : ""}`;334 if (artifacts.length) text += `\n[Vector copies (SVG, PDF) and the PNG of each figure are saved under artifacts/figures/ in the workspace.]`;335 return text;336}337338/** Announces a notebook cell before it runs, so a client shows it as running instead of inferring it. */339export function announceNotebookExecution(ctx: ResearchContext, o: { code: string; description?: string; agent?: string; toolId?: string }): void {340 ctx.emit({ type: "code_execution_start", toolId: o.toolId ?? null, agent: o.agent ?? "lead", description: o.description ?? null, codeHash: sha256(o.code ?? "").slice(0, 16), lines: (o.code ?? "").split("\n").length });341}342343/**344 * Records the figures of a cell once their addresses are known: one row each (title, files, linter verdict) so a345 * study reopened later shows them as they were live, and one `figure_lint` event each.346 */347export function recordFigures(ctx: ResearchContext, ws: Workspace, o: { reports: Array<{ title?: string; ok: boolean; issues: FigureIssue[]; files?: Record<string, unknown> }>; urls: string[]; toolId?: string; code?: string }): ResearchFigure[] {348 const out: ResearchFigure[] = [];349 o.reports.forEach((r, idx) => {350 try {351 const fig = addFigure(ws, { sessionId: ctx.sessionId, generationId: ctx.generationId, toolId: o.toolId, title: r.title, url: o.urls[idx] ?? null, files: r.files ?? null, issues: r.issues ?? [], codeHash: o.code ? sha256(o.code).slice(0, 16) : null });352 out.push(fig);353 ctx.emit({ type: "figure_lint", figureId: fig.id, toolId: o.toolId ?? null, index: idx, title: fig.title, caption: fig.caption, url: fig.url, ok: r.ok, status: fig.status, fixes: fig.fixes, findings: fig.findings, issues: r.issues, files: fig.files });354 } catch {355 /* a figure that cannot be recorded is still delivered */356 }357 });358 return out;359}360361/** A file path reported by the sandboxed process, accepted only when it is a regular file inside the workspace. */362export function trustedOutputFile(ws: Workspace, reported: string): string | null {363 try {364 const root = fs.realpathSync(ws.dir);365 if (fs.lstatSync(reported).isSymbolicLink()) return null;366 const real = fs.realpathSync(reported);367 if (!real.startsWith(root + path.sep) || !fs.statSync(real).isFile()) return null;368 return real;369 } catch {370 return null;371 }372}373374// ─── Quality gate ────────────────────────────────────────────────────────────375export interface GateFinding {376 id: string;377 severity: "info" | "warning" | "error";378 finding: string;379 evidence: string;380}381382/**383 * What is checked before a research answer is final (contract §9.3): the figures quoted in the text must be384 * traceable to what the executions of this generation printed or returned; figures must have passed the linter;385 * experiments that failed or were dropped during this generation must not be passed over in silence.386 * `numberChecks` are the deterministic checks of the review module run on the answer.387 */388export function researchGate(o: { owner: string; ws: Workspace; generationId: string; numberChecks: Array<{ id: string; severity: "info" | "warning" | "error"; finding: string; evidence: string }>; figureIssues: Array<{ title?: string | null; messages: string[] }>; answer: string }): GateFinding[] {389 const out: GateFinding[] = [];390 for (const c of o.numberChecks) if (c.id === "numbers" || c.id.startsWith("significance") || c.id === "sample") out.push({ id: c.id, severity: c.severity, finding: c.finding, evidence: c.evidence });391 if (o.figureIssues.length) out.push({ id: "figures", severity: "warning", finding: `${o.figureIssues.length} figure(s) produced in this analysis still have defects the linter could not repair.`, evidence: o.figureIssues.slice(0, 6).map((f) => `${f.title ?? "figure"}: ${f.messages.join(" ")}`).join(" | ").slice(0, 1500) });392 const all = listExperiments(o.owner, o.ws.id, { generationId: o.generationId, limit: 500 });393 const declared = all.filter((e) => e.kind === "experiment");394 const failed = declared.filter((e) => ["failed", "inconclusive", "abandoned", "timeout", "killed", "interrupted"].includes(e.status));395 const failedRuns = all.filter((e) => e.kind === "execution" && e.runId && e.status !== "ok" && e.status !== "running");396 if (failed.length || failedRuns.length) {397 const lower = o.answer.toLowerCase();398 const mentioned = /\b(failed|did not converge|abandon|inconclusive|could not|unsuccessful|échou|échec|abandonn|non concluant|n'a pas (pu|converg))/i.test(lower);399 out.push({400 id: "failed_experiments",401 severity: mentioned ? "info" : "warning",402 finding: `${failed.length} declared experiment(s) and ${failedRuns.length} run(s) of this analysis did not succeed${mentioned ? "; the answer speaks of failures" : " and the answer does not seem to mention any failure"}.`,403 evidence: [...failed.map((e) => `#${e.seq} ${e.title} [${e.status}]${e.notes ? `: ${e.notes.slice(0, 120)}` : e.error ? `: ${e.error.slice(0, 120)}` : ""}`), ...failedRuns.map((e) => `run ${e.title} [${e.status}]`)].slice(0, 10).join(" | "),404 });405 }406 const running = all.filter((e) => e.status === "running");407 if (running.length) out.push({ id: "still_running", severity: "warning", finding: `${running.length} run(s) or experiment(s) of this analysis are still marked running.`, evidence: running.slice(0, 6).map((e) => `#${e.seq} ${e.title}`).join(" | ") });408 if (declared.length === 0 && all.length >= 3) out.push({ id: "ledger_empty", severity: "info", finding: `${all.length} executions were logged but no experiment was declared in the ledger.`, evidence: "log_experiment records what was tested and what came out, for the user and for later conversations." });409 return out;410}411