Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit e1c45c6f2d337d4b22ae61f2c618ac0bd5a377f9
parent 4682362d27fdb31aa8a3fdf816cd49aaf0f30672
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 05:18:05 -0500

common, umtool, editor, mcp: model log review round -- every scrub pattern is linear and a text is cut before it is scrubbed; links survive; more credential shapes, fewer false ones; the log is capped and a poll reads only what was appended

MUST-FIX. The `user:password@` rule's scheme prefix restarted at every `.`
and `-`: one unbroken 160,000-character token took ~40 s through scrubText on
the editor's event loop, and record() scrubbed the whole text before its
40,000-character cap. Every pattern now has bounded quantifiers and, where it
starts on a run of ordinary characters, a lookbehind that lets it start only
at the run's first one; record() cuts each text to its cap and an 8,192
character margin before the scrub (scrubBounded: on white space in the margin,
else the token the cut fell in is dropped -- no half of a credential is kept).
A test times 28 trigger strings of 160,000 characters under 250 ms each.
promptChars / answerChars are now what was sent, before the scrub.

- Links are not host paths: a path starts only where one can (not after a
  host or path character), so https://pbs.twimg.com/media/... and
  example.com/home/page stay; "/media/" alone in prose stays.
- Shapes added: JSON-quoted names and values, a cookie-jar line (name, tab,
  value), `password: ...` / "token":"..." when the value reads like one, an
  environment assignment (WORKER_TOKEN=..., NAME_KEY=...), an Authorization
  header's value whatever it is.
- Words are left: `Basic counterintelligence`, `bearer of bad news`; a Cookie
  line is scrubbed only at the start of a line or a JSON field and when
  nothing but cookie pairs follows.
- writeIterationFile refuses calls.jsonl and calls-text.jsonl (their writer
  appends; nothing replaces them); the MCP's iteration summary no longer
  lists their paths, as it never listed turns.jsonl and trace.jsonl.
- locateJobModelLog takes where.json's article only when it is a report id
  and its n only when it is 1 or more.
- The API key's redaction is resolved inside a record (lazyKeyRedactor), not
  on every structured / extractor / agent call: no stat and file read per call
  with a key file, none at all with no log open.
- calls.jsonl is capped at 20,000 calls or 32 MB: one `full` row, then no
  further call or decision is recorded; the run's log says so once, both
  panels and `umtool model-log` say the log is full. readModelLog keeps each
  file's fold and offset and reads only whole lines appended since (a replaced
  or shorter file is read again; 24 logs held), so a 2.5 s poll no longer
  reads and folds the whole file.

Checked, not changed: the agent loop cuts a tool result (60,000 characters on
Claude, 2,500 local) before it reaches a message, so before record(); nothing
that composes or publishes reads an iteration directory -- the test "iterations
are never published" (bin/compose-homepage.test.ts) now writes a model log
into the iteration and holds both file names and its words off the site.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/bin/compose-homepage.test.ts | 10++++++++--
Mcommon/controller/jobModelLog.test.ts | 19+++++++++++++++++++
Mcommon/controller/jobModelLog.ts | 5++++-
Mcommon/lib/llm/agent.ts | 7++++---
Mcommon/lib/llm/callLog-server.ts | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mcommon/lib/llm/callLog.test.ts | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/llm/callLog.ts | 138++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/lib/llm/callLogPrivacy.test.ts | 123++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/llm/callLogView.ts | 7+++++++
Mcommon/lib/llm/structured.ts | 5++---
Mcommon/lib/report/draft/tasks/llmText.ts | 5++---
Mcommon/lib/report/iterations.test.ts | 3+++
Mcommon/lib/report/iterations.ts | 6++++++
Meditor/CHANGELOG.md | 4++--
Meditor/app/jobs/[id]/components/JobModelLog.tsx | 5+++++
Mmcp/src/generation.test.ts | 5+++++
Mmcp/src/generation.ts | 7++++++-
Mumtool/bin/model-log.ts | 5+++--
Mumtool/components/model-log/ModelLog.tsx | 5+++++
19 files changed, 592 insertions(+), 67 deletions(-)

diff --git a/common/bin/compose-homepage.test.ts b/common/bin/compose-homepage.test.ts @@ -30,7 +30,8 @@ const { getPaths } = await import("../lib/paths"); const { buildIndex } = await import("../controller/buildIndex"); const { articleDir, configureArticle } = await import("../lib/report/registry"); const { main, channelSiteUrlOf } = await import("./compose-homepage"); -const { createIteration, updateIteration, writeIterationFile } = await import("../lib/report/iterations"); +const { createIteration, iterationDir, updateIteration, writeIterationFile } = await import("../lib/report/iterations"); +const { ModelLogWriter, modelLogFilesIn, recordModelCall, runWithModelLog } = await import("../lib/llm/callLog-server"); const { REPORT_MEDIA_FORMAT, REPORT_MEDIA_VERSION } = await import("../publish/reportMedia"); const paths = getPaths(); @@ -159,6 +160,11 @@ test("iterations are never published: a public article's iterations and an artic await writeIterationFile("open", 1, "report.json", article("open", { title: `${MARK} title` }), paths); await writeIterationFile("open", 1, "sweep.md", `# ${MARK}\n`, paths); await writeIterationFile("open", 1, "turns.jsonl", `${JSON.stringify({ role: "user", content: MARK })}\n`, paths); + // The model log too (demo epic D3): the prompts and answers of the iteration's runs. + const modelLog = new ModelLogWriter({ files: modelLogFilesIn(iterationDir(paths, "open", 1)), task: "sweep", scrub: {} }); + await runWithModelLog(modelLog, async () => recordModelCall({ phase: "terms", model: "qwen3:8b", route: "local", system: MARK, prompt: `${MARK} asked`, answer: `${MARK} answered`, seconds: 1 })); + await modelLog.flush(); + assert.ok(existsSync(path.join(iterationDir(paths, "open", 1), "calls.jsonl")) && existsSync(path.join(iterationDir(paths, "open", 1), "calls-text.jsonl"))); await updateIteration("open", 1, { status: "done" }, paths); await createIteration("in-the-making", { kind: "sweep", model: "qwen3:8b", question: `${MARK}?` }, paths); await writeIterationFile("in-the-making", 1, "report.json", article("in-the-making", { title: MARK }), paths); @@ -166,7 +172,7 @@ test("iterations are never published: a public article's iterations and an artic await quietly(() => main({ paths, audience })); const files = filesUnder(PUBLIC); assert.ok(files.length > 0); - assert.deepEqual(files.filter((f) => /iteration|in-the-making|turns\.jsonl|sweep\.md/.test(f)), [], `${audience}: no iteration file`); + assert.deepEqual(files.filter((f) => /iteration|in-the-making|turns\.jsonl|sweep\.md|calls(-text)?\.jsonl/.test(f)), [], `${audience}: no iteration file`); const leaked = files.filter((f) => /\.(json|html|md|txt|xml)$/.test(f) && readFileSync(path.join(PUBLIC, f), "utf8").includes(MARK)); assert.deepEqual(leaked, [], `${audience}: no iteration's words`); const index = readJson<{ reports: { id: string }[] }>(path.join(PUBLIC, "articles", "index.json")); diff --git a/common/controller/jobModelLog.test.ts b/common/controller/jobModelLog.test.ts @@ -71,3 +71,22 @@ test("a job id is a name, never a way up: dots alone are refused", () => { for (const bad of ["..", ".", "a/b", ""]) assert.throws(() => jobModelLogDir(paths, bad), /not a job id/); assert.equal(jobModelLogDir(paths, "job-1.a"), path.join(os.tmpdir(), ".generation", "calls", "job-1.a")); }); + +test("a pointer that names no report id leads nowhere: `..` in where.json never reaches a path", async () => { + const t = await setup(); + try { + const { mkdir, writeFile } = await import("node:fs/promises"); + for (const [job, where] of [ + ["job-up", { v: 1, article: "../../etc", n: 1 }], + ["job-slash", { v: 1, article: "a/b", n: 1 }], + ["job-zero", { v: 1, article: "art", n: 0 }], + ["job-num", { v: 1, article: 7, n: 1 }], + ] as const) { + await mkdir(jobModelLogDir(t.paths, job), { recursive: true }); + await writeFile(path.join(jobModelLogDir(t.paths, job), "where.json"), JSON.stringify(where)); + assert.equal(await locateJobModelLog(t.paths, job), null, job); + } + } finally { + await t.done(); + } +}); diff --git a/common/controller/jobModelLog.ts b/common/controller/jobModelLog.ts @@ -16,6 +16,7 @@ import { iterationDir } from "../lib/report/iterations"; import { ModelLogWriter, modelLogFilesIn, processScrub, readModelLog, runWithModelLog, type InnerLogWhere, type LocalCallTally, type ModelLogFiles } from "../lib/llm/callLog-server"; import { appendGenerationUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import type { Paths } from "../lib/paths"; +import { isReportId } from "../lib/report/schema"; type UsagePaths = Pick<Paths, "generationUsageFile">; @@ -99,7 +100,9 @@ export async function locateJobModelLog( } catch { return null; } - if (typeof w.article !== "string" || !Number.isInteger(w.n)) return null; + // The pointer names an article and an iteration, and nothing else: a name + // that is not a report id never reaches a path. + if (typeof w.article !== "string" || !isReportId(w.article) || !Number.isInteger(w.n) || (w.n as number) < 1) return null; const files = modelLogFilesIn(iterationDir(paths, w.article, w.n as number)); const log = await readModelLog(files); if (!log.runs.some((r) => r.jobId === jobId)) return null; diff --git a/common/lib/llm/agent.ts b/common/lib/llm/agent.ts @@ -20,12 +20,11 @@ import { CancelledError, cacheControl, isStrictModel, - keyRedactor, textOf, toolUsesOf, type ContentBlock, } from "./anthropic"; -import { recordModelCall } from "./callLog-server"; +import { lazyKeyRedactor, recordModelCall } from "./callLog-server"; import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig, type Provider } from "./config"; import type { Meter, Usage } from "./meter"; import { @@ -447,6 +446,8 @@ async function runLocal(o: AgentOptions): Promise<AgentResult> { const resultChars = o.resultChars ?? LOCAL_RESULT_CHARS; const maxTurns = o.maxTurns ?? DEFAULT_MAX_TURNS; const byName = new Map(o.tools.map((t) => [t.name, t])); + // One redactor for the run's turns, its key read only if a turn is recorded. + const localRedact = lazyKeyRedactor(o.llm.anthropic); const tools = toOllamaTools(o.tools); const messages: OllamaMessage[] = [ { role: "system", content: o.system }, @@ -479,7 +480,7 @@ async function runLocal(o: AgentOptions): Promise<AgentResult> { const fresh = messagesText(messages.slice(turn === 0 ? 1 : recorded)); const t0 = Date.now(); const turnRecord = (answer: string, extra: { tokensIn?: number; tokensOut?: number; error?: string }) => - recordModelCall({ phase: "agent", label: `turn ${turn + 1}`, model: o.model, route: "local", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra, redact: keyRedactor(o.llm.anthropic) }); + recordModelCall({ phase: "agent", label: `turn ${turn + 1}`, model: o.model, route: "local", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra, redact: localRedact }); try { reply = await ollamaChat(cfg, { model: o.model, messages, tools, signal: o.signal }); } catch (err) { diff --git a/common/lib/llm/callLog-server.ts b/common/lib/llm/callLog-server.ts @@ -16,7 +16,7 @@ // process, on globalThis (the house pattern: Next may load a module twice). import { AsyncLocalStorage } from "node:async_hooks"; -import { appendFile, mkdir, readFile, stat } from "node:fs/promises"; +import { appendFile, mkdir, open, stat } from "node:fs/promises"; import { createReadStream } from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -26,16 +26,24 @@ import type { LlmConfig } from "./config"; import { ANSWER_CAP_CHARS, CALLS_FILE, + CALLS_MAX_BYTES, + CALLS_MAX_CALLS, CALLS_TEXT_FILE, CALLS_TEXT_MAX_BYTES, + HEAD_CHARS, + ITEM_TEXT_CHARS, + WHY_CHARS, MODEL_LOG_VERSION, PROMPT_CAP_CHARS, answerText, boundDecision, boundItems, - foldModelLog, + foldModelLogInto, headOf, + newModelLogState, outcomeOfItems, + SCRUB_MARGIN_CHARS, + scrubBounded, scrubText, type CallDecision, type CallItem, @@ -44,7 +52,9 @@ import { type ModelCallText, type ModelDecisionRow, type ModelLog, + type ModelLogFullRow, type ModelLogRunRow, + type ModelLogState, type ModelRoute, type Scrub, } from "./callLog"; @@ -84,6 +94,15 @@ const compactJson = (v: unknown) => { } }; +// The configured API key's redaction, resolved the first time a text is +// actually redacted — inside a record, never per call: reading the key is a +// stat and a file read when it lives in a key file, and a call made with no +// log open must not pay for it. +export function lazyKeyRedactor(cfg: LlmConfig["anthropic"] | undefined): (s: string) => string { + let r: ((s: string) => string) | null = null; + return (s) => (r ??= keyRedactor(cfg))(s); +} + // ─── The writer ─── // The secrets and roots every record of this process is scrubbed of: the @@ -114,6 +133,12 @@ const URL_IN_ERROR = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>()]+/gi; const ADDRESS_IN_ERROR = /\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b|\[[0-9a-f:]*:[0-9a-f:]+\](?::\d+)?|(?<![0-9a-f:])::1(?::\d+)?\b/gi; const scrubErrorUrls = (s: string) => s.replace(URL_IN_ERROR, "<url>").replace(ADDRESS_IN_ERROR, "<host>"); +// A text whose scrubbed length is this much under its raw length was cut +// before the scrub (a scrub alone shortens by less than a margin). +const SCRUB_SLACK = SCRUB_MARGIN_CHARS; +// Items past what a row keeps are not scrubbed at all (MAX_ITEMS = 40). +const MAX_RECORD_ITEMS = 64; + export type ModelCallEntry = { phase?: string; label?: string; @@ -177,11 +202,19 @@ export class ModelLogWriter { private failed = false; private textFull = false; private readonly textMaxBytes: number; + // The log's own cap: the calls it held when this run began plus this run's, + // and its size. Full: one `full` row, then nothing more from this writer. + private held = 0; + private full = false; + private readonly maxCalls: number; + private readonly maxBytes: number; private pending: Promise<unknown> = Promise.resolve(); - constructor(o: { files: ModelLogFiles; task: string; jobId?: string; model?: string; where?: { article: string; iteration: number }; scrub?: Scrub; now?: () => Date; log?: (line: string) => void; textMaxBytes?: number }) { + constructor(o: { files: ModelLogFiles; task: string; jobId?: string; model?: string; where?: { article: string; iteration: number }; scrub?: Scrub; now?: () => Date; log?: (line: string) => void; textMaxBytes?: number; maxCalls?: number; maxBytes?: number }) { this.files = o.files; this.textMaxBytes = o.textMaxBytes ?? CALLS_TEXT_MAX_BYTES; + this.maxCalls = o.maxCalls ?? CALLS_MAX_CALLS; + this.maxBytes = o.maxBytes ?? CALLS_MAX_BYTES; this.where = o.where; this.task = o.task; this.jobId = o.jobId; @@ -208,9 +241,11 @@ export class ModelLogWriter { // This run's number, allocated (with its `run` row) on the first write. private async ensureRun(): Promise<number> { if (this.run !== null) return this.run; - const text = await readFile(this.files.calls, "utf8").catch(() => ""); - const max = foldModelLog(text).runs.reduce((m, r) => Math.max(m, r.run), 0); + const before = await readModelLog(this.files); + const max = before.runs.reduce((m, r) => Math.max(m, r.run), 0); this.run = max + 1; + this.held = before.calls.length; + this.full = !!before.full; const row: ModelLogRunRow = { v: MODEL_LOG_VERSION, t: "run", run: this.run, at: this.now().toISOString(), task: this.task, ...(this.jobId ? { jobId: this.jobId } : {}), ...(this.model ? { model: this.model } : {}) }; await mkdir(path.dirname(this.files.calls), { recursive: true }); await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); @@ -222,20 +257,44 @@ export class ModelLogWriter { return this.queue(() => this.ensureRun()); } + // True once the log is at its cap; the first time, the `full` row is + // written and the run is told. + private async atCap(run: number): Promise<boolean> { + if (this.full) return true; + const bytes = await stat(this.files.calls).then( + (st) => st.size, + () => 0, + ); + if (this.held < this.maxCalls && bytes < this.maxBytes) return false; + this.full = true; + const row: ModelLogFullRow = { v: MODEL_LOG_VERSION, t: "full", at: this.now().toISOString(), run, calls: this.held, bytes }; + await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); + this.log?.(`model log: full (${this.held.toLocaleString("en-US")} calls, ${Math.round(bytes / 1e6)} MB) — later calls are not recorded`); + return true; + } + record(e: ModelCallEntry): Promise<string | null> { const at = this.now().toISOString(); return this.queue(async () => { const run = await this.ensureRun(); + if (await this.atCap(run)) return null; const id = `${run}.${++this.seq}`; const clean = (s: string) => { const r = e.redact ? e.redact(s) : s; return scrubText(r, this.scrub); }; - const system = clean(e.system ?? ""); - const prompt = clean(e.prompt ?? ""); - const answer = clean(answerText(e.answer)); - const items = boundItems(e.items?.map((i) => ({ ...i, text: clean(i.text), why: clean(i.why) }))); - const decision = e.decision ? boundDecision({ ...e.decision, why: clean(e.decision.why) }) : items ? { outcome: outcomeOfItems(items), why: "" } : { outcome: "n/a" as const, why: e.error ? "the call failed" : "" }; + // Each text is cut to what is kept of it (and a margin) BEFORE the + // scrub: a megabyte of prompt is never scrubbed to keep 40,000 characters. + const bounded = (s: string, cap: number) => scrubBounded(s, cap, clean); + const rawSystem = e.system ?? ""; + const rawPrompt = e.prompt ?? ""; + const rawAnswer = answerText(e.answer); + const system = bounded(rawSystem, PROMPT_CAP_CHARS); + const prompt = bounded(rawPrompt, PROMPT_CAP_CHARS); + const answer = bounded(rawAnswer, ANSWER_CAP_CHARS); + const boundItem = (i: CallItem) => ({ ...i, text: bounded(String(i.text ?? ""), ITEM_TEXT_CHARS), why: bounded(String(i.why ?? ""), WHY_CHARS) }); + const items = boundItems(e.items?.slice(0, MAX_RECORD_ITEMS).map(boundItem)); + const decision = e.decision ? boundDecision({ ...e.decision, why: bounded(String(e.decision.why ?? ""), WHY_CHARS) }) : items ? { outcome: outcomeOfItems(items), why: "" } : { outcome: "n/a" as const, why: e.error ? "the call failed" : "" }; const row: ModelCallRow = { v: MODEL_LOG_VERSION, t: "call", @@ -244,32 +303,34 @@ export class ModelLogWriter { at, task: this.task, phase: e.phase || this.task, - ...(e.label ? { label: clean(e.label).slice(0, 120) } : {}), + ...(e.label ? { label: bounded(e.label, 120).slice(0, 120) } : {}), model: e.model, route: e.route, - promptChars: system.length + prompt.length, + // What was sent and what came back, in characters (before the scrub). + promptChars: rawSystem.length + rawPrompt.length, promptHead: headOf(prompt || system), - answerChars: answer.length, + answerChars: rawAnswer.length, // A structured answer's head is its compact JSON (the whole text keeps it laid out). - answerHead: headOf(typeof e.answer === "string" || e.answer === undefined ? answer : clean(compactJson(e.answer))), + answerHead: headOf(typeof e.answer === "string" || e.answer === undefined ? answer : bounded(compactJson(e.answer), HEAD_CHARS * 2)), seconds: Math.round((Number.isFinite(e.seconds) ? e.seconds : 0) * 10) / 10, ...(typeof e.tokensIn === "number" ? { tokensIn: e.tokensIn } : {}), ...(typeof e.tokensOut === "number" ? { tokensOut: e.tokensOut } : {}), - ...(e.error ? { error: scrubErrorUrls(clean(e.error)).slice(0, 600) } : {}), + ...(e.error ? { error: scrubErrorUrls(bounded(e.error, 600)).slice(0, 600) } : {}), decision, ...(items ? { items } : {}), }; // The prompt cap is on the system and the rest together, the system first. const sys = system.slice(0, PROMPT_CAP_CHARS); const rest = prompt.slice(0, Math.max(0, PROMPT_CAP_CHARS - sys.length)); + const keptAnswer = answer.slice(0, ANSWER_CAP_CHARS); const text: ModelCallText = { v: MODEL_LOG_VERSION, id, system: sys, prompt: rest, - ...(sys.length + rest.length < system.length + prompt.length ? { promptCut: true as const } : {}), - answer: answer.slice(0, ANSWER_CAP_CHARS), - ...(answer.length > ANSWER_CAP_CHARS ? { answerCut: true as const } : {}), + ...(sys.length < system.length || rest.length < prompt.length || system.length < rawSystem.length - SCRUB_SLACK || prompt.length < rawPrompt.length - SCRUB_SLACK ? { promptCut: true as const } : {}), + answer: keptAnswer, + ...(keptAnswer.length < answer.length || rawAnswer.length > ANSWER_CAP_CHARS + SCRUB_MARGIN_CHARS ? { answerCut: true as const } : {}), }; // The text first: a row the list shows has its text to expand — until // the text file is full (CALLS_TEXT_MAX_BYTES): then the row alone is @@ -285,6 +346,7 @@ export class ModelLogWriter { this.log?.(`model log: the calls' text is full (${Math.round(this.textMaxBytes / 1e6)} MB) — later calls keep their row, not their whole text`); } await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); + this.held++; return id; }); } @@ -294,14 +356,17 @@ export class ModelLogWriter { void this.queue(async () => { const call = await id; if (!call) return; + // A full log takes nothing more, a decision included. + if (this.full) return; const clean = (s: string) => scrubText(redact ? redact(s) : s, this.scrub); - const b = boundItems(items?.map((i) => ({ ...i, text: clean(i.text), why: clean(i.why) }))); + const bounded = (s: string, cap: number) => scrubBounded(String(s ?? ""), cap, clean); + const b = boundItems(items?.slice(0, MAX_RECORD_ITEMS).map((i) => ({ ...i, text: bounded(i.text, ITEM_TEXT_CHARS), why: bounded(i.why, WHY_CHARS) }))); const row: ModelDecisionRow = { v: MODEL_LOG_VERSION, t: "decision", call, at, - ...(decision ? { decision: boundDecision({ ...decision, why: clean(decision.why) }) } : {}), + ...(decision ? { decision: boundDecision({ ...decision, why: bounded(decision.why, WHY_CHARS) }) } : {}), ...(b ? { items: b } : {}), }; await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); @@ -381,14 +446,62 @@ export function recordModelCall(e: ModelCallEntry, slot?: CallSlot): void { // `llm`: the run's config, whose API key (if any) is scrubbed from it too. export function recordSessionAnswer(e: { phase?: string; label?: string; system: string; prompt: string; answer: unknown; llm?: LlmConfig }, slot?: CallSlot): void { const { llm, ...rest } = e; - recordModelCall({ ...rest, label: e.label ?? "a Claude Code session's answer", model: "claude-code", route: "claude-code", seconds: 0, redact: keyRedactor(llm?.anthropic) }, slot); + recordModelCall({ ...rest, label: e.label ?? "a Claude Code session's answer", model: "claude-code", route: "claude-code", seconds: 0, redact: lazyKeyRedactor(llm?.anthropic) }, slot); } // ─── Reading ─── +// A poll reads only what was appended: per file, the fold so far and the +// offset it reached (whole lines only — a line still being written waits for +// the next read). A file that shrank or was replaced is read again from its +// start. At most READ_CACHE_FILES logs are held (each at most CALLS_MAX_BYTES +// of rows); the oldest read goes first. +type ReadState = { ino: number; born: number; offset: number; state: ModelLogState }; +const READ_CACHE_FILES = 24; +const READ_KEY = Symbol.for("archilyzer.modelLog.readers"); +function readers(): Map<string, ReadState> { + const g = globalThis as unknown as Record<symbol, Map<string, ReadState> | undefined>; + return (g[READ_KEY] ??= new Map()); +} +const snapshot = (st: ModelLogState): ModelLog => ({ runs: [...st.runs], calls: [...st.calls], ...(st.full ? { full: true } : {}) }); + export async function readModelLog(files: ModelLogFiles): Promise<ModelLog> { - const text = await readFile(files.calls, "utf8").catch(() => null); - return foldModelLog(text); + const cache = readers(); + const file = files.calls; + // One read of a file at a time, in this process: two polls never fold the same bytes twice. + return enqueue(`read:${file}`, async () => { + const st = await stat(file).catch(() => null); + if (!st) { + cache.delete(file); + return { runs: [], calls: [] }; + } + let entry = cache.get(file); + if (!entry || entry.ino !== st.ino || entry.born !== st.birthtimeMs || st.size < entry.offset) entry = { ino: st.ino, born: st.birthtimeMs, offset: 0, state: newModelLogState() }; + if (st.size > entry.offset) { + const fh = await open(file, "r"); + try { + const want = st.size - entry.offset; + const buf = Buffer.allocUnsafe(want); + let got = 0; + while (got < want) { + const { bytesRead } = await fh.read(buf, got, want - got, entry.offset + got); + if (!bytesRead) break; + got += bytesRead; + } + const end = buf.subarray(0, got).lastIndexOf(0x0a); + if (end >= 0) { + foldModelLogInto(entry.state, buf.subarray(0, end).toString("utf8")); + entry.offset += end + 1; + } + } finally { + await fh.close(); + } + } + cache.delete(file); + cache.set(file, entry); // most recently read last + while (cache.size > READ_CACHE_FILES) cache.delete(cache.keys().next().value!); + return snapshot(entry.state); + }); } // One call's whole text, read line by line until its id (never the whole file diff --git a/common/lib/llm/callLog.test.ts b/common/lib/llm/callLog.test.ts @@ -22,6 +22,7 @@ import { 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 @@ -305,3 +306,143 @@ test("a failed call's error names no address: an IP and port, and a URL of any s 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<string, string | undefined>, { + 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(); + } +}); diff --git a/common/lib/llm/callLog.ts b/common/lib/llm/callLog.ts @@ -32,7 +32,9 @@ // written (`scrubText`) — and of anything shaped like a credential, whoever's // it is: a URL's user:password, a query parameter named like a token (and a // signed URL's `ip`), a Bearer value, a Cookie line, a key that says what it -// is. A failed call's message is scrubbed of URLs and addresses too. +// is. A failed call's message is scrubbed of URLs and addresses too. A text is +// cut to what the record keeps of it, and a margin, BEFORE it is scrubbed +// (`scrubBounded`), and every pattern is linear in its input. // // A reader skips a line that does not parse and a row of an unknown version; // a later version adds fields, never renames one. @@ -48,6 +50,11 @@ export const ANSWER_CAP_CHARS = 40_000; // All the calls' whole text of one log (calls-text.jsonl): past this the // writer keeps a call's row and no longer its text. export const CALLS_TEXT_MAX_BYTES = 64 * 1024 * 1024; +// calls.jsonl itself (the rows every panel poll folds): past either cap the +// writer appends one `full` row and records no further call — neither its row +// nor its text — and the panel and the run's log say so. +export const CALLS_MAX_CALLS = 20_000; +export const CALLS_MAX_BYTES = 32 * 1024 * 1024; export const HEAD_CHARS = 280; export const HEAD_LINES = 3; export const WHY_CHARS = 400; @@ -98,7 +105,10 @@ export type ModelCallRow = { export type ModelDecisionRow = { v: 1; t: "decision"; call: string; at: string; decision?: CallDecision; items?: CallItem[] }; -export type ModelLogRow = ModelLogRunRow | ModelCallRow | ModelDecisionRow; +// Written once, when the log reaches its cap: nothing is recorded after it. +export type ModelLogFullRow = { v: 1; t: "full"; at: string; run: number; calls: number; bytes: number }; + +export type ModelLogRow = ModelLogRunRow | ModelCallRow | ModelDecisionRow | ModelLogFullRow; export type ModelCallText = { v: 1; id: string; system: string; prompt: string; promptCut?: true; answer: string; answerCut?: true }; @@ -121,31 +131,67 @@ export function headOf(text: string): string { export type Scrub = { secrets?: readonly string[]; roots?: readonly string[] }; const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +// EVERY PATTERN BELOW IS LINEAR. A transcript can be one unbroken token of +// 160,000 characters, and this runs on the editor's event loop: no pattern has +// an unbounded quantifier it can restart inside (each is bounded, and each +// that starts on a run of ordinary characters has a lookbehind that lets it +// start only at the run's first one). The test times them. + +// A path is a path where one can begin: not after a host or another path +// character — `https://pbs.twimg.com/media/F.jpg` and `example.com/home/page` +// are links, and stay. +const PATH_START = "(?<![A-Za-z0-9._~%:/@-])"; +const PATH_REST = "[^\\s\"'`<>()[\\]{},;]"; // A home directory on any of the usual systems, even when it is not ours. -const HOME_PATH = /(?:\/home\/|\/Users\/|\/root\/|\/run\/media\/|\/mnt\/|\/media\/)[^\s"'`<>()[\]{},;]*/g; +const HOME_PATH = new RegExp(`${PATH_START}(?:/home/|/Users/|/root/|/run/media/|/mnt/|/media/)${PATH_REST}{1,4096}`, "g"); // A credential by its SHAPE, whoever's it is: a transcript, a tool result or // an error can carry one this process never held (a signed media URL, a pasted // header, a cookie line). Each keeps its name and loses its value. -const CREDENTIAL_PARAM = "(?:[\\w.-]*[_.-])?(?:access|api|auth|session)?_?(?:token|key|secret|password|passwd|pwd|signature|sig|lsig|auth|session|sessionid|sid|clearance|cookie|credentials?)"; -const CREDENTIAL_SHAPES: readonly (readonly [RegExp, string])[] = [ +const CREDENTIAL_WORD = "(?:token|key|secret|password|passwd|pwd|signature|sig|lsig|auth|session|sessionid|sid|clearance|cookie|credentials?)"; +const CREDENTIAL_PARAM = `(?:[\\w.-]{0,64}[_.-])?(?:access|api|auth|session)?_?${CREDENTIAL_WORD}`; +// The login cookies of the platforms this archive fetches. +const LOGIN_COOKIE = "(?:auth_token|ct0|cf_clearance|sessionid|csrftoken|SAPISID|__Secure-[\\w-]{1,64})"; +// A value that reads like a credential and not like a word: a digit, a +// base64 or URL-safe sign, or a capital inside it. +const LOOKS_SECRET = "(?=[A-Za-z0-9._~+/=-]{0,200}?(?:[0-9+/=_~]|[a-z][A-Z]))"; +// (For a pattern that ignores case, where "a capital inside" means nothing.) +const LOOKS_SECRET_ANY_CASE = "(?=[A-Za-z0-9._~+/=-]{0,200}?[0-9+/=_~])"; +const ENV_CREDENTIAL = /(?:^|_)(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|PWD|CREDENTIALS?|COOKIES?|AUTH)$/; + +type Shape = readonly [RegExp, string | ((...m: string[]) => string)]; +const CREDENTIAL_SHAPES: readonly Shape[] = [ // user:password@ in a URL - [/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/@:"'<>]*:[^\s/@"'<>]+@/gi, "$1[secret]@"], + [/(?<![A-Za-z0-9+.-])([a-z][a-z0-9+.-]{0,20}:\/\/)[^\s/@:"'<>]{0,256}:[^\s/@"'<>]{1,512}@/gi, "$1[secret]@"], // a query parameter named like a credential — and `ip`, the fetcher's public // address in a signed media URL - [new RegExp(`([?&;](?:${CREDENTIAL_PARAM}|ip|ipbits))=[^&\\s"'\`<>#;)\\]}]+`, "gi"), "$1=[secret]"], - // an Authorization value, a Cookie line, a key header - [/\b(Bearer|Basic)[ \t]+[A-Za-z0-9._~+/=-]{16,}/g, "$1 [secret]"], - [/\b((?:set-)?cookie[ \t]*:[ \t]*)[^\s=;:]+=[^\n]*/gi, "$1[secret]"], - [/\b((?:x-api-key|api[-_]?key|authorization|proxy-authorization)[ \t]*[:=][ \t]*)["']?[A-Za-z0-9._~+/-]{16,}["']?/gi, "$1[secret]"], - // the login cookies of the platforms this archive fetches, wherever they are quoted - [/\b(auth_token|ct0|cf_clearance|sessionid|SAPISID|__Secure-[\w-]+)=[^;\s"'&]+/g, "$1=[secret]"], + [new RegExp(`([?&;](?:${CREDENTIAL_PARAM}|ip|ipbits))=[^&\\s"'\`<>#;)\\]}]{1,4096}`, "gi"), "$1=[secret]"], + // an Authorization header's value, whatever it is + [/\b(authorization["']?[ \t]{0,8}[:=][ \t]{0,8}["']?(?:Bearer|Basic)[ \t]{1,8})[^\s"']{1,4096}/gi, "$1[secret]"], + // Bearer / Basic anywhere, when what follows reads like a credential + // ("Basic counterintelligence" and "bearer of bad news" are words) + [new RegExp(`\\b(Bearer|Basic)[ \\t]{1,8}${LOOKS_SECRET}[A-Za-z0-9._~+/=-]{16,4096}`, "g"), "$1 [secret]"], + // a Cookie header: at the start of a line (or a JSON field), and nothing + // but cookie pairs to the end of it — "cookie: chocolate=best ever" is a sentence + [/(^|[\n{,])([ \t]{0,16}["']?(?:set-)?cookie["']?[ \t]{0,8}:[ \t]{0,8}["']?)[\w.%!#$&*+^`|~-]{1,128}=[^\s;,"']{0,4096}(?:;[ \t]?[\w.%-]{1,128}(?:=[^\s;,"']{0,4096})?){0,64};?(?=[ \t]{0,8}(?:["'}\r\n]|$))/gi, "$1$2[secret]"], + // a key header + [/\b((?:x-api-key|api[-_]?key|authorization|proxy-authorization)["']?[ \t]{0,8}[:=][ \t]{0,8}["']?)[A-Za-z0-9._~+/-]{16,4096}/gi, "$1[secret]"], + // a login cookie wherever it is quoted: name=value, "name":"value", a + // cookie-jar line (name <tab> value) + [new RegExp(`\\b(${LOGIN_COOKIE})(["']?[ \\t]{0,8}[:=][ \\t]{0,8}["']?)[^;\\s"'&,}]{1,4096}`, "g"), "$1$2[secret]"], + [new RegExp(`\\b(${LOGIN_COOKIE})([ \\t]{1,8})[A-Za-z0-9._~%+/=-]{16,4096}`, "g"), "$1$2[secret]"], + // a password, a token, a secret written out: `password: hunter2…`, + // "token":"…" — when the value reads like one + [new RegExp(`\\b(pass(?:word|wd)|pwd|secret|(?:access|auth|api|session)[_-]?(?:token|key)|token)(["']?[ \\t]{0,8}[:=][ \\t]{0,8}["']?)${LOOKS_SECRET_ANY_CASE}[^\\s"',;]{8,4096}`, "gi"), "$1$2[secret]"], + // an environment assignment: WORKER_TOKEN=…, NAME_KEY=… + [/(?<![A-Za-z0-9_])([A-Z][A-Z0-9_]{2,80})=([^\s"'&;,]{8,4096})/g, (m, name) => (ENV_CREDENTIAL.test(name!) ? `${name}=[secret]` : m!)], // keys that say what they are - [/\bsk-(?:ant-)?[A-Za-z0-9_-]{20,}/g, "[secret]"], - [/\bgh[pousr]_[A-Za-z0-9]{30,}/g, "[secret]"], - [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, "[secret]"], + [/\bsk-(?:ant-)?[A-Za-z0-9_-]{20,512}/g, "[secret]"], + [/\bgh[pousr]_[A-Za-z0-9]{30,255}/g, "[secret]"], + [/\bxox[abprs]-[A-Za-z0-9-]{10,255}/g, "[secret]"], [/\bAKIA[0-9A-Z]{16}\b/g, "[secret]"], - [/\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, "[secret]"], + [/\beyJ[A-Za-z0-9_-]{8,4096}\.eyJ[A-Za-z0-9_-]{8,4096}\.[A-Za-z0-9_-]{8,4096}/g, "[secret]"], ]; export function scrubText(text: string, s: Scrub = {}): string { @@ -153,12 +199,41 @@ export function scrubText(text: string, s: Scrub = {}): string { for (const secret of s.secrets ?? []) { if (secret && secret.length >= 8) out = out.split(secret).join("[secret]"); } - for (const [re, to] of CREDENTIAL_SHAPES) out = out.replace(re, to); + for (const [re, to] of CREDENTIAL_SHAPES) out = typeof to === "string" ? out.replace(re, to) : out.replace(re, to); const roots = [...new Set((s.roots ?? []).filter((r) => r && r.length > 1 && r.startsWith("/")).map((r) => r.replace(/\/+$/, "")))].sort((a, b) => b.length - a.length); - for (const r of roots) out = out.replace(new RegExp(`${escapeRe(r)}(?:/[^\\s"'\`<>()[\\]{},;]*)?`, "g"), "<path>"); + for (const r of roots) out = out.replace(new RegExp(`${PATH_START}${escapeRe(r)}(?:/${PATH_REST}{0,4096})?`, "g"), "<path>"); return out.replace(HOME_PATH, "<path>"); } +// A text cut to what a record keeps of it BEFORE it is scrubbed: `cap` +// characters and a margin, so a secret that straddles the cap is still whole +// when the scrub sees it. The cut falls on white space inside the margin when +// there is any; when there is none (one unbroken token), the token the cut +// fell in is dropped after the scrub — a half of a credential is never kept. +export const SCRUB_MARGIN_CHARS = 8_192; +export function scrubBounded(text: string, cap: number, clean: (s: string) => string): string { + if (text.length <= cap + SCRUB_MARGIN_CHARS) return clean(text); + const end = cap + SCRUB_MARGIN_CHARS; + let ws = -1; + for (let i = end - 1; i >= cap; i--) { + const ch = text.charCodeAt(i); + if (ch === 32 || ch === 10 || ch === 9 || ch === 13) { + ws = i; + break; + } + } + if (ws >= 0) return clean(text.slice(0, ws)); + const out = clean(text.slice(0, end)); + let i = out.length; + while (i > 0) { + const ch = out.charCodeAt(i - 1); + if (ch === 32 || ch === 10 || ch === 9 || ch === 13) break; + i--; + } + // The whole of it one token: keep the cap's worth (there is no word to end on). + return i > 0 ? out.slice(0, i) : out.slice(0, cap); +} + // A recorded text printed to a terminal (`umtool model-log`): what a model // answered, or a transcript said, must not drive the operator's terminal. Every // control character but \n and \t -- ESC and the rest of C0, DEL, C1 (a CSI or @@ -217,15 +292,21 @@ export type ModelLog = { runs: ModelLogRunRow[]; // Every call, its decision rows applied, in the order they were made. calls: ModelCall[]; + // The log reached its cap (CALLS_MAX_CALLS / CALLS_MAX_BYTES): calls made + // after that were not recorded. + full?: boolean; }; const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v); -// calls.jsonl's text → the runs and the calls (decisions folded in). -export function foldModelLog(text: string | null | undefined): ModelLog { - const runs: ModelLogRunRow[] = []; - const calls: ModelCall[] = []; - const byId = new Map<string, ModelCall>(); +// calls.jsonl's text → the runs and the calls (decisions folded in). A fold +// can be CONTINUED: `foldModelLogInto` applies more lines to a state, so a +// reader that polls reads only what was appended (callLog-server.ts). +export type ModelLogState = ModelLog & { byId: Map<string, ModelCall> }; +export const newModelLogState = (): ModelLogState => ({ runs: [], calls: [], byId: new Map() }); + +export function foldModelLogInto(state: ModelLogState, text: string | null | undefined): ModelLogState { + const { runs, calls, byId } = state; for (const line of (text ?? "").split("\n")) { if (!line.trim()) continue; let r: unknown; @@ -248,9 +329,14 @@ export function foldModelLog(text: string | null | undefined): ModelLog { if (d.items?.length) c.items = [...(c.items ?? []), ...d.items].slice(0, MAX_ITEMS); if (d.decision) c.decision = d.decision; else if (c.items?.length) c.decision = { outcome: outcomeOfItems(c.items), why: c.decision.why }; - } + } else if (r.t === "full") state.full = true; } - return { runs, calls }; + return state; +} + +export function foldModelLog(text: string | null | undefined): ModelLog { + const { runs, calls, full } = foldModelLogInto(newModelLogState(), text); + return { runs, calls, ...(full ? { full } : {}) }; } // What a filter asks for. `outcome` matches a call whose decision is it, or diff --git a/common/lib/llm/callLogPrivacy.test.ts b/common/lib/llm/callLogPrivacy.test.ts @@ -6,7 +6,7 @@ import path from "node:path"; import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, toolUseBlock, turn, type FakeAnthropic } from "../../testing/llm/fakeAnthropic.mjs"; import { jsonReply, reply, startFakeOllama, type FakeOllama } from "../../testing/llm/fakeOllama.mjs"; import { runAgent } from "./agent"; -import { scrubText } from "./callLog"; +import { SCRUB_MARGIN_CHARS, scrubBounded, scrubText } from "./callLog"; import { ModelLogWriter, modelLogFilesIn, recordSessionAnswer, runWithModelLog } from "./callLog-server"; import { Meter } from "./meter"; import { structuredAnswer } from "./structured"; @@ -138,3 +138,124 @@ test("scrubText: a credential by its shape, whoever's it is -- the name stays, t ]) assert.equal(scrubText(plain, {}), plain); }); + +// ─── Review round (12 Nov): linear patterns, links that survive, more shapes ─── + +test("every scrub pattern is linear: 160,000 characters of each rule's trigger scrub in well under 250 ms", () => { + const N = 160_000; + const rep = (unit: string) => unit.repeat(Math.ceil(N / unit.length)).slice(0, N); + const inputs: Record<string, string> = { + "a.": rep("a."), + "a-": rep("a-"), + "& then a.": `&${rep("a.")}`, + "Bearer + letters": `Bearer ${"a".repeat(N)} `, + "Basic + letters": `Basic ${"a".repeat(N)}`, + "Bearer repeated": rep("Bearer "), + "cookie: repeated": rep("cookie: "), + "a cookie line of pairs": `cookie: ${rep("a=b; ")}`, + "scheme then colons": `a://${rep("b:")}`, + "://": rep("://"), + "/home/": rep("/home/"), + "/": rep("/"), + "eyJ + letters": `eyJ${"a".repeat(N)}`, + "eyJ. repeated": rep("eyJaaaaaaaa."), + "api_key=": rep("api_key="), + "? then a_": `?${rep("a_")}x`, + "?a_": rep("?a_"), + "A_": rep("A_"), + "A": "A".repeat(N), + "password:": rep("password: "), + "auth_token": rep("auth_token "), + "sk-": rep("sk-"), + "sk- + letters": `sk-${"a".repeat(N)}`, + "@": rep("@"), + ":": rep(":"), + "=": rep("="), + "authorization:": rep("authorization: "), + "one long word": "a".repeat(N), + }; + const scrub = { secrets: ["abcdefFAKE-TEST-VALUE"], roots: ["/srv/archive", "/home/someone"] }; + scrubText("warm up https://u:p@h/x?token=abc Bearer abcdefghijklmnop0123", scrub); + const slow: string[] = []; + for (const [name, text] of Object.entries(inputs)) { + const t0 = performance.now(); + scrubText(text, scrub); + const ms = performance.now() - t0; + if (ms >= 250) slow.push(`${name}: ${Math.round(ms)} ms`); + } + assert.deepEqual(slow, []); +}); + +test("scrubText: a link is not a host path — X image links and /home/ in a URL survive; a real path still goes", () => { + for (const link of [ + "https://pbs.twimg.com/media/Fxyz.jpg", + "see https://pbs.twimg.com/media/GabC-12_x?format=jpg&name=large here", + "https://example.com/home/page and https://rumble.com/user/media/x", + "https://x.com/home/user", + "example.com/mnt/data", + "see /media/ and /mnt/ in prose", + ]) + assert.equal(scrubText(link, { roots: ["/home/user"] }), link); + assert.equal(scrubText("read /home/user/Projects/x.json and (/mnt/media/a.mp4)", { roots: ["/home/user"] }), "read <path> and (<path>)"); + assert.equal(scrubText('cwd="/home/ann/.config/x"', {}), 'cwd="<path>"'); + assert.equal(scrubText("file=/media/drive/v.mkv", {}), "file=<path>"); +}); + +test("scrubText: the shapes the first pass missed — JSON-quoted, a cookie-jar line, a written-out password, an environment assignment", () => { + const cases: [string, string][] = [ + ['{"auth_token":"deadbeefdeadbeefdeadbeef","ct0": "0123abcd"}', '{"auth_token":"[secret]","ct0": "[secret]"}'], + ["auth_token deadbeefdeadbeefdeadbeef", "auth_token [secret]"], + [".x.com\tTRUE\t/\tTRUE\t1799\tauth_token\tdeadbeefdeadbeefdeadbeef", ".x.com\tTRUE\t/\tTRUE\t1799\tauth_token\t[secret]"], + [".rumble.com\tTRUE\t/\tTRUE\t1799\tcf_clearance\tZx9.yQ-77_abcdefghij", ".rumble.com\tTRUE\t/\tTRUE\t1799\tcf_clearance\t[secret]"], + ["password: hunter2hunter2hunter2", "password: [secret]"], + ['"password":"hunter2hunter2"', '"password":"[secret]"'], + ["WORKER_TOKEN=abcd1234abcd1234abcd", "WORKER_TOKEN=[secret]"], + ["export NAME_TOKEN=abcd1234abcd1234 && run", "export NAME_TOKEN=[secret] && run"], + ["AWS_SECRET_ACCESS_KEY=FAKE-TEST-VALUE", "AWS_SECRET_ACCESS_KEY=[secret]"], + ['"authorization":"Bearer abcdefghijklmnopqrstuvwxyz"', '"authorization":"Bearer [secret]"'], + ["Authorization: Bearer abcdefghijklmnopqrstuvwxyz", "Authorization: Bearer [secret]"], + ["HTTPS://U:PASS@HOST/x and https://u:p%40ss@host/x", "HTTPS://[secret]@HOST/x and https://[secret]@host/x"], + ['{"cookie": "auth_token=aaaa; ct0=bbbb"}', '{"cookie": "[secret]"}'], + ["Set-Cookie: sid=abc123; Path=/; HttpOnly", "Set-Cookie: [secret]"], + ]; + for (const [text, want] of cases) assert.equal(scrubText(text, {}), want); + // Not credentials: an assignment that is not named like one, a short value, words. + for (const plain of ["NODE_ENV=production-like-value", "PATH_LIKE=abcdefghijkl", "TOKEN=short", "password: none, she said", "the token: congratulations everyone", "at 12:30 he said t=5 and ip=dynamic"]) + assert.equal(scrubText(plain, {}), plain); +}); + +test("scrubText: words are not credentials — `Basic counterintelligence`, `bearer of bad news`, a sentence about a cookie", () => { + for (const plain of [ + "Basic counterintelligence is hard. Bearer of bad news-and-other-things.", + "Basic Counterintelligence, he called it", + "He said: cookie: chocolate=best ever, really", + "cookie: chocolate=best ever, really", + "my cookie: oatmeal", + ]) + assert.equal(scrubText(plain, {}), plain); + assert.equal(scrubText("Basic dXNlcjpodW50ZXIyaHVudGVyMg==", {}), "Basic [secret]"); + assert.equal(scrubText("sent Bearer abcdefgh1jklmnopqrst to it", {}), "sent Bearer [secret] to it"); +}); + +test("scrubBounded: a text is cut to its cap and a margin before the scrub — a secret across the cap is still whole, a token the cut fell in is dropped", () => { + const clean = (s: string) => scrubText(s, { secrets: ["SECRET-0123456789"] }); + // Short: scrubbed whole. + assert.equal(scrubBounded("say SECRET-0123456789 now", 10, clean), "say [secret] now"); + // Long, with white space in the margin: cut there; the secret straddling the cap is scrubbed whole. + const cap = 1_000; + const long = `${"word ".repeat(198)}xx SECRET-0123456789 ${"tail ".repeat(5_000)}`; + assert.ok(long.indexOf("SECRET") < cap && long.indexOf("SECRET") + 17 > cap, "the secret straddles the cap"); + const out = scrubBounded(long, cap, clean); + assert.ok(!out.includes("SECRET") && out.includes("[secret]")); + assert.ok(out.length <= cap + SCRUB_MARGIN_CHARS && out.length >= cap); + // One unbroken token far longer than cap + margin, a secret cut in half at the end of what is scrubbed: no half of it is kept. + const cutAt = cap + SCRUB_MARGIN_CHARS; + const token = `start ${"x".repeat(cutAt - 6 - 8)}SECRET-0123456789${"y".repeat(50_000)}`; + const hard = scrubBounded(token, cap, clean); + assert.ok(!hard.includes("SECRET-"), "no half of a credential"); + assert.equal(hard, "start "); + // And it is fast whatever the size. + const t0 = performance.now(); + scrubBounded("a.".repeat(2_000_000), 40_000, clean); + assert.ok(performance.now() - t0 < 250); +}); diff --git a/common/lib/llm/callLogView.ts b/common/lib/llm/callLogView.ts @@ -6,6 +6,8 @@ // the editor's job page and `umtool model-log` all read this. import { + CALLS_MAX_BYTES, + CALLS_MAX_CALLS, CALL_OUTCOMES, callMatches, phaseLabel, @@ -52,6 +54,9 @@ export type ModelLogView = { counts: Record<"all" | CallOutcome, number>; outcome: CallOutcome | null; groups: ModelLogViewGroup[]; + // The log is at its cap: calls made after it were not recorded. + full: boolean; + cap: { calls: number; megabytes: number }; }; const listRow = (c: ModelCall): ModelLogViewRow => ({ ...c, items: c.items?.slice(0, LIST_ITEMS), itemsTotal: c.items?.length ?? 0 }); @@ -103,6 +108,8 @@ export function modelLogView(log: ModelLog, q: ModelLogViewQuery = {}): ModelLog counts, outcome: q.outcome ?? null, groups: q.phase ? groups : groups.filter((g) => g.calls > 0 || !q.outcome), + full: !!log.full, + cap: { calls: CALLS_MAX_CALLS, megabytes: Math.round(CALLS_MAX_BYTES / (1024 * 1024)) }, }; } diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts @@ -14,13 +14,12 @@ import { AnthropicClient, AnthropicError, isStrictModel, - keyRedactor, toolUsesOf, type ContentBlock, type MessagesResponse, } from "./anthropic"; import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig } from "./config"; -import { CallSlot, recordModelCall } from "./callLog-server"; +import { CallSlot, lazyKeyRedactor, recordModelCall } from "./callLog-server"; import type { Meter, Usage } from "./meter"; import { ollamaChat, OllamaError, PromptTooLargeError, promptEstimate } from "./ollama"; @@ -84,7 +83,7 @@ const spend = (s: Spent, u: Usage | undefined) => { export async function structuredAnswer<T>(o: Opts): Promise<T> { const route = providerOf(o.model); - const spent: Spent = { tokensIn: 0, tokensOut: 0, any: false, sent: o.user, redact: keyRedactor(o.llm.anthropic) }; + const spent: Spent = { tokensIn: 0, tokensOut: 0, any: false, sent: o.user, redact: lazyKeyRedactor(o.llm.anthropic) }; const t0 = Date.now(); const images = o.images?.length ? `\n\n[${o.images.length} image${o.images.length === 1 ? "" : "s"} sent with this prompt]` : ""; const record = (answer: unknown, error?: unknown) => diff --git a/common/lib/report/draft/tasks/llmText.ts b/common/lib/report/draft/tasks/llmText.ts @@ -7,7 +7,6 @@ import { AnthropicClient, anthropicConfigOf, isStrictModel, - keyRedactor, ollamaChat, ollamaConfigOf, promptCapOf, @@ -17,7 +16,7 @@ import { type Meter, type StructuredCallMeta, } from "../../../llm"; -import { recordModelCall } from "../../../llm/callLog-server"; +import { lazyKeyRedactor, recordModelCall } from "../../../llm/callLog-server"; // Characters a token takes in the ollama estimate (lib/llm/ollama.ts). const CHARS_PER_TOKEN = 3.5; @@ -35,7 +34,7 @@ export async function plainAnswer(o: { }): Promise<string> { const route = providerOf(o.model); const t0 = Date.now(); - let redact: ((s: string) => string) | undefined = keyRedactor(o.llm.anthropic); + let redact: ((s: string) => string) | undefined = lazyKeyRedactor(o.llm.anthropic); const record = (answer: string, tokens: { tokensIn?: number; tokensOut?: number }, error?: unknown) => recordModelCall( { diff --git a/common/lib/report/iterations.test.ts b/common/lib/report/iterations.test.ts @@ -185,6 +185,9 @@ test("refusals: a revision needs a done parent and feedback; fixed keys; files b await assert.rejects(writeIterationFile("r", 1, "../evil.json" as "sweep.md", "x", paths), /not an iteration file/); await assert.rejects(writeIterationFile("r", 1, "report.json", doc("other"), paths), /is "other", not "r"|does not parse/); await assert.rejects(writeIterationFile("r", 1, "report.json", "{nope", paths), /not JSON/); + // The model log is its writer's: a name of the iteration, never one this replaces. + await assert.rejects(writeIterationFile("r", 1, "calls.jsonl", "{}\n", paths), /is the model log/); + await assert.rejects(writeIterationFile("r", 1, "calls-text.jsonl", "{}\n", paths), /is the model log/); await assert.rejects(writeIterationFile("r", 1, "turns.jsonl", '{"a":1}\nnope\n', paths), /line 2 is not JSON/); await assert.rejects(writeIterationFile("r", 9, "sweep.md", "# x", paths), /no iteration i9/); // Made current: needs a report in its lineage, and a sound one. diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts @@ -85,6 +85,9 @@ export type IterationStepStatus = (typeof ITERATION_STEP_STATUSES)[number]; // appended by its writer only, never through writeIterationFile. export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl", "refresh.json", "calls.jsonl", "calls-text.jsonl"] as const; export type IterationFile = (typeof ITERATION_FILES)[number]; +// The files only their own writer appends to (lib/llm/callLog-server.ts): a +// name of the iteration, never one writeIterationFile replaces. +export const APPEND_ONLY_ITERATION_FILES: readonly IterationFile[] = ["calls.jsonl", "calls-text.jsonl"]; // A revision needs something to revise (and feedback saying how); a refresh // needs the iteration it refreshes (its feedback is what it finds). @@ -703,6 +706,9 @@ export async function writeIterationFile( if (!(ITERATION_FILES as readonly string[]).includes(name)) { throw new ArticleRegistryError(`"${name}" is not an iteration file (${ITERATION_FILES.join(", ")})`); } + if (APPEND_ONLY_ITERATION_FILES.includes(name)) { + throw new ArticleRegistryError(`"${name}" is the model log: its writer appends to it, and nothing replaces it`); + } const text = fileText(name, data, id); return withArticleStoreLock(async () => { if (!(await readIteration(id, n, paths))) throw new ArticleRegistryError(`"${id}" has no iteration ${iterationLabel(n)}`); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,8 +1,8 @@ # Changelog ## [Unreleased] -- **umtool: a Model log shows what the model was asked, what it answered, and what the code did with it.** Until now a prompt was shown nowhere, and a local model's calls were in no ledger. Every model call of a run is now recorded, on every route (a local model, the Claude API, this session), and listed in a **Model log** panel on the run page (`/research/runs/<article>/<n>`), the article's Iterations tab and each media draft. Calls are grouped by phase (terms, reading, meaning check, grouping). A row has the first lines of what was asked, what came back, the seconds, and whether its answer was kept, dropped or rewritten, with the reason and each item's fate. A row opens to the whole prompt and answer (40,000 characters of each are kept). The header counts the calls, the seconds and the models; a filter narrows to kept, dropped or rewritten; the list follows a run while it runs. `umtool model-log <article> <n>` (or `--job <jobId>`) prints the same, with `--phase`, `--outcome`, `--task`, `--run`, `--call <run.call>` for one call's whole text, and `--json`; a control sequence in a recorded text is printed as its escape (`\x1b`), never sent to the terminal. `/settings/generation` shows, per task, the route and the model it will run on, "no API key configured" when there is none, and the model of its last run. -- **The job page has the Model log too, and a local model's calls are in the usage ledger.** A job that calls a model (a report draft, a refresh, triage, verdicts, a frame scan, clip suggestions, video assist) shows its calls on `/jobs/<id>`, as umtool does. Calls to a local model are appended to `.generation/usage.jsonl` with route `local` and cost 0, so `pnpm ops get generation-usage` lists every model a run called, and a run that was local only lists no other. `pnpm ops get iterations` gains each iteration's call count and seconds. The record keeps the text sent to the model and nothing else: no header and no model host; the editor's `WORKER_TOKEN`, an API key, every environment variable named like a credential, and host paths are taken out before a line is written, and a failed call's message has its URLs removed. +- **umtool: a Model log shows what the model was asked, what it answered, and what the code did with it.** Until now a prompt was shown nowhere, and a local model's calls were in no ledger. Every model call of a run is now recorded, on every route (a local model, the Claude API, this session), and listed in a **Model log** panel on the run page (`/research/runs/<article>/<n>`), the article's Iterations tab and each media draft. Calls are grouped by phase (terms, reading, meaning check, grouping). A row has the first lines of what was asked, what came back, the seconds, and whether its answer was kept, dropped or rewritten, with the reason and each item's fate. A row opens to the whole prompt and answer (40,000 characters of each are kept). A log holds 20,000 calls or 32 MB; past that the panel says the log is full, and later calls are not recorded. The header counts the calls, the seconds and the models; a filter narrows to kept, dropped or rewritten; the list follows a run while it runs. `umtool model-log <article> <n>` (or `--job <jobId>`) prints the same, with `--phase`, `--outcome`, `--task`, `--run`, `--call <run.call>` for one call's whole text, and `--json`; a control sequence in a recorded text is printed as its escape (`\x1b`), never sent to the terminal. `/settings/generation` shows, per task, the route and the model it will run on, "no API key configured" when there is none, and the model of its last run. +- **The job page has the Model log too, and a local model's calls are in the usage ledger.** A job that calls a model (a report draft, a refresh, triage, verdicts, a frame scan, clip suggestions, video assist) shows its calls on `/jobs/<id>`, as umtool does. Calls to a local model are appended to `.generation/usage.jsonl` with route `local` and cost 0, so `pnpm ops get generation-usage` lists every model a run called, and a run that was local only lists no other. `pnpm ops get iterations` gains each iteration's call count and seconds. The record keeps the text sent to the model and nothing else: no header and no model host; the editor's `WORKER_TOKEN`, an API key, every environment variable named like a credential, and host paths are taken out before a line is written, anything shaped like a credential (a URL's user and password, a token in a query string, a `Bearer` value, a cookie line, a key that says what it is) loses its value whoever's it is, and a failed call's message has its URLs and addresses removed. Links are kept. - **umtool: record, filter and listen before anything is kept.** On the record page a recording became a take the moment its last part was in, and hearing it in the character's voice meant importing it on the Voices page and waiting for three takes (operator, 11 Nov: "run the filter and preview it seamlessly in the record UI"). With **Filter before keeping** (on by itself for a post whose character has a stock voice to convert to) the post now waits. **Filter** (`f`) runs the character's recorded preset as one job: clean, cut, convert. Its result is a preview in `narration/.record-preview/<postId>.<label>/`, not a take. The page shows the three stages and the time it has run, and a wait at the editor's queue or the machine's heavy slot reads "waiting for memory … the gate working, not an error". **▶ Raw** and **▶ Filtered** play at one loudness. **Keep** (`Enter`) makes the recorded, cleaned and converted takes from the preview's files, converts nothing again, picks the last and opens the next post not recorded; **Again** (`Backspace` or `r`) drops the preview and records the part again. Each part's waveform carries two **cut marks** at the auto trim's answer; drag one, or press the arrow keys on it, to cut a keyboard click off the start or the end. **Pitch** and **semitones** (a Seed-VC convert) default to the preset's and re-run the convert alone; **Save to character** writes them back, and a post read as the narrator or as nobody offers **Keep in this video only**. Above the record button: the character, its direction line and **▶ <voice> reads it** (its synthetic preset's voice), which plays the read kept from before when there is one and asks the editor only when pressed. Cancel stops the editor's job too. Opened over http from the LAN the page says the microphone is off (a browser opens it only on localhost or https); **Use a sound file…** takes a recording made elsewhere, and Filter, the preview and Keep work there. From a terminal: `umtool posts narrate <p> <item> --recording <file> --preview [--out <file>] [--trim-span 0.4-3.1]` prints the paths and makes no take, `--keep-preview` keeps it, `--discard-preview` drops it. A "start on speech" trigger was not built: it would lose the start of the first word, and the auto trim already cuts the silence before it. ([knobs.md](../umtool/docs/knobs.md#record-filter-preview-on-the-record-page)) - **umtool: a convert made from a take uses its character's voice, not the editor's default.** On 11 Nov `umtool posts narrate <p> <item> --derive <n> --op convert` with no flags made a take in the wrong voice: it asked the editor with nothing, and the editor used its own default target. A convert now takes its engine, stock voice, pitch and semitones from the recorded preset of the character the read is made as (`--as`, else the item's own, this video's for the author, the cast's, the narrator); a flag overrides its own key. With no character and no `--voice` it is refused in one sentence. The post bench's **run AI on take** does the same on the server. - **Lookouts: a saved set of channels and days, and a dry run that lists what it would read.** A lookout (lane/lookout) will read its channels' recent transcripts and answer with video ideas; this first part has no model. `settings.lookouts` holds the lookouts (off and empty by default; nothing in code names a channel), and `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists the week it would read: every video by its AIR date in the lookout's time zone (a stream that starts at 8:20 pm in New York is 3 Nov, not the 4 Nov of its UTC upload date), a recording uploaded twice read once with the other upload named beside it, a stream's cut-downs credited to the stream, the longest 40 read and every one left out listed with why. Over the pilot's week, read-only, it found all 6 of the pilot's duplicate uploads and all 18 of its stream cut-downs. `pnpm ops get lookouts` is the readout. Runs and verdicts will live in `transcripts/.lookouts/`, never published. diff --git a/editor/app/jobs/[id]/components/JobModelLog.tsx b/editor/app/jobs/[id]/components/JobModelLog.tsx @@ -140,6 +140,11 @@ export function JobModelLog({ jobId, initiallyRunning }: { jobId: string; initia ))} </span> </div> + {v?.full && ( + <p className="text-xs text-amber-700 dark:text-amber-400" data-model-log-full=""> + The log is full ({v.cap.calls.toLocaleString("en-US")} calls or {v.cap.megabytes} MB): calls made after that were not recorded. + </p> + )} {!v || v.counts.all === 0 ? ( <p className="text-xs text-muted-foreground" data-model-log-empty=""> {running diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts @@ -364,6 +364,11 @@ test("a media draft's answer puts its video project first, above the iteration's assert.equal(step[1], "Video project: /srv/projects/synth-a/i3"); assert.equal(step.filter((l) => l.startsWith("Video project:")).length, 1); assert.ok(step.indexOf("Where (the editor's disk): /srv/reports/synth-a/iterations/3") > 1); + // The run's records are not listed as paths: the turns, the trace, the model log. + const records = { ...files, "turns.jsonl": "/srv/x/turns.jsonl", "trace.jsonl": "/srv/x/trace.jsonl", "calls.jsonl": "/srv/x/calls.jsonl", "calls-text.jsonl": "/srv/x/calls-text.jsonl" }; + const listed = renderIterationSummary({ task: "social", article: "synth-a", jobId: "job-9", marker: null, iteration: iteration as never, dir: "/srv/reports/synth-a/iterations/3", files: records }); + assert.ok(!/turns\.jsonl|trace\.jsonl|calls\.jsonl|calls-text\.jsonl/.test(listed), listed); + assert.match(listed, /sweep\.md: \/srv/); const revise = renderIterationSummary({ task: "revise-video", article: "synth-a", jobId: "job-8", marker: null, iteration: { ...iteration, kind: "revise-video", steps: [] } as never, dir: "/srv/reports/synth-a/iterations/3", files }).split("\n"); assert.ok(revise.indexOf("Video project: /srv/projects/synth-a/i3") > revise.indexOf("Where (the editor's disk): /srv/reports/synth-a/iterations/3")); }); diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts @@ -12,6 +12,11 @@ import type { FetchClipDeps, PollProgress } from "./fetchClip"; import { mediaReviewGuidance, reviewGuidance, type GenerationRoute, type PlanGeneration } from "./instructions"; import type { ToolAnswer } from "./archivalTools"; +// An iteration's run records — the model's turns, the sweep's trace, the model +// log — are read through the editor (the run page, `umtool model-log`), never +// listed as paths on the editor's disk. +const RUN_RECORD_FILES: ReadonlySet<string> = new Set(["turns.jsonl", "trace.jsonl", "calls.jsonl", "calls-text.jsonl"]); + // ─── The Claude Code balance (release 27 S9; D8) ─── // // Report and video generation runs in the editor, as `report-draft` jobs on @@ -709,7 +714,7 @@ export function renderIterationSummary( if (o.dir) { const present = Object.entries(o.files ?? {}).filter(([, p]) => p) as [string, string][]; lines.push(`Where (the editor's disk): ${o.dir}`); - for (const [name, p] of present) if (name !== "turns.jsonl" && name !== "trace.jsonl") lines.push(` - ${name}: ${p}`); + for (const [name, p] of present) if (!RUN_RECORD_FILES.has(name)) lines.push(` - ${name}: ${p}`); } if (it.projectDir && !projectFirst) lines.push(`Video project: ${it.projectDir}`); if (it.kind === "research") { diff --git a/umtool/bin/model-log.ts b/umtool/bin/model-log.ts @@ -14,7 +14,7 @@ // answer is a model's (or a transcript's) text, and an ESC in it would be the // terminal's to obey. --json prints JSON through `sayJson`, which escapes what // JSON.stringify leaves (DEL, C1, bidi controls) as \u…: the same document. -import { CALL_OUTCOMES, callMatches, phaseLabel, phaseOrder, summarizeCalls, terminalSafe, terminalSafeJson, type CallOutcome, type ModelCall } from "yt-dlp-transcript-common/lib/llm/callLog"; +import { CALLS_MAX_BYTES, CALLS_MAX_CALLS, CALL_OUTCOMES, callMatches, phaseLabel, phaseOrder, summarizeCalls, terminalSafe, terminalSafeJson, type CallOutcome, type ModelCall } from "yt-dlp-transcript-common/lib/llm/callLog"; import { readModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; import { ModelLogError, jobLogOf, modelLogFilesOf, readModelCall, type ModelLogSource } from "../lib/model-log"; @@ -75,7 +75,7 @@ try { const shown = scoped.filter((c) => callMatches(c, { ...(phase ? { phase } : {}), ...(outcome ? { outcome: outcome as CallOutcome } : {}) })); const summary = summarizeCalls(scoped); if (json) { - sayJson({ source: src, runs: log.runs, summary, calls: shown }); + sayJson({ source: src, runs: log.runs, summary, full: !!log.full, calls: shown }); process.exit(0); } if (!scoped.length) { @@ -83,6 +83,7 @@ try { process.exit(0); } say(`${where} · ${summary.calls} call${summary.calls === 1 ? "" : "s"} · ${secs(summary.seconds)} · ${summary.models.map((m) => `${m.model} (${m.route}, ${m.calls})`).join(", ")}${summary.failed ? ` · ${summary.failed} failed` : ""}`); + if (log.full) say(`the log is full (${CALLS_MAX_CALLS.toLocaleString("en-US")} calls or ${Math.round(CALLS_MAX_BYTES / (1024 * 1024))} MB): calls made after that were not recorded`); const runs = log.runs.filter((r) => scoped.some((c) => c.run === r.run)); if (runs.length > 1) say(`runs: ${runs.map((r) => `${r.run} ${r.task} ${r.at.slice(0, 16)}`).join(" · ")}`); for (const p of phaseOrder(shown.map((c) => c.phase))) { diff --git a/umtool/components/model-log/ModelLog.tsx b/umtool/components/model-log/ModelLog.tsx @@ -360,6 +360,11 @@ export default function ModelLog({ {error} </p> )} + {view?.full && ( + <p className="m-0 text-[12px] text-reject-text" data-model-log-full=""> + The log is full ({view.cap.calls.toLocaleString("en-US")} calls or {view.cap.megabytes} MB): calls made after that were not recorded. + </p> + )} {empty ? ( <p className="m-0 text-[12.5px] text-muted-2" data-model-log-empty=""> {emptyText ??