Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : client/src/lib/research/ledger.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 experiment ledger as rows of one table (CONTRACT §9.3): what the agent declared (`experiment`) and what the47 * runtime logged by itself (`execution`: notebook cells and script runs). Failed, inconclusive and abandoned48 * entries are rows like the others — with their reason.49 */50import { formatNumber } from "@/lib/format";51import type { Execution, Experiment, ExperimentStatus, ResearchState, Run } from "./types";5253export type LedgerKind = "experiment" | "cell" | "run";54export type LedgerOutcome = "ok" | "problem" | "open" | "running";5556export interface LedgerRow {57 key: string;58 kind: LedgerKind;59 seq: number | null;60 title: string;61 hypothesis: string | null;62 method: string | null;63 status: ExperimentStatus | "done" | "cancelled";64 outcome: LedgerOutcome;65 /** why it failed / was abandoned / is inconclusive, in the agent's or the runtime's words */66 reason: string | null;67 metrics: Array<{ name: string; value: string; numeric: boolean }>;68 metricCount: number;69 envHash: string | null;70 /** workspace path of the code, when there is one */71 codePath: string | null;72 codeRef: string | null;73 artifacts: string[];74 runId: string | null;75 durationMs: number | null;76 startedAt: number | null;77 generationId: string | null;78 notes: string | null;79 diagnostics: unknown;80}8182export const STATUS_LABEL: Record<string, string> = {83 ok: "Réussie", done: "Terminée", running: "En cours", failed: "Échec", timeout: "Délai dépassé", killed: "Arrêtée par le bac à sable",84 interrupted: "Interrompue", inconclusive: "Non concluante", abandoned: "Abandonnée", cancelled: "Annulée",85};8687export function outcomeOf(status: string): LedgerOutcome {88 if (status === "ok" || status === "done") return "ok";89 if (status === "running") return "running";90 if (status === "inconclusive" || status === "abandoned" || status === "cancelled") return "open";91 return "problem";92}9394/** A metric value as text: numbers through the app's formatter (up to 4 significant decimals), the rest as is. */95export function formatMetric(value: unknown): { value: string; numeric: boolean } {96 if (typeof value === "number" && Number.isFinite(value)) {97 const abs = Math.abs(value);98 const decimals = Number.isInteger(value) ? 0 : abs >= 100 ? 1 : abs >= 1 ? 3 : 4;99 return { value: formatNumber(value, { decimals }), numeric: true };100 }101 if (typeof value === "boolean") return { value: value ? "oui" : "non", numeric: false };102 if (value == null) return { value: "—", numeric: false };103 if (typeof value === "object") return { value: JSON.stringify(value).slice(0, 80), numeric: false };104 return { value: String(value).slice(0, 80), numeric: false };105}106107export function shapeMetrics(metrics: Record<string, unknown> | null, max = 4): { shown: LedgerRow["metrics"]; total: number } {108 const entries = Object.entries(metrics ?? {});109 return { shown: entries.slice(0, max).map(([name, v]) => ({ name, ...formatMetric(v) })), total: entries.length };110}111112const firstLine = (text: string | null, max = 220): string | null => {113 if (!text) return null;114 // The runtime's error starts with the output before the failure; the exception itself is the informative line.115 const lines = text.split("\n").map((l) => l.trim()).filter(Boolean);116 const exception = [...lines].reverse().find((l) => /^[A-Za-z_.]*(Error|Exception|Warning|Interrupt)\b.*:/.test(l) || /^(ERROR|Error):/.test(l));117 const line = exception ?? lines.find((l) => !/^Output before the error:?$/i.test(l)) ?? lines[0] ?? "";118 return line.length > max ? `${line.slice(0, max)}…` : line;119};120121function experimentRow(x: Experiment): LedgerRow {122 const m = shapeMetrics(x.metrics);123 const outcome = outcomeOf(x.status);124 return {125 key: `e:${x.id}`, kind: "experiment", seq: x.seq, title: x.title, hypothesis: x.hypothesis, method: x.method, status: x.status, outcome,126 reason: outcome === "ok" || outcome === "running" ? null : x.notes ?? firstLine(x.error) ?? null,127 metrics: m.shown, metricCount: m.total, envHash: x.envHash, codePath: x.codeRef && !x.codeRef.startsWith("notebook:") ? x.codeRef : null, codeRef: x.codeRef,128 artifacts: x.artifacts, runId: x.runId, durationMs: x.durationMs, startedAt: x.startedAt, generationId: x.generationId, notes: x.notes, diagnostics: x.diagnostics,129 };130}131132function cellRow(x: Execution): LedgerRow {133 const outcome = outcomeOf(x.status);134 return {135 key: `c:${x.key}`, kind: "cell", seq: x.seq, title: x.title ?? "Cellule sans description", hypothesis: null, method: null, status: x.status, outcome,136 reason: outcome === "problem" ? firstLine(x.error) : null, metrics: [], metricCount: 0, envHash: x.envHash, codePath: x.codePath, codeRef: `notebook:${x.agent}`,137 artifacts: [], runId: null, durationMs: x.durationMs, startedAt: x.startedAt, generationId: x.generationId, notes: null, diagnostics: null,138 };139}140141function runRow(r: Run): LedgerRow {142 const outcome = outcomeOf(r.status);143 return {144 key: `r:${r.id}`, kind: "run", seq: null, title: r.label ?? r.code ?? "Exécution de script", hypothesis: null, method: null, status: r.status, outcome,145 reason: outcome === "ok" || outcome === "running" ? null : firstLine(r.error) ?? (r.exitCode != null ? `Code de sortie ${r.exitCode}` : null), metrics: [], metricCount: 0, envHash: null,146 codePath: r.code, codeRef: r.code, artifacts: [], runId: r.id, durationMs: r.startedAt != null && r.finishedAt != null ? r.finishedAt - r.startedAt : null,147 startedAt: r.startedAt, generationId: r.generationId, notes: null, diagnostics: null,148 };149}150151export function ledgerRows(state: Pick<ResearchState, "experiments" | "executions" | "runs">): LedgerRow[] {152 return [...state.experiments.map(experimentRow), ...state.executions.map(cellRow), ...state.runs.map(runRow)];153}154155export type LedgerKindFilter = "experiment" | "execution" | "all";156export type LedgerOutcomeFilter = "all" | "ok" | "problem" | "open";157export interface LedgerFilter { kind: LedgerKindFilter; outcome: LedgerOutcomeFilter; query: string }158export const DEFAULT_LEDGER_FILTER: LedgerFilter = { kind: "experiment", outcome: "all", query: "" };159160export function filterLedger(rows: LedgerRow[], f: LedgerFilter): LedgerRow[] {161 const q = f.query.trim().toLocaleLowerCase("fr");162 return rows.filter((r) => {163 if (f.kind === "experiment" && r.kind !== "experiment") return false;164 if (f.kind === "execution" && r.kind === "experiment") return false;165 if (f.outcome !== "all" && r.outcome !== f.outcome && !(f.outcome === "ok" && r.outcome === "running")) return false;166 if (!q) return true;167 return [r.title, r.hypothesis, r.method, r.reason, r.codeRef, ...r.metrics.map((m) => m.name)].some((t) => t && t.toLocaleLowerCase("fr").includes(q));168 });169}170171export function ledgerCounts(rows: LedgerRow[]): Record<LedgerKindFilter, number> & Record<"ok" | "problem" | "open", number> {172 const declared = rows.filter((r) => r.kind === "experiment");173 return {174 experiment: declared.length, execution: rows.length - declared.length, all: rows.length,175 ok: rows.filter((r) => r.outcome === "ok").length, problem: rows.filter((r) => r.outcome === "problem").length, open: rows.filter((r) => r.outcome === "open").length,176 };177}178