Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/services/research/store.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 * Research workspace store (contract: docs/next/CONTRACT.md §9.1, §9.3, §9.4).47 *48 * A workspace is a directory on the server plus its rows in SQLite:49 *50 * <root>/<owner>/<workspaceId>/51 * code/ programs the agent writes (importable: on PYTHONPATH)52 * data/ uploaded and derived datasets53 * artifacts/ figures (PNG + SVG + PDF), tables, models, reports54 * runs/<id>/ stdout.log, stderr.log, status.json of each script run55 * logs/ executions.jsonl (every notebook cell and run), network.log56 * environment.lock.txt every installed distribution and its version (base + overlay)57 * .site/ .cache/ .tmp/ .home/ package overlay, caches and scratch of the sandbox58 * <root>/<owner>/_library/vqlib/ the person's reusable code library (read-only inside the sandbox)59 *60 * A conversation that belongs to a research project uses the workspace of the project (`p-<projectId>`), so every61 * conversation of the project sees the same files, experiments and notes; otherwise it has its own (`s-<sessionId>`).62 * The root is outside the application tree (VQ_RESEARCH_DIR, default ~/vquant-research/<app directory name>) so a63 * deployment that replaces the tree does not touch it.64 */65import type Database from "better-sqlite3";66import { createHash, randomUUID } from "node:crypto";67import fs from "node:fs";68import os from "node:os";69import path from "node:path";70import { isSqlite, pool } from "../../db";7172type Db = Database.Database;73const db = (): Db => {74 if (!isSqlite) throw new Error("The research workspace needs the SQLite database");75 return pool as Db;76};7778export class ResearchError extends Error {79 constructor(message: string, public status = 400) {80 super(message);81 }82}8384// ─── Paths ───────────────────────────────────────────────────────────────────85const ID_RE = /^[A-Za-z0-9_-]{1,80}$/;86export const WORKSPACE_DIRS = ["code", "data", "artifacts", "runs", "logs", ".site", ".cache", ".tmp", ".home"];8788export function researchRoot(): string {89 const root = process.env.VQ_RESEARCH_DIR || path.join(os.homedir(), "vquant-research", path.basename(process.cwd()));90 fs.mkdirSync(root, { recursive: true, mode: 0o700 });91 return fs.realpathSync(root);92}9394function ownerDir(owner: string): string {95 if (!/^[a-z][a-z0-9_-]{1,23}$/.test(owner)) throw new ResearchError("Invalid owner");96 return path.join(researchRoot(), owner);97}9899export function workspaceDir(owner: string, workspaceId: string): string {100 if (!ID_RE.test(workspaceId) || workspaceId.startsWith("_")) throw new ResearchError("Invalid workspace id");101 return path.join(ownerDir(owner), workspaceId);102}103104export function libraryDir(owner: string): string {105 const dir = path.join(ownerDir(owner), "_library");106 const pkg = path.join(dir, "vqlib");107 if (!fs.existsSync(path.join(pkg, "__init__.py"))) {108 fs.mkdirSync(pkg, { recursive: true });109 fs.writeFileSync(path.join(pkg, "__init__.py"), '"""Reusable functions saved from earlier research (code_library tool)."""\n');110 }111 return dir;112}113114/**115 * Absolute path of `rel` inside the workspace. Refuses absolute paths, `..`, NUL bytes, the sandbox's private116 * directories when `userVisible`, and any path that resolves (through a symlink) outside the workspace.117 */118export function resolveInside(wsDir: string, rel: string, opts: { userVisible?: boolean } = {}): string {119 const clean = String(rel ?? "").replace(/\\/g, "/").replace(/^\.\//, "");120 if (!clean || clean.includes("\0") || clean.startsWith("/") || clean.startsWith("~") || clean.split("/").includes("..")) throw new ResearchError(`Invalid path "${String(rel).slice(0, 80)}": use a path relative to the workspace, without "..".`);121 if (clean.length > 400) throw new ResearchError("Path too long.");122 if (opts.userVisible && /^\.(site|cache|tmp|home)(\/|$)/.test(clean)) throw new ResearchError("That directory is internal to the sandbox.");123 const root = fs.realpathSync(wsDir);124 const target = path.resolve(root, clean);125 if (target !== root && !target.startsWith(root + path.sep)) throw new ResearchError("Path escapes the workspace.");126 // The deepest existing ancestor must still be inside once symlinks are resolved.127 let probe = target;128 while (!fs.existsSync(probe)) probe = path.dirname(probe);129 const realProbe = fs.realpathSync(probe);130 if (realProbe !== root && !realProbe.startsWith(root + path.sep)) throw new ResearchError("Path escapes the workspace through a link.");131 return target;132}133134// ─── Workspaces ──────────────────────────────────────────────────────────────135export interface Workspace {136 id: string;137 owner: string;138 kind: "session" | "project";139 ref: string;140 title: string | null;141 createdAt: number;142 updatedAt: number;143 dir: string;144}145146const toWorkspace = (r: any): Workspace => ({ id: r.id, owner: r.owner, kind: r.kind, ref: r.ref, title: r.title, createdAt: r.created_at, updatedAt: r.updated_at, dir: workspaceDir(r.owner, r.id) });147148export function getWorkspace(owner: string, id: string): Workspace | null {149 if (!ID_RE.test(id)) return null;150 const r = db().prepare("SELECT * FROM vq_research_workspaces WHERE owner = ? AND id = ?").get(owner, id);151 return r ? toWorkspace(r) : null;152}153154export function listWorkspaces(owner: string): Workspace[] {155 return (db().prepare("SELECT * FROM vq_research_workspaces WHERE owner = ? ORDER BY updated_at DESC LIMIT 200").all(owner) as any[]).map(toWorkspace);156}157158/** The workspace of a conversation, created on first use. A project conversation shares the project's workspace. */159export function ensureWorkspace(owner: string, o: { sessionId: string; projectId?: string | null; title?: string | null }): Workspace {160 const sid = o.sessionId.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64);161 if (!sid) throw new ResearchError("A session id is required");162 const d = db();163 const mapped = d.prepare("SELECT workspace_id FROM vq_research_sessions WHERE owner = ? AND session_id = ?").get(owner, o.sessionId) as { workspace_id: string } | undefined;164 const id = mapped?.workspace_id ?? (o.projectId && ID_RE.test(o.projectId) ? `p-${o.projectId}`.slice(0, 80) : `s-${sid}`);165 const now = Date.now();166 if (!mapped) d.prepare("INSERT OR IGNORE INTO vq_research_sessions (owner, session_id, workspace_id) VALUES (?, ?, ?)").run(owner, o.sessionId, id);167 const kind = id.startsWith("p-") ? "project" : "session";168 d.prepare("INSERT INTO vq_research_workspaces (id, owner, kind, ref, title, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(owner, id) DO UPDATE SET title = coalesce(vq_research_workspaces.title, excluded.title)").run(id, owner, kind, kind === "project" ? id.slice(2) : o.sessionId, o.title?.slice(0, 200) ?? null, now, now);169 const dir = workspaceDir(owner, id);170 for (const sub of WORKSPACE_DIRS) fs.mkdirSync(path.join(dir, sub), { recursive: true, mode: 0o700 });171 return getWorkspace(owner, id)!;172}173174export function workspaceOfSession(owner: string, sessionId: string): Workspace | null {175 const mapped = db().prepare("SELECT workspace_id FROM vq_research_sessions WHERE owner = ? AND session_id = ?").get(owner, sessionId) as { workspace_id: string } | undefined;176 return mapped ? getWorkspace(owner, mapped.workspace_id) : null;177}178179export function sessionsOfWorkspace(owner: string, workspaceId: string): string[] {180 return (db().prepare("SELECT session_id FROM vq_research_sessions WHERE owner = ? AND workspace_id = ?").all(owner, workspaceId) as { session_id: string }[]).map((r) => r.session_id);181}182183export function touchWorkspace(owner: string, id: string): void {184 db().prepare("UPDATE vq_research_workspaces SET updated_at = ? WHERE owner = ? AND id = ?").run(Date.now(), owner, id);185}186187// ─── Files ───────────────────────────────────────────────────────────────────188export interface FileEntry {189 path: string;190 type: "file" | "dir";191 bytes: number;192 modifiedAt: number;193}194const MAX_TEXT_WRITE = 2 * 1024 * 1024;195196export function listFiles(ws: Workspace, rel = "", opts: { recursive?: boolean; max?: number } = {}): FileEntry[] {197 const base = rel ? resolveInside(ws.dir, rel, { userVisible: true }) : fs.realpathSync(ws.dir);198 const out: FileEntry[] = [];199 const max = opts.max ?? 500;200 const walk = (dir: string, depth: number) => {201 let names: string[];202 try {203 names = fs.readdirSync(dir).sort();204 } catch {205 return;206 }207 for (const name of names) {208 if (out.length >= max) return;209 if (dir === fs.realpathSync(ws.dir) && /^\.(site|cache|tmp|home)$/.test(name)) continue;210 if (name === "__pycache__" || name === ".DS_Store") continue;211 const full = path.join(dir, name);212 let st: fs.Stats;213 try {214 st = fs.lstatSync(full);215 } catch {216 continue;217 }218 if (st.isSymbolicLink()) continue; // links are never followed or listed219 const p = path.relative(fs.realpathSync(ws.dir), full);220 if (st.isDirectory()) {221 out.push({ path: p, type: "dir", bytes: 0, modifiedAt: st.mtimeMs });222 if (opts.recursive && depth < 6) walk(full, depth + 1);223 } else if (st.isFile()) out.push({ path: p, type: "file", bytes: st.size, modifiedAt: st.mtimeMs });224 }225 };226 walk(base, 0);227 return out;228}229230export function writeTextFile(ws: Workspace, rel: string, content: string): { path: string; bytes: number; sha256: string } {231 if (typeof content !== "string") throw new ResearchError("content must be text.");232 if (Buffer.byteLength(content) > MAX_TEXT_WRITE) throw new ResearchError("File too large to write in one call (2 MB): generate it from code instead.");233 const target = resolveInside(ws.dir, rel, { userVisible: true });234 fs.mkdirSync(path.dirname(target), { recursive: true });235 if (fs.existsSync(target) && fs.lstatSync(target).isSymbolicLink()) throw new ResearchError("Refusing to write through a link.");236 fs.writeFileSync(target, content);237 touchWorkspace(ws.owner, ws.id);238 return { path: path.relative(fs.realpathSync(ws.dir), target), bytes: Buffer.byteLength(content), sha256: sha256(content) };239}240241export function readTextFile(ws: Workspace, rel: string, opts: { offset?: number; limit?: number; maxBytes?: number } = {}): { path: string; bytes: number; totalLines: number; from: number; to: number; text: string; truncated: boolean } {242 const target = resolveInside(ws.dir, rel, { userVisible: true });243 if (!fs.existsSync(target) || !fs.statSync(target).isFile()) throw new ResearchError(`No such file: ${rel}`, 404);244 const size = fs.statSync(target).size;245 const maxBytes = opts.maxBytes ?? 4 * 1024 * 1024;246 const fd = fs.openSync(target, "r");247 const buf = Buffer.alloc(Math.min(size, maxBytes));248 fs.readSync(fd, buf, 0, buf.length, 0);249 fs.closeSync(fd);250 if (buf.subarray(0, 8192).includes(0)) throw new ResearchError(`${rel} is a binary file (${size} bytes): read it from Python instead.`);251 const lines = buf.toString("utf8").split("\n");252 const from = Math.max(1, Math.floor(opts.offset ?? 1));253 const limit = Math.min(2000, Math.max(1, Math.floor(opts.limit ?? 400)));254 const slice = lines.slice(from - 1, from - 1 + limit);255 return { path: rel, bytes: size, totalLines: lines.length, from, to: from + slice.length - 1, text: slice.join("\n"), truncated: size > maxBytes || from - 1 + limit < lines.length };256}257258/** Replaces one exact occurrence of `oldText` by `newText` (the edit fails when it is absent or ambiguous). */259export function patchTextFile(ws: Workspace, rel: string, oldText: string, newText: string): { path: string; bytes: number; sha256: string } {260 const target = resolveInside(ws.dir, rel, { userVisible: true });261 if (!fs.existsSync(target)) throw new ResearchError(`No such file: ${rel}`, 404);262 const text = fs.readFileSync(target, "utf8");263 if (!oldText) throw new ResearchError("old text is required.");264 const count = text.split(oldText).length - 1;265 if (count === 0) throw new ResearchError("The text to replace was not found in the file: read the file and copy the exact lines.");266 if (count > 1) throw new ResearchError(`The text to replace occurs ${count} times: include more surrounding lines so it is unique.`);267 return writeTextFile(ws, rel, text.replace(oldText, () => newText));268}269270export function deleteFile(ws: Workspace, rel: string): void {271 const target = resolveInside(ws.dir, rel, { userVisible: true });272 if (!fs.existsSync(target)) throw new ResearchError(`No such file: ${rel}`, 404);273 if (WORKSPACE_DIRS.includes(rel.replace(/\/+$/, ""))) throw new ResearchError("That directory is part of the workspace layout.");274 fs.rmSync(target, { recursive: true, force: true });275}276277export const sha256 = (data: string | Buffer): string => createHash("sha256").update(data).digest("hex");278279// ─── Dataset uploads ─────────────────────────────────────────────────────────280export const UPLOAD_MAX_BYTES = 200 * 1024 * 1024;281const UPLOAD_TYPES: Record<string, "text" | "parquet" | "zip" | "ole" | "feather"> = { ".csv": "text", ".tsv": "text", ".txt": "text", ".json": "text", ".jsonl": "text", ".parquet": "parquet", ".xlsx": "zip", ".xls": "ole", ".feather": "feather" };282283/** Checks a dataset upload: extension, size, and that the bytes are what the extension says. Returns the safe file name. */284export function validateUpload(filename: string, data: Buffer): string {285 const base = path.basename(String(filename ?? "").replace(/\\/g, "/")).normalize("NFKD").replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^\.+/, "").slice(0, 120);286 const ext = path.extname(base).toLowerCase();287 const kind = UPLOAD_TYPES[ext];288 if (!base || !kind) throw new ResearchError(`Unsupported dataset type "${ext || "(none)"}". Accepted: ${Object.keys(UPLOAD_TYPES).join(", ")}.`, 415);289 if (data.length === 0) throw new ResearchError("The file is empty.");290 if (data.length > UPLOAD_MAX_BYTES) throw new ResearchError(`The file is larger than ${UPLOAD_MAX_BYTES / 1024 / 1024} MB.`, 413);291 const head = data.subarray(0, 8);292 const magic = (s: string) => head.subarray(0, s.length).equals(Buffer.from(s, "latin1"));293 if (kind === "parquet" && !(magic("PAR1") && data.subarray(-4).equals(Buffer.from("PAR1")))) throw new ResearchError("This is not a Parquet file.", 415);294 if (kind === "zip" && !magic("PK\x03\x04")) throw new ResearchError("This is not an .xlsx workbook.", 415);295 if (kind === "ole" && !head.equals(Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]))) throw new ResearchError("This is not an .xls workbook.", 415);296 if (kind === "feather" && !magic("ARROW1")) throw new ResearchError("This is not a Feather file.", 415);297 if (kind === "text") {298 const sample = data.subarray(0, 64 * 1024);299 if (sample.includes(0)) throw new ResearchError(`This ${ext} file contains binary data.`, 415);300 if (magic("PK\x03\x04") || magic("%PDF") || magic("\x7fELF") || magic("MZ") || head.subarray(0, 4).equals(Buffer.from([0xcf, 0xfa, 0xed, 0xfe]))) throw new ResearchError(`This ${ext} file is not text.`, 415);301 }302 return base;303}304305export function saveUpload(ws: Workspace, filename: string, data: Buffer): { path: string; bytes: number; sha256: string } {306 const name = validateUpload(filename, data);307 const rel = `data/${name}`;308 const target = resolveInside(ws.dir, rel, { userVisible: true });309 fs.mkdirSync(path.dirname(target), { recursive: true });310 fs.writeFileSync(target, data, { mode: 0o600 });311 touchWorkspace(ws.owner, ws.id);312 return { path: rel, bytes: data.length, sha256: sha256(data) };313}314315// ─── Experiment ledger ───────────────────────────────────────────────────────316export type ExperimentStatus = "running" | "ok" | "failed" | "timeout" | "killed" | "interrupted" | "inconclusive" | "abandoned";317export const EXPERIMENT_STATUSES: ExperimentStatus[] = ["running", "ok", "failed", "timeout", "killed", "interrupted", "inconclusive", "abandoned"];318319export interface Experiment {320 id: string;321 workspaceId: string;322 sessionId: string | null;323 generationId: string | null;324 seq: number;325 /** "execution" = logged by the runtime for every notebook cell and script run; "experiment" = declared by the agent */326 kind: "execution" | "experiment";327 title: string | null;328 hypothesis: string | null;329 method: string | null;330 codeRef: string | null;331 codeHash: string | null;332 envHash: string | null;333 runId: string | null;334 status: ExperimentStatus;335 metrics: Record<string, unknown> | null;336 diagnostics: unknown;337 artifacts: string[] | null;338 notes: string | null;339 error: string | null;340 startedAt: number;341 finishedAt: number | null;342 durationMs: number | null;343}344345const parse = (s: string | null) => {346 if (!s) return null;347 try {348 return JSON.parse(s);349 } catch {350 return null;351 }352};353const toExperiment = (r: any): Experiment => ({354 id: r.id, workspaceId: r.workspace_id, sessionId: r.session_id, generationId: r.generation_id, seq: r.seq, kind: r.kind, title: r.title, hypothesis: r.hypothesis, method: r.method,355 codeRef: r.code_ref, codeHash: r.code_hash, envHash: r.env_hash, runId: r.run_id, status: r.status, metrics: parse(r.metrics), diagnostics: parse(r.diagnostics), artifacts: parse(r.artifacts),356 notes: r.notes, error: r.error, startedAt: r.started_at, finishedAt: r.finished_at, durationMs: r.duration_ms,357});358359export interface ExperimentInput {360 kind: "execution" | "experiment";361 sessionId?: string | null;362 generationId?: string | null;363 title?: string | null;364 hypothesis?: string | null;365 method?: string | null;366 codeRef?: string | null;367 codeHash?: string | null;368 runId?: string | null;369 status: ExperimentStatus;370 metrics?: Record<string, unknown> | null;371 diagnostics?: unknown;372 artifacts?: string[] | null;373 notes?: string | null;374 error?: string | null;375 startedAt?: number;376 finishedAt?: number | null;377 durationMs?: number | null;378}379380const cap = (v: unknown, n: number): string | null => (v === null || v === undefined || v === "" ? null : String(v).slice(0, n));381const json = (v: unknown, n: number): string | null => {382 if (v === null || v === undefined) return null;383 const s = JSON.stringify(v);384 if (s.length > n) throw new ResearchError(`That field is too large for the ledger (${s.length} characters, limit ${n}): record the key figures and keep the full output in a file under artifacts/.`);385 return s;386};387388/** Hash of the environment a result was produced in: the lockfile when one was recorded, else null. */389export function environmentHash(ws: Workspace): string | null {390 try {391 return sha256(fs.readFileSync(path.join(ws.dir, "environment.lock.txt"))).slice(0, 16);392 } catch {393 return null;394 }395}396397export function addExperiment(ws: Workspace, e: ExperimentInput): Experiment {398 if (!EXPERIMENT_STATUSES.includes(e.status)) throw new ResearchError(`status must be one of ${EXPERIMENT_STATUSES.join(", ")}.`);399 const d = db();400 const id = randomUUID();401 const now = Date.now();402 d.transaction(() => {403 const seq = ((d.prepare("SELECT max(seq) AS m FROM vq_experiments WHERE owner = ? AND workspace_id = ?").get(ws.owner, ws.id) as { m: number | null }).m ?? 0) + 1;404 d.prepare(405 "INSERT INTO vq_experiments (id, owner, workspace_id, session_id, generation_id, seq, kind, title, hypothesis, method, code_ref, code_hash, env_hash, run_id, status, metrics, diagnostics, artifacts, notes, error, started_at, finished_at, duration_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",406 ).run(id, ws.owner, ws.id, e.sessionId ?? null, e.generationId ?? null, seq, e.kind, cap(e.title, 200), cap(e.hypothesis, 2000), cap(e.method, 4000), cap(e.codeRef, 400), cap(e.codeHash, 64), environmentHash(ws), cap(e.runId, 64), e.status,407 json(e.metrics, 20_000), json(e.diagnostics, 20_000), json(e.artifacts, 8000), cap(e.notes, 6000), cap(e.error, 4000), e.startedAt ?? now, e.finishedAt === undefined ? (e.status === "running" ? null : now) : e.finishedAt, e.durationMs ?? null);408 })();409 touchWorkspace(ws.owner, ws.id);410 return getExperiment(ws.owner, id)!;411}412413export function updateExperiment(owner: string, id: string, patch: Partial<Omit<ExperimentInput, "kind">>): Experiment {414 const cur = getExperiment(owner, id);415 if (!cur) throw new ResearchError("No experiment with this id.", 404);416 if (patch.status && !EXPERIMENT_STATUSES.includes(patch.status)) throw new ResearchError(`status must be one of ${EXPERIMENT_STATUSES.join(", ")}.`);417 const status = patch.status ?? cur.status;418 const finished = patch.finishedAt !== undefined ? patch.finishedAt : status !== "running" && cur.finishedAt === null ? Date.now() : cur.finishedAt;419 db()420 .prepare("UPDATE vq_experiments SET title = ?, hypothesis = ?, method = ?, code_ref = ?, code_hash = ?, run_id = ?, status = ?, metrics = ?, diagnostics = ?, artifacts = ?, notes = ?, error = ?, finished_at = ?, duration_ms = ? WHERE id = ? AND owner = ?")421 .run(cap(patch.title ?? cur.title, 200), cap(patch.hypothesis ?? cur.hypothesis, 2000), cap(patch.method ?? cur.method, 4000), cap(patch.codeRef ?? cur.codeRef, 400), cap(patch.codeHash ?? cur.codeHash, 64), cap(patch.runId ?? cur.runId, 64), status,422 json(patch.metrics === undefined ? cur.metrics : patch.metrics, 20_000), json(patch.diagnostics === undefined ? cur.diagnostics : patch.diagnostics, 20_000), json(patch.artifacts === undefined ? cur.artifacts : patch.artifacts, 8000),423 cap(patch.notes ?? cur.notes, 6000), cap(patch.error === undefined ? cur.error : patch.error, 4000), finished, patch.durationMs ?? cur.durationMs ?? (finished ? finished - cur.startedAt : null), id, owner);424 return getExperiment(owner, id)!;425}426427export function getExperiment(owner: string, id: string): Experiment | null {428 const r = db().prepare("SELECT * FROM vq_experiments WHERE id = ? AND owner = ?").get(id, owner);429 return r ? toExperiment(r) : null;430}431432export function listExperiments(owner: string, workspaceId: string, opts: { kind?: "execution" | "experiment"; sessionId?: string; generationId?: string; limit?: number } = {}): Experiment[] {433 const where = ["owner = ?", "workspace_id = ?"];434 const args: unknown[] = [owner, workspaceId];435 if (opts.kind) (where.push("kind = ?"), args.push(opts.kind));436 if (opts.sessionId) (where.push("session_id = ?"), args.push(opts.sessionId));437 if (opts.generationId) (where.push("generation_id = ?"), args.push(opts.generationId));438 return (db().prepare(`SELECT * FROM vq_experiments WHERE ${where.join(" AND ")} ORDER BY seq DESC LIMIT ?`).all(...args, Math.min(1000, opts.limit ?? 300)) as any[]).map(toExperiment).reverse();439}440441/** One line per execution in logs/executions.jsonl: the durable, append-only record beside the database. */442export function appendExecutionLog(ws: Workspace, entry: Record<string, unknown>): void {443 try {444 fs.appendFileSync(path.join(ws.dir, "logs", "executions.jsonl"), JSON.stringify({ at: new Date().toISOString(), ...entry }) + "\n");445 } catch {446 /* the ledger row is the record of reference */447 }448}449450// ─── Figures ─────────────────────────────────────────────────────────────────451export interface FigureIssue {452 code: string;453 severity: "error" | "warning" | "info";454 message: string;455 fixed: boolean;456}457export interface ResearchFigure {458 id: string;459 workspaceId: string;460 sessionId: string | null;461 generationId: string | null;462 /** the tool call (notebook cell) that produced it */463 toolId: string | null;464 at: number;465 /** the title drawn on the figure, which is also its caption in the report */466 title: string | null;467 caption: string | null;468 /** address of the PNG as shown in the conversation (/figures/…): served while the build keeps it */469 url: string | null;470 /** durable copies in the workspace: { png, svg, pdf } paths (read them with the file route) */471 files: Record<string, string> | null;472 /** "passed" = nothing found; "fixed" = defects found and all repaired automatically; "issues" = findings remain */473 status: "passed" | "fixed" | "issues";474 /** automatic repairs applied */475 fixes: FigureIssue[];476 /** what the linter found and did not repair (information-level findings included) */477 findings: FigureIssue[];478 codeHash: string | null;479}480const toFigure = (r: any): ResearchFigure => ({ id: r.id, workspaceId: r.workspace_id, sessionId: r.session_id, generationId: r.generation_id, toolId: r.tool_id, at: r.at, title: r.title, caption: r.title, url: r.url, files: parse(r.files), status: r.status, fixes: parse(r.fixes) ?? [], findings: parse(r.findings) ?? [], codeHash: r.code_hash });481482/** The verdict of the linter on one figure, from its list of issues. Pure. */483export function figureVerdict(issues: FigureIssue[]): { status: ResearchFigure["status"]; fixes: FigureIssue[]; findings: FigureIssue[] } {484 const fixes = issues.filter((i) => i.fixed);485 const findings = issues.filter((i) => !i.fixed);486 return { status: findings.some((i) => i.severity !== "info") ? "issues" : fixes.length ? "fixed" : "passed", fixes, findings };487}488489export function addFigure(ws: Workspace, f: { sessionId?: string | null; generationId?: string | null; toolId?: string | null; title?: string | null; url?: string | null; files?: Record<string, unknown> | null; issues: FigureIssue[]; codeHash?: string | null }): ResearchFigure {490 const id = randomUUID();491 const v = figureVerdict(f.issues);492 const files = f.files ? Object.fromEntries(Object.entries(f.files).filter(([, p]) => typeof p === "string")) : null;493 db().prepare("INSERT INTO vq_research_figures (id, owner, workspace_id, session_id, generation_id, tool_id, at, title, url, files, status, fixes, findings, code_hash) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")494 .run(id, ws.owner, ws.id, f.sessionId ?? null, f.generationId ?? null, f.toolId ?? null, Date.now(), cap(f.title, 300), cap(f.url, 300), files ? JSON.stringify(files) : null, v.status, JSON.stringify(v.fixes).slice(0, 8000), JSON.stringify(v.findings).slice(0, 8000), cap(f.codeHash, 64));495 return toFigure(db().prepare("SELECT * FROM vq_research_figures WHERE id = ?").get(id));496}497export function listFigures(owner: string, workspaceId: string, limit = 500): ResearchFigure[] {498 return (db().prepare("SELECT * FROM vq_research_figures WHERE owner = ? AND workspace_id = ? ORDER BY at, rowid LIMIT ?").all(owner, workspaceId, limit) as any[]).map(toFigure);499}500501// ─── Research notes (project memory) ─────────────────────────────────────────502export const NOTE_KINDS = ["dataset", "model", "decision", "implementation", "failure", "hypothesis", "finding", "workflow"] as const;503export type NoteKind = (typeof NOTE_KINDS)[number];504export interface ResearchNote {505 id: string;506 workspaceId: string;507 kind: NoteKind;508 title: string;509 body: string;510 sessionId: string | null;511 createdAt: number;512 updatedAt: number;513}514const toNote = (r: any): ResearchNote => ({ id: r.id, workspaceId: r.workspace_id, kind: r.kind, title: r.title, body: r.body, sessionId: r.session_id, createdAt: r.created_at, updatedAt: r.updated_at });515const MAX_NOTES = 400;516517/** Saves a note; a note of the same kind and title is replaced (a decision that changed, a dataset re-profiled). */518export function saveNote(ws: Workspace, n: { kind: string; title: string; body: string; sessionId?: string | null }): ResearchNote {519 if (!(NOTE_KINDS as readonly string[]).includes(n.kind)) throw new ResearchError(`kind must be one of ${NOTE_KINDS.join(", ")}.`);520 const title = String(n.title ?? "").trim().slice(0, 160);521 const body = String(n.body ?? "").trim().slice(0, 8000);522 if (!title || !body) throw new ResearchError("A note needs a title and a body.");523 const d = db();524 const now = Date.now();525 const same = d.prepare("SELECT id FROM vq_research_notes WHERE owner = ? AND workspace_id = ? AND kind = ? AND lower(title) = lower(?)").get(ws.owner, ws.id, n.kind, title) as { id: string } | undefined;526 if (same) {527 d.prepare("UPDATE vq_research_notes SET body = ?, updated_at = ?, session_id = ? WHERE id = ?").run(body, now, n.sessionId ?? null, same.id);528 return toNote(d.prepare("SELECT * FROM vq_research_notes WHERE id = ?").get(same.id));529 }530 const count = (d.prepare("SELECT count(*) AS n FROM vq_research_notes WHERE owner = ? AND workspace_id = ?").get(ws.owner, ws.id) as { n: number }).n;531 if (count >= MAX_NOTES) throw new ResearchError(`The research memory of this workspace is full (${MAX_NOTES} notes): delete or merge outdated ones.`);532 const id = randomUUID().slice(0, 8);533 d.prepare("INSERT INTO vq_research_notes (id, owner, workspace_id, kind, title, body, session_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)").run(id, ws.owner, ws.id, n.kind, title, body, n.sessionId ?? null, now, now);534 touchWorkspace(ws.owner, ws.id);535 return toNote(d.prepare("SELECT * FROM vq_research_notes WHERE id = ?").get(id));536}537export function listNotes(owner: string, workspaceId: string, kind?: string): ResearchNote[] {538 const rows = kind ? db().prepare("SELECT * FROM vq_research_notes WHERE owner = ? AND workspace_id = ? AND kind = ? ORDER BY updated_at").all(owner, workspaceId, kind) : db().prepare("SELECT * FROM vq_research_notes WHERE owner = ? AND workspace_id = ? ORDER BY updated_at").all(owner, workspaceId);539 return (rows as any[]).map(toNote);540}541export function deleteNote(owner: string, workspaceId: string, id: string): boolean {542 return db().prepare("DELETE FROM vq_research_notes WHERE owner = ? AND workspace_id = ? AND id = ?").run(owner, workspaceId, id).changes === 1;543}544545// ─── Code library ────────────────────────────────────────────────────────────546export interface LibraryEntry {547 name: string;548 description: string;549 savedAt: number;550 sha256: string;551 bytes: number;552 exports: string[];553}554const indexPath = (owner: string) => path.join(libraryDir(owner), "vqlib", "index.json");555export function listLibrary(owner: string): LibraryEntry[] {556 try {557 return JSON.parse(fs.readFileSync(indexPath(owner), "utf8"));558 } catch {559 return [];560 }561}562/** Saves a module in the person's library as vqlib/<name>.py (importable in every later workspace). */563export function saveLibraryModule(owner: string, name: string, code: string, description: string): LibraryEntry {564 if (!/^[a-z][a-z0-9_]{1,40}$/.test(name) || name === "index") throw new ResearchError("The module name must be a lowercase Python identifier (letters, digits, underscores).");565 if (!code.trim()) throw new ResearchError("No code to save.");566 if (Buffer.byteLength(code) > 400_000) throw new ResearchError("Module too large for the library (400 kB).");567 const dir = path.join(libraryDir(owner), "vqlib");568 fs.writeFileSync(path.join(dir, `${name}.py`), code);569 const exports = [...code.matchAll(/^(?:def|class)\s+([A-Za-z_][A-Za-z0-9_]*)/gm)].map((m) => m[1]).filter((n) => !n.startsWith("_")).slice(0, 40);570 const entry: LibraryEntry = { name, description: String(description ?? "").trim().slice(0, 400), savedAt: Date.now(), sha256: sha256(code), bytes: Buffer.byteLength(code), exports };571 const index = listLibrary(owner).filter((e) => e.name !== name);572 index.push(entry);573 fs.writeFileSync(indexPath(owner), JSON.stringify(index.sort((a, b) => a.name.localeCompare(b.name)), null, 2));574 return entry;575}576export function readLibraryModule(owner: string, name: string): string {577 if (!/^[a-z][a-z0-9_]{1,40}$/.test(name)) throw new ResearchError("Invalid module name.");578 const file = path.join(libraryDir(owner), "vqlib", `${name}.py`);579 if (!fs.existsSync(file)) throw new ResearchError(`No module "${name}" in the library.`, 404);580 return fs.readFileSync(file, "utf8");581}582583// ─── Environment ─────────────────────────────────────────────────────────────584export function readEnvironment(ws: Workspace): { lockfile: string | null; hash: string | null; packages: number; overlay: string[] } {585 let lockfile: string | null = null;586 try {587 lockfile = fs.readFileSync(path.join(ws.dir, "environment.lock.txt"), "utf8");588 } catch {589 /* nothing recorded yet */590 }591 let overlay: string[] = [];592 try {593 overlay = fs.readdirSync(path.join(ws.dir, ".site")).filter((n) => n.endsWith(".dist-info")).map((n) => n.replace(/\.dist-info$/, "").replace(/-(?=\d)/, "==")).sort();594 } catch {595 /* no overlay yet */596 }597 return { lockfile, hash: environmentHash(ws), packages: lockfile ? lockfile.split("\n").filter((l) => l && !l.startsWith("#")).length : 0, overlay };598}599600/** What a resumed conversation is given about its workspace: files, notes, experiments, library. Compact by design. */601export function workspaceDigest(ws: Workspace, maxChars = 7000): string {602 const files = listFiles(ws, "", { recursive: true, max: 400 }).filter((f) => f.type === "file" && !f.path.startsWith("runs/") && !f.path.startsWith("logs/"));603 const notes = listNotes(ws.owner, ws.id);604 const experiments = listExperiments(ws.owner, ws.id, { kind: "experiment", limit: 60 });605 const executions = listExperiments(ws.owner, ws.id, { kind: "execution", limit: 400 });606 const library = listLibrary(ws.owner);607 if (files.length === 0 && notes.length === 0 && experiments.length === 0 && library.length === 0) return "";608 const kb = (n: number) => (n > 1e6 ? `${(n / 1e6).toFixed(1)} MB` : `${Math.max(1, Math.round(n / 1000))} kB`);609 const parts: string[] = [`RESEARCH WORKSPACE (${ws.kind === "project" ? "shared by the conversations of this project" : "of this conversation"}; persistent on the server; your Python runs with it as working directory)`];610 if (files.length) {611 const shown = files.slice(0, 60).map((f) => `${f.path} (${kb(f.bytes)})`);612 parts.push(`Files: ${shown.join(", ")}${files.length > 60 ? `, … ${files.length - 60} more (workspace_files list)` : ""}`);613 }614 if (notes.length) {615 parts.push("Research memory (research_memory tool; newest last):");616 for (const kind of NOTE_KINDS) {617 const of = notes.filter((n) => n.kind === kind).slice(-8);618 for (const n of of) parts.push(`- [${kind}] ${n.title}: ${n.body.replace(/\s+/g, " ").slice(0, 420)}${n.body.length > 420 ? "…" : ""}`);619 }620 }621 if (experiments.length) {622 parts.push("Experiment ledger (declared experiments; failed ones included):");623 for (const e of experiments.slice(-25)) parts.push(`- #${e.seq} [${e.status}] ${e.title ?? e.hypothesis?.slice(0, 80) ?? ""}${e.method ? ` — ${e.method.replace(/\s+/g, " ").slice(0, 140)}` : ""}${e.metrics ? ` — ${JSON.stringify(e.metrics).slice(0, 200)}` : ""}${e.error ? ` — ${e.error.replace(/\s+/g, " ").slice(0, 140)}` : ""}`);624 }625 if (executions.length) parts.push(`Executions logged so far: ${executions.length} (${executions.filter((e) => e.status !== "ok").length} did not succeed).`);626 if (library.length) parts.push(`Your code library (import with \`from vqlib.<module> import …\`): ${library.map((l) => `${l.name} [${l.exports.slice(0, 6).join(", ")}]${l.description ? ` — ${l.description.slice(0, 100)}` : ""}`).join("; ")}`);627 const env = readEnvironment(ws);628 if (env.overlay.length) parts.push(`Packages installed in this workspace on top of the base environment: ${env.overlay.slice(0, 40).join(", ")}`);629 const text = parts.join("\n");630 return text.length > maxChars ? `${text.slice(0, maxChars)}\n[workspace digest cut: use the workspace tools for the rest]` : text;631}632