SPB Git

Repository Public MIT

reducer.test.ts 27.0 KB 447 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : VQuant8 * File             : client/src/lib/research/reducer.test.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 */4445import { describe, expect, it } from "vitest";46import fs from "node:fs";47import path from "node:path";48import { countsOf, hasResearch, initialResearchState, reduceResearch, replay } from "./reducer";49import { mergeLive, stateFromSnapshot, figuresFromFiles } from "./snapshot";50import type { SessionDetail, StoredMessage, StreamEvent } from "./types";5152// Real payloads of the study of 2026-11-20 on the research test copy (docs/next/RESEARCH_AGENT.md §7), trimmed.53const fixture = <T,>(name: string): T => JSON.parse(fs.readFileSync(path.join(__dirname, "__fixtures__", name), "utf8")) as T;54const stream = fixture<StreamEvent[]>("stream-study.json");55const detail = fixture<SessionDetail>("workspace-detail.json");56const conversation = fixture<{ messages: StoredMessage[] }>("conversation.json");57const GEN = "0bc4b1ce-439f-451e-a893-f49987b53db6";5859describe("reduceResearch on the real stream of a study", () => {60  const state = replay(stream);6162  it("rebuilds the whole study", () => {63    expect(state.workspace).toEqual({ id: "s-3d04acf2-235e-46e3-8c2d-bf26b0ba3c81", kind: "session" });64    expect(state.generationId).toBe(GEN);65    expect(state.objective).toContain("us_macro_quarterly.csv");66    expect(state.plan).toHaveLength(7);67    expect(state.datasets).toEqual([{ path: "data/us_macro_quarterly.csv", rows: 203, columns: 13, bytes: 17424 }]);68    expect(state.installs).toEqual([expect.objectContaining({ spec: "ruptures", ok: true })]);69    expect(state.finished).toBe(true);70  });7172  it("keeps every execution, the failed ones included (4 of 56)", () => {73    expect(state.executions).toHaveLength(46);74    expect(state.runs).toHaveLength(10);75    const failed = state.executions.filter((x) => x.status !== "ok");76    expect(failed).toHaveLength(4);77    expect(failed.every((x) => x.status === "failed" && x.error)).toBe(true);78    expect(countsOf(state)).toMatchObject({ executions: 56, failed: 4, running: 0, runs: 10, runsRunning: 0, experiments: 9, figures: 14, installs: 1 });79    // every cell carries the code the stream announced and the place it is kept80    expect(state.executions.every((x) => x.code && x.codePath === `logs/cells/${x.codeHash}.py` && x.id)).toBe(true);81    // the full tool error replaces the 400-character cut of code_execution82    expect(failed[0].error).toContain("ModuleNotFoundError");83  });8485  it("tolerates the duplicated start events of runs", () => {86    expect(stream.filter((e) => e.type === "research_run")).toHaveLength(30);87    expect(new Set(state.runs.map((r) => r.id)).size).toBe(10);88    expect(state.runs.every((r) => r.status === "done" && r.progress === 1 && r.exitCode === 0)).toBe(true);89    expect(state.timeline.filter((t) => t.kind === "run")).toHaveLength(10);90  });9192  it("lists failed and abandoned experiments with the others", () => {93    expect(state.experiments).toHaveLength(9);94    expect(state.experiments.map((x) => x.status).sort()).toEqual(["abandoned", "failed", "ok", "ok", "ok", "ok", "ok", "ok", "ok"]);95    expect(state.experiments[0].metrics).toMatchObject({ "infl ADF p full": 0.027 });96  });9798  it("attaches each figure report to the cell that drew it", () => {99    expect(state.figures).toHaveLength(14);100    expect(state.figures.every((f) => f.files?.png && f.files.svg && f.files.pdf && f.execKey)).toBe(true);101    // a stream recorded before figures had a `status`: the verdict is derived from `ok` and the issue list102    expect(state.figures.filter((f) => f.status === "issues")).toHaveLength(3);103    expect(state.figures.filter((f) => f.status === "fixed").length).toBeGreaterThan(8);104    expect(state.figures[0].fixes[0]).toMatchObject({ code: "contrast", fixed: true });105    const owner = state.executions.find((x) => x.key === state.figures[0].execKey)!;106    expect(owner.figureKeys).toContain(state.figures[0].key);107  });108109  it("records the quality gate with its findings", () => {110    expect(state.gates).toHaveLength(1);111    expect(state.gates[0].passed).toBe(false);112    expect(state.gates[0].findings.map((f) => f.id)).toEqual(expect.arrayContaining(["numbers", "significance", "figures"]));113  });114115  it("orders the timeline as things happened", () => {116    const kinds = state.timeline.map((t) => t.kind);117    expect(kinds[0]).toBe("workspace");118    expect(kinds.indexOf("dataset")).toBeLessThan(kinds.indexOf("plan"));119    expect(kinds.indexOf("plan")).toBeLessThan(kinds.indexOf("execution"));120    expect(kinds.indexOf("install")).toBeLessThan(kinds.indexOf("run"));121    // the gate comes after the last figure; in this study the agent then logged its reservation as an experiment122    expect(kinds.lastIndexOf("gate")).toBeGreaterThan(kinds.lastIndexOf("figure"));123    expect(kinds.slice(kinds.lastIndexOf("gate") + 1)).toEqual(["experiment"]);124    expect(new Set(state.timeline.map((t) => t.key)).size).toBe(state.timeline.length);125    // executions appear in the order they were started126    const order = state.timeline.filter((t) => t.kind === "execution").map((t) => t.ref);127    expect(order).toEqual(state.executions.map((x) => x.key));128  });129130  it("gives the same state event by event as in one pass", () => {131    let s = initialResearchState();132    for (const e of stream) s = reduceResearch(s, e);133    expect(s).toEqual(state);134  });135});136137describe("replay and re-attachment", () => {138  it("ignores events already applied when a stream is re-attached from an earlier index", () => {139    const full = replay(stream, initialResearchState(), 0);140    // watched up to event 120, connection cut, re-attached with ?from=80: events 80–120 arrive a second time141    let s = replay(stream.slice(0, 121), initialResearchState(), 0);142    s = replay(stream.slice(80), s, 80);143    expect(s).toEqual(full);144    expect(s.lastIndex).toBeGreaterThan(250);145  });146147  it("rebuilds from zero after a page reload (attach with from=0)", () => {148    const first = replay(stream.slice(0, 150), initialResearchState(), 0);149    const reloaded = replay(stream.slice(0, 150), initialResearchState(), 0);150    expect(reloaded).toEqual(first);151    expect(first.finished).toBe(false);152    expect(first.executions.length).toBeGreaterThan(10);153  });154155  it("returns the very same object for events it does not use", () => {156    const s = replay(stream.slice(0, 60));157    for (const e of [{ type: "text", content: "abc" }, { type: "thinking", content: "…" }, { type: "status", message: "x" }, { type: "something_new_in_2027", payload: 1 }, { type: "tool_start", tool: "get_stock_quote", toolId: "t1", input: {} }, {} as StreamEvent, null as unknown as StreamEvent]) {158      expect(reduceResearch(s, e)).toBe(s);159    }160  });161162  it("does not bring a finished run back to life on a late start event", () => {163    const start = stream.find((e) => e.type === "research_run")!;164    const s = reduceResearch(replay(stream), start);165    expect(s.runs.find((r) => r.id === (start.run as { id: string }).id)!.status).toBe("done");166  });167});168169describe("cells, outputs and approvals", () => {170  const start = (toolId: string, description: string): StreamEvent => ({ type: "tool_start", tool: "execute_custom_python_analysis", toolId, input: { code: "print(1)\nprint(2)", description } });171172  it("shows a cell as running, then with its output", () => {173    let s = reduceResearch(initialResearchState(), start("t1", "Essai"));174    expect(s.executions[0]).toMatchObject({ status: "running", code: "print(1)\nprint(2)", lines: 2, title: "Essai" });175    s = reduceResearch(s, { type: "code_execution", agent: "lead", description: "Essai", codeHash: "abc", code: "logs/cells/abc.py", lines: 2, ok: true, durationMs: 12, error: null, experimentId: "e1" });176    s = reduceResearch(s, { type: "tool_complete", tool: "execute_custom_python_analysis", toolId: "t1", duration: 14 });177    s = reduceResearch(s, { type: "tool_result", tool: "execute_custom_python_analysis", result: { success: true, output: "1\n2\n\n[Notebook session — variables in memory: x: int]" } });178    expect(s.executions).toHaveLength(1);179    expect(s.executions[0]).toMatchObject({ status: "ok", id: "e1", durationMs: 12, output: "1\n2" });180  });181182  it("pairs parallel cells by their description", () => {183    let s = reduceResearch(initialResearchState(), start("t1", "A"));184    s = reduceResearch(s, start("t2", "B"));185    s = reduceResearch(s, { type: "code_execution", agent: "lead", description: "B", codeHash: "b", code: "logs/cells/b.py", lines: 2, ok: false, durationMs: 5, error: "ValueError: x", experimentId: "eb" });186    expect(s.executions.map((x) => x.status)).toEqual(["running", "failed"]);187  });188189  it("adds a sub-analyst's cell that had no tool_start", () => {190    const s = reduceResearch(initialResearchState(), { type: "code_execution", agent: "analyst-2", description: "Vérification", codeHash: "c", code: "logs/cells/c.py", lines: 9, ok: true, durationMs: 40, error: null, experimentId: "ec" });191    expect(s.executions[0]).toMatchObject({ agent: "analyst-2", status: "ok", code: null, codePath: "logs/cells/c.py" });192  });193194  it("closes cells left open when the generation ends", () => {195    const s = reduceResearch(reduceResearch(initialResearchState(), start("t1", "Long")), { type: "done", sessionId: "s" });196    expect(s.finished).toBe(true);197    expect(s.executions[0].status).toBe("interrupted");198  });199200  it("follows an approval from request to answer and never reopens it", () => {201    const request: StreamEvent = { type: "approval_request", approval: { id: "a1", action: "open_network", reason: "Télécharger la série FRED", detail: { host: "fred.stlouisfed.org" }, status: "pending", createdAt: 1000, resolvedAt: null } };202    let s = reduceResearch(initialResearchState(), request);203    expect(countsOf(s).pendingApprovals).toBe(1);204    expect(hasResearch(s)).toBe(true);205    s = reduceResearch(s, { type: "approval_resolved", approval: { id: "a1", action: "open_network", status: "denied", createdAt: 1000, resolvedAt: 5000 } });206    expect(s.approvals[0]).toMatchObject({ status: "denied", resolvedAt: 5000, reason: "Télécharger la série FRED" });207    expect(reduceResearch(s, request)).toBe(s);208    expect(s.timeline.filter((t) => t.kind === "approval")).toHaveLength(1);209  });210211  it("counts a new plan as a revision only when its steps change", () => {212    let s = reduceResearch(initialResearchState(), { type: "plan", steps: [{ title: "A", status: "in_progress" }, { title: "B", status: "pending" }] });213    s = reduceResearch(s, { type: "plan", steps: [{ title: "A", status: "done" }, { title: "B", status: "in_progress" }] });214    expect(s.planRevisions).toBe(0);215    s = reduceResearch(s, { type: "plan", steps: [{ title: "A", status: "done" }, { title: "C", status: "in_progress" }] });216    expect(s.planRevisions).toBe(1);217    expect(s.timeline.filter((t) => t.kind === "plan")).toHaveLength(2);218  });219});220221describe("a finished study rebuilt from the REST and the stored conversation", () => {222  const snapshot = stateFromSnapshot(detail, conversation.messages);223224  it("has the same ledger as the server", () => {225    expect(snapshot.workspace?.id).toBe(detail.session.id);226    expect(snapshot.runs).toHaveLength(detail.runs.length);227    expect(snapshot.executions).toHaveLength(detail.executions.filter((x) => !x.runId).length);228    expect(snapshot.executions.filter((x) => x.status !== "ok")).toHaveLength(5);229    expect(snapshot.experiments).toHaveLength(10);230    expect(snapshot.experiments.filter((x) => x.status === "abandoned")[0].notes).toContain("BIC");231    expect(snapshot.finished).toBe(true);232  });233234  it("finds the figures of an older workspace among its files, without a verdict", () => {235    const pngs = detail.files.filter((f) => f.path.startsWith("artifacts/figures/") && f.path.endsWith(".png"));236    expect(snapshot.figures).toHaveLength(pngs.length);237    expect(snapshot.figures.every((f) => f.status === null && f.files?.png)).toBe(true);238    expect(snapshot.figures.filter((f) => f.execKey).length).toBeGreaterThan(0);239    expect(figuresFromFiles(["artifacts/figures/a.png", "artifacts/figures/a.svg", "artifacts/figures/a.pdf", "artifacts/x.csv", "artifacts/figures/b.pdf"])).toEqual([{ stem: "artifacts/figures/a", files: { png: "artifacts/figures/a.png", svg: "artifacts/figures/a.svg", pdf: "artifacts/figures/a.pdf" } }]);240  });241242  it("attaches the stored console outputs when their count matches the ledger", () => {243    const first = snapshot.executions.filter((x) => x.generationId === GEN && x.status === "ok");244    expect(first).toHaveLength(42);245    expect(first.every((x) => typeof x.output === "string" || x.output === null)).toBe(true);246    expect(first[0].output).toContain("(203, 13)");247    // failed cells have an error, never someone else's output248    expect(snapshot.executions.filter((x) => x.status === "failed").every((x) => x.output === null && x.error)).toBe(true);249  });250251  it("keeps the outcome of the quality gate of each generation", () => {252    expect(snapshot.gates).toHaveLength(2);253    expect(snapshot.gates[0].generationId).toBe(GEN);254    expect(snapshot.gates[0].passed).toBe(false);255  });256257  it("orders its timeline by time", () => {258    const times = snapshot.timeline.map((t) => t.at).filter((t): t is number => t != null);259    expect([...times].sort((a, b) => a - b)).toEqual(times);260    expect(new Set(snapshot.timeline.map((t) => t.key)).size).toBe(snapshot.timeline.length);261  });262263  it("puts a live generation on top of what the workspace already held, without duplicates", () => {264    const live = replay(stream);265    const merged = mergeLive(live, snapshot);266    const otherCells = detail.executions.filter((x) => !x.runId && x.generationId !== GEN).length;267    expect(merged.executions).toHaveLength(46 + otherCells);268    expect(merged.runs).toHaveLength(detail.runs.length);269    expect(merged.experiments).toHaveLength(10);270    expect(new Set(merged.timeline.map((t) => t.key)).size).toBe(merged.timeline.length);271    // the stream does not carry the agent's notes nor the environment hash: the REST fills them272    const failed = merged.experiments.find((x) => x.status === "failed")!;273    expect(failed.notes).toContain("pip");274    expect(failed.envHash).toBe("af5ef3d79d245a52");275    expect(merged.executions.find((x) => x.generationId === GEN)!.envHash).toBeTruthy();276    expect(mergeLive(live, null)).toBe(live);277  });278});279280// The study run through the web UI on 2026-11-20 (port 5057, Grunfeld panel, claude-sonnet-5-5): the complete281// stream with its SSE ids, console results and image addresses included (text and reasoning chunks dropped).282describe("the stream of the study run through the UI, with its real ids", () => {283  const run = fixture<Array<{ i: number; e: StreamEvent }>>("stream-ui-run.json");284  const feed = (list: typeof run, from = initialResearchState()) => list.reduce((s, x) => reduceResearch(s, x.e, x.i < 0 ? undefined : x.i), from);285  const full = feed(run);286287  it("pairs each console result and each image with its cell, even with other tools in between", () => {288    expect(full.executions).toHaveLength(4);289    expect(full.executions.every((x) => x.status === "ok" && x.code && x.toolId)).toBe(true);290    // (the largest console result was cut out of the fixture)291    expect(full.executions.filter((x) => x.output).length).toBeGreaterThanOrEqual(3);292    expect(full.runs).toHaveLength(1);293    expect(full.runs[0].status).toBe("done");294    expect(full.figures).toHaveLength(3);295    expect(full.figures.every((f) => f.url?.startsWith("/figures/") && f.files?.svg && f.status !== null)).toBe(true);296    expect(full.figures.map((f) => f.execKey)).toEqual([full.executions[2].key, full.executions[2].key, full.executions[3].key]);297    expect(full.experiments).toHaveLength(6);298    expect(full.experiments.map((x) => x.status)).toEqual(expect.arrayContaining(["inconclusive", "failed", "ok"]));299    expect(full.gates).toHaveLength(1);300    expect(full.finished).toBe(true);301  });302303  it("gives the same view after a cut and a re-attachment from an earlier id", () => {304    const cut = run.findIndex((x) => x.i >= 172);305    const again = run.findIndex((x) => x.i >= 110);306    expect(feed(run.slice(again), feed(run.slice(0, cut + 1)))).toEqual(full);307  });308309  it("shows the cell in progress when the stream is in the middle", () => {310    const mid = feed(run.filter((x) => x.i <= 172));311    expect(mid.finished).toBe(false);312    expect(mid.executions.map((x) => x.status)).toEqual(["ok", "ok", "ok", "running"]);313    expect(countsOf(mid)).toMatchObject({ running: 1, figures: 2, experiments: 3 });314  });315});316317// Two real runs recorded by the back end (tests/fixtures/research/approval_stream.json): the agent asks for open318// network; the client approves in one, denies in the other. Events carry `at` and `toolId` (current contract).319describe("a real approval, approved and denied", () => {320  const recorded = JSON.parse(fs.readFileSync(path.join(__dirname, "../../../../tests/fixtures/research/approval_stream.json"), "utf8")) as Record<"approved" | "denied", { events: StreamEvent[] }>;321  const upTo = (events: StreamEvent[], type: string) => events.slice(0, events.findIndex((e) => e.type === type) + 1);322323  it("blocks on the request, with what is asked and why", () => {324    const pending = replay(upTo(recorded.approved.events, "approval_request"));325    expect(countsOf(pending).pendingApprovals).toBe(1);326    expect(pending.approvals[0]).toMatchObject({ action: "open_network", status: "pending", resolvedAt: null });327    expect(pending.approvals[0].reason).toContain("raw.githubusercontent.com");328    expect(pending.approvals[0].createdAt).toBeGreaterThan(1.7e12);329    expect(pending.budgetApplied).toEqual({ maxCostUsd: 1, maxMinutes: 10, source: "request" });330    expect(pending.finished).toBe(false);331  });332333  it("approved: the run starts with the network open and ends", () => {334    const s = replay(recorded.approved.events);335    expect(s.approvals).toHaveLength(1);336    expect(s.approvals[0].status).toBe("approved");337    expect(s.approvals[0].resolvedAt! - s.approvals[0].createdAt!).toBeGreaterThan(0);338    expect(s.runs).toHaveLength(1);339    expect(s.runs[0]).toMatchObject({ status: "done", network: "open", exitCode: 0 });340    expect(s.gates[0].passed).toBe(true);341    expect(s.finished).toBe(true);342    // the feed is stamped with the server's clock, in order343    const times = s.timeline.map((t) => t.at).filter((t): t is number => t != null);344    expect(times.length).toBe(s.timeline.length);345    expect([...times].sort((a, b) => a - b)).toEqual(times);346    expect(s.timeline.map((t) => t.kind)).toEqual(["workspace", "approval", "run", "gate"]);347  });348349  it("denied: nothing runs, and the refusal stays in the record", () => {350    const s = replay(recorded.denied.events);351    expect(s.approvals).toHaveLength(1);352    expect(s.approvals[0].status).toBe("denied");353    expect(s.runs).toHaveLength(0);354    expect(countsOf(s).pendingApprovals).toBe(0);355    expect(s.finished).toBe(true);356    // replaying the request after the answer (a re-attached stream) does not reopen it357    expect(reduceResearch(s, recorded.denied.events.find((e) => e.type === "approval_request")!)).toBe(s);358  });359});360361// The study of 2026-11-20 run through the UI in a research project (port 5057, p-demo-project-vol), reopened362// from the REST once its stream was gone: generations with plan and applied budget, figures with their verdict.363describe("a study reopened from the REST (stored plan, budget, figure verdicts)", () => {364  const reopened = fixture<SessionDetail>("workspace-detail-reopen.json");365  const stored = fixture<{ messages: string | StoredMessage[] }>("conversation-reopen.json");366  const messages = typeof stored.messages === "string" ? (JSON.parse(stored.messages) as StoredMessage[]) : stored.messages;367  const s = stateFromSnapshot(reopened, messages);368369  it("has the plan, the budget the server applied and its source", () => {370    expect(s.workspace).toEqual({ id: "p-demo-project-vol", kind: "project" });371    expect(s.plan).toHaveLength(5);372    expect(s.plan[0]).toEqual({ title: "Charger et contrôler les données NVDA", status: "in_progress" });373    expect(s.budgetApplied).toEqual({ maxCostUsd: 3, maxMinutes: 15, source: "request" });374    expect(s.generations).toEqual([expect.objectContaining({ status: "done", mode: "research", model: "claude-sonnet-5-5" })]);375    expect(s.timeline.some((t) => t.kind === "plan")).toBe(true);376  });377378  it("has each figure with its caption, durable files, address and stored verdict — nothing recovered by guesswork", () => {379    expect(s.figures).toHaveLength(2);380    for (const f of s.figures) {381      expect(f.status).toBe("fixed");382      expect(f.fixes[0]).toMatchObject({ code: "contrast", fixed: true });383      expect(f.findings).toEqual([]);384      expect(f.caption).toBeTruthy();385      expect(f.files?.png && f.files.svg && f.files.pdf).toBeTruthy();386      expect(f.url).toMatch(/^\/figures\//);387      expect(f.at).toBeGreaterThan(1.7e12);388    }389    expect(s.figures[0].caption).toContain("NVDA");390    // each one attached to the cell whose code drew it391    const owners = s.figures.map((f) => s.executions.find((x) => x.key === f.execKey)!);392    expect(owners.map((x) => x.codeHash)).toEqual(["40a88138ff76a285", "c486858d0ff3b0fe"]);393    expect(owners[0].figureKeys).toEqual([s.figures[0].key]);394  });395396  it("keeps the ledger with notes and environment hashes on experiments", () => {397    expect(s.experiments).toHaveLength(3);398    expect(s.experiments.every((x) => x.envHash === "90eda188b0bc3e14")).toBe(true);399    expect(s.executions).toHaveLength(4);400    expect(s.runs).toHaveLength(1);401  });402403  it("marks a generation cut by a restart", () => {404    const cut = stateFromSnapshot({ ...reopened, generations: [{ ...reopened.generations![0], status: "interrupted", finishedAt: null }] }, messages);405    expect(cut.generations[0].status).toBe("interrupted");406  });407});408409describe("events of the current contract (toolId everywhere, cell start, server time)", () => {410  const T0 = 1795217950000;411  it("opens a cell on code_execution_start, closes it and attaches output and figure by toolId — no ordering assumed", () => {412    let s = initialResearchState();413    const feed = (e: StreamEvent) => { s = reduceResearch(s, e); };414    feed({ type: "budget_applied", maxCostUsd: 3, maxMinutes: 15, source: "request", at: T0 });415    // two cells running at once: a sub-analyst's (no tool_start) and the lead's416    feed({ type: "code_execution_start", toolId: "tA", agent: "analyst-1", description: "Vérification", codeHash: "aaaa", lines: 12, at: T0 + 1000 });417    feed({ type: "tool_start", tool: "execute_custom_python_analysis", toolId: "tB", input: { code: "print(1)", description: "Estimation" }, at: T0 + 1100 });418    feed({ type: "code_execution_start", toolId: "tB", agent: "lead", description: "Estimation", codeHash: "bbbb", lines: 1, at: T0 + 1200 });419    expect(s.executions.map((x) => [x.toolId, x.status, x.agent, x.codeHash])).toEqual([["tA", "running", "analyst-1", "aaaa"], ["tB", "running", "lead", "bbbb"]]);420    expect(s.executions[0].codePath).toBe("logs/cells/aaaa.py");421    expect(s.executions[1].code).toBe("print(1)");422    // they end in the other order, results arrive interleaved423    feed({ type: "code_execution", toolId: "tB", agent: "lead", description: "Estimation", codeHash: "bbbb", code: "logs/cells/bbbb.py", lines: 1, ok: true, durationMs: 800, error: null, experimentId: "eB", at: T0 + 2000 });424    feed({ type: "figure_lint", figureId: "fig1", toolId: "tB", index: 0, title: "Estimation", caption: "La persistance ne monte pas", url: "/figures/x-0.png", ok: true, status: "fixed", fixes: [{ code: "contrast", severity: "warning", message: "recoloured", fixed: true }], findings: [], issues: [], files: { png: "artifacts/figures/x.png", svg: "artifacts/figures/x.svg", pdf: "artifacts/figures/x.pdf" }, at: T0 + 2010 });425    feed({ type: "code_execution", toolId: "tA", agent: "analyst-1", description: "Vérification", codeHash: "aaaa", code: "logs/cells/aaaa.py", lines: 12, ok: false, durationMs: 1500, error: "ValueError: x", experimentId: "eA", at: T0 + 2500 });426    feed({ type: "tool_result", tool: "execute_custom_python_analysis", toolId: "tB", result: { output: "1" }, at: T0 + 2600 });427    feed({ type: "custom_python_figures", toolId: "tB", figureId: "fig-x", figureUrls: ["/figures/x-0.png"], at: T0 + 2700 });428    expect(s.executions).toHaveLength(2);429    expect(s.executions[1]).toMatchObject({ status: "ok", output: "1", figureKeys: ["fig1"], startedAt: T0 + 1100, durationMs: 800 });430    expect(s.executions[0]).toMatchObject({ status: "failed", output: null, figureKeys: [], error: "ValueError: x" });431    expect(s.figures).toEqual([expect.objectContaining({ key: "fig1", status: "fixed", caption: "La persistance ne monte pas", url: "/figures/x-0.png", execKey: s.executions[1].key, at: T0 + 2010 })]);432    expect(s.budgetApplied).toEqual({ maxCostUsd: 3, maxMinutes: 15, source: "request" });433    expect(s.timeline.map((t) => [t.kind, t.at])).toEqual([["execution", T0 + 1000], ["execution", T0 + 1100], ["figure", T0 + 2010]]);434    // a replayed start or lint changes nothing435    const before = s;436    feed({ type: "code_execution_start", toolId: "tB", agent: "lead", description: "Estimation", codeHash: "bbbb", lines: 1, at: T0 + 1200 });437    feed({ type: "figure_lint", figureId: "fig1", toolId: "tB", index: 0, status: "fixed", fixes: [], findings: [], files: null, at: T0 + 2010 });438    expect(s).toBe(before);439  });440441  it("takes notes, code and environment hashes from the experiment event itself", () => {442    const s = reduceResearch(initialResearchState(), { type: "experiment", experiment: { id: "e1", seq: 3, kind: "experiment", title: "BIC", status: "abandoned", notes: "Jamais de minimum.", envHash: "90eda188b0bc3e14", codeHash: "c486858d0ff3b0fe" }, at: T0 });443    expect(s.experiments[0]).toMatchObject({ notes: "Jamais de minimum.", envHash: "90eda188b0bc3e14", codeHash: "c486858d0ff3b0fe", status: "abandoned" });444    expect(s.timeline[0].at).toBe(T0);445  });446});447
Files main
Menu

Theme