import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { startFakeAnthropic, textTurn, toolTurn, toolUseBlock, turn } from "../../testing/llm/fakeAnthropic.mjs"; import { jsonReply, reply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs"; import { runAgent } from "./agent"; import { CALLS_FILE, CALLS_TEXT_FILE, PROMPT_CAP_CHARS, callMatches, foldModelLog, headOf, phaseOrder, scrubText, summarizeCalls, terminalSafe, terminalSafeJson, } from "./callLog"; import { CallSlot, ModelLogWriter, modelLogFilesIn, processScrub, readModelCallText, readModelLog, recordModelCall, recordSessionAnswer, runWithModelLog } from "./callLog-server"; import { Meter } from "./meter"; import { structuredAnswer } from "./structured"; import { modelLogView } from "./callLogView"; import { plainAnswer } from "../report/draft/tasks/llmText"; // Run with: pnpm -C common exec tsx --test lib/llm/callLog.test.ts // // THE MODEL LOG (demo epic D3): every call on every route through ONE // function, recorded in the run's files; a decision appended once code knows // it; nothing recorded outside a run. const schema = { type: "object", properties: { terms: { type: "array", items: { type: "string" } } }, required: ["terms"] }; async function tmpLog(task = "sweep") { const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); const files = modelLogFilesIn(dir); const writer = new ModelLogWriter({ files, task, jobId: "job-1", model: "qwen3:8b", scrub: {} }); return { dir, files, writer, done: () => rm(dir, { recursive: true, force: true }) }; } test("the rows: a run row first, then each call; a decision folded into its call; ids in order", async () => { const t = await tmpLog(); try { const slot = new CallSlot(); await runWithModelLog(t.writer, async () => { recordModelCall({ phase: "terms", model: "qwen3:8b", route: "local", system: "Plan.", prompt: "Research question: ovens?", answer: { terms: ["oven"] }, seconds: 1.234, tokensIn: 40, tokensOut: 6 }, slot); slot.decide("kept", "searched for oven", [{ text: "oven", outcome: "kept", why: "searched" }]); recordModelCall({ phase: "reading", label: "extract a@0", model: "qwen3:8b", route: "local", system: "Read.", prompt: "line one\nline two\nline three\nline four", answer: { items: [] }, seconds: 2 }); }); await t.writer.flush(); const raw = (await readFile(t.files.calls, "utf8")).trim().split("\n").map((l) => JSON.parse(l)); assert.deepEqual(raw.map((r) => r.t), ["run", "call", "decision", "call"]); assert.deepEqual([raw[0].run, raw[0].task, raw[0].jobId, raw[0].model], [1, "sweep", "job-1", "qwen3:8b"]); const log = await readModelLog(t.files); assert.deepEqual(log.calls.map((c) => c.id), ["1.1", "1.2"]); const [a, b] = log.calls; assert.deepEqual([a!.phase, a!.route, a!.seconds, a!.tokensIn, a!.tokensOut], ["terms", "local", 1.2, 40, 6]); assert.deepEqual(a!.decision, { outcome: "kept", why: "searched for oven" }); assert.deepEqual(a!.items, [{ text: "oven", outcome: "kept", why: "searched" }]); assert.deepEqual(b!.decision, { outcome: "n/a", why: "" }); assert.equal(b!.promptHead, "line one\nline two\nline three…", "the list's head: the first three lines"); assert.equal(b!.label, "extract a@0"); // The whole text, one row, by id. const text = await readModelCallText(t.files, "1.2"); assert.equal(text!.system, "Read."); assert.equal(text!.prompt, "line one\nline two\nline three\nline four"); assert.match(text!.answer, /"items"/); assert.equal(await readModelCallText(t.files, "9.9"), null); // A second writer on the same files is run 2. const w2 = new ModelLogWriter({ files: t.files, task: "narrate", scrub: {} }); await runWithModelLog(w2, async () => recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 0 })); await w2.flush(); const again = await readModelLog(t.files); assert.deepEqual(again.runs.map((r) => [r.run, r.task]), [[1, "sweep"], [2, "narrate"]]); assert.equal(again.calls.at(-1)!.id, "2.1"); assert.equal(again.calls.at(-1)!.phase, "narrate", "no phase: the task's name"); } finally { await t.done(); } }); test("nothing is recorded outside a run, and a slot outside one is a no-op", async () => { const slot = new CallSlot(); recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 0 }, slot); assert.equal(slot.recorded, false); slot.decide("dropped", "nothing to say it to"); }); test("caps: the prompt kept to 40k characters and said so; the row stays small", async () => { const t = await tmpLog(); try { const big = "word ".repeat(20_000); await runWithModelLog(t.writer, async () => recordModelCall({ model: "qwen3:8b", route: "local", system: "S", prompt: big, answer: big, seconds: 1 })); await t.writer.flush(); const [c] = (await readModelLog(t.files)).calls; assert.equal(c!.promptChars, big.length + 1); assert.ok(c!.promptHead.length <= 281); const text = (await readModelCallText(t.files, c!.id))!; assert.equal(text.system.length + text.prompt.length, PROMPT_CAP_CHARS); assert.equal(text.promptCut, true); assert.equal(text.answerCut, true); assert.ok((await readFile(t.files.calls, "utf8")).length < 2_000, "calls.jsonl holds no whole prompt"); } finally { await t.done(); } }); test("the fold: a filter by outcome matches a call's items; phases in the sweep's order; the summary", () => { const rows = [ { v: 1, t: "run", run: 1, at: "x", task: "sweep" }, { v: 1, t: "call", id: "1.1", run: 1, at: "x", task: "sweep", phase: "grouping", model: "qwen3:8b", route: "local", promptChars: 1, promptHead: "", answerChars: 1, answerHead: "", seconds: 3, decision: { outcome: "kept", why: "" } }, { v: 1, t: "call", id: "1.2", run: 1, at: "x", task: "sweep", phase: "reading", model: "qwen3:8b", route: "local", promptChars: 1, promptHead: "", answerChars: 1, answerHead: "", seconds: 2, decision: { outcome: "n/a", why: "" } }, { v: 1, t: "decision", call: "1.2", at: "x", items: [{ text: "q1", outcome: "kept", why: "verbatim" }, { text: "q2", outcome: "dropped", why: "not verbatim in its window" }] }, { v: 2, t: "call", id: "future" }, "not json", ]; const log = foldModelLog(rows.map((r) => (typeof r === "string" ? r : JSON.stringify(r))).join("\n")); assert.equal(log.calls.length, 2, "a later version's row and a torn line are skipped"); const reading = log.calls.find((c) => c.id === "1.2")!; assert.equal(reading.decision.outcome, "kept", "items alone: the decision is what they add up to"); assert.ok(callMatches(reading, { outcome: "dropped" })); assert.ok(callMatches(reading, { outcome: "kept" })); assert.ok(!callMatches(log.calls[0]!, { outcome: "dropped" })); assert.deepEqual(phaseOrder(["grouping", "draft", "reading", "terms"]), ["terms", "reading", "grouping", "draft"]); const s = summarizeCalls(log.calls); assert.deepEqual([s.calls, s.seconds, s.models], [2, 5, [{ model: "qwen3:8b", route: "local", calls: 2 }]]); assert.deepEqual(s.phases.map((p) => p.phase), ["reading", "grouping"]); assert.equal(headOf(""), ""); }); test("the one function on every route: structuredAnswer on ollama and on Claude, an agent's turns, the extractor, a Claude Code session", async () => { const t = await tmpLog(); const ol = await startFakeOllama({ turns: [jsonReply({ terms: ["oven"] }), reply("- a line"), reply("", { message: { role: "assistant", content: "done" } })] }); const api = await startFakeAnthropic({ turns: [turn([toolUseBlock("answer", { terms: ["bread"] })]), toolTurn("lookup", { q: "oven" }), textTurn("all read")] }); try { const llm = { ollama: { baseUrl: ol.url }, anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }; const meter = new Meter(); const slot = new CallSlot(); await runWithModelLog(t.writer, async () => { await structuredAnswer({ llm, model: "qwen3:8b", system: "Plan.", user: "Ovens?", schema, meter, call: { phase: "terms", slot } }); slot.decide("kept", "searched"); await structuredAnswer({ llm, model: "claude-haiku-4-5", system: "Plan.", user: "Bread?", schema, meter, call: { phase: "terms", label: "api" } }); await plainAnswer({ llm, model: "qwen3:8b", system: "Extract.", user: "the batch", meter, call: { phase: "reading" } }); await runAgent({ llm, model: "claude-haiku-4-5", system: "You research.", user: "Go.", meter, tools: [{ name: "lookup", description: "look", inputSchema: { type: "object", properties: { q: { type: "string" } } }, run: async () => "the oven is hot" }], }); recordSessionAnswer({ phase: "assist", system: "Assist.", prompt: "make the joins 0.15 s", answer: { ops: [] } }); }); await t.writer.flush(); const { calls } = await readModelLog(t.files); assert.deepEqual( calls.map((c) => [c.phase, c.route, c.model]), [ ["terms", "local", "qwen3:8b"], ["terms", "api", "claude-haiku-4-5"], ["reading", "local", "qwen3:8b"], ["agent", "api", "claude-haiku-4-5"], ["agent", "api", "claude-haiku-4-5"], ["assist", "claude-code", "claude-code"], ], ); assert.equal(calls[0]!.decision.outcome, "kept"); assert.ok((calls[0]!.tokensIn ?? 0) > 0, "ollama's counts"); assert.ok((calls[1]!.tokensIn ?? 0) > 0, "the API's usage"); assert.match(calls[3]!.answerHead, /→ lookup/); assert.match((await readModelCallText(t.files, calls[4]!.id))!.prompt, /\[tool result\]\nthe oven is hot/); assert.equal((await readModelCallText(t.files, calls[3]!.id))!.system, "You research.", "turn 1 carries the system prompt"); assert.match(calls[1]!.promptHead, /^Bread\?/); } finally { await ol.close(); await api.close(); await t.done(); } }); test("a failed call is recorded with its error, its decision n/a", async () => { const t = await tmpLog(); const ol = await startFakeOllama({ turns: [reply("not json"), reply("still not")] }); try { await runWithModelLog(t.writer, async () => { await assert.rejects(structuredAnswer({ llm: { ollama: { baseUrl: ol.url } }, model: "qwen3:8b", system: "S", user: "U", schema })); }); await t.writer.flush(); const [c] = (await readModelLog(t.files)).calls; assert.match(c!.error ?? "", /no structured answer/); assert.deepEqual(c!.decision, { outcome: "n/a", why: "the call failed" }); assert.ok(CALLS_FILE && CALLS_TEXT_FILE); } finally { await ol.close(); await t.done(); } }); test("the calls' text is bounded as a file: past the cap a call keeps its row, not its text, and the run is told once", async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); const files = modelLogFilesIn(dir); const said: string[] = []; const writer = new ModelLogWriter({ files, task: "sweep", scrub: {}, textMaxBytes: 3_000, log: (l) => said.push(l) }); try { const prompt = "word ".repeat(400); // 2,000 characters: one fits, the second does not await runWithModelLog(writer, async () => { for (let i = 0; i < 3; i++) recordModelCall({ model: "qwen3:8b", route: "local", prompt, answer: "ok", seconds: 1 }); }); await writer.flush(); const { calls } = await readModelLog(files); assert.equal(calls.length, 3, "every call has its row"); assert.ok((await readModelCallText(files, calls[0]!.id)) !== null); assert.equal(await readModelCallText(files, calls[1]!.id), null); assert.equal(await readModelCallText(files, calls[2]!.id), null); assert.ok((await readFile(files.text, "utf8")).length <= 3_000); assert.equal(said.filter((l) => /text is full/.test(l)).length, 1); } finally { await rm(dir, { recursive: true, force: true }); } }); test("a failed call's error names no host: the model's URL is taken out of it", async () => { const t = await tmpLog(); try { await runWithModelLog(t.writer, async () => { // Nothing listens on port 9 here: ollama's client names the base URL in its error. await assert.rejects(structuredAnswer({ llm: { ollama: { baseUrl: "http://127.0.0.1:9" } }, model: "qwen3:8b", system: "S", user: "U", schema })); }); await t.writer.flush(); const [c] = (await readModelLog(t.files)).calls; assert.ok(c!.error, "the error is kept"); assert.ok(!/127\.0\.0\.1/.test(await readFile(t.files.calls, "utf8")), "no host in calls.jsonl"); assert.match(c!.error!, //); } finally { await t.done(); } }); test("processScrub: a variable of the environment named like a credential is a secret; a path or a short value is not", () => { // Set by name (these are not variables anything reads). const vars: Record = { MLOG_T_API_TOKEN: "FAKE-TEST-VALUE", MLOG_T_KEY: "/etc/keys/a-key-file-somewhere", MLOG_T_SECRET: "production" }; const env = process.env as Record; for (const [k, v] of Object.entries(vars)) env[k] = v; try { const s = processScrub(); assert.ok(s.secrets!.includes("FAKE-TEST-VALUE")); assert.ok(!s.secrets!.includes("/etc/keys/a-key-file-somewhere")); assert.ok(!s.secrets!.includes("production")); assert.equal(scrubText("it said FAKE-TEST-VALUE in production", s), "it said [secret] in production"); } finally { for (const k of Object.keys(vars)) delete env[k]; } }); test("terminalSafe: a recorded text cannot drive a terminal -- ESC, C0, DEL, C1 and bidi controls are printed as escapes; \\n, \\t and ordinary text stay", () => { assert.equal(terminalSafe("a\x1b[2Jb"), "a\\x1b[2Jb"); assert.equal(terminalSafe("\x1b]0;title\x07"), "\\x1b]0;title\\x07"); assert.equal(terminalSafe("over\rwritten\b\x00\x7f"), "over\\x0dwritten\\x08\\x00\\x7f"); assert.equal(terminalSafe("c1 \u009b31m \u0090 \u009d"), "c1 \\x9b31m \\x90 \\x9d"); assert.equal(terminalSafe("rtl \u202e \u2066 \u2028"), "rtl \\u202e \\u2066 \\u2028"); const plain = "line one\n\ttabbed — “quoted” é 日本語 🙂"; assert.equal(terminalSafe(plain), plain); // Nothing a terminal acts on is left, whatever the input. let all = ""; for (let i = 0; i < 0x100; i++) all += String.fromCharCode(i); assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(terminalSafe(all))); }); test("terminalSafeJson: printed JSON carries no DEL, C1 or bidi control, and parses to the same value", () => { const v = { answer: "csi \u009b31m del \x7f esc \x1b[2J rtl \u202e\nnext\tline", n: 1 }; const out = terminalSafeJson(JSON.stringify(v, null, 2)); assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202e]/.test(out), out); assert.deepEqual(JSON.parse(out), v); }); test("what code says about an answer is scrubbed as the call was: the call's own redaction covers its decision and items", async () => { const t = await tmpLog(); try { const KEY = "file-held-key-0123456789"; const slot = new CallSlot(); await runWithModelLog(t.writer, async () => { recordModelCall({ model: "claude-haiku-4-5", route: "api", prompt: "p", answer: "a", seconds: 1, redact: (s) => s.split(KEY).join("[redacted]") }, slot); slot.decide("dropped", `refused: echoed ${KEY}`, [{ text: `op ${KEY}`, outcome: "dropped", why: `why ${KEY}` }]); }); await t.writer.flush(); const raw = await readFile(t.files.calls, "utf8"); assert.ok(!raw.includes(KEY), raw); assert.match(raw, /refused: echoed \[redacted\]/); } finally { await t.done(); } }); test("a failed call's error names no address: an IP and port, and a URL of any scheme, are taken out", async () => { const t = await tmpLog(); try { await runWithModelLog(t.writer, async () => { recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: null, seconds: 1, error: "connect ECONNREFUSED 192.168.1.44:11434 (also [fe80::1]:11434, ::1:11434, ws://gpu.lan:8080/x) after 3 tries" }); }); await t.writer.flush(); const [c] = (await readModelLog(t.files)).calls; assert.equal(c!.error, "connect ECONNREFUSED (also , , ) after 3 tries"); } finally { await t.done(); } }); // ─── Review round (12 Nov): the log's own cap, a poll that reads what was appended, a lazy key ─── test("calls.jsonl is capped: past it one `full` row is written, no further call is recorded, the run is told once, and the view says so", async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); const files = modelLogFilesIn(dir); const said: string[] = []; const writer = new ModelLogWriter({ files, task: "sweep", scrub: {}, maxCalls: 3, log: (l) => said.push(l) }); try { const slots: CallSlot[] = []; await runWithModelLog(writer, async () => { for (let i = 0; i < 6; i++) { const slot = new CallSlot(); slots.push(slot); recordModelCall({ model: "qwen3:8b", route: "local", prompt: `p${i}`, answer: "ok", seconds: 1 }, slot); } }); await writer.flush(); slots[5]!.decide("kept", "a decision on a call that was not recorded"); slots[0]!.decide("kept", "after the log was full"); await writer.flush(); const log = await readModelLog(files); assert.equal(log.calls.length, 3); assert.equal(log.full, true); assert.equal(log.calls[0]!.decision.outcome, "n/a", "a full log takes nothing more"); const raw = (await readFile(files.calls, "utf8")).trim().split("\n").map((l) => JSON.parse(l)); assert.deepEqual(raw.map((r) => r.t), ["run", "call", "call", "call", "full"]); assert.equal((await readFile(files.text, "utf8")).trim().split("\n").length, 3, "no text for a call with no row"); assert.equal(said.filter((l) => /model log: full/.test(l)).length, 1); const view = modelLogView(log); assert.equal(view.full, true); assert.deepEqual(view.cap, { calls: 20_000, megabytes: 32 }); // A later run on the same log finds it full and adds nothing but its run row. const later = new ModelLogWriter({ files, task: "sweep", scrub: {}, maxCalls: 3 }); await runWithModelLog(later, async () => recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 1 })); await later.flush(); assert.equal((await readModelLog(files)).calls.length, 3); } finally { await rm(dir, { recursive: true, force: true }); } }); test("the byte cap: a log past its size takes no further call", async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); const files = modelLogFilesIn(dir); const writer = new ModelLogWriter({ files, task: "sweep", scrub: {}, maxBytes: 600 }); try { await runWithModelLog(writer, async () => { for (let i = 0; i < 8; i++) recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p ".repeat(60), answer: "ok", seconds: 1 }); }); await writer.flush(); const log = await readModelLog(files); assert.equal(log.full, true); assert.ok(log.calls.length >= 1 && log.calls.length < 8, String(log.calls.length)); } finally { await rm(dir, { recursive: true, force: true }); } }); test("a poll reads only what was appended: the fold continues, a half-written line waits, a replaced file is read again", async () => { const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); const files = modelLogFilesIn(dir); const { appendFile, writeFile, open } = await import("node:fs/promises"); const call = (id: string, run = 1) => JSON.stringify({ v: 1, t: "call", id, run, at: "2026-11-12T00:00:00.000Z", task: "sweep", phase: "terms", model: "m", route: "local", promptChars: 1, promptHead: "p", answerChars: 1, answerHead: "a", seconds: 1, decision: { outcome: "n/a", why: "" } }); try { await writeFile(files.calls, `${JSON.stringify({ v: 1, t: "run", run: 1, at: "2026-11-12T00:00:00.000Z", task: "sweep" })}\n${call("1.1")}\n`); assert.deepEqual((await readModelLog(files)).calls.map((c) => c.id), ["1.1"]); // Bytes already folded are not read again: overwrite them in place (same size) and append. const fh = await open(files.calls, "r+"); await fh.write("X", 0); await fh.close(); await appendFile(files.calls, `${call("1.2")}\n${JSON.stringify({ v: 1, t: "decision", call: "1.1", at: "x", decision: { outcome: "kept", why: "later" } })}\n${call("1.3").slice(0, 40)}`); const second = await readModelLog(files); assert.deepEqual(second.calls.map((c) => c.id), ["1.1", "1.2"], "the half line waits"); assert.equal(second.runs.length, 1, "the first line was not read again (it no longer parses)"); assert.equal(second.calls[0]!.decision.outcome, "kept", "a decision appended later lands on the call folded earlier"); await appendFile(files.calls, `${call("1.3").slice(40)}\n`); assert.deepEqual((await readModelLog(files)).calls.map((c) => c.id), ["1.1", "1.2", "1.3"]); // A snapshot is the reader's own: a later fold does not grow it. assert.equal(second.calls.length, 2); // Replaced by a shorter file: read from its start. await writeFile(files.calls, `${call("9.1", 9)}\n`); assert.deepEqual((await readModelLog(files)).calls.map((c) => c.id), ["9.1"]); await rm(files.calls); assert.deepEqual(await readModelLog(files), { runs: [], calls: [] }); } finally { await rm(dir, { recursive: true, force: true }); } }); test("the API key is read for a record, never for a call: with no log open a structured call does not touch it", async () => { const ol = await startFakeOllama({ turns: [jsonReply({ terms: ["a"] }), jsonReply({ terms: ["b"] })] }); const t = await tmpLog(); let reads = 0; const env = new Proxy({} as Record, { get: (_t, k) => { if (k === "ANTHROPIC_API_KEY") reads++; return k === "ANTHROPIC_API_KEY" ? "sk-ant-key-FAKE-TEST-VALUE" : undefined; }, }); try { const llm = { ollama: { baseUrl: ol.url }, anthropic: { env } }; await structuredAnswer({ llm, model: "qwen3:8b", system: "S", user: "U", schema }); assert.equal(reads, 0, "no log: the key is not read"); await runWithModelLog(t.writer, async () => { await structuredAnswer({ llm, model: "qwen3:8b", system: "S", user: "say sk-ant-key-FAKE-TEST-VALUE", schema }); }); await t.writer.flush(); assert.equal(reads, 1, "read once, for the record"); assert.ok(!(await readFile(t.files.text, "utf8")).includes("sk-ant-key-FAKE-TEST-VALUE")); } finally { await ol.close(); await t.done(); } }); test("a megabyte of prompt is cut before it is scrubbed: the record keeps 40,000 characters, says it was cut, and counts what was sent", async () => { const t = await tmpLog(); try { const prompt = "word ".repeat(400_000); // 2,000,000 characters let scrubbed = 0; await runWithModelLog(t.writer, async () => { recordModelCall({ model: "qwen3:8b", route: "local", prompt, answer: "a.".repeat(500_000), seconds: 1, redact: (s) => ((scrubbed = Math.max(scrubbed, s.length)), s) }); }); const t0 = performance.now(); await t.writer.flush(); assert.ok(performance.now() - t0 < 1_000); assert.ok(scrubbed <= 40_000 + 8_192, `the scrub saw at most the cap and its margin (${scrubbed})`); const [c] = (await readModelLog(t.files)).calls; assert.equal(c!.promptChars, 2_000_000); assert.equal(c!.answerChars, 1_000_000); const text = (await readModelCallText(t.files, c!.id))!; assert.equal(text.prompt.length, 40_000); assert.equal(text.promptCut, true); assert.equal(text.answer.length, 40_000); assert.equal(text.answerCut, true); } finally { await t.done(); } });