Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : client/src/lib/research/snapshot.ts9 * Module : lib10 * 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 * The same view model as the stream reducer, rebuilt from what the server keeps once a generation is over47 * ("Reopening a study", CONTRACT §9.6): the research REST (`GET /api/v2/research/sessions/:id`: generations with48 * their plan and applied budget, figures with their caption, durable files and linter verdict, ledger, runs, notes,49 * pending approvals) and the stored conversation (console outputs, the outcome of the quality gate).50 *51 * A workspace written by an older server has no `figures`: its figures are then found among its files, without a52 * verdict (`status: null`) — said as such, never guessed.53 */54import { initialResearchState, lintOf, NOTEBOOK_TOOL, outputOfToolResult } from "./reducer";55import type { Execution, Experiment, Figure, GenerationInfo, QualityGate, ResearchState, Run, SessionDetail, StoredMessage, TimelineItem } from "./types";5657const FIGURE_DIR = "artifacts/figures/";5859/** Groups `artifacts/figures/<stem>.{png,svg,pdf}` into one figure per stem, in file-name (chronological) order. */60export function figuresFromFiles(paths: string[]): Array<{ stem: string; files: { png?: string; svg?: string; pdf?: string } }> {61 const byStem = new Map<string, { png?: string; svg?: string; pdf?: string }>();62 for (const p of paths) {63 if (!p.startsWith(FIGURE_DIR)) continue;64 const m = /^(.*)\.(png|svg|pdf)$/i.exec(p);65 if (!m) continue;66 const files = byStem.get(m[1]) ?? {};67 files[m[2].toLowerCase() as "png" | "svg" | "pdf"] = p;68 byStem.set(m[1], files);69 }70 return [...byStem].filter(([, f]) => f.png || f.svg).sort(([a], [b]) => a.localeCompare(b)).map(([stem, files]) => ({ stem, files }));71}7273/** A readable title out of a figure file name (`20261120-222127-01-trois-s-ries…` → `trois s ries…`); last resort only. */74function titleFromStem(stem: string): string {75 return stem.slice(FIGURE_DIR.length).replace(/^\d{8}-\d{6}-\d+-/, "").replace(/-/g, " ").trim();76}7778export function stateFromSnapshot(detail: SessionDetail, stored: StoredMessage[] = []): ResearchState {79 const state = initialResearchState();80 const wsId = detail.session.id;81 state.workspace = { id: wsId, kind: detail.session.kind };82 state.sessionId = detail.session.sessionIds[detail.session.sessionIds.length - 1] ?? null;83 state.finished = true;8485 const mine = stored.filter((m) => !m.research || m.research.workspaceId === wsId);86 state.objective = mine[0]?.question ?? detail.session.title ?? null;8788 // Console outputs: the stored conversation keeps the results of the successful notebook calls of a generation,89 // in order. They are attached only when the count matches the ledger exactly — a wrong pairing would be worse90 // than no output.91 const outputs = new Map<string, string | null>();92 for (const m of mine) {93 if (!m.generationId) continue;94 const results = (m.toolResults ?? []).filter((t) => t.tool === NOTEBOOK_TOOL);95 const cells = detail.executions.filter((x) => x.generationId === m.generationId && !x.runId && x.status === "ok").sort((a, b) => a.seq - b.seq);96 if (results.length === 0 || results.length !== cells.length) continue;97 cells.forEach((c, i) => outputs.set(c.id, outputOfToolResult(results[i].result)));98 }99100 // Figures: the stored records when the server has them; otherwise (older workspace) the files, without a verdict.101 const stored_ = detail.figures ?? [];102 const figureByPng = new Map<string, Figure>();103 const figures: Figure[] = stored_.length > 0104 ? stored_.map((f) => ({105 key: f.id, title: f.title, caption: f.caption, ...lintOf(f as unknown as Record<string, unknown>), toolId: f.toolId ?? null, at: f.at ?? null, files: f.files, url: f.url,106 execKey: null, generationId: f.generationId ?? null,107 }))108 : figuresFromFiles(detail.files.filter((f) => f.type === "file").map((f) => f.path)).map((f) => ({109 key: `f:${f.stem}`, title: titleFromStem(f.stem) || null, caption: null, status: null, fixes: [], findings: [], toolId: null, at: null, files: f.files, url: null, execKey: null, generationId: null,110 }));111 for (const f of figures) if (f.files?.png) figureByPng.set(f.files.png, f);112 const storedByCode = new Map<string, Figure[]>();113 stored_.forEach((f, i) => { if (f.codeHash) storedByCode.set(`${f.generationId}:${f.codeHash}`, [...(storedByCode.get(`${f.generationId}:${f.codeHash}`) ?? []), figures[i]]); });114115 const executions: Execution[] = [];116 const timeline: TimelineItem[] = [];117 for (const x of [...detail.executions].sort((a, b) => a.seq - b.seq)) {118 if (x.runId) continue; // script runs are shown from `runs`119 const key = x.id;120 // The figures of a cell: by the hash of the code that drew them (stored records), else by its artifacts.121 const own = new Set<Figure>(storedByCode.get(`${x.generationId}:${x.codeHash}`) ?? []);122 for (const path of x.artifacts ?? []) { const f = figureByPng.get(path); if (f) own.add(f); }123 const figureKeys: string[] = [];124 for (const figure of own) {125 if (figure.execKey) continue;126 figure.execKey = key;127 figure.generationId = figure.generationId ?? x.generationId ?? null;128 figureKeys.push(figure.key);129 }130 executions.push({131 key, id: x.id, seq: x.seq, agent: x.codeRef?.startsWith("notebook:") ? x.codeRef.slice(9) : "lead", title: x.title && x.title !== "Notebook cell" ? x.title : null,132 codeHash: x.codeHash, codePath: x.codeHash ? `logs/cells/${x.codeHash}.py` : null, code: null, lines: null,133 status: (["ok", "failed", "timeout", "killed", "interrupted", "running"].includes(x.status) ? x.status : "failed") as Execution["status"],134 durationMs: x.durationMs, error: x.error, output: outputs.get(x.id) ?? null, envHash: x.envHash, generationId: x.generationId ?? null, startedAt: x.startedAt, toolId: null, figureKeys,135 });136 timeline.push({ key: `execution:${key}`, kind: "execution", ref: key, at: x.startedAt, generationId: x.generationId ?? null });137 }138 for (const f of figures) {139 const owner = executions.find((x) => x.key === f.execKey);140 timeline.push({ key: `figure:${f.key}`, kind: "figure", ref: f.key, at: f.at ?? (owner?.startedAt != null ? owner.startedAt + (owner.durationMs ?? 0) : null), generationId: f.generationId });141 }142143 const runs: Run[] = [...detail.runs].sort((a, b) => (a.startedAt ?? 0) - (b.startedAt ?? 0)).map((r) => ({144 id: r.id, label: r.label, code: r.codeRef ?? r.code ?? null, codeHash: r.codeHash ?? null, args: r.args ?? [], status: r.status, progress: r.progress, exitCode: r.exitCode,145 error: r.error, network: r.network === "open" ? "open" : "default", startedAt: r.startedAt, finishedAt: r.finishedAt, generationId: r.generationId ?? null,146 }));147 runs.forEach((r) => timeline.push({ key: `run:${r.id}`, kind: "run", ref: r.id, at: r.startedAt, generationId: r.generationId }));148149 const experiments: Experiment[] = [...detail.experiments].sort((a, b) => a.seq - b.seq).map((x) => ({150 id: x.id, seq: x.seq, title: x.title ?? "Expérience sans titre", hypothesis: x.hypothesis, method: x.method, status: x.status, metrics: x.metrics, diagnostics: x.diagnostics,151 artifacts: x.artifacts ?? [], codeRef: x.codeRef, runId: x.runId, codeHash: x.codeHash, notes: x.notes, error: x.error, envHash: x.envHash, generationId: x.generationId ?? null,152 startedAt: x.startedAt, finishedAt: x.finishedAt, durationMs: x.durationMs,153 }));154 experiments.forEach((x) => timeline.push({ key: `experiment:${x.id}`, kind: "experiment", ref: x.id, at: x.startedAt, generationId: x.generationId }));155156 state.notes = detail.notes.map((n) => ({ id: n.id, kind: n.kind, title: n.title, body: n.body, createdAt: n.createdAt ?? null }));157 state.notes.forEach((n) => timeline.push({ key: `note:${n.id}`, kind: "note", ref: n.id, at: n.createdAt, generationId: null }));158159 state.approvals = detail.approvals.map((a) => ({ id: a.id, action: a.action, reason: a.reason, detail: a.detail, status: a.status, createdAt: a.createdAt, resolvedAt: a.resolvedAt }));160 state.approvals.forEach((a) => timeline.push({ key: `approval:${a.id}`, kind: "approval", ref: a.id, at: a.createdAt, generationId: null }));161162 // Datasets: the files of data/ (their profile is read on demand through the inspect route).163 state.datasets = detail.files.filter((f) => f.type === "file" && f.path.startsWith("data/")).map((f) => ({ path: f.path, rows: null, columns: null, bytes: f.bytes }));164165 const gates: QualityGate[] = [];166 for (const m of mine) {167 const findings = m.research?.qualityGate;168 if (!findings) continue;169 const gate = { generationId: m.generationId ?? null, passed: !findings.some((f) => f.severity !== "info"), findings: findings.map((f) => ({ ...f, evidence: f.evidence ?? null })) };170 gates.push(gate);171 // The gate closes its generation: it sits after everything else that generation did.172 const last = Math.max(0, ...timeline.filter((t) => t.generationId === gate.generationId && t.at != null).map((t) => t.at as number));173 timeline.push({ key: `gate:${gate.generationId ?? "0"}`, kind: "gate", ref: gate.generationId ?? "0", at: last ? last + 1 : null, generationId: gate.generationId });174 }175176 // The analyses run here, the plan of the latest one that has one, and the budget that applied to it.177 const generations: GenerationInfo[] = (detail.generations ?? []).map((g) => ({ generationId: g.generationId, status: g.status, startedAt: g.startedAt, finishedAt: g.finishedAt, mode: g.mode ?? null, model: g.model ?? null, budgetApplied: g.budgetApplied ?? null }));178 const latest = generations[generations.length - 1];179 state.generations = generations;180 state.generationId = latest?.generationId ?? null;181 state.budgetApplied = latest?.budgetApplied ?? null;182 state.plan = (detail.plan ?? []).map((p) => ({ title: p.title, status: p.status }));183 for (const g of detail.generations ?? []) for (const b of g.budget ?? []) if (g.generationId === latest?.generationId) state.budgetHits.push(b);184 if (state.plan.length > 0) {185 const planned = [...(detail.generations ?? [])].reverse().find((g) => (g.plan ?? []).length > 0);186 timeline.push({ key: "plan:0", kind: "plan", ref: "0", at: planned?.startedAt ?? null, generationId: planned?.generationId ?? null });187 }188189 state.executions = executions;190 state.figures = figures;191 state.runs = runs;192 state.experiments = experiments;193 state.gates = gates;194 // Chronological; entries without a time keep their relative order at the end.195 state.timeline = timeline.map((t, i) => ({ t, i })).sort((a, b) => (a.t.at ?? Number.MAX_SAFE_INTEGER) - (b.t.at ?? Number.MAX_SAFE_INTEGER) || a.i - b.i).map((x) => x.t);196 state.timeline.unshift({ key: `workspace:${wsId}`, kind: "workspace", ref: wsId, at: detail.session.createdAt, generationId: null });197 return state;198}199200/**201 * The view of a study that is running (or was just watched): the live state of its generation on top of what the202 * workspace already held from earlier generations. Live entities win; the snapshot fills what the stream does not203 * carry (the agent's notes on an experiment, the environment hash of an execution, times).204 */205export function mergeLive(live: ResearchState, snapshot: ResearchState | null): ResearchState {206 if (!snapshot) return live;207 const gen = live.generationId;208 const older = <T extends { generationId: string | null }>(list: T[]) => list.filter((x) => x.generationId !== gen || gen === null);209 const liveExecIds = new Set(live.executions.map((x) => x.id).filter(Boolean));210 const liveRunIds = new Set(live.runs.map((r) => r.id));211 const liveExpIds = new Set(live.experiments.map((x) => x.id));212 const liveNoteIds = new Set(live.notes.map((n) => n.id));213 const livePngs = new Set(live.figures.map((f) => f.files?.png).filter(Boolean));214 const liveFigureKeys = new Set(live.figures.map((f) => f.key));215 const snapExec = new Map(snapshot.executions.map((x) => [x.id, x]));216 const snapExp = new Map(snapshot.experiments.map((x) => [x.id, x]));217218 const executions = [219 ...older(snapshot.executions).filter((x) => !liveExecIds.has(x.id)),220 ...live.executions.map((x) => {221 const s = x.id ? snapExec.get(x.id) : undefined;222 return s ? { ...x, seq: x.seq ?? s.seq, envHash: x.envHash ?? s.envHash, startedAt: x.startedAt ?? s.startedAt } : x;223 }),224 ];225 const experiments = [226 ...older(snapshot.experiments).filter((x) => !liveExpIds.has(x.id)),227 ...live.experiments.map((x) => {228 const s = snapExp.get(x.id);229 return s ? { ...x, notes: x.notes ?? s.notes, envHash: x.envHash ?? s.envHash } : x;230 }),231 ];232 const runs = [...older(snapshot.runs).filter((r) => !liveRunIds.has(r.id)), ...live.runs.map((r) => {233 const s = snapshot.runs.find((y) => y.id === r.id);234 // The stream stops reporting a run when its generation ends; the server goes on watching it.235 return s && r.status === "running" && live.finished ? { ...r, status: s.status, progress: s.progress, exitCode: s.exitCode, error: s.error, finishedAt: s.finishedAt } : s ? { ...r, codeHash: r.codeHash ?? s.codeHash, args: r.args.length ? r.args : s.args } : r;236 })];237 const notes = [...snapshot.notes.filter((n) => !liveNoteIds.has(n.id)), ...live.notes];238 const figures = [...older(snapshot.figures).filter((f) => !liveFigureKeys.has(f.key) && !livePngs.has(f.files?.png)), ...live.figures];239 const approvals = [...snapshot.approvals.filter((a) => !live.approvals.some((b) => b.id === a.id)), ...live.approvals];240 const gates = [...snapshot.gates.filter((g) => g.generationId !== gen), ...live.gates];241 const kept = new Set<string>([242 ...executions.map((x) => `execution:${x.key}`), ...experiments.map((x) => `experiment:${x.id}`), ...runs.map((r) => `run:${r.id}`),243 ...notes.map((n) => `note:${n.id}`), ...figures.map((f) => `figure:${f.key}`), ...approvals.map((a) => `approval:${a.id}`), ...gates.map((g) => `gate:${g.generationId ?? "0"}`),244 ]);245 const liveKeys = new Set(live.timeline.map((t) => t.key));246 const timeline = [247 ...snapshot.timeline.filter((t) => t.kind !== "workspace" && t.kind !== "plan" && kept.has(t.key) && !liveKeys.has(t.key) && t.generationId !== gen),248 ...live.timeline,249 ];250 return {251 ...live,252 workspace: live.workspace ?? snapshot.workspace,253 plan: live.plan.length > 0 ? live.plan : live.finished ? snapshot.plan : live.plan,254 budgetApplied: live.budgetApplied ?? null,255 generations: snapshot.generations,256 objective: live.objective ?? snapshot.objective,257 datasets: [...snapshot.datasets.filter((d) => !live.datasets.some((l) => l.path === d.path)), ...live.datasets],258 executions, experiments, runs, notes, figures, approvals, gates, timeline,259 };260}261