Archilyzer · Source

archilyzer

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

commit bdea6e6a92323877394d9233156937cb2c01c5bb
parent b25865f94f437358a0ae4ac40a24ea8dd4fe7f5a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 00:25:09 -0500

common: model log review fixes -- every credential-named variable of the environment is scrubbed, a failed call's error names no URL, the calls' text is capped at 64 MB, and a job id of dots alone is refused

processScrub took WORKER_TOKEN and ANTHROPIC_API_KEY only: it now takes every
variable named ...TOKEN / KEY / SECRET / PASSWORD / CREDENTIALS whose value
reads like a credential (16 characters, no space, not a path), longest first.
A failed call's message (ollama's client names its base URL) has its URLs
replaced by <url>. calls-text.jsonl stops growing at CALLS_TEXT_MAX_BYTES: a
later call keeps its row, not its whole text, and the run's log says so once.
jobModelLogDir refused a slash but not "..". Tests for each.

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

Diffstat:
Mcommon/controller/jobModelLog.test.ts | 6++++++
Mcommon/controller/jobModelLog.ts | 2+-
Mcommon/lib/llm/callLog-server.ts | 46++++++++++++++++++++++++++++++++++++++--------
Mcommon/lib/llm/callLog.test.ts | 59++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/lib/llm/callLog.ts | 8++++++--
5 files changed, 109 insertions(+), 12 deletions(-)

diff --git a/common/controller/jobModelLog.test.ts b/common/controller/jobModelLog.test.ts @@ -65,3 +65,9 @@ test("a job over an iteration: the iteration's log takes the calls, the job's di await t.done(); } }); + +test("a job id is a name, never a way up: dots alone are refused", () => { + const paths = { generationUsageFile: path.join(os.tmpdir(), ".generation", "usage.jsonl") }; + 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")); +}); diff --git a/common/controller/jobModelLog.ts b/common/controller/jobModelLog.ts @@ -20,7 +20,7 @@ import type { Paths } from "../lib/paths"; type UsagePaths = Pick<Paths, "generationUsageFile">; export function jobModelLogDir(paths: UsagePaths, jobId: string): string { - if (!/^[A-Za-z0-9._-]+$/.test(jobId)) throw new Error(`not a job id: ${JSON.stringify(jobId)}`); + if (!/^[A-Za-z0-9._-]+$/.test(jobId) || /^\.+$/.test(jobId)) throw new Error(`not a job id: ${JSON.stringify(jobId)}`); return path.join(path.dirname(paths.generationUsageFile), "calls", jobId); } 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 } from "node:fs/promises"; +import { appendFile, mkdir, readFile, stat } from "node:fs/promises"; import { createReadStream } from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -27,6 +27,7 @@ import { ANSWER_CAP_CHARS, CALLS_FILE, CALLS_TEXT_FILE, + CALLS_TEXT_MAX_BYTES, MODEL_LOG_VERSION, PROMPT_CAP_CHARS, answerText, @@ -86,15 +87,30 @@ const compactJson = (v: unknown) => { // ─── The writer ─── // The secrets and roots every record of this process is scrubbed of: the -// editor's WORKER_TOKEN and an API key in the environment, the home directory, -// the checkout. +// editor's WORKER_TOKEN, an API key and every other variable of the +// environment named like a credential (…TOKEN, …KEY, …SECRET, …PASSWORD), the +// home directory, the checkout. +const SECRET_ENV_NAME = /(?:^|_)(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?)$/i; export function processScrub(extraRoots: readonly string[] = []): Scrub { const env = process.env; - const secrets = [env.WORKER_TOKEN, env.ANTHROPIC_API_KEY].filter((s): s is string => !!s && s.trim().length >= 8).map((s) => s.trim()); + // A credential by its name only when it reads like one (16 characters, no + // space): a short or worded value would take ordinary words out of a prompt. + const named = Object.entries(env) + .filter(([k, v]) => SECRET_ENV_NAME.test(k) && !!v && v.trim().length >= 16 && !/\s/.test(v.trim())) + .map(([, v]) => v); + const secrets = [...new Set([env.WORKER_TOKEN, env.ANTHROPIC_API_KEY, ...named].filter((s): s is string => !!s && s.trim().length >= 8).map((s) => s.trim()))] + // A value that is a path (a key FILE) is not a secret; the roots take paths. + .filter((s) => !s.startsWith("/")) + .sort((a, b) => b.length - a.length); const roots = [os.homedir(), process.cwd(), ...extraRoots].filter((r) => !!r && r !== "/"); return { secrets, roots }; } +// A failed call's message may name the host it was sent to (ollama's base +// URL): an error keeps its words, never an address. +const URL_IN_ERROR = /\bhttps?:\/\/[^\s"'`<>()]+/g; +const scrubErrorUrls = (s: string) => s.replace(URL_IN_ERROR, "<url>"); + export type ModelCallEntry = { phase?: string; label?: string; @@ -152,10 +168,13 @@ export class ModelLogWriter { private run: number | null = null; private seq = 0; private failed = false; + private textFull = false; + private readonly textMaxBytes: 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 }) { + 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 }) { this.files = o.files; + this.textMaxBytes = o.textMaxBytes ?? CALLS_TEXT_MAX_BYTES; this.where = o.where; this.task = o.task; this.jobId = o.jobId; @@ -229,7 +248,7 @@ export class ModelLogWriter { 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: clean(e.error).slice(0, 600) } : {}), + ...(e.error ? { error: scrubErrorUrls(clean(e.error)).slice(0, 600) } : {}), decision, ...(items ? { items } : {}), }; @@ -245,8 +264,19 @@ export class ModelLogWriter { answer: answer.slice(0, ANSWER_CAP_CHARS), ...(answer.length > ANSWER_CAP_CHARS ? { answerCut: true as const } : {}), }; - // The text first: a row the list shows always has its text to expand. - await appendFile(this.files.text, `${JSON.stringify(text)}\n`); + // 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 + // kept, and the panel says the call's text was not. + const line = `${JSON.stringify(text)}\n`; + const held = await stat(this.files.text).then( + (st) => st.size, + () => 0, + ); + if (held + Buffer.byteLength(line) <= this.textMaxBytes) await appendFile(this.files.text, line); + else if (!this.textFull) { + this.textFull = true; + 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`); return id; }); diff --git a/common/lib/llm/callLog.test.ts b/common/lib/llm/callLog.test.ts @@ -14,9 +14,10 @@ import { foldModelLog, headOf, phaseOrder, + scrubText, summarizeCalls, } from "./callLog"; -import { CallSlot, ModelLogWriter, modelLogFilesIn, readModelCallText, readModelLog, recordModelCall, recordSessionAnswer, runWithModelLog } from "./callLog-server"; +import { CallSlot, ModelLogWriter, modelLogFilesIn, processScrub, readModelCallText, readModelLog, recordModelCall, recordSessionAnswer, runWithModelLog } from "./callLog-server"; import { Meter } from "./meter"; import { structuredAnswer } from "./structured"; import { plainAnswer } from "../report/draft/tasks/llmText"; @@ -193,3 +194,59 @@ test("a failed call is recorded with its error, its decision n/a", async () => { 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!, /<url>/); + } 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<string, string> = { 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<string, string | undefined>; + 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]; + } +}); diff --git a/common/lib/llm/callLog.ts b/common/lib/llm/callLog.ts @@ -27,8 +27,9 @@ // // PRIVACY. `system` and `prompt` are the text sent to the model and nothing // else (no header, no key, no URL of the model's host); every text is scrubbed -// of the run's secrets (the API key, the editor's WORKER_TOKEN) and of host -// paths before it is written (`scrubText`). +// of the run's secrets (the API key, the editor's WORKER_TOKEN, every variable +// of the environment named like a credential) and of host paths before it is +// written (`scrubText`); a failed call's message is scrubbed of URLs too. // // A reader skips a line that does not parse and a row of an unknown version; // a later version adds fields, never renames one. @@ -41,6 +42,9 @@ export const CALLS_TEXT_FILE = "calls-text.jsonl" as const; // rest is cut and said so); a head is the first lines a list row shows. export const PROMPT_CAP_CHARS = 40_000; 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; export const HEAD_CHARS = 280; export const HEAD_LINES = 3; export const WHY_CHARS = 400;