// THE MODEL LOG (demo epic D3) — every model call a job makes, on every route // (a local model on ollama, the Claude API, a Claude Code session), as one // record: what was asked, what came back, how long it took, and what CODE did // with the answer and why. It is what the "Model log" panel shows and what // `umtool model-log` prints. Pure (types, caps, the scrub, the fold): the // writer and the readers are ./callLog-server.ts. // // WHERE. A run over an iteration writes its iteration's `calls.jsonl` and // `calls-text.jsonl` (a media draft is a step on its iteration: the same // files, its rows carry its `task`). A job with no iteration writes the same // pair beside its output (callLog-server.ts `jobModelLogFiles`). // // THE ROWS (calls.jsonl — small; a list or a count reads only this file): // {v, t: "run", run, at, task, jobId?, model?} a run began // {v, t: "call", id, run, at, task, phase, label?, model, route, // promptChars, promptHead, answerChars, answerHead, seconds, // tokensIn?, tokensOut?, error?, decision, items?} one model call // {v, t: "decision", call, at, decision?, items?} what code did with // call `call`'s answer, // appended once known // and calls-text.jsonl, one row per call (the panel fetches it per row): // {v, id, system, prompt, promptCut?, answer, answerCut?} // // A LATER STAGE only appends: a new `phase` (the meaning check's // "meaning-check") and its `decision` — through structuredAnswer's `call` // option and its CallSlot (callLog-server.ts), never a new row kind. // // 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, every variable // of the environment named like a credential) and of host paths before it is // 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. 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. export const MODEL_LOG_VERSION = 1 as const; export const CALLS_FILE = "calls.jsonl" as const; export const CALLS_TEXT_FILE = "calls-text.jsonl" as const; // The caps: a prompt and an answer are kept to PROMPT_CAP_CHARS each (the // 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; // 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; export const ITEM_TEXT_CHARS = 300; export const MAX_ITEMS = 40; // `local`: ollama · `api`: the Claude API with a key · `claude-code`: a Claude // Code session answered (the `code` route). export const MODEL_ROUTES = ["local", "api", "claude-code"] as const; export type ModelRoute = (typeof MODEL_ROUTES)[number]; export const CALL_OUTCOMES = ["kept", "dropped", "rewritten", "n/a"] as const; export type CallOutcome = (typeof CALL_OUTCOMES)[number]; export type CallDecision = { outcome: CallOutcome; why: string }; // One item of an answer (an extracted quote, a drafted field) and its fate. export type CallItem = CallDecision & { text: string }; // The phases a sweep goes through, in the order the panel lists them; any // other phase follows them in the order it first appears. export const PHASE_ORDER = ["terms", "reading", "meaning-check", "grouping"] as const; const PHASE_LABELS: Record = { terms: "Terms", reading: "Reading", "meaning-check": "Meaning check", grouping: "Grouping", agent: "Agent turns" }; export const phaseLabel = (p: string) => PHASE_LABELS[p] ?? p.charAt(0).toUpperCase() + p.slice(1).replace(/-/g, " "); export type ModelLogRunRow = { v: 1; t: "run"; run: number; at: string; task: string; jobId?: string; model?: string }; export type ModelCallRow = { v: 1; t: "call"; id: string; run: number; at: string; task: string; phase: string; label?: string; model: string; route: ModelRoute; promptChars: number; promptHead: string; answerChars: number; answerHead: string; seconds: number; tokensIn?: number; tokensOut?: number; error?: string; decision: CallDecision; items?: CallItem[]; }; export type ModelDecisionRow = { v: 1; t: "decision"; call: string; at: string; decision?: CallDecision; items?: CallItem[] }; // 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 }; // ─── Text ─── const cutTo = (s: string, max: number) => (s.length > max ? s.slice(0, max) : s); // The first lines a list row shows: up to HEAD_LINES non-empty lines, at most // HEAD_CHARS, an ellipsis when there was more. export function headOf(text: string): string { const lines = text.split("\n").map((l) => l.trimEnd()).filter((l) => l.trim()); let head = lines.slice(0, HEAD_LINES).join("\n"); const more = lines.length > HEAD_LINES || head.length > HEAD_CHARS; head = cutTo(head, HEAD_CHARS); return more ? `${head}…` : head; } // What a scrub removes: exact secret values, and absolute paths under the // host's own roots (the home directory, the checkout, the data roots). 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 home directory on any of the usual systems, even when it is not ours. 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_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)$/; // What follows `secret:` / `token:` / `password:` is a credential unless it is // a date or a time ("Secret: 2026-11-07T10:00 meeting", "token: 10:30am-11am") // or a link ("Token: https://…" — a link's own credentials are the other // rules'). An ordinary word never gets this far: the rules that call this ask // for a digit or a sign in the value first. (Each alternative starts on its own // character, and the trailing punctuation is trimmed by a loop: linear.) const DATE_OR_TIME = /^(?:[\d.:/,+-]|T|Z|[ap]\.?m\.?|utc|gmt)+$/i; const TRAILING_PUNCT = ").]!?:"; const credentialLike = (v: string) => { let end = v.length; while (end > 0 && TRAILING_PUNCT.includes(v[end - 1]!)) end--; const core = v.slice(0, end); if (/\d/.test(core) && /[-:/]/.test(core) && DATE_OR_TIME.test(core)) return false; return !/^[a-z][a-z0-9+.-]{0,20}:\/\//i.test(core); }; type Shape = readonly [RegExp, string | ((...m: string[]) => string)]; const CREDENTIAL_SHAPES: readonly Shape[] = [ // user:password@ in a URL [/(?]{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 // — after `?`, `&` or `;` however the text writes them (`\u0026` in a // player's JSON, `&`, `%26`), and `=` or its `%3D` [new RegExp(`((?:[?&;]|\\\\u0026|&|%26|%3F)(?:${CREDENTIAL_PARAM}|ip|ipbits))(=|%3D)[^&\\s"'\`<>#;)\\]}\\\\]{1,4096}`, "gi"), "$1$2[secret]"], // an Authorization header's value, whatever it is // (a scheme word that is one: Bearer, Basic, Token, Digest, …) [/\b((?:proxy-)?authorization["']?[ \t]{0,8}[:=][ \t]{0,8}["']?(?:Bearer|Basic|Token|Digest|Negotiate|Api-?Key|OAuth|JWT|Hawk|NTLM|AWS4-HMAC-SHA256)[ \t]{1,8})[^\s"']{1,4096}/gi, "$1[secret]"], // (any other scheme word, when what follows it reads like a credential — // `SharedKey acct:sig…` has a colon in it, so the look ahead takes any // character the value can hold) [/\b((?:proxy-)?authorization["']?[ \t]{0,8}[:=][ \t]{0,8}["']?[A-Za-z][\w-]{0,24}[ \t]{1,8})(?=[^\s"']{0,200}?[0-9+/=_~])([^\s"']{8,4096})/gi, (m, head, value) => (credentialLike(value!) ? `${head}[secret]` : m!)], // 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}(?:[:=]|%3D)[ \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 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}(?:[:=]|%3D)[ \\t]{0,8}["']?)${LOOKS_SECRET_ANY_CASE}([^\\s"',;]{8,4096})`, "gi"), (m, name, sep, value) => (credentialLike(value!) ? `${name}${sep}[secret]` : m!)], // an environment assignment: WORKER_TOKEN=…, NAME_KEY=… [/(? (ENV_CREDENTIAL.test(name!) && credentialLike(value!) ? `${name}=[secret]` : m!)], // keys that say what they are [/\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,4096}\.eyJ[A-Za-z0-9_-]{8,4096}\.[A-Za-z0-9_-]{8,4096}/g, "[secret]"], ]; export function scrubText(text: string, s: Scrub = {}): string { let out = text; 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 = 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(`${PATH_START}${escapeRe(r)}(?:/${PATH_REST}{0,4096})?`, "g"), ""); return out.replace(HOME_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 // OSC in one byte) -- is printed as its escape (\x1b), and the characters that // reorder or hide text (bidi controls, the line and paragraph separators) as // \u…. JSON printed to a terminal goes through `terminalSafeJson`: // JSON.stringify escapes C0 only, and leaves DEL, C1 (U+009B is a CSI to some // terminals) and the bidi controls as they are; there they become JSON's own // \u…. escapes, so the document parses to the same text. const TERMINAL_UNSAFE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028-\u202e\u2066-\u2069]/g; export function terminalSafe(text: string): string { return text.replace(TERMINAL_UNSAFE, (ch) => { const n = ch.charCodeAt(0); return n <= 0xff ? `\\x${n.toString(16).padStart(2, "0")}` : `\\u${n.toString(16).padStart(4, "0")}`; }); } export function terminalSafeJson(json: string): string { return json.replace(TERMINAL_UNSAFE, (ch) => (ch === "\n" || ch === "\t" ? ch : `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`)); } // An answer as the record keeps it: a string as it is, anything else as JSON. export function answerText(answer: unknown): string { if (typeof answer === "string") return answer; if (answer === undefined) return ""; try { return JSON.stringify(answer, null, 1) ?? ""; } catch { return String(answer); } } export function boundDecision(d: CallDecision): CallDecision { const outcome = (CALL_OUTCOMES as readonly string[]).includes(d.outcome) ? d.outcome : "n/a"; return { outcome, why: cutTo(String(d.why ?? ""), WHY_CHARS) }; } export function boundItems(items: readonly CallItem[] | undefined): CallItem[] | undefined { if (!items?.length) return undefined; return items.slice(0, MAX_ITEMS).map((i) => ({ ...boundDecision(i), text: cutTo(String(i.text ?? ""), ITEM_TEXT_CHARS) })); } // The outcome a call's items add up to: kept when any was kept, rewritten // when any was rewritten and none kept, else dropped. export function outcomeOfItems(items: readonly CallItem[]): CallOutcome { if (items.some((i) => i.outcome === "kept")) return "kept"; if (items.some((i) => i.outcome === "rewritten")) return "rewritten"; if (items.length && items.every((i) => i.outcome === "dropped")) return "dropped"; return "n/a"; } // ─── Reading ─── export type ModelCall = ModelCallRow; 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 => !!v && typeof v === "object" && !Array.isArray(v); // 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 }; 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; try { r = JSON.parse(line); } catch { continue; // a torn line } if (!isObj(r) || r.v !== MODEL_LOG_VERSION) continue; if (r.t === "run" && typeof r.run === "number") runs.push(r as ModelLogRunRow); else if (r.t === "call" && typeof r.id === "string") { const c = { ...(r as ModelCallRow) }; if (!isObj(c.decision)) c.decision = { outcome: "n/a", why: "" }; byId.set(c.id, c); calls.push(c); } else if (r.t === "decision" && typeof r.call === "string") { const c = byId.get(r.call); if (!c) continue; const d = r as ModelDecisionRow; 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 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 // any of whose items is (a call that kept two quotes and dropped one is in // both "kept" and "dropped"). export type ModelLogQuery = { task?: string; run?: number; jobId?: string; phase?: string; outcome?: CallOutcome }; export function callMatches(c: ModelCall, q: ModelLogQuery): boolean { if (q.task && c.task !== q.task) return false; if (q.run !== undefined && c.run !== q.run) return false; if (q.phase && c.phase !== q.phase) return false; if (q.outcome && c.decision.outcome !== q.outcome && !(c.items ?? []).some((i) => i.outcome === q.outcome)) return false; return true; } // The runs a query's task and job name: by task, then by job. export function runsOf(log: ModelLog, q: Pick): ModelLogRunRow[] { return log.runs.filter((r) => (!q.task || r.task === q.task) && (!q.jobId || r.jobId === q.jobId)); } export function phaseOrder(phases: Iterable): string[] { const seen = [...new Set(phases)]; const known = PHASE_ORDER.filter((p) => seen.includes(p)); return [...known, ...seen.filter((p) => !(PHASE_ORDER as readonly string[]).includes(p))]; } export type ModelLogSummary = { calls: number; seconds: number; failed: number; models: { model: string; route: ModelRoute; calls: number }[]; phases: { phase: string; calls: number; seconds: number }[]; outcomes: Record; tokensIn: number; tokensOut: number; }; const round1 = (v: number) => Math.round(v * 10) / 10; export function summarizeCalls(calls: readonly ModelCall[]): ModelLogSummary { const models = new Map(); const phases = new Map(); const outcomes: Record = { kept: 0, dropped: 0, rewritten: 0, "n/a": 0 }; let seconds = 0; let failed = 0; let tokensIn = 0; let tokensOut = 0; for (const c of calls) { seconds += c.seconds || 0; if (c.error) failed++; tokensIn += c.tokensIn ?? 0; tokensOut += c.tokensOut ?? 0; const mk = `${c.route}:${c.model}`; const m = models.get(mk) ?? { model: c.model, route: c.route, calls: 0 }; m.calls++; models.set(mk, m); const p = phases.get(c.phase) ?? { phase: c.phase, calls: 0, seconds: 0 }; p.calls++; p.seconds += c.seconds || 0; phases.set(c.phase, p); outcomes[c.decision.outcome] = (outcomes[c.decision.outcome] ?? 0) + 1; } const order = phaseOrder(phases.keys()); return { calls: calls.length, seconds: round1(seconds), failed, models: [...models.values()].sort((a, b) => b.calls - a.calls), phases: order.map((p) => ({ ...phases.get(p)!, seconds: round1(phases.get(p)!.seconds) })), outcomes, tokensIn, tokensOut, }; }