import { test, before, after } from "node:test"; import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import { CallSlot, ModelLogWriter, modelLogFilesIn, recordModelCall, runWithModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; // Run with: pnpm -C umtool exec tsx --test lib/research/model-log.test.ts // // `umtool model-log` (demo epic D3, the CLI twin of the Model log panel): an // iteration's calls by phase with what code did and why, a filter, one call's // whole text, --json; a job's calls followed through its pointer to the // iteration it ran on. Over a temp article store (ARTICLES_DIR) and ledger dir. const UMTOOL = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); const run = promisify(execFile); let tmp: string; let env: NodeJS.ProcessEnv; async function cli(...args: string[]): Promise<{ code: number; out: string; err: string }> { try { const r = await run(process.execPath, [path.join(UMTOOL, "bin/umtool.mjs"), "model-log", ...args], { cwd: UMTOOL, env }); return { code: 0, out: r.stdout, err: r.stderr }; } catch (e) { const x = e as { code?: number; stdout?: string; stderr?: string }; return { code: x.code ?? 1, out: x.stdout ?? "", err: x.stderr ?? "" }; } } before(async () => { tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-model-log-")); const articles = path.join(tmp, "reports"); const dir = path.join(articles, "mlog", "iterations", "1"); await mkdir(dir, { recursive: true }); const at = "2026-11-11T10:00:00.000Z"; await writeFile(path.join(dir, "iteration.json"), JSON.stringify({ format: "archilyzer-iteration", version: 1, article: "mlog", n: 1, kind: "sweep", parent: null, copyOf: null, model: "qwen3:8b", question: "q", status: "done", usage: {}, steps: [], jobId: "job-7", createdAt: at, updatedAt: at })); const w = new ModelLogWriter({ files: modelLogFilesIn(dir), task: "sweep", jobId: "job-7", model: "qwen3:8b", where: { article: "mlog", iteration: 1 }, scrub: {} }); const slot = new CallSlot(); await runWithModelLog(w, async () => { recordModelCall({ phase: "terms", label: "terms", model: "qwen3:8b", route: "local", system: "Plan.", prompt: "Research question: pies?", answer: { terms: ["pie"] }, seconds: 1.5 }); recordModelCall({ phase: "reading", label: "extract v1@0", model: "qwen3:8b", route: "local", system: "Read.", prompt: "Research question: pies?\n\nTranscript excerpt:\n[0:00] I made a pie", answer: { items: [] }, seconds: 4.25 }, slot); slot.decide("kept", "1 of 2 items kept", [ { text: "“I made a pie”", outcome: "kept", why: "verbatim in its window" }, { text: "“I won the contest”", outcome: "dropped", why: "not verbatim in its window" }, ]); }); await w.flush(); // A second iteration whose model answered with terminal control sequences. const dir2 = path.join(articles, "mlog", "iterations", "2"); await mkdir(dir2, { recursive: true }); await writeFile(path.join(dir2, "iteration.json"), JSON.stringify({ format: "archilyzer-iteration", version: 1, article: "mlog", n: 2, kind: "sweep", parent: null, copyOf: null, model: "qwen3:8b", question: "q", status: "done", usage: {}, steps: [], createdAt: at, updatedAt: at })); const w2 = new ModelLogWriter({ files: modelLogFilesIn(dir2), task: "sweep", model: "qwen3:8b", where: { article: "mlog", iteration: 2 }, scrub: {} }); const slot2 = new CallSlot(); await runWithModelLog(w2, async () => { recordModelCall({ phase: "reading", label: "extract \x1b[31mred", model: "qwen3:8b", route: "local", system: "Read.\x1b[2J", prompt: "asked \x1b]0;owned\x07 this\nsecond line\tkept", answer: "back \x1b[2J\x1b[H wiped \u009b31m and\rover", seconds: 1 }, slot2); slot2.decide("dropped", "why \x1b[1mbold", [{ text: "item \x1b[5mblink", outcome: "dropped", why: "because \x07bell" }]); }); await w2.flush(); // The job's pointer (what a report-draft job beside its iteration writes). const usage = path.join(tmp, ".generation", "usage.jsonl"); await mkdir(path.join(tmp, ".generation", "calls", "job-7"), { recursive: true }); await writeFile(path.join(tmp, ".generation", "calls", "job-7", "where.json"), JSON.stringify({ v: 1, article: "mlog", n: 1 })); env = { ...process.env, ARTICLES_DIR: articles, GENERATION_USAGE_FILE: usage }; delete env.REPORTS_DIR; delete env.CHANNELS_DIR; delete env.SONG_DIR; }); after(async () => { await rm(tmp, { recursive: true, force: true }); }); test("the calls by phase, what code did and why, each item's fate", async () => { const r = await cli("mlog", "1"); assert.equal(r.code, 0, r.err); assert.match(r.out, /^mlog i1 · 2 calls · 5\.8 s · qwen3:8b \(local, 2\)/); assert.match(r.out, /\nTerms · 1 call · 1\.5 s\n/); assert.match(r.out, /\nReading · 1 call · 4\.3 s\n/); assert.match(r.out, /1\.2 +4\.3 s kept +extract v1@0 — 1 of 2 items kept/); assert.match(r.out, /dropped +“I won the contest” — not verbatim in its window/); assert.match(r.out, /asked: Research question: pies\?/); }); test("--outcome dropped narrows to the calls that dropped something; --phase to one phase", async () => { const d = await cli("mlog", "1", "--outcome", "dropped"); assert.ok(!d.out.includes("Terms ·"), d.out); assert.match(d.out, /dropped +“I won the contest”/); assert.ok(!d.out.includes("I made a pie”"), "only the dropped items"); const p = await cli("mlog", "1", "--phase", "terms"); assert.ok(p.out.includes("Terms ·") && !p.out.includes("Reading ·")); }); test("--call prints one call's whole text; --json the calls", async () => { const c = await cli("mlog", "1", "--call", "1.2"); assert.equal(c.code, 0, c.err); assert.match(c.out, /── system ──\nRead\./); assert.match(c.out, /── asked ──\nResearch question: pies\?\n\nTranscript excerpt:\n\[0:00\] I made a pie/); const j = JSON.parse((await cli("mlog", "1", "--json")).out); assert.equal(j.summary.calls, 2); assert.deepEqual(j.calls.map((x: { phase: string }) => x.phase), ["terms", "reading"]); assert.equal((await cli("mlog", "1", "--call", "9.9")).code, 1); }); test("--job: a job's calls, through its pointer to the iteration it ran on", async () => { const r = await cli("--job", "job-7"); assert.equal(r.code, 0, r.err); assert.match(r.out, /^job job-7 · 2 calls/); const none = await cli("--job", "job-unknown"); assert.match(none.out, /job job-unknown: no model call recorded/); assert.equal((await cli("nope")).code, 2, "usage"); }); test("a recorded text cannot drive the terminal: control sequences are printed as escapes, in the list and in --call; --json is JSON", async () => { const raw = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/; const list = await cli("mlog", "2"); assert.equal(list.code, 0, list.err); assert.ok(!raw.test(list.out), JSON.stringify(list.out)); assert.match(list.out, /extract \\x1b\[31mred — why \\x1b\[1mbold/); assert.match(list.out, /dropped +item \\x1b\[5mblink — because \\x07bell/); const one = await cli("mlog", "2", "--call", "1.1"); assert.equal(one.code, 0, one.err); assert.ok(!raw.test(one.out), JSON.stringify(one.out)); assert.match(one.out, /── system ──\nRead\.\\x1b\[2J/); assert.match(one.out, /── asked ──\nasked \\x1b\]0;owned\\x07 this\nsecond line\tkept/, "newlines and tabs stay"); assert.match(one.out, /── came back ──\nback \\x1b\[2J\\x1b\[H wiped \\x9b31m and\\x0dover/); // --json: the text as recorded, in JSON's own escapes -- no raw control byte either. const j = await cli("mlog", "2", "--call", "1.1", "--json"); assert.ok(!raw.test(j.out)); assert.equal(JSON.parse(j.out).text.answer, "back \x1b[2J\x1b[H wiped \u009b31m and\rover"); });