commit 82dcb117f51e30fa337a8081e43057b237d07981 parent b5277a59f60d9b5fd3b27be07031315d9da4c95e Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Thu, 12 Nov 2026 08:53:39 -0500 Merge main (fcaf0358) into lane/local-media: model-log under the vtt short-form slice One conflict, editor/CHANGELOG.md's [Unreleased] head: both sides kept. Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
134 files changed, 4747 insertions(+), 131 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md @@ -363,9 +363,13 @@ get coverage <slug> is what a channel holds by date: held, dated (by get generation-usage [<day>] is the day's Claude API spend on generation (the usage ledger's total for the UTC day, default today) and the daily - cap it is checked against: {day, usd, jobs, daily}. + cap it is checked against: {day, usd, jobs, daily}; and `models`, every + model the day's generation called and on which route ("local" at no + cost) — a local-only day lists no Claude model. get iterations <article> is an article's iterations (iteration.json each) - and which is current. (The MCP's generate reads one, with its files.) + and which is current, each with `calls`: its model log counted (calls, + seconds, failed, models and phases; `umtool model-log <article> <n>` the + calls). (The MCP's generate reads one, with its files.) get transcript <videoId> [--slug <slug>] reads one video's cues off disk with no index: a fresh cues.json, else what build-cues would write, else diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -224,6 +224,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_TEST_ROUTES` | off | `1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else. | editor/app/api/test/_guard.ts, editor/instrumentation.ts | | `E2E_MODE` | `start` | `start`: the editor and umtool suites run against `next start` from a build `scripts/e2e-stamp.mjs` vouches for, rebuilt through the heavy slot when the tree moved. `dev`: against `next dev`, for iterating on one spec. The export and homepage suites always run `next dev` (static exports) and say so when asked for `start`. | editor/playwright.config.ts, umtool/playwright.config.ts, scripts/e2e-stamp.mjs | | `E2E_NEXT_DIST_DIR` | `.next` | The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server — and for the editor suite's export dev server (`.next/e2e-editor`), which then runs beside the export suite's own (Next allows one `next dev` per dist dir). | editor/next.config.ts, export/next.config.ts | +| `E2E_MODEL_LOG_SHOTS` | unset (no screenshots) | A directory: the model log's e2e (demo epic D3) saves its 1366×768 screenshots of the panel there — the run page live and done, a call opened, the Iterations tab, a media draft, the settings table, the editor's job page — for a lane's report. Unset, none is taken. | umtool/e2e/model-log.spec.ts, editor/e2e/report-draft.spec.ts | | `E2E_DATA_ROOT` | the editor directory | Where the editor test server's data lives: `test-transcripts/`, `test-settings.json` and the disposable changelogs sit under it. The test server's scripts and the specs' `testPaths()` read the same variable, so they agree by construction. E2E_-prefixed, never TRANSCRIPTS_DIR: a `--share-data` worktree's `.worktree-env` points that at the real corpus. | editor/package.json (dev:test, start:test), editor/e2e/testPaths.ts | | `E2E_WORKERS` | 1 | How many workers the editor suite runs, each with a server set of its own (editor, export dev server, Ollama stub) over its own data root (`editor/.e2e-workers/w<n>`): a number (up to 8), or `auto` — floor((MemAvailable − HEAVY_MIN_FREE_MB) / 1.5 GB), 1 to 3. Specs in `editor/e2e/serial.ts` run afterwards on one worker. | editor/playwright.config.ts (editor/e2e/servers.ts) | | `E2E_SERIAL_LAST` | — | Set by the editor suite's runner for its workers: `1` when the run is whole (no spec file or filter on the command line), so the @serial project runs last; `0` for a focused run, where Playwright would run a teardown project whole. | editor/playwright.config.ts | diff --git a/common/bin/_spawnBin.ts b/common/bin/_spawnBin.ts @@ -13,6 +13,7 @@ import { spawn } from "node:child_process"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import "../lib/childKillGuard"; const COMMON = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); export const REPO_ROOT = path.resolve(COMMON, ".."); 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/bin/evidence-pack.ts b/common/bin/evidence-pack.ts @@ -53,6 +53,7 @@ import type { FlagValue } from "./_parseFlags"; // (social/postCapture.test.ts): a private package, written outside the // corpus, that nothing in the export or publish layer imports. import { CAPTURE_FILENAME, postsMediaDir } from "../social/postCapture"; +import "../lib/childKillGuard"; export const SUMS_FILE = "SHA256SUMS"; export const OTS_FILE = "SHA256SUMS.ots"; diff --git a/common/controller/attachMedia.ts b/common/controller/attachMedia.ts @@ -95,6 +95,7 @@ import { type CopiedEntry, type ZipEntry, } from "../lib/zipReader"; +import "../lib/childKillGuard"; export const ATTACH_MEDIA_REQUESTER = "attach-media"; diff --git a/common/controller/backupSavedVideos.ts b/common/controller/backupSavedVideos.ts @@ -15,6 +15,7 @@ import { } from "../lib/savedVideoBackup"; import { listSavedVideos } from "./savedVideoInventory"; import { updateSavedVideoChecksum } from "../lib/savedVideo-server"; +import "../lib/childKillGuard"; // Backup tooling for the saved-video store (Phase 4 of the video-persistence // feature). `dest` is treated as a local filesystem path (typically a mounted diff --git a/common/controller/benchVerdicts.ts b/common/controller/benchVerdicts.ts @@ -29,6 +29,7 @@ // (`diskCuesOf`): a fact-check may cite channels no build carries. The log // ends `@@bench-verdicts {json}` with the run's id, status and spend. +import { modelLogged } from "./jobModelLog"; import { getSettings } from "../lib/settings"; import type { Paths } from "../lib/paths"; import type { GenerationSettings } from "../lib/generationSettings"; @@ -218,7 +219,7 @@ export async function enqueueVerdictBench( kind: BENCH_VERDICTS_JOB_KIND, queueKey: anyLocal ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, - fn: async (onLog, signal, _progress, ctx) => { + fn: modelLogged({ paths, task: "bench-verdicts" }, async (onLog, signal, _progress, ctx) => { const g = (deps.settings ?? getSettings)().generation; // Again at the job's turn: jobs ahead in the queue may have spent the day. const late = await benchDailyCapRefusal(opts, paths, g, deps.now?.()); @@ -229,7 +230,7 @@ export async function enqueueVerdictBench( { paths, gen: g, onLog, signal, jobId: ctx.jobId, gpu: true, ...(deps.now ? { now: deps.now } : {}), ...(deps.root ? { root: deps.root } : {}) }, ); if (out.summary.status === "cancelled" || signal.aborted) throw new Error("cancelled"); - }, + }), }); if (!result.ok) return { result }; return { result, run }; diff --git a/common/controller/checkAvailability.ts b/common/controller/checkAvailability.ts @@ -34,6 +34,7 @@ import { resolveShardItems } from "./shard"; import type { Paths } from "../lib/paths"; import { jitterYtdlpSleeps } from "../lib/jitter"; import { jitterMs } from "../lib/jitter"; +import "../lib/childKillGuard"; export type CheckAvailabilityMode = | "resume" diff --git a/common/controller/clipsSuggest.ts b/common/controller/clipsSuggest.ts @@ -25,6 +25,7 @@ // {article: "", iteration: 0, task: "clips-suggest", kind, project, status, // summary, usd, suggestions | ask}`. +import { modelLogged } from "./jobModelLog"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; @@ -149,7 +150,7 @@ export async function enqueueClipsSuggest(body: ReportDraftBody, deps: ClipsSugg kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, - fn: async (onLog, signal, setProgress, ctx) => { + fn: modelLogged({ paths, task: "clips-suggest" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); @@ -225,7 +226,7 @@ export async function enqueueClipsSuggest(body: ReportDraftBody, deps: ClipsSugg ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (out.status === "failed") throw new Error(out.summary); - }, + }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; diff --git a/common/controller/diarizeOne.ts b/common/controller/diarizeOne.ts @@ -34,6 +34,7 @@ import { import type { AudioIntegrityVerdict } from "../lib/audioIntegrity"; import { pickPreferredAudio } from "../lib/mediaFiles"; import { resolveSavedVideo } from "../lib/savedVideo-server"; +import "../lib/childKillGuard"; const { readdir } = fs; diff --git a/common/controller/frameScan.ts b/common/controller/frameScan.ts @@ -32,6 +32,7 @@ // usage ledger (task `frame-scan`, no article). The log ends // `@@frame-scan {json}` with the run's counts, spend, and events. +import { modelLogged } from "./jobModelLog"; import path from "node:path"; import { readFile } from "node:fs/promises"; import { getSettings } from "../lib/settings"; @@ -268,7 +269,7 @@ export async function enqueueFrameScan(raw: Record<string, unknown>, deps: Frame paths, channelSlug: body.slug, videoId: body.id, - fn: async (onLog, signal, setProgress, ctx) => { + fn: modelLogged({ paths, task: "frames" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; // Again at the job's turn: jobs ahead in the queue may have spent the day. const late = await capRefusal(); @@ -351,7 +352,7 @@ export async function enqueueFrameScan(raw: Record<string, unknown>, deps: Frame await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); } } - }, + }), }); if (!result.ok) return { result }; return { result, model, queueKey }; diff --git a/common/controller/generationUsage.test.ts b/common/controller/generationUsage.test.ts @@ -26,3 +26,19 @@ test("the usage ledger: rows appended, the day's total read back, a torn line sk await rm(dir, { recursive: true, force: true }); } }); + +test("lastRunsByTask (demo epic D3): each task's newest job, its models and route; a frame scan's job is the frames task", async () => { + const { lastRunsByTask } = await import("./generationUsage"); + const row = (task: string, jobId: string, model: string, at: string, route?: "local") => ({ at, day: at.slice(0, 10), jobId, article: "a", iteration: 1, task, model, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 0, ...(route ? { route } : {}) }); + const out = lastRunsByTask([ + row("sweep", "j1", "claude-sonnet-5-5", "2026-11-01T10:00:00Z"), + row("sweep", "j1", "claude-haiku-4-5", "2026-11-01T10:00:00Z"), + row("sweep", "j2", "qwen3:8b", "2026-11-02T10:00:00Z", "local"), + row("narrate", "j3", "qwen3:8b", "2026-11-01T09:00:00Z", "local"), + row("frame-scan", "j4", "claude-haiku-4-5", "2026-11-03T09:00:00Z"), + ]); + assert.deepEqual(out.sweep, { at: "2026-11-02T10:00:00Z", jobId: "j2", models: ["qwen3:8b"], route: "local" }); + assert.deepEqual(out.narrate!.models, ["qwen3:8b"]); + assert.deepEqual(out.frames, { at: "2026-11-03T09:00:00Z", jobId: "j4", models: ["claude-haiku-4-5"], route: "api" }); + assert.equal(out["revise-report"], undefined); +}); diff --git a/common/controller/generationUsage.ts b/common/controller/generationUsage.ts @@ -22,6 +22,11 @@ export type GenerationUsageRow = { cacheReadTokens: number; cacheWriteTokens: number; usd: number; + // "local": a local model's calls (demo epic D3) — cost 0, never counted + // against the cap; the ledger is the proof a run stayed local. Absent: an + // API row (every row before D3). + route?: "api" | "local"; + calls?: number; }; export const utcDay = (d: Date = new Date()) => d.toISOString().slice(0, 10); @@ -52,9 +57,11 @@ export async function readGenerationUsage(file: string): Promise<GenerationUsage return out; } -// The day's API spend: its total and how many jobs it took. +export const isLocalUsage = (r: Pick<GenerationUsageRow, "route">) => r.route === "local"; + +// The day's API spend: its total and how many jobs it took (local rows apart). export async function dayUsage(file: string, day: string = utcDay()): Promise<{ day: string; usd: number; jobs: number }> { - const rows = (await readGenerationUsage(file)).filter((r) => r.day === day); + const rows = (await readGenerationUsage(file)).filter((r) => r.day === day && !isLocalUsage(r)); const usd = Math.round(rows.reduce((s, r) => s + r.usd, 0) * 10_000) / 10_000; return { day, usd, jobs: new Set(rows.map((r) => r.jobId)).size }; } @@ -67,3 +74,55 @@ export function dailyCapRefusal(day: { day: string; usd: number }, daily: number "daily cap (settings.generation.caps.daily) — refused; it resets at midnight UTC" ); } + +// The models the day's generation called, on which route: what proves a run +// stayed local (a local-only day lists no Claude model). +export type UsageModel = { model: string; route: "api" | "local"; calls: number; jobs: number; inputTokens: number; outputTokens: number }; + +export async function dayModels(file: string, day: string = utcDay()): Promise<UsageModel[]> { + const rows = (await readGenerationUsage(file)).filter((r) => r.day === day); + return usageModelsOf(rows); +} + +export function usageModelsOf(rows: readonly GenerationUsageRow[]): UsageModel[] { + const by = new Map<string, UsageModel & { ids: Set<string> }>(); + for (const r of rows) { + const route = isLocalUsage(r) ? "local" : "api"; + const k = `${route}:${r.model}`; + const m = by.get(k) ?? { model: r.model, route, calls: 0, jobs: 0, inputTokens: 0, outputTokens: 0, ids: new Set<string>() }; + m.calls += typeof r.calls === "number" ? r.calls : 0; + m.inputTokens += r.inputTokens || 0; + m.outputTokens += r.outputTokens || 0; + m.ids.add(r.jobId); + by.set(k, m); + } + return [...by.values()].map(({ ids, ...m }) => ({ ...m, jobs: ids.size })).sort((a, b) => a.route.localeCompare(b.route) || b.jobs - a.jobs || a.model.localeCompare(b.model)); +} + +// The task a ledger row is of, as settings.generation names it (a frame +// scan's job writes "frame-scan"). +const TASK_ALIASES: Record<string, string> = { "frame-scan": "frames" }; + +// Each task's last run in the ledger (demo epic D3, the settings page): the +// newest job of the task, the models it called and on which route. +export type LastRun = { at: string; jobId: string; models: string[]; route: "api" | "local" | "mixed" }; + +export function lastRunsByTask(rows: readonly GenerationUsageRow[]): Record<string, LastRun> { + const jobs = new Map<string, { task: string; at: string; models: Set<string>; routes: Set<"api" | "local"> }>(); + for (const r of rows) { + if (!r.jobId || !r.task) continue; + const task = TASK_ALIASES[r.task] ?? r.task; + const j = jobs.get(`${task}\u0000${r.jobId}`) ?? { task, at: r.at, models: new Set<string>(), routes: new Set<"api" | "local">() }; + j.models.add(r.model); + j.routes.add(isLocalUsage(r) ? "local" : "api"); + if (r.at > j.at) j.at = r.at; + jobs.set(`${task}\u0000${r.jobId}`, j); + } + const out: Record<string, LastRun> = {}; + for (const [key, j] of jobs) { + const jobId = key.slice(key.indexOf("\u0000") + 1); + if (out[j.task] && out[j.task]!.at >= j.at) continue; + out[j.task] = { at: j.at, jobId, models: [...j.models].sort(), route: j.routes.size > 1 ? "mixed" : [...j.routes][0]! }; + } + return out; +} diff --git a/common/controller/jobModelLog.test.ts b/common/controller/jobModelLog.test.ts @@ -0,0 +1,92 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { ModelLogWriter, modelLogFilesIn, readModelLog, recordModelCall, runWithModelLog } from "../lib/llm/callLog-server"; +import { iterationDir } from "../lib/report/iterations"; +import { readGenerationUsage } from "./generationUsage"; +import { jobModelLogDir, locateJobModelLog, modelLogged } from "./jobModelLog"; + +// Run with: pnpm -C common exec tsx --test controller/jobModelLog.test.ts +// +// A generation job's model log (demo epic D3): a job with no iteration keeps +// its calls in `.generation/calls/<job>/`; a job whose calls went to an +// iteration's log leaves a pointer there, and the job's page finds them +// through it; either way its local calls reach the usage ledger at no cost. + +async function setup() { + const tmp = await mkdtemp(path.join(os.tmpdir(), "job-model-log-")); + const paths = { generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), articlesDir: path.join(tmp, "reports"), exportIndexDir: path.join(tmp, "idx") }; + return { tmp, paths, done: () => rm(tmp, { recursive: true, force: true }) }; +} +const noLog = () => {}; + +test("a job with no iteration: its calls in its own dir, found there; its local calls in the ledger", async () => { + const t = await setup(); + try { + const fn = modelLogged({ paths: t.paths, task: "video-assist" }, async () => { + recordModelCall({ phase: "assist", model: "qwen3:8b", route: "local", prompt: "make the joins 0.15 s", answer: { ops: [] }, seconds: 2, tokensIn: 300, tokensOut: 20 }); + return "ok"; + }); + assert.equal(await fn(noLog, new AbortController().signal, null, { jobId: "job-a" }), "ok"); + const at = await locateJobModelLog(t.paths, "job-a"); + assert.deepEqual(at?.where, null); + assert.equal(at?.files.calls, path.join(jobModelLogDir(t.paths, "job-a"), "calls.jsonl")); + const log = await readModelLog(at!.files); + assert.deepEqual(log.calls.map((c) => [c.task, c.phase, c.route]), [["video-assist", "assist", "local"]]); + const rows = await readGenerationUsage(t.paths.generationUsageFile); + assert.deepEqual(rows.map((r) => [r.jobId, r.task, r.model, r.route, r.usd, r.calls, r.inputTokens]), [["job-a", "video-assist", "qwen3:8b", "local", 0, 1, 300]]); + assert.equal(await locateJobModelLog(t.paths, "job-none"), null); + } finally { + await t.done(); + } +}); + +test("a job over an iteration: the iteration's log takes the calls, the job's dir points at it, the locator follows (that job's run only)", async () => { + const t = await setup(); + try { + const dir = iterationDir(t.paths, "art", 2); + const fn = modelLogged({ paths: t.paths, task: "report-draft" }, async () => { + const inner = new ModelLogWriter({ files: modelLogFilesIn(dir), task: "sweep", jobId: "job-b", where: { article: "art", iteration: 2 }, scrub: {} }); + await runWithModelLog(inner, async () => recordModelCall({ phase: "terms", model: "qwen3:8b", route: "local", prompt: "q", answer: { terms: [] }, seconds: 1 })); + await inner.flush(); + }); + await fn(noLog, new AbortController().signal, null, { jobId: "job-b" }); + assert.deepEqual(JSON.parse(await readFile(path.join(jobModelLogDir(t.paths, "job-b"), "where.json"), "utf8")), { v: 1, article: "art", n: 2 }); + const at = await locateJobModelLog(t.paths, "job-b"); + assert.deepEqual(at?.where, { article: "art", n: 2 }); + assert.equal(at?.files.calls, path.join(dir, "calls.jsonl")); + // The ledger names the iteration the calls were made on. + const rows = await readGenerationUsage(t.paths.generationUsageFile); + assert.deepEqual(rows.map((r) => [r.jobId, r.article, r.iteration, r.task, r.route]), [["job-b", "art", 2, "sweep", "local"]]); + assert.throws(() => jobModelLogDir(t.paths, "../x"), /not a job id/); + } finally { + 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")); +}); + +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 @@ -0,0 +1,110 @@ +// A GENERATION JOB'S MODEL LOG when it has no iteration (demo epic D3; the +// shape is lib/llm/callLog.ts): a verdict proposal, a frame scan, the clip +// finder, the video assistant, claim groups, a triage, the verdict bench, a +// learning pass. Its calls go to `<generation dir>/calls/<jobId>/` (beside +// the usage ledger: editor state, never the corpus). A job over an iteration +// records into the iteration's own files instead (tasks/run.ts opens that +// log inside this one, and the inner one wins); this one stays empty and +// is never created; `where.json` there points at the iteration instead, so +// the job's page can find its calls (`locateJobModelLog`). +// +// SERVER-ONLY. + +import { mkdir, readFile, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +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">; + +export function jobModelLogDir(paths: UsagePaths, jobId: string): string { + 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); +} + +export function jobModelLogFiles(paths: UsagePaths, jobId: string): ModelLogFiles { + return modelLogFilesIn(jobModelLogDir(paths, jobId)); +} + +export const WHERE_FILE = "where.json"; + +type JobFn<R> = (onLog: (line: string) => void, signal: AbortSignal, setProgress: any, ctx: { jobId: string }) => Promise<R>; + +// The job's `fn`, run inside its own model log; when it ends, its local calls +// go to the usage ledger (route "local", cost 0) — API spend is recorded by +// each job as before, never here. +export function modelLogged<R>(o: { paths: UsagePaths; task: string; model?: string }, fn: JobFn<R>): JobFn<R> { + return async (onLog, signal, setProgress, ctx) => { + const writer = new ModelLogWriter({ + files: jobModelLogFiles(o.paths, ctx.jobId), + task: o.task, + jobId: ctx.jobId, + ...(o.model ? { model: o.model } : {}), + scrub: processScrub([path.dirname(o.paths.generationUsageFile)]), + log: onLog, + }); + const tally: LocalCallTally = new Map(); + const dir = jobModelLogDir(o.paths, ctx.jobId); + let pointed: Promise<void> | null = null; + const onInner = (where: InnerLogWhere) => { + pointed ??= mkdir(dir, { recursive: true }) + .then(() => writeFile(path.join(dir, WHERE_FILE), `${JSON.stringify({ v: 1, article: where.article, n: where.iteration })}\n`)) + .catch((e) => onLog(`model log pointer not kept: ${(e as Error).message}`)); + }; + try { + return await runWithModelLog(writer, () => fn(onLog, signal, setProgress, ctx), { tally, onInner }); + } finally { + await writer.flush(); + await pointed; + await appendLocalUsage(o.paths, ctx.jobId, tally).catch((e) => onLog(`local usage not recorded: ${(e as Error).message}`)); + } + }; +} + +export async function appendLocalUsage(paths: UsagePaths, jobId: string, tally: LocalCallTally, now: Date = new Date()): Promise<void> { + const rows: GenerationUsageRow[] = [...tally.values()].map((t) => ({ + at: now.toISOString(), + day: utcDay(now), + jobId, + article: t.article, + iteration: t.iteration, + task: t.task, + model: t.model, + inputTokens: t.tokensIn, + outputTokens: t.tokensOut, + cacheReadTokens: 0, + cacheWriteTokens: 0, + usd: 0, + route: "local", + calls: t.calls, + })); + await appendGenerationUsage(paths.generationUsageFile, rows); +} + +// Where a job's calls are: its own log, else the iteration its pointer names +// (checked: that log holds a run of this job). Null: none recorded (yet). +export async function locateJobModelLog( + paths: UsagePaths & { articlesDir: string; exportIndexDir: string }, + jobId: string, +): Promise<{ files: ModelLogFiles; where: { article: string; n: number } | null } | null> { + const own = jobModelLogFiles(paths, jobId); + if (await stat(own.calls).then(() => true, () => false)) return { files: own, where: null }; + const raw = await readFile(path.join(jobModelLogDir(paths, jobId), WHERE_FILE), "utf8").catch(() => null); + if (!raw) return null; + let w: { article?: unknown; n?: unknown }; + try { + w = JSON.parse(raw); + } catch { + 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; + return { files, where: { article: w.article, n: w.n as number } }; +} diff --git a/common/controller/landMedia.ts b/common/controller/landMedia.ts @@ -59,6 +59,7 @@ import { loadSavedVideo, persistSourceVideo } from "../lib/savedVideo-server"; import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; import { ffmpegRemux } from "./preparePlayable"; import { transcodeAudio } from "./transcode"; +import "../lib/childKillGuard"; // Free space the store's disk keeps beyond the file (attach-media's margin). export const LAND_MEDIA_DISK_MARGIN_BYTES = 2 * 1024 ** 3; diff --git a/common/controller/preparePlayable.ts b/common/controller/preparePlayable.ts @@ -55,6 +55,7 @@ import { type PlayableEntry, type PlayableManifest, } from "../lib/playableMedia"; +import "../lib/childKillGuard"; // The creation date every torrent carries: fixed, so the same copy makes the // same .torrent file byte for byte (the infohash never depended on it). diff --git a/common/controller/proposeGroups.ts b/common/controller/proposeGroups.ts @@ -21,6 +21,7 @@ // `@@report-draft {article: "", iteration: 0, task: "propose-groups", // project, status, summary, usd, groups: {at, proposed, refused, file}}`. +import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; @@ -82,7 +83,7 @@ export async function enqueueProposeGroups(body: ReportDraftBody, deps: ReportDr kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, - fn: async (onLog, signal, setProgress, ctx) => { + fn: modelLogged({ paths, task: "propose-groups" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); @@ -158,7 +159,7 @@ export async function enqueueProposeGroups(body: ReportDraftBody, deps: ReportDr ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (out.status === "failed") throw new Error(out.summary); - }, + }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -104,6 +104,7 @@ import { findVideoSourceUrl } from "./undownloadedVideos"; import { jitterYtdlpSleeps } from "../lib/jitter"; import { parsePreclipKnob, type PreclipOptions } from "../lib/livePreclip"; import { jitterMs } from "../lib/jitter"; +import "../lib/childKillGuard"; export const RECORD_LIVE_JOB_KIND = "record-live"; export const RECORD_LIVE_RESULT_MARKER = "@@record-live "; diff --git a/common/controller/relocateDir.ts b/common/controller/relocateDir.ts @@ -21,6 +21,7 @@ import type { RelocationMarker, RelocationPhase, } from "../lib/channelMedia"; +import "../lib/childKillGuard"; // MOVING A DIRECTORY TO ANOTHER DRIVE AND LEAVING A SYMLINK — the mechanism, // with no opinion about whose directory it is. diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -60,6 +60,7 @@ // The corpus tools come in from the caller (`deps.corpusTools`): they are the // MCP's, and common cannot import the mcp package. +import { modelLogged } from "./jobModelLog"; import os from "node:os"; import { projectsRootFrom } from "../lib/projectsRoot.mjs"; import { originOfHandle } from "../lib/remoteArchives"; @@ -763,7 +764,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, - fn: (onLog, signal, setProgress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal, setProgress }, deps), + fn: modelLogged({ paths, task: "report-draft" }, (onLog, signal, setProgress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal, setProgress }, deps)), }); if (!result.ok) { if (!isStepTask(body.task)) await updateIteration(body.article, n, { status: "failed", error: result.error }, paths).catch(() => {}); diff --git a/common/controller/reportLearn.ts b/common/controller/reportLearn.ts @@ -19,6 +19,7 @@ // when a pass is due — never proposed, terms changed, or a week since the last // (controller/reportTick.ts learnStep). +import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { getRegistry } from "../jobs/registry"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; @@ -140,7 +141,7 @@ export async function enqueueLearn(id: string, trigger: LearnTrigger, deps: Repo kind: REPORT_DRAFT_JOB_KIND, queueKey: plan.provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, - fn: (onLog, signal, _setProgress, ctx) => runLearnJob({ id, trigger, plan, maxUsd, jobId: ctx.jobId, onLog, signal }, deps), + fn: modelLogged({ paths, task: "learn" }, (onLog, signal, _setProgress, ctx) => runLearnJob({ id, trigger, plan, maxUsd, jobId: ctx.jobId, onLog, signal }, deps)), }); if (!result.ok) return { ok: false, error: result.error, plan }; return { ok: true, jobId: result.jobId, plan, result: result as Extract<StreamActionResult, { ok: true }> }; diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts @@ -21,6 +21,7 @@ // The iteration refreshed: `iteration` when given, else the current report's // (current.json), else the newest done iteration that carries a report. +import { modelLogged } from "./jobModelLog"; import { access, readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; @@ -263,7 +264,7 @@ export async function enqueueRefresh(body: ReportDraftBody, deps: ReportDraftDep kind: REPORT_DRAFT_JOB_KIND, queueKey: DRAFT_REFRESH_QUEUE, paths, - fn: (onLog, signal, setProgress, ctx) => runRefreshJob({ body, n: it.n, model: m.model, capUsd: m.capUsd, extractor: m.extractor, jobId: ctx.jobId, onLog, signal, setProgress }, deps), + fn: modelLogged({ paths, task: "refresh" }, (onLog, signal, setProgress, ctx) => runRefreshJob({ body, n: it.n, model: m.model, capUsd: m.capUsd, extractor: m.extractor, jobId: ctx.jobId, onLog, signal, setProgress }, deps)), }); if (!result.ok) { await updateIteration(body.article, it.n, { status: "failed", error: result.error }, paths).catch(() => {}); diff --git a/common/controller/reportTriage.ts b/common/controller/reportTriage.ts @@ -22,6 +22,7 @@ // `ids` (the candidates, named: no scan), `windows` ({id: [{start, end}]}), // `maxCandidates`, `model`, `maxUsd`, `source`/`build`. +import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { JobProgress } from "../jobs/registry"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; @@ -99,7 +100,7 @@ export async function enqueueTriage(body: ReportDraftBody, deps: ReportDraftDeps kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, - fn: (onLog, signal, setProgress, ctx) => runTriageJob({ body, k, model, provider, maxUsd, jobId: ctx.jobId, onLog, signal, setProgress }, deps), + fn: modelLogged({ paths, task: "triage" }, (onLog, signal, setProgress, ctx) => runTriageJob({ body, k, model, provider, maxUsd, jobId: ctx.jobId, onLog, signal, setProgress }, deps)), }); const mark = async (patch: Partial<TriageFile>) => { const cur = await readTriageFile(body.article, k, paths).catch(() => null); diff --git a/common/controller/reportVerdicts.ts b/common/controller/reportVerdicts.ts @@ -21,6 +21,7 @@ // through patchArticle, reject marks the proposal only // (lib/report/verdictProposals.ts). +import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; @@ -66,7 +67,7 @@ export async function enqueueVerdictProposals(body: ReportDraftBody, deps: Repor kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, - fn: async (onLog, signal, setProgress, ctx) => { + fn: modelLogged({ paths, task: "verdicts" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { // Again at the job's turn: jobs ahead in the queue may have spent the day. @@ -144,7 +145,7 @@ export async function enqueueVerdictProposals(body: ReportDraftBody, deps: Repor })}`, ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); - }, + }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; diff --git a/common/controller/scanCorruptMedia.ts b/common/controller/scanCorruptMedia.ts @@ -70,6 +70,7 @@ import { type MediaScanReport, type MediaScanVerdict, } from "../lib/mediaScan"; +import "../lib/childKillGuard"; const MEDIA_EXT_SET = new Set(MEDIA_EXTS); diff --git a/common/controller/transcode.ts b/common/controller/transcode.ts @@ -4,6 +4,7 @@ import { execa } from "execa"; import type { Paths } from "../lib/paths"; import type { AudioFormat } from "../lib/channelConfig"; import { tierMediaFile } from "../lib/mediaTier-server"; +import "../lib/childKillGuard"; const CODEC_ARGS: Record<AudioFormat, string[]> = { m4a: ["-c:a", "aac"], diff --git a/common/controller/transcribeFile.ts b/common/controller/transcribeFile.ts @@ -61,6 +61,7 @@ import { type StreamActionResult, } from "../jobs/streamCommand"; import { transcribeWithWorker } from "./transcribeOne"; +import "../lib/childKillGuard"; export const TRANSCRIBE_FILE_JOB_KIND = "transcribe-file"; diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts @@ -42,6 +42,7 @@ import { import { writeFileAtomic } from "../lib/jsonFile-server"; import { probeMedia } from "../lib/evidenceClip-server"; import { savedWindowSource } from "../lib/savedVideoWindow-server"; +import "../lib/childKillGuard"; const { pathExists, readdir, rename } = fs; diff --git a/common/controller/ttsFile.ts b/common/controller/ttsFile.ts @@ -61,6 +61,7 @@ import { copyFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server"; import { getSettings } from "../lib/settings"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { corpusRootContaining, corpusRoots, realpathDeep } from "./transcribeFile"; +import "../lib/childKillGuard"; export const TTS_FILE_JOB_KIND = "tts-file"; diff --git a/common/controller/ttsServer.ts b/common/controller/ttsServer.ts @@ -27,6 +27,7 @@ import { createWriteStream, existsSync, type WriteStream } from "node:fs"; import net from "node:net"; import path from "node:path"; import type { TtsServerCommand } from "../lib/ttsApps"; +import "../lib/childKillGuard"; export type TtsServerHandle = { url: string; release: () => void }; diff --git a/common/controller/videoAssist.ts b/common/controller/videoAssist.ts @@ -24,6 +24,7 @@ // `video-assist`). The log ends `@@report-draft {article: "", iteration: 0, // task: "video-assist", project, status, summary, usd, assist}`. +import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; @@ -136,7 +137,7 @@ export async function enqueueVideoAssist(body: ReportDraftBody, deps: VideoAssis kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, - fn: async (onLog, signal, setProgress, ctx) => { + fn: modelLogged({ paths, task: "video-assist" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); @@ -219,7 +220,7 @@ export async function enqueueVideoAssist(body: ReportDraftBody, deps: VideoAssis ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (out.status === "failed") throw new Error(out.summary); - }, + }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; diff --git a/common/controller/voiceFile.ts b/common/controller/voiceFile.ts @@ -88,6 +88,7 @@ import { getSettings } from "../lib/settings"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { corpusRootContaining, corpusRoots, realpathDeep } from "./transcribeFile"; import { enqueueTtsFile, resolveTtsRequest, ttsCacheKey } from "./ttsFile"; +import "../lib/childKillGuard"; export const VOICE_JOB_KIND: Record<VoiceOp, string> = { enhance: "voice-enhance", convert: "voice-convert" }; diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -402,10 +402,13 @@ class JobRegistry { job.abortController?.abort(); // Also abort the drain signal so any code awaiting a drain unblocks. job.drainController?.abort(); - if (job.child) { + // A child with no pid never started (its spawn failed): Node would + // signal this process's own group (lib/childKillGuard.ts). This module + // stays free of node imports, so the check is made here. + if (job.child && job.child.pid !== undefined) { job.child.kill("SIGTERM"); setTimeout(() => { - if (job.child && !job.child.killed) job.child.kill("SIGKILL"); + if (job.child && job.child.pid !== undefined && !job.child.killed) job.child.kill("SIGKILL"); }, 5_000).unref?.(); } return true; @@ -428,7 +431,7 @@ class JobRegistry { if (job) { job.abortController?.abort(); job.drainController?.abort(); - if (job.child && !job.child.killed) job.child.kill("SIGKILL"); + if (job.child && job.child.pid !== undefined && !job.child.killed) job.child.kill("SIGKILL"); if (job.status === "queued" || job.status === "running") { job.status = "cancelled"; job.endedAt = Date.now(); diff --git a/common/jobs/runChild.ts b/common/jobs/runChild.ts @@ -1,4 +1,5 @@ import { execa, type ResultPromise } from "execa"; +import "../lib/childKillGuard"; export type RunChildOpts = { command: string; diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -2,6 +2,7 @@ import path from "node:path"; import { mkdir } from "node:fs/promises"; import { createWriteStream, type WriteStream } from "node:fs"; import { execa } from "execa"; +import "../lib/childKillGuard"; import { getRegistry, newJobId, diff --git a/common/lib/archiveOrgTorrent-server.ts b/common/lib/archiveOrgTorrent-server.ts @@ -34,6 +34,7 @@ import { type ParsedTorrent, type TorrentFileEntry, } from "./archiveOrgTorrent"; +import "./childKillGuard"; // ─── Is aria2c here? ─── diff --git a/common/lib/childKillGuard.fixture.ts b/common/lib/childKillGuard.fixture.ts @@ -0,0 +1,75 @@ +// The fixture of childKillGuard.test.ts: run DETACHED (a process group of its +// own), it kills a child whose spawn failed and reports who was signalled — +// itself, and a sibling in its group. `guard` or `noguard`, then the case. +import { spawn } from "node:child_process"; +import os from "node:os"; +import path from "node:path"; + +const [guard, mode] = process.argv.slice(2); +if (guard === "guard") await import("./childKillGuard"); +const { execa } = await import("execa"); + +let selfSigterm = 0; +process.on("SIGTERM", () => { + selfSigterm++; +}); +let canarySignal: string | null = null; +const canary = spawn("sleep", ["30"], { stdio: "ignore" }); // same group as this process +canary.on("exit", (_c, s) => { + canarySignal = s; +}); +await new Promise((r) => setTimeout(r, 150)); + +// A directory that does not exist (nothing ever makes it). +const missing = path.join(os.tmpdir(), "archilyzer-child-kill-guard-no-such-dir", "gone"); +const notes: Record<string, unknown> = {}; +if (mode === "spawn-kill") { + const c = spawn("sleep", ["5"], { cwd: missing }); + c.on("error", () => {}); + notes.pid = c.pid ?? null; + notes.killed = c.kill("SIGTERM"); +} else if (mode === "execa-aborted") { + const ac = new AbortController(); + ac.abort(); + const p = execa("sleep", ["5"], { cwd: missing, cancelSignal: ac.signal, reject: false }); + notes.pid = p.pid ?? null; + const r = await p; + notes.failed = r.failed; +} else if (mode === "execa-kill") { + const p = execa("sleep", ["5"], { cwd: missing, reject: false }); + notes.pid = p.pid ?? null; + notes.killed = p.kill("SIGTERM"); + await p; +} else if (mode === "launcher-abort-after") { + // The download launcher over a channel directory that is gone, cancelled in + // the same tick it launched. + const { runOneYtdlp } = await import("../ytdlp/runOneYtdlp"); + const ac = new AbortController(); + const run = runOneYtdlp({ ytdlpBin: "sleep", onLog: () => {}, signal: ac.signal }, missing, ["5"]); + ac.abort(); + notes.outcome = await run; +} else if (mode === "launcher-aborted-before") { + // Already cancelled when asked to launch: nothing is spawned at all. + const { runOneYtdlp } = await import("../ytdlp/runOneYtdlp"); + const ac = new AbortController(); + ac.abort(); + const said: string[] = []; + notes.outcome = await runOneYtdlp({ ytdlpBin: "sleep", onLog: (l) => said.push(l), signal: ac.signal }, missing, ["5"]); + notes.said = said.length; +} else if (mode === "launcher-aborted-by-log") { + // Cancelled by the log sink, on the launch line itself. + const { runOneYtdlp } = await import("../ytdlp/runOneYtdlp"); + const ac = new AbortController(); + notes.outcome = await runOneYtdlp({ ytdlpBin: "sleep", onLog: () => ac.abort(), signal: ac.signal }, missing, ["5"]); +} else if (mode === "started-child") { + // The guard leaves a real child alone: it is killed as before. + const c = spawn("sleep", ["30"], { stdio: "ignore" }); + await new Promise((r) => setTimeout(r, 100)); + notes.killed = c.kill("SIGTERM"); + notes.signal = await new Promise((r) => c.on("exit", (_c, s) => r(s))); +} +await new Promise((r) => setTimeout(r, 400)); +const out = { selfSigterm, canarySignal, ...notes }; +canary.kill("SIGKILL"); +console.log(JSON.stringify(out)); +process.exit(0); diff --git a/common/lib/childKillGuard.test.ts b/common/lib/childKillGuard.test.ts @@ -0,0 +1,129 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// Run with: pnpm -C common exec tsx --test lib/childKillGuard.test.ts +// +// A kill on a child whose spawn FAILED signals the caller's own process group +// on Node (lib/childKillGuard.ts): the guard makes it a no-op. Each case runs +// in a detached fixture — a group of its own, so a signal to "the group" +// reaches the fixture and its canary, never this test runner. + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const COMMON = path.resolve(HERE, ".."); +const FIXTURE = path.join(HERE, "childKillGuard.fixture.ts"); + +type Report = { selfSigterm: number; canarySignal: string | null; pid?: number | null; killed?: boolean; signal?: string; outcome?: unknown }; + +function detached(guard: "guard" | "noguard", mode: string): Promise<Report> { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [...process.execArgv, FIXTURE, guard, mode], { cwd: COMMON, detached: true, stdio: ["ignore", "pipe", "pipe"] }); + let out = ""; + let err = ""; + child.stdout.on("data", (c: Buffer) => (out += c.toString("utf8"))); + child.stderr.on("data", (c: Buffer) => (err += c.toString("utf8"))); + const timer = setTimeout(() => { + try { + process.kill(-child.pid!, "SIGKILL"); + } catch { + /* gone */ + } + }, 60_000); + child.on("exit", (code, signal) => { + clearTimeout(timer); + const line = out.trim().split("\n").pop() ?? ""; + try { + resolve(JSON.parse(line) as Report); + } catch { + reject(new Error(`fixture ${guard} ${mode} ended ${code ?? signal} with nothing readable: ${out}\n${err}`)); + } + }); + }); +} + +for (const mode of ["spawn-kill", "execa-aborted", "execa-kill", "launcher-abort-after"]) { + test(`a failed spawn followed by a kill signals nothing: ${mode}`, async () => { + const r = await detached("guard", mode); + assert.equal(r.selfSigterm, 0, `the caller was signalled: ${JSON.stringify(r)}`); + assert.equal(r.canarySignal, null, `a sibling in the caller's group was signalled: ${JSON.stringify(r)}`); + if ("pid" in r) assert.equal(r.pid, null, "the spawn failed: no pid"); + if ("killed" in r) assert.equal(r.killed, false, "the kill says it did nothing"); + }); +} + +// The launcher's own rule, WITHOUT the guard: yt-dlp is never launched for a +// run that is already cancelled, so execa is never handed an aborted signal. +for (const mode of ["launcher-aborted-before", "launcher-aborted-by-log"]) { + test(`a cancelled run launches nothing, guard or no guard: ${mode}`, async () => { + const r = (await detached("noguard", mode)) as Report & { said?: number }; + assert.equal(r.selfSigterm, 0, JSON.stringify(r)); + assert.equal(r.canarySignal, null, JSON.stringify(r)); + assert.deepEqual(r.outcome, { exitCode: null, stderrTail: "", archiveLine: null, formatLine: null }); + if (mode === "launcher-aborted-before") assert.equal(r.said, 0, "not even the launch line is logged"); + }); +} + +test("the hazard the guard is for, on this Node: without it the same kill reaches the caller's group", async (t) => { + const r = await detached("noguard", "spawn-kill"); + // Informational when a later Node guards it itself: the guard is then idle, not wrong. + if (r.selfSigterm === 0 && r.canarySignal === null) { + t.diagnostic(`Node ${process.version} no longer signals the group for an unspawned child`); + return; + } + assert.ok(r.selfSigterm > 0 || r.canarySignal === "SIGTERM", JSON.stringify(r)); +}); + +test("a child that started is killed as before", async () => { + const r = await detached("guard", "started-child"); + assert.equal(r.killed, true); + assert.equal(r.signal, "SIGTERM"); + assert.equal(r.selfSigterm, 0); + assert.equal(r.canarySignal, null); +}); + +// Every module of common/ that hands a child a `cancelSignal` or calls +// `.kill()` on one installs the guard by importing it. jobs/registry.ts is the +// one exception: it carries no node import (Next analyses it for the edge +// bundle) and checks the pid at its three kills instead. +const EXEMPT = new Set(["jobs/registry.ts", "lib/childKillGuard.ts", "lib/childKillGuard.fixture.ts"]); +async function sources(dir: string, out: string[] = []): Promise<string[]> { + for (const e of await readdir(dir, { withFileTypes: true })) { + if (e.name === "node_modules" || e.name.startsWith(".")) continue; + const p = path.join(dir, e.name); + if (e.isDirectory()) await sources(p, out); + else if (/\.(ts|tsx|mts)$/.test(e.name) && !/\.test\.|\.d\.ts$/.test(e.name)) out.push(p); + } + return out; +} + +test("every module of common/ that cancels or kills a child imports the guard", async () => { + const missing: string[] = []; + let spawners = 0; + for (const file of await sources(COMMON)) { + const rel = path.relative(COMMON, file); + const text = await readFile(file, "utf8"); + const code = text + .split("\n") + .filter((l) => !/^\s*(\/\/|\*|\/\*)/.test(l)) + .join("\n") + .replace(/process\.kill\(/g, ""); + if (!/cancelSignal\s*[:,}]|\w\??\.kill\(/.test(code)) continue; + spawners++; + if (EXEMPT.has(rel)) continue; + if (!/^import "(\.\.?\/)+(lib\/)?childKillGuard";$/m.test(text)) missing.push(rel); + } + assert.ok(spawners > 30, `the scan found the spawning modules (${spawners})`); + assert.deepEqual(missing, [], "import \"…/lib/childKillGuard\" in each"); +}); + +test("jobs/registry.ts checks the pid at every kill (it cannot import the guard)", async () => { + const text = await readFile(path.join(COMMON, "jobs/registry.ts"), "utf8"); + const kills = text.split("\n").filter((l) => /job\.child\.kill\(/.test(l) && !/^\s*\/\//.test(l)); + assert.equal(kills.length, 3); + // Each kill is on a line, or inside a block, that names the pid check. + const guarded = text.match(/job\.child\.pid !== undefined/g) ?? []; + assert.equal(guarded.length, 3); +}); diff --git a/common/lib/childKillGuard.ts b/common/lib/childKillGuard.ts @@ -0,0 +1,42 @@ +// A KILL ON A CHILD THAT NEVER STARTED IS A NO-OP — process-wide. +// +// Node's ChildProcess.kill() is `this._handle.kill(signal)` with no look at +// `this.pid`. When a spawn FAILS (the binary is not there, the cwd is gone) +// Node keeps the handle until the next tick, with no pid in it, and a kill in +// that window signals pid 0: THE CALLER'S OWN PROCESS GROUP. Verified on Node +// 22.23.5 (12 Nov 2026) with a group leader, a missing cwd and +// · spawn(...).kill("SIGTERM") in the same tick, +// · execa(..., { cancelSignal }) with a signal that is already aborted, +// · execa(...).kill("SIGTERM") in the same tick: +// in each the caller and a sibling in its group received SIGTERM, and with +// the same aborted signal and a cwd that exists, neither did. That is what +// took the editor's test server down (and pnpm with it, "Command failed with +// signal SIGTERM") whenever a download was cancelled while its channel +// directory was being removed — and it would do the same to a live editor. +// +// execa kills from inside itself (cancelSignal, timeout, forceKillAfterDelay), +// so no call site can guard that: the guard is on the prototype. Importing +// this module installs it; every module of common/ that spawns with a +// `cancelSignal` or calls `.kill()` on a child imports it (the test +// lib/childKillGuard.test.ts holds them to it). Idempotent, and per process: +// the mark is on the prototype, which Next's two module graphs share. + +import { ChildProcess } from "node:child_process"; + +const MARK = Symbol.for("archilyzer.childKillGuard"); +type Guarded = { [MARK]?: true; kill: ChildProcess["kill"] }; + +export function installChildKillGuard(): void { + const proto = ChildProcess.prototype as unknown as Guarded; + if (proto[MARK]) return; + const kill = proto.kill; + proto.kill = function guardedKill(this: ChildProcess, signal?: NodeJS.Signals | number): boolean { + // No pid: the spawn failed (or has not happened). There is nothing to + // signal, and the handle would signal the group. + if (this.pid === undefined) return false; + return kill.call(this, signal); + }; + proto[MARK] = true; +} + +installChildKillGuard(); diff --git a/common/lib/clipWindowSync-server.ts b/common/lib/clipWindowSync-server.ts @@ -22,6 +22,7 @@ import { type ProbedWindowStream, type RecordedClipWindowSync, } from "./clipWindowSync"; +import "./childKillGuard"; // A window's streams, or null when they cannot be read. Injectable so tests // decide what a window holds without a real one. diff --git a/common/lib/digestApps.ts b/common/lib/digestApps.ts @@ -27,6 +27,7 @@ import { type DigestAppConfig, type DigestLane, } from "./digest"; +import "./childKillGuard"; // The lane type, the app ids and DigestAppConfig are defined in the client-safe // digest.ts and re-exported here, so settings.ts can consume them without diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -221,6 +221,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_TEST_ROUTES", audience: "test", default: "off", readBy: "editor/app/api/test/_guard.ts, editor/instrumentation.ts", doc: "`1` opens the editor's `/api/test/*` routes and marks a test server at boot. Set by `editor/playwright.config.ts` on its test server, and by nothing else." }, { name: "E2E_MODE", audience: "test", default: "`start`", readBy: "editor/playwright.config.ts, umtool/playwright.config.ts, scripts/e2e-stamp.mjs", doc: "`start`: the editor and umtool suites run against `next start` from a build `scripts/e2e-stamp.mjs` vouches for, rebuilt through the heavy slot when the tree moved. `dev`: against `next dev`, for iterating on one spec. The export and homepage suites always run `next dev` (static exports) and say so when asked for `start`." }, { name: "E2E_NEXT_DIST_DIR", audience: "test", default: "`.next`", readBy: "editor/next.config.ts, export/next.config.ts", doc: "The editor's build directory for the e2e suite's start mode (`.next/e2e`), so a test build never replaces the `.next` a running editor serves from. Set by `scripts/e2e-stamp.mjs` for its build and by `editor/playwright.config.ts` for its test server — and for the editor suite's export dev server (`.next/e2e-editor`), which then runs beside the export suite's own (Next allows one `next dev` per dist dir)." }, + { name: "E2E_MODEL_LOG_SHOTS", audience: "test", default: "unset (no screenshots)", readBy: "umtool/e2e/model-log.spec.ts, editor/e2e/report-draft.spec.ts", doc: "A directory: the model log's e2e (demo epic D3) saves its 1366×768 screenshots of the panel there — the run page live and done, a call opened, the Iterations tab, a media draft, the settings table, the editor's job page — for a lane's report. Unset, none is taken." }, { name: "E2E_DATA_ROOT", audience: "test", default: "the editor directory", readBy: "editor/package.json (dev:test, start:test), editor/e2e/testPaths.ts", doc: "Where the editor test server's data lives: `test-transcripts/`, `test-settings.json` and the disposable changelogs sit under it. The test server's scripts and the specs' `testPaths()` read the same variable, so they agree by construction. E2E_-prefixed, never TRANSCRIPTS_DIR: a `--share-data` worktree's `.worktree-env` points that at the real corpus." }, { name: "E2E_WORKERS", audience: "test", default: "1", readBy: "editor/playwright.config.ts (editor/e2e/servers.ts)", doc: "How many workers the editor suite runs, each with a server set of its own (editor, export dev server, Ollama stub) over its own data root (`editor/.e2e-workers/w<n>`): a number (up to 8), or `auto` — floor((MemAvailable − HEAVY_MIN_FREE_MB) / 1.5 GB), 1 to 3. Specs in `editor/e2e/serial.ts` run afterwards on one worker." }, { name: "E2E_SERIAL_LAST", audience: "test", default: "—", readBy: "editor/playwright.config.ts", doc: "Set by the editor suite's runner for its workers: `1` when the run is whole (no spec file or filter on the command line), so the @serial project runs last; `0` for a focused run, where Playwright would run a teardown project whole." }, diff --git a/common/lib/evidenceClip-server.ts b/common/lib/evidenceClip-server.ts @@ -57,6 +57,7 @@ import { resolveCorpusSource, } from "./evidenceClip.mjs"; import { resolveVideoDir } from "./videoDir-server.mjs"; +import "./childKillGuard"; // Bumped whenever the arguments below change what a clip looks like: it is in // every hash, so a new profile re-cuts rather than serving an old file. diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -196,3 +196,12 @@ test("claim groups for a cut (lane L4): local in every preset but api; a file fr } assert.equal(sanitizeGeneration({}).routes["propose-groups"], "local"); }); + +test("plannedModelOf (demo epic D3): a task's route and the model it will run on; code has none; a frame scan's vision model; the API needs a key", async () => { + const { plannedModelOf, sanitizeGeneration } = await import("./generationSettings"); + const gen = sanitizeGeneration({ routes: { sweep: "code", narrate: "local", "revise-report": "api", frames: "local" }, models: { api: "claude-sonnet-5-5", local: "qwen2.5:7b" } }); + assert.deepEqual(plannedModelOf(gen, "sweep"), { route: "code", model: null, needsKey: false }); + assert.deepEqual(plannedModelOf(gen, "narrate"), { route: "local", model: "qwen2.5:7b", needsKey: false }); + assert.deepEqual(plannedModelOf(gen, "revise-report"), { route: "api", model: "claude-sonnet-5-5", needsKey: true }); + assert.deepEqual(plannedModelOf(gen, "frames"), { route: "local", model: "qwen2.5vl:7b", needsKey: false }); +}); diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -406,6 +406,17 @@ function sanitizeVerdicts(v: unknown): GenerationVerdicts { return { bar: { agreement: frac(b.agreement), contradictedRecall: frac(b.contradictedRecall), notFoundRecall: frac(b.notFoundRecall) }, models, window }; } +// The model a task will run on as the policy stands (demo epic D3, the +// settings page's per-task row): its route's model — a frame scan's the +// vision model of its route — or none on `code` (a Claude Code session +// answers it). `needsKey`: the Claude API is called, so a key must be there. +export function plannedModelOf(gen: GenerationSettings, task: GenerationTask): { route: GenerationRoute; model: string | null; needsKey: boolean } { + const route = gen.routes[task]; + if (route === "code") return { route, model: null, needsKey: false }; + const model = task === "frames" ? (route === "api" ? gen.frames.apiModel : gen.frames.localModel) : route === "api" ? gen.models.api : gen.models.local; + return { route, model, needsKey: route === "api" }; +} + export function presetOf(routes: GenerationRoutes): GenerationPreset | "custom" { return GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => routes[t] === GENERATION_PRESETS[p][t])) ?? "custom"; } diff --git a/common/lib/livePreclip-server.ts b/common/lib/livePreclip-server.ts @@ -30,6 +30,7 @@ import { clipWindowFile, type ClipProvenance } from "./clipWindow"; import { clipWindowPath, writeClipProvenance, type ClipWindow } from "./clipWindow-server"; import { tmpPathFor } from "./jsonFile-server"; import { decodeSpan } from "./montage/voiceMatch.mjs"; +import "./childKillGuard"; export const liveTranscriptSidecar = sidecar(LIVE_TRANSCRIPT_FILENAME, sidecarField(coerceLiveTranscript), { indent: 0 }); export const livePreclipSidecar = sidecar(LIVE_PRECLIP_FILENAME, sidecarField(coerceLivePreclipState)); diff --git a/common/lib/llm/agent.ts b/common/lib/llm/agent.ts @@ -24,6 +24,7 @@ import { toolUsesOf, type ContentBlock, } from "./anthropic"; +import { lazyKeyRedactor, recordModelCall } from "./callLog-server"; import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig, type Provider } from "./config"; import type { Meter, Usage } from "./meter"; import { @@ -158,6 +159,33 @@ export function clip(v: unknown, max = TRANSCRIPT_RESULT_CHARS): unknown { const cut = (s: string, max: number) => s.length > max ? `${s.slice(0, max)}\n(cut at ${max} chars — narrow the call)` : s; +// A turn's new messages as the model log keeps them: the text sent, each tool +// result under the call it answers; an image or a server block by its kind. +export function messagesText(msgs: readonly { role: string; content?: unknown; tool_name?: unknown }[]): string { + const out: string[] = []; + for (const m of msgs) { + const c = m.content; + if (typeof c === "string") { + if (c.trim()) out.push(m.role === "tool" ? `[tool result: ${String(m.tool_name ?? "")}]\n${c}` : m.role === "user" ? c : `[${m.role}]\n${c}`); + continue; + } + if (!Array.isArray(c)) continue; + for (const b of c as ContentBlock[]) { + if (b.type === "text" && typeof b.text === "string") out.push(b.text); + else if (b.type === "tool_result") { + const inner = typeof b.content === "string" ? b.content : Array.isArray(b.content) ? (b.content as ContentBlock[]).map((x) => (typeof x.text === "string" ? x.text : `[${x.type}]`)).join("\n") : ""; + out.push(`[tool result]\n${inner}`); + } else out.push(`[${b.type}]`); + } + } + return out.join("\n\n"); +} + +// A turn's answer as the model log keeps it: its text, then each tool call. +function answerOf(text: string, calls: { name: string; input: unknown }[]): string { + return [text, ...calls.map((c) => `→ ${c.name} ${JSON.stringify(c.input ?? {})}`)].filter((x) => x && x.trim()).join("\n"); +} + function hasThinking(messages: { role: string; content: unknown }[]): boolean { return messages.some( (m) => @@ -323,13 +351,18 @@ async function runClaude(o: AgentOptions): Promise<AgentResult> { messagesTotal: messages.length, }); lastTools = toolsJson; + const fresh = messagesText(messages.slice(recorded)); recorded = messages.length; let res; const before = o.meter.usd; + 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: "api", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra, redact: (s) => client.redactText(s) }); try { res = await client.messages(body, { meter: o.meter, signal: o.signal }); } catch (err) { + turnRecord("", { error: (err as Error)?.message ?? String(err) }); if (isCancel(err, o.signal)) return run.finish(turn, lastText, "cancelled"); if (serverSearch && err instanceof AnthropicError && err.status === 400 && /web_search/.test(err.message)) { serverSearch = false; @@ -347,6 +380,7 @@ async function runClaude(o: AgentOptions): Promise<AgentResult> { const calls = toolUsesOf(res); const text = textOf(res); if (text) lastText = text; + turnRecord(answerOf(text, calls), { tokensIn: lastInput, tokensOut: Number(u.output_tokens) || 0 }); run.transcript.push({ kind: "response", turn, @@ -412,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 }, @@ -441,9 +477,14 @@ async function runLocal(o: AgentOptions): Promise<AgentResult> { let reply; const before = o.meter.usd; + 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: localRedact }); try { reply = await ollamaChat(cfg, { model: o.model, messages, tools, signal: o.signal }); } catch (err) { + turnRecord("", { error: (err as Error)?.message ?? String(err) }); if (isCancel(err, o.signal)) return run.finish(turn, lastText, "cancelled"); throw err; } @@ -459,6 +500,7 @@ async function runLocal(o: AgentOptions): Promise<AgentResult> { recorded = messages.length; const calls = toolCallsOf(msg); if (msg.content) lastText = msg.content; + turnRecord(answerOf(msg.content ?? "", calls), { tokensIn: reply.promptTokens, tokensOut: reply.evalTokens }); run.transcript.push({ kind: "response", turn, diff --git a/common/lib/llm/anthropic.ts b/common/lib/llm/anthropic.ts @@ -144,6 +144,20 @@ export function redact(text: string, key: string | undefined): string { return out; } +// A text with the configured key taken out, whatever route the text went to +// (the model log's records: a local prompt is scrubbed of it too). No key +// configured, or one that does not read: the text as it is. +export function keyRedactor(cfg: AnthropicConfig | undefined): (text: string) => string { + if (!cfg) return (t) => t; + let key: string | undefined; + try { + key = readApiKey(cfg); + } catch { + key = undefined; + } + return (t) => redact(t, key); +} + // ─── Errors ─── export class AnthropicError extends Error { @@ -249,6 +263,12 @@ export class AnthropicClient { return this.describe(); } + // A text with this client's key taken out (the model log's records): the + // key itself never leaves the client. + redactText(text: string): string { + return redact(text, this.#key); + } + private key(): string { this.#key ??= readApiKey(this.#cfg); return this.#key; diff --git a/common/lib/llm/callLog-server.ts b/common/lib/llm/callLog-server.ts @@ -0,0 +1,539 @@ +// THE MODEL LOG's writer and readers (demo epic D3; the shape is ./callLog.ts). +// +// A run opens a ModelLogWriter over its files and runs its body inside +// `runWithModelLog`; every model call under it — structuredAnswer on either +// provider, each turn of the agent loop, a Claude Code session's answer — goes +// through ONE function, `recordModelCall`, which finds the writer in the async +// context and appends the call. Outside a run (a test calling a task directly, +// a CLI run with no log) there is no writer and nothing is recorded. +// +// A RECORD NEVER FAILS THE RUN: every append is caught and the first failure +// logged once. Writes are queued one at a time, in order, per file, across +// every writer in the process (two media drafts on one iteration share its +// files), so a run's number and its call ids are allocated in order. +// +// SERVER-ONLY (node:async_hooks, node:fs). One storage and one queue per +// process, on globalThis (the house pattern: Next may load a module twice). + +import { AsyncLocalStorage } from "node:async_hooks"; +import { appendFile, mkdir, open, stat } from "node:fs/promises"; +import { createReadStream } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createInterface } from "node:readline"; +import { keyRedactor } from "./anthropic"; +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, + foldModelLogInto, + headOf, + newModelLogState, + outcomeOfItems, + SCRUB_MARGIN_CHARS, + scrubBounded, + scrubText, + type CallDecision, + type CallItem, + type CallOutcome, + type ModelCallRow, + type ModelCallText, + type ModelDecisionRow, + type ModelLog, + type ModelLogFullRow, + type ModelLogRunRow, + type ModelLogState, + type ModelRoute, + type Scrub, +} from "./callLog"; + +export type ModelLogFiles = { calls: string; text: string }; + +export const modelLogFilesIn = (dir: string): ModelLogFiles => ({ calls: path.join(dir, CALLS_FILE), text: path.join(dir, CALLS_TEXT_FILE) }); + +// ─── The per-file queue ─── + +const QUEUE_KEY = Symbol.for("archilyzer.modelLog.queues"); +function queues(): Map<string, Promise<unknown>> { + const g = globalThis as unknown as Record<symbol, Map<string, Promise<unknown>> | undefined>; + return (g[QUEUE_KEY] ??= new Map()); +} + +function enqueue<T>(file: string, op: () => Promise<T>): Promise<T> { + const q = queues(); + const prev = q.get(file) ?? Promise.resolve(); + const next = prev.then(op, op); + const tail = next.then( + () => undefined, + () => undefined, + ); + q.set(file, tail); + void tail.then(() => { + if (q.get(file) === tail) q.delete(file); + }); + return next; +} + +const compactJson = (v: unknown) => { + try { + return JSON.stringify(v) ?? ""; + } catch { + return String(v); + } +}; + +// 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 +// editor's WORKER_TOKEN, an API key and every other variable of the +// environment named like a credential (…TOKEN, …KEY, …SECRET, …PASSWORD, +// …COOKIE, …AUTH), the +// home directory, the checkout. +const SECRET_ENV_NAME = /(?:^|_)(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|CREDENTIALS?|COOKIES?|AUTH)$/i; +export function processScrub(extraRoots: readonly string[] = []): Scrub { + const env = process.env; + // 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 = /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'`<>()]+/gi; +// … nor the address a connection was refused at (ECONNREFUSED 10.0.0.5:11434). +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; + model: string; + route: ModelRoute; + // The text sent: the system prompt and the rest (the user turn, an agent + // turn's new messages). Never a header, a key or a URL. + system?: string; + prompt: string; + answer: unknown; + seconds: number; + tokensIn?: number; + tokensOut?: number; + error?: string; + decision?: CallDecision; + items?: CallItem[]; + // One call's own redaction (the API client's key), on top of the writer's. + redact?: (s: string) => string; +}; + +// What a caller holds to say, once code has used an answer, what it did. +// Handed to structuredAnswer as `call.slot`; a no-op when nothing recorded. +export class CallSlot { + #writer: ModelLogWriter | null = null; + #id: Promise<string | null> | null = null; + // The call's own redaction (the API client's key): what code says about the + // answer afterwards is scrubbed of it as the call was. + #redact: ((s: string) => string) | undefined; + bind(writer: ModelLogWriter, id: Promise<string | null>, redact?: (s: string) => string): void { + this.#writer = writer; + this.#id = id; + this.#redact = redact; + } + get recorded(): boolean { + return !!this.#writer; + } + // The call's decision (and its items'). Items alone: the decision is what + // they add up to. + decide(outcome: CallOutcome, why: string, items?: CallItem[]): void { + if (!this.#writer || !this.#id) return; + this.#writer.decide(this.#id, { outcome, why }, items, this.#redact); + } + items(items: CallItem[]): void { + if (!this.#writer || !this.#id || !items.length) return; + this.#writer.decide(this.#id, null, items, this.#redact); + } +} + +export class ModelLogWriter { + readonly files: ModelLogFiles; + readonly task: string; + readonly jobId: string | undefined; + readonly model: string | undefined; + readonly scrub: Scrub; + // The article and iteration the log is of, when it is an iteration's. + readonly where: { article: string; iteration: number } | undefined; + private readonly now: () => Date; + private readonly log: ((line: string) => void) | undefined; + private run: number | null = null; + private seq = 0; + 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; 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; + this.model = o.model; + this.scrub = o.scrub ?? processScrub(); + this.now = o.now ?? (() => new Date()); + this.log = o.log; + } + + private fail(err: unknown) { + if (!this.failed) this.log?.(`model log not kept: ${(err as Error)?.message ?? String(err)}`); + this.failed = true; + } + + private queue<T>(op: () => Promise<T>): Promise<T | null> { + const p = enqueue(this.files.calls, op).catch((err) => { + this.fail(err); + return null; + }); + this.pending = Promise.all([this.pending, p]); + return p; + } + + // 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 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`); + return this.run; + } + + // Starts the run now (its `run` row), so a page sees the run before its first call. + start(): Promise<number | null> { + 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); + }; + // 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", + id, + run, + at, + task: this.task, + phase: e.phase || this.task, + ...(e.label ? { label: bounded(e.label, 120).slice(0, 120) } : {}), + model: e.model, + route: e.route, + // What was sent and what came back, in characters (before the scrub). + promptChars: rawSystem.length + rawPrompt.length, + promptHead: headOf(prompt || system), + 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 : 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(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 < 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 + // 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`); + this.held++; + return id; + }); + } + + decide(id: Promise<string | null>, decision: CallDecision | null, items?: CallItem[], redact?: (s: string) => string): void { + const at = this.now().toISOString(); + 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 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: bounded(decision.why, WHY_CHARS) }) } : {}), + ...(b ? { items: b } : {}), + }; + await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); + }); + } + + // Every queued write, done (never rejects). + async flush(): Promise<void> { + let seen: Promise<unknown> | null = null; + while (seen !== this.pending) { + seen = this.pending; + await seen.catch(() => {}); + } + } +} + +// ─── The context ─── + +// A job's local calls, counted wherever they were recorded (its own log or an +// iteration's inside it): what the usage ledger is told when the job ends. +export type LocalCallTally = Map<string, { model: string; task: string; article: string; iteration: number; calls: number; tokensIn: number; tokensOut: number }>; + +// `onInner`: told where a nested log is (an iteration's, inside a job's own), +// so the job can say where its calls went. +export type InnerLogWhere = { article: string; iteration: number }; +type Ctx = { writer: ModelLogWriter; tally?: LocalCallTally; onInner?: (where: InnerLogWhere) => void }; +const ALS_KEY = Symbol.for("archilyzer.modelLog.context"); +function storage(): AsyncLocalStorage<Ctx> { + const g = globalThis as unknown as Record<symbol, AsyncLocalStorage<Ctx> | undefined>; + return (g[ALS_KEY] ??= new AsyncLocalStorage<Ctx>()); +} + +// A nested log takes the call (the innermost wins); the tally is the outer one's. +export function runWithModelLog<T>(writer: ModelLogWriter | null, fn: () => T, o: { tally?: LocalCallTally; onInner?: (where: InnerLogWhere) => void } = {}): T { + if (!writer) return fn(); + const outer = storage().getStore(); + const tally = o.tally ?? outer?.tally; + if (outer?.onInner && writer.where) { + try { + outer.onInner(writer.where); + } catch { + // a pointer never stops the run + } + } + return storage().run({ writer, ...(tally ? { tally } : {}), ...(o.onInner ? { onInner: o.onInner } : {}) }, fn); +} + +export function currentModelLog(): ModelLogWriter | null { + return storage().getStore()?.writer ?? null; +} + +// THE ONE RECORDING FUNCTION: every model call on every route comes here. +// Nothing is recorded outside a run's log; `slot` (when given) is bound to the +// call so the caller can say what code did with the answer. +export function recordModelCall(e: ModelCallEntry, slot?: CallSlot): void { + const ctx = storage().getStore(); + const w = ctx?.writer; + if (!w) return; + if (ctx.tally && e.route === "local") { + const key = `${e.model}\u0000${w.task}\u0000${w.where?.article ?? ""}\u0000${w.where?.iteration ?? 0}`; + const t = ctx.tally.get(key) ?? { model: e.model, task: w.task, article: w.where?.article ?? "", iteration: w.where?.iteration ?? 0, calls: 0, tokensIn: 0, tokensOut: 0 }; + t.calls++; + t.tokensIn += e.tokensIn ?? 0; + t.tokensOut += e.tokensOut ?? 0; + ctx.tally.set(key, t); + } + try { + const id = w.record(e); + slot?.bind(w, id, e.redact); + } catch { + // a record never stops the run + } +} + +// A Claude Code session's answer (the `code` route): the request the plan +// handed it, and what it posted. Its seconds are the session's, unknown here. +// `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: 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 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 +// into memory at once); null when it has none. +export async function readModelCallText(files: ModelLogFiles, id: string): Promise<ModelCallText | null> { + let stream: ReturnType<typeof createReadStream>; + try { + stream = createReadStream(files.text, { encoding: "utf8" }); + } catch { + return null; + } + const want = `"id":${JSON.stringify(id)}`; + try { + const rl = createInterface({ input: stream, crlfDelay: Infinity }); + for await (const line of rl) { + if (!line.includes(want)) continue; + try { + const r = JSON.parse(line) as ModelCallText; + if (r && r.v === MODEL_LOG_VERSION && r.id === id) { + rl.close(); + stream.destroy(); + return r; + } + } catch { + // a torn line + } + } + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") return null; + throw err; + } finally { + stream.destroy(); + } + return null; +} diff --git a/common/lib/llm/callLog.test.ts b/common/lib/llm/callLog.test.ts @@ -0,0 +1,448 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { startFakeAnthropic, textTurn, toolTurn, toolUseBlock, turn } from "../../testing/llm/fakeAnthropic.mjs"; +import { jsonReply, reply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs"; +import { runAgent } from "./agent"; +import { + CALLS_FILE, + CALLS_TEXT_FILE, + PROMPT_CAP_CHARS, + callMatches, + foldModelLog, + headOf, + phaseOrder, + scrubText, + summarizeCalls, + terminalSafe, + terminalSafeJson, +} from "./callLog"; +import { CallSlot, ModelLogWriter, modelLogFilesIn, processScrub, readModelCallText, readModelLog, recordModelCall, recordSessionAnswer, runWithModelLog } from "./callLog-server"; +import { Meter } from "./meter"; +import { structuredAnswer } from "./structured"; +import { modelLogView } from "./callLogView"; +import { plainAnswer } from "../report/draft/tasks/llmText"; + +// Run with: pnpm -C common exec tsx --test lib/llm/callLog.test.ts +// +// THE MODEL LOG (demo epic D3): every call on every route through ONE +// function, recorded in the run's files; a decision appended once code knows +// it; nothing recorded outside a run. + +const schema = { type: "object", properties: { terms: { type: "array", items: { type: "string" } } }, required: ["terms"] }; + +async function tmpLog(task = "sweep") { + const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); + const files = modelLogFilesIn(dir); + const writer = new ModelLogWriter({ files, task, jobId: "job-1", model: "qwen3:8b", scrub: {} }); + return { dir, files, writer, done: () => rm(dir, { recursive: true, force: true }) }; +} + +test("the rows: a run row first, then each call; a decision folded into its call; ids in order", async () => { + const t = await tmpLog(); + try { + const slot = new CallSlot(); + await runWithModelLog(t.writer, async () => { + recordModelCall({ phase: "terms", model: "qwen3:8b", route: "local", system: "Plan.", prompt: "Research question: ovens?", answer: { terms: ["oven"] }, seconds: 1.234, tokensIn: 40, tokensOut: 6 }, slot); + slot.decide("kept", "searched for oven", [{ text: "oven", outcome: "kept", why: "searched" }]); + recordModelCall({ phase: "reading", label: "extract a@0", model: "qwen3:8b", route: "local", system: "Read.", prompt: "line one\nline two\nline three\nline four", answer: { items: [] }, seconds: 2 }); + }); + await t.writer.flush(); + const raw = (await readFile(t.files.calls, "utf8")).trim().split("\n").map((l) => JSON.parse(l)); + assert.deepEqual(raw.map((r) => r.t), ["run", "call", "decision", "call"]); + assert.deepEqual([raw[0].run, raw[0].task, raw[0].jobId, raw[0].model], [1, "sweep", "job-1", "qwen3:8b"]); + const log = await readModelLog(t.files); + assert.deepEqual(log.calls.map((c) => c.id), ["1.1", "1.2"]); + const [a, b] = log.calls; + assert.deepEqual([a!.phase, a!.route, a!.seconds, a!.tokensIn, a!.tokensOut], ["terms", "local", 1.2, 40, 6]); + assert.deepEqual(a!.decision, { outcome: "kept", why: "searched for oven" }); + assert.deepEqual(a!.items, [{ text: "oven", outcome: "kept", why: "searched" }]); + assert.deepEqual(b!.decision, { outcome: "n/a", why: "" }); + assert.equal(b!.promptHead, "line one\nline two\nline three…", "the list's head: the first three lines"); + assert.equal(b!.label, "extract a@0"); + // The whole text, one row, by id. + const text = await readModelCallText(t.files, "1.2"); + assert.equal(text!.system, "Read."); + assert.equal(text!.prompt, "line one\nline two\nline three\nline four"); + assert.match(text!.answer, /"items"/); + assert.equal(await readModelCallText(t.files, "9.9"), null); + // A second writer on the same files is run 2. + const w2 = new ModelLogWriter({ files: t.files, task: "narrate", scrub: {} }); + await runWithModelLog(w2, async () => recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 0 })); + await w2.flush(); + const again = await readModelLog(t.files); + assert.deepEqual(again.runs.map((r) => [r.run, r.task]), [[1, "sweep"], [2, "narrate"]]); + assert.equal(again.calls.at(-1)!.id, "2.1"); + assert.equal(again.calls.at(-1)!.phase, "narrate", "no phase: the task's name"); + } finally { + await t.done(); + } +}); + +test("nothing is recorded outside a run, and a slot outside one is a no-op", async () => { + const slot = new CallSlot(); + recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 0 }, slot); + assert.equal(slot.recorded, false); + slot.decide("dropped", "nothing to say it to"); +}); + +test("caps: the prompt kept to 40k characters and said so; the row stays small", async () => { + const t = await tmpLog(); + try { + const big = "word ".repeat(20_000); + await runWithModelLog(t.writer, async () => recordModelCall({ model: "qwen3:8b", route: "local", system: "S", prompt: big, answer: big, seconds: 1 })); + await t.writer.flush(); + const [c] = (await readModelLog(t.files)).calls; + assert.equal(c!.promptChars, big.length + 1); + assert.ok(c!.promptHead.length <= 281); + const text = (await readModelCallText(t.files, c!.id))!; + assert.equal(text.system.length + text.prompt.length, PROMPT_CAP_CHARS); + assert.equal(text.promptCut, true); + assert.equal(text.answerCut, true); + assert.ok((await readFile(t.files.calls, "utf8")).length < 2_000, "calls.jsonl holds no whole prompt"); + } finally { + await t.done(); + } +}); + +test("the fold: a filter by outcome matches a call's items; phases in the sweep's order; the summary", () => { + const rows = [ + { v: 1, t: "run", run: 1, at: "x", task: "sweep" }, + { v: 1, t: "call", id: "1.1", run: 1, at: "x", task: "sweep", phase: "grouping", model: "qwen3:8b", route: "local", promptChars: 1, promptHead: "", answerChars: 1, answerHead: "", seconds: 3, decision: { outcome: "kept", why: "" } }, + { v: 1, t: "call", id: "1.2", run: 1, at: "x", task: "sweep", phase: "reading", model: "qwen3:8b", route: "local", promptChars: 1, promptHead: "", answerChars: 1, answerHead: "", seconds: 2, decision: { outcome: "n/a", why: "" } }, + { v: 1, t: "decision", call: "1.2", at: "x", items: [{ text: "q1", outcome: "kept", why: "verbatim" }, { text: "q2", outcome: "dropped", why: "not verbatim in its window" }] }, + { v: 2, t: "call", id: "future" }, + "not json", + ]; + const log = foldModelLog(rows.map((r) => (typeof r === "string" ? r : JSON.stringify(r))).join("\n")); + assert.equal(log.calls.length, 2, "a later version's row and a torn line are skipped"); + const reading = log.calls.find((c) => c.id === "1.2")!; + assert.equal(reading.decision.outcome, "kept", "items alone: the decision is what they add up to"); + assert.ok(callMatches(reading, { outcome: "dropped" })); + assert.ok(callMatches(reading, { outcome: "kept" })); + assert.ok(!callMatches(log.calls[0]!, { outcome: "dropped" })); + assert.deepEqual(phaseOrder(["grouping", "draft", "reading", "terms"]), ["terms", "reading", "grouping", "draft"]); + const s = summarizeCalls(log.calls); + assert.deepEqual([s.calls, s.seconds, s.models], [2, 5, [{ model: "qwen3:8b", route: "local", calls: 2 }]]); + assert.deepEqual(s.phases.map((p) => p.phase), ["reading", "grouping"]); + assert.equal(headOf(""), ""); +}); + +test("the one function on every route: structuredAnswer on ollama and on Claude, an agent's turns, the extractor, a Claude Code session", async () => { + const t = await tmpLog(); + const ol = await startFakeOllama({ turns: [jsonReply({ terms: ["oven"] }), reply("- a line"), reply("", { message: { role: "assistant", content: "done" } })] }); + const api = await startFakeAnthropic({ turns: [turn([toolUseBlock("answer", { terms: ["bread"] })]), toolTurn("lookup", { q: "oven" }), textTurn("all read")] }); + try { + const llm = { ollama: { baseUrl: ol.url }, anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }; + const meter = new Meter(); + const slot = new CallSlot(); + await runWithModelLog(t.writer, async () => { + await structuredAnswer({ llm, model: "qwen3:8b", system: "Plan.", user: "Ovens?", schema, meter, call: { phase: "terms", slot } }); + slot.decide("kept", "searched"); + await structuredAnswer({ llm, model: "claude-haiku-4-5", system: "Plan.", user: "Bread?", schema, meter, call: { phase: "terms", label: "api" } }); + await plainAnswer({ llm, model: "qwen3:8b", system: "Extract.", user: "the batch", meter, call: { phase: "reading" } }); + await runAgent({ + llm, + model: "claude-haiku-4-5", + system: "You research.", + user: "Go.", + meter, + tools: [{ name: "lookup", description: "look", inputSchema: { type: "object", properties: { q: { type: "string" } } }, run: async () => "the oven is hot" }], + }); + recordSessionAnswer({ phase: "assist", system: "Assist.", prompt: "make the joins 0.15 s", answer: { ops: [] } }); + }); + await t.writer.flush(); + const { calls } = await readModelLog(t.files); + assert.deepEqual( + calls.map((c) => [c.phase, c.route, c.model]), + [ + ["terms", "local", "qwen3:8b"], + ["terms", "api", "claude-haiku-4-5"], + ["reading", "local", "qwen3:8b"], + ["agent", "api", "claude-haiku-4-5"], + ["agent", "api", "claude-haiku-4-5"], + ["assist", "claude-code", "claude-code"], + ], + ); + assert.equal(calls[0]!.decision.outcome, "kept"); + assert.ok((calls[0]!.tokensIn ?? 0) > 0, "ollama's counts"); + assert.ok((calls[1]!.tokensIn ?? 0) > 0, "the API's usage"); + assert.match(calls[3]!.answerHead, /→ lookup/); + assert.match((await readModelCallText(t.files, calls[4]!.id))!.prompt, /\[tool result\]\nthe oven is hot/); + assert.equal((await readModelCallText(t.files, calls[3]!.id))!.system, "You research.", "turn 1 carries the system prompt"); + assert.match(calls[1]!.promptHead, /^Bread\?/); + } finally { + await ol.close(); + await api.close(); + await t.done(); + } +}); + +test("a failed call is recorded with its error, its decision n/a", async () => { + const t = await tmpLog(); + const ol = await startFakeOllama({ turns: [reply("not json"), reply("still not")] }); + try { + await runWithModelLog(t.writer, async () => { + await assert.rejects(structuredAnswer({ llm: { ollama: { baseUrl: ol.url } }, model: "qwen3:8b", system: "S", user: "U", schema })); + }); + await t.writer.flush(); + const [c] = (await readModelLog(t.files)).calls; + assert.match(c!.error ?? "", /no structured answer/); + assert.deepEqual(c!.decision, { outcome: "n/a", why: "the call failed" }); + assert.ok(CALLS_FILE && CALLS_TEXT_FILE); + } finally { + await ol.close(); + await t.done(); + } +}); + +test("the calls' text is bounded as a file: past the cap a call keeps its row, not its text, and the run is told once", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); + const files = modelLogFilesIn(dir); + const said: string[] = []; + const writer = new ModelLogWriter({ files, task: "sweep", scrub: {}, textMaxBytes: 3_000, log: (l) => said.push(l) }); + try { + const prompt = "word ".repeat(400); // 2,000 characters: one fits, the second does not + await runWithModelLog(writer, async () => { + for (let i = 0; i < 3; i++) recordModelCall({ model: "qwen3:8b", route: "local", prompt, answer: "ok", seconds: 1 }); + }); + await writer.flush(); + const { calls } = await readModelLog(files); + assert.equal(calls.length, 3, "every call has its row"); + assert.ok((await readModelCallText(files, calls[0]!.id)) !== null); + assert.equal(await readModelCallText(files, calls[1]!.id), null); + assert.equal(await readModelCallText(files, calls[2]!.id), null); + assert.ok((await readFile(files.text, "utf8")).length <= 3_000); + assert.equal(said.filter((l) => /text is full/.test(l)).length, 1); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a failed call's error names no host: the model's URL is taken out of it", async () => { + const t = await tmpLog(); + try { + await runWithModelLog(t.writer, async () => { + // Nothing listens on port 9 here: ollama's client names the base URL in its error. + await assert.rejects(structuredAnswer({ llm: { ollama: { baseUrl: "http://127.0.0.1:9" } }, model: "qwen3:8b", system: "S", user: "U", schema })); + }); + await t.writer.flush(); + const [c] = (await readModelLog(t.files)).calls; + assert.ok(c!.error, "the error is kept"); + assert.ok(!/127\.0\.0\.1/.test(await readFile(t.files.calls, "utf8")), "no host in calls.jsonl"); + assert.match(c!.error!, /<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]; + } +}); + +test("terminalSafe: a recorded text cannot drive a terminal -- ESC, C0, DEL, C1 and bidi controls are printed as escapes; \\n, \\t and ordinary text stay", () => { + assert.equal(terminalSafe("a\x1b[2Jb"), "a\\x1b[2Jb"); + assert.equal(terminalSafe("\x1b]0;title\x07"), "\\x1b]0;title\\x07"); + assert.equal(terminalSafe("over\rwritten\b\x00\x7f"), "over\\x0dwritten\\x08\\x00\\x7f"); + assert.equal(terminalSafe("c1 \u009b31m \u0090 \u009d"), "c1 \\x9b31m \\x90 \\x9d"); + assert.equal(terminalSafe("rtl \u202e \u2066 \u2028"), "rtl \\u202e \\u2066 \\u2028"); + const plain = "line one\n\ttabbed — “quoted” é 日本語 🙂"; + assert.equal(terminalSafe(plain), plain); + // Nothing a terminal acts on is left, whatever the input. + let all = ""; + for (let i = 0; i < 0x100; i++) all += String.fromCharCode(i); + assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/.test(terminalSafe(all))); +}); + +test("terminalSafeJson: printed JSON carries no DEL, C1 or bidi control, and parses to the same value", () => { + const v = { answer: "csi \u009b31m del \x7f esc \x1b[2J rtl \u202e\nnext\tline", n: 1 }; + const out = terminalSafeJson(JSON.stringify(v, null, 2)); + assert.ok(!/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u202e]/.test(out), out); + assert.deepEqual(JSON.parse(out), v); +}); + +test("what code says about an answer is scrubbed as the call was: the call's own redaction covers its decision and items", async () => { + const t = await tmpLog(); + try { + const KEY = "file-held-key-0123456789"; + const slot = new CallSlot(); + await runWithModelLog(t.writer, async () => { + recordModelCall({ model: "claude-haiku-4-5", route: "api", prompt: "p", answer: "a", seconds: 1, redact: (s) => s.split(KEY).join("[redacted]") }, slot); + slot.decide("dropped", `refused: echoed ${KEY}`, [{ text: `op ${KEY}`, outcome: "dropped", why: `why ${KEY}` }]); + }); + await t.writer.flush(); + const raw = await readFile(t.files.calls, "utf8"); + assert.ok(!raw.includes(KEY), raw); + assert.match(raw, /refused: echoed \[redacted\]/); + } finally { + await t.done(); + } +}); + +test("a failed call's error names no address: an IP and port, and a URL of any scheme, are taken out", async () => { + const t = await tmpLog(); + try { + await runWithModelLog(t.writer, async () => { + recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: null, seconds: 1, error: "connect ECONNREFUSED 192.168.1.44:11434 (also [fe80::1]:11434, ::1:11434, ws://gpu.lan:8080/x) after 3 tries" }); + }); + await t.writer.flush(); + const [c] = (await readModelLog(t.files)).calls; + assert.equal(c!.error, "connect ECONNREFUSED <host> (also <host>, <host>, <url>) after 3 tries"); + } finally { + await t.done(); + } +}); + +// ─── Review round (12 Nov): the log's own cap, a poll that reads what was appended, a lazy key ─── + +test("calls.jsonl is capped: past it one `full` row is written, no further call is recorded, the run is told once, and the view says so", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); + const files = modelLogFilesIn(dir); + const said: string[] = []; + const writer = new ModelLogWriter({ files, task: "sweep", scrub: {}, maxCalls: 3, log: (l) => said.push(l) }); + try { + const slots: CallSlot[] = []; + await runWithModelLog(writer, async () => { + for (let i = 0; i < 6; i++) { + const slot = new CallSlot(); + slots.push(slot); + recordModelCall({ model: "qwen3:8b", route: "local", prompt: `p${i}`, answer: "ok", seconds: 1 }, slot); + } + }); + await writer.flush(); + slots[5]!.decide("kept", "a decision on a call that was not recorded"); + slots[0]!.decide("kept", "after the log was full"); + await writer.flush(); + const log = await readModelLog(files); + assert.equal(log.calls.length, 3); + assert.equal(log.full, true); + assert.equal(log.calls[0]!.decision.outcome, "n/a", "a full log takes nothing more"); + const raw = (await readFile(files.calls, "utf8")).trim().split("\n").map((l) => JSON.parse(l)); + assert.deepEqual(raw.map((r) => r.t), ["run", "call", "call", "call", "full"]); + assert.equal((await readFile(files.text, "utf8")).trim().split("\n").length, 3, "no text for a call with no row"); + assert.equal(said.filter((l) => /model log: full/.test(l)).length, 1); + const view = modelLogView(log); + assert.equal(view.full, true); + assert.deepEqual(view.cap, { calls: 20_000, megabytes: 32 }); + // A later run on the same log finds it full and adds nothing but its run row. + const later = new ModelLogWriter({ files, task: "sweep", scrub: {}, maxCalls: 3 }); + await runWithModelLog(later, async () => recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 1 })); + await later.flush(); + assert.equal((await readModelLog(files)).calls.length, 3); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("the byte cap: a log past its size takes no further call", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); + const files = modelLogFilesIn(dir); + const writer = new ModelLogWriter({ files, task: "sweep", scrub: {}, maxBytes: 600 }); + try { + await runWithModelLog(writer, async () => { + for (let i = 0; i < 8; i++) recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p ".repeat(60), answer: "ok", seconds: 1 }); + }); + await writer.flush(); + const log = await readModelLog(files); + assert.equal(log.full, true); + assert.ok(log.calls.length >= 1 && log.calls.length < 8, String(log.calls.length)); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("a poll reads only what was appended: the fold continues, a half-written line waits, a replaced file is read again", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); + const files = modelLogFilesIn(dir); + const { appendFile, writeFile, open } = await import("node:fs/promises"); + const call = (id: string, run = 1) => JSON.stringify({ v: 1, t: "call", id, run, at: "2026-11-12T00:00:00.000Z", task: "sweep", phase: "terms", model: "m", route: "local", promptChars: 1, promptHead: "p", answerChars: 1, answerHead: "a", seconds: 1, decision: { outcome: "n/a", why: "" } }); + try { + await writeFile(files.calls, `${JSON.stringify({ v: 1, t: "run", run: 1, at: "2026-11-12T00:00:00.000Z", task: "sweep" })}\n${call("1.1")}\n`); + assert.deepEqual((await readModelLog(files)).calls.map((c) => c.id), ["1.1"]); + // Bytes already folded are not read again: overwrite them in place (same size) and append. + const fh = await open(files.calls, "r+"); + await fh.write("X", 0); + await fh.close(); + await appendFile(files.calls, `${call("1.2")}\n${JSON.stringify({ v: 1, t: "decision", call: "1.1", at: "x", decision: { outcome: "kept", why: "later" } })}\n${call("1.3").slice(0, 40)}`); + const second = await readModelLog(files); + assert.deepEqual(second.calls.map((c) => c.id), ["1.1", "1.2"], "the half line waits"); + assert.equal(second.runs.length, 1, "the first line was not read again (it no longer parses)"); + assert.equal(second.calls[0]!.decision.outcome, "kept", "a decision appended later lands on the call folded earlier"); + await appendFile(files.calls, `${call("1.3").slice(40)}\n`); + assert.deepEqual((await readModelLog(files)).calls.map((c) => c.id), ["1.1", "1.2", "1.3"]); + // A snapshot is the reader's own: a later fold does not grow it. + assert.equal(second.calls.length, 2); + // Replaced by a shorter file: read from its start. + await writeFile(files.calls, `${call("9.1", 9)}\n`); + assert.deepEqual((await readModelLog(files)).calls.map((c) => c.id), ["9.1"]); + await rm(files.calls); + assert.deepEqual(await readModelLog(files), { runs: [], calls: [] }); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("the API key is read for a record, never for a call: with no log open a structured call does not touch it", async () => { + const ol = await startFakeOllama({ turns: [jsonReply({ terms: ["a"] }), jsonReply({ terms: ["b"] })] }); + const t = await tmpLog(); + let reads = 0; + const env = new Proxy({} as Record<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 @@ -0,0 +1,436 @@ +// 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<string, string> = { 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-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 = 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 + [/(?<![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 + // — 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 <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}(?:[:=]|%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=… + [/(?<![A-Za-z0-9_])([A-Z][A-Z0-9_]{2,80})=([^\s"'&;,]{8,4096})/g, (m, name, value) => (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"), "<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 +// 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<string, unknown> => !!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<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; + 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<ModelLogQuery, "task" | "jobId">): ModelLogRunRow[] { + return log.runs.filter((r) => (!q.task || r.task === q.task) && (!q.jobId || r.jobId === q.jobId)); +} + +export function phaseOrder(phases: Iterable<string>): 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<CallOutcome, number>; + tokensIn: number; + tokensOut: number; +}; + +const round1 = (v: number) => Math.round(v * 10) / 10; + +export function summarizeCalls(calls: readonly ModelCall[]): ModelLogSummary { + const models = new Map<string, { model: string; route: ModelRoute; calls: number }>(); + const phases = new Map<string, { phase: string; calls: number; seconds: number }>(); + const outcomes: Record<CallOutcome, number> = { 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, + }; +} diff --git a/common/lib/llm/callLogPrivacy.test.ts b/common/lib/llm/callLogPrivacy.test.ts @@ -0,0 +1,325 @@ +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { 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 { SCRUB_MARGIN_CHARS, scrubBounded, scrubText } from "./callLog"; +import { ModelLogWriter, modelLogFilesIn, recordSessionAnswer, runWithModelLog } from "./callLog-server"; +import { Meter } from "./meter"; +import { structuredAnswer } from "./structured"; +import { plainAnswer } from "../report/draft/tasks/llmText"; + +// Run with: pnpm -C common exec tsx --test lib/llm/callLogPrivacy.test.ts +// +// THE MODEL LOG KEEPS THE TEXT SENT TO THE MODEL, AND NOTHING ELSE (demo epic +// D3, item 4): on every route a record holds no API key, no WORKER_TOKEN, no +// Authorization header's secret and no host path — even when the prompt +// itself carries them (a transcript can say anything). The secrets below are +// recognisable and injected into each prompt and answer to prove it. + +const TOKEN = "worker-token-0000-TEST-never-real"; +const HOST_PATH = path.join(os.homedir(), "Projects", "yt-dlp-transcript-browser", "transcripts", "reports", "a", "iteration.json"); +const POISON = `see ${HOST_PATH} and /home/someone/secret/file.txt; Authorization: Bearer ${TOKEN}; x-api-key: ${FAKE_KEY}`; +const schema = { type: "object", properties: { terms: { type: "array", items: { type: "string" } } }, required: ["terms"] }; + +let ol: FakeOllama; +let api: FakeAnthropic; +let saved: string | undefined; + +before(async () => { + saved = process.env.WORKER_TOKEN; + process.env.WORKER_TOKEN = TOKEN; + ol = await startFakeOllama({ turns: [jsonReply({ terms: [POISON] }), reply(POISON), reply("done")] }); + api = await startFakeAnthropic({ + turns: [turn([toolUseBlock("answer", { terms: [POISON] })]), textTurn(POISON), toolTurn("lookup", { q: POISON }), textTurn(`read: ${POISON}`)], + }); +}); + +after(async () => { + if (saved === undefined) delete process.env.WORKER_TOKEN; + else process.env.WORKER_TOKEN = saved; + await ol.close(); + await api.close(); +}); + +function assertClean(text: string, where: string) { + assert.ok(text.length > 0, `${where}: something was recorded`); + assert.ok(!text.includes(FAKE_KEY), `${where}: the API key`); + assert.ok(!text.includes(FAKE_KEY.slice(0, 16)), `${where}: a run of the API key`); + assert.ok(!text.includes(TOKEN), `${where}: the WORKER_TOKEN`); + assert.ok(!text.includes(os.homedir()), `${where}: the home directory`); + assert.ok(!text.includes("/home/someone"), `${where}: a host path`); + assert.ok(!text.includes(api.url) && !text.includes(ol.url), `${where}: the model host's URL`); +} + +test("every route's record holds no key, no WORKER_TOKEN and no host path", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-privacy-")); + try { + // An API config whose key is the fake's, read from the config's own env + // (never process.env): the client's redaction is what keeps it out. + const llm = { ollama: { baseUrl: ol.url }, anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY } } }; + const meter = new Meter(); + const routes: [string, () => Promise<unknown>][] = [ + ["local structured", () => structuredAnswer({ llm, model: "qwen3:8b", system: `System ${POISON}`, user: `User ${POISON}`, schema, meter })], + ["local extractor", () => plainAnswer({ llm, model: "qwen3:8b", system: "S", user: POISON, meter })], + ["local agent", () => runAgent({ llm, model: "qwen3:8b", system: POISON, user: POISON, meter, tools: [] })], + ["api structured", () => structuredAnswer({ llm, model: "claude-haiku-4-5", system: POISON, user: POISON, schema, meter })], + ["api extractor", () => plainAnswer({ llm, model: "claude-haiku-4-5", system: "S", user: POISON, meter })], + [ + "api agent", + () => + runAgent({ + llm, + model: "claude-haiku-4-5", + system: POISON, + user: POISON, + meter, + tools: [{ name: "lookup", description: "look", inputSchema: { type: "object", properties: { q: { type: "string" } } }, run: async () => `result ${POISON}` }], + }), + ], + ["claude-code", async () => recordSessionAnswer({ system: POISON, prompt: POISON, answer: { ops: [POISON] }, llm })], + ]; + for (const [name, call] of routes) { + const files = modelLogFilesIn(path.join(dir, name.replace(/\s+/g, "-"))); + // The process's scrub (WORKER_TOKEN from the environment, the home + // directory, the checkout), as every run's writer has it. + const w = new ModelLogWriter({ files, task: "sweep" }); + await runWithModelLog(w, call); + await w.flush(); + assertClean(await readFile(files.calls, "utf8"), `${name}: calls.jsonl`); + assertClean(await readFile(files.text, "utf8"), `${name}: calls-text.jsonl`); + // What was scrubbed is said, never dropped silently. + assert.match(await readFile(files.text, "utf8"), /\[secret\]|\[redacted\]/, `${name}: the secret is marked`); + assert.match(await readFile(files.text, "utf8"), /<path>/, `${name}: the path is marked`); + } + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + +test("scrubText: secrets and roots out, words of a transcript untouched", () => { + const s = { secrets: ["abcdefgh-secret"], roots: ["/srv/archive"] }; + assert.equal(scrubText("he said abcdefgh-secret at /srv/archive/x.json today", s), "he said [secret] at <path> today"); + assert.equal(scrubText("a short one: abc", { secrets: ["abc"] }), "a short one: abc", "a secret under 8 characters is not a secret"); + assert.equal(scrubText("the 5/10 split and and/or rules", s), "the 5/10 split and and/or rules"); + assert.equal(scrubText("files in /home/ann/.config/x", {}), "files in <path>"); +}); + +test("scrubText: a credential by its shape, whoever's it is -- the name stays, the value goes", () => { + const cases: [string, string, string[]][] = [ + ["fetch https://user:hunter2hunter2@ollama.lan:11434/api/chat now", "fetch https://[secret]@ollama.lan:11434/api/chat now", ["hunter2"]], + [ + "https://rr3.googlevideo.com/videoplayback?expire=1794&ei=abc&ip=203.0.113.77&id=o-AB&sig=AOq0QJ8wRgIhAJ&lsig=ZZtop99 end", + "https://rr3.googlevideo.com/videoplayback?expire=1794&ei=abc&ip=[secret]&id=o-AB&sig=[secret]&lsig=[secret] end", + ["203.0.113.77", "AOq0QJ8wRgIhAJ", "ZZtop99"], + ], + ["GET /clip?v=dQw4w9WgXcQ&t=42&access_token=abc123def456&api_key=k-998877&X-Amz-Signature=deadbeef", "GET /clip?v=dQw4w9WgXcQ&t=42&access_token=[secret]&api_key=[secret]&X-Amz-Signature=[secret]", ["abc123def456", "k-998877", "deadbeef"]], + ["Authorization: Bearer abcdefghijklmnop0123456789", "Authorization: Bearer [secret]", ["abcdefghijklmnop"]], + ["Cookie: auth_token=aaaabbbbccccdddd; ct0=eeeeffff0000\nnext line stays", "Cookie: [secret]\nnext line stays", ["aaaabbbbccccdddd", "eeeeffff0000"]], + ["the jar had cf_clearance=Zx9.yQ-77_abc and ct0=0f0f0f0f in it", "the jar had cf_clearance=[secret] and ct0=[secret] in it", ["Zx9.yQ-77_abc", "0f0f0f0f"]], + ["x-api-key: FAKE-TEST-VALUE", "x-api-key: [secret]", ["FAKE-TEST-VALUE"]], + ["key sk-ant-api03-AbCdEfGhIjKlMnOpQrStUv and ghp_FAKE-TEST-VALUEghijklmnopqrstuvwxyz", "key [secret] and [secret]", ["AbCdEfGh", "ghp_0123"]], + ["jwt FAKE-TEST-VALUE", "jwt [secret]", ["eyJhbGci", "dBjftJeZ"]], + ]; + for (const [text, want, gone] of cases) { + const out = scrubText(text, {}); + assert.equal(out, want); + for (const g of gone) assert.ok(!out.includes(g), `${g} in ${out}`); + } + // Words a transcript says, and a public link, are left as they are. + for (const plain of [ + "the key to the token economy is a secret; password: none, she said", + "watch https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=42s and https://x.com/a/status/1?s=20", + "cookie: chocolate chip. Basic income, bearer of bad news; the monkey=banana joke", + "[12:04] my ip is whatever, the signature move", + ]) + 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), + // The second review's (12 Nov): a brace before a cookie name, and the rest of its list. + "{cookie:a=x": rep("{cookie:a=xxxxxxxxxx"), + ",cookie:a=b;c": rep(",cookie:a=b;c=d;e"), + "&a": rep("&a"), + "&a-": rep("&a-"), + "?a_b.": rep("?a_b."), + ";access_": rep(";access_"), + "a://b:c": rep("a://b:cccccc"), + "a://b:c:": rep("a://b:c:c:c:"), + "Bearer short": rep("Bearer aaaaaaaaaaaaaaa "), + "token:word": rep("token:aaaaaaa "), + "token=long": rep(`token=${"a".repeat(300)} `), + "eyJ.eyJ.": rep("eyJaaaaaaaa.eyJaaaaaaaa."), + "auth_token tab": rep("auth_token\taaaaaaa "), + "AB_KEY=short": rep("AB_KEY=short "), + " /home/x": rep(" /home/x"), + "authorization: Bearer": rep("authorization: Bearer "), + "authorization: word": rep("authorization: word "), + "x-api-key:": rep("x-api-key:aaaa "), + "__Secure-": rep("__Secure-a"), + "sk-short": rep("sk-aaaaaaaaaaaaaaaaaaa "), + "set-cookie lines": rep("\nset-cookie: a=b; c"), + "\\u0026": rep("\\u0026a"), + "%26": rep("%26a%3D"), + "&": rep("&a"), + }; + 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); +}); + +test("scrubText (second review): an ampersand however it is written, an encoded `=`, any Authorization scheme", () => { + const cases: [string, string][] = [ + ['"url":"https://rr1.googlevideo.com/videoplayback?expire=1\\u0026token=FAKE-TEST-VALUE\\u0026ip=203.0.113.9\\u0026itag=18"', '"url":"https://rr1.googlevideo.com/videoplayback?expire=1\\u0026token=[secret]\\u0026ip=[secret]\\u0026itag=18"'], + ["a href=?v=1&sig=AAAA.BBBB&t=4", "a href=?v=1&sig=[secret]&t=4"], + ["api_key%3DFAKE-TEST-VALUE", "api_key%3D[secret]"], + ["next=%2Fcb%3Fx%3D1%26access_token%3DFAKE-TEST-VALUE", "next=%2Fcb%3Fx%3D1%26access_token%3D[secret]"], + ['Authorization: "Token FAKE-TEST-VALUEabcdef"', 'Authorization: "Token [secret]"'], + ["authorization: Digest dXNlcjpwYXNz", "authorization: Digest [secret]"], + ["Proxy-Authorization: Basic dXNlcjpwYXNz", "Proxy-Authorization: Basic [secret]"], + ["Authorization: SharedKey acct:FAKE-TEST-VALUE", "Authorization: SharedKey [secret]"], + ["\\u0026token=FAKE-TEST-VALUE", "\\u0026token=[secret]"], + ["?a=1&token=FAKE-TEST-VALUE&b=2", "?a=1&token=[secret]&b=2"], + ]; + for (const [text, want] of cases) assert.equal(scrubText(text, {}), want); + // An authorization that is a sentence stays one. + for (const plain of ["authorization: pending approval tomorrow", "Authorization: granted by the committee", "Authorization: expires 2026-11-07T10:00."]) assert.equal(scrubText(plain, {}), plain); +}); + +test("scrubText (second review): what follows secret: / token: / password: is a credential, not a date, a time or a link", () => { + for (const plain of [ + "Secret: 2026-11-07T10:00 meeting", + "password: 2026-11-07, as agreed", + "token: 10:30-11:45", + "token: 10:30am-11:45am, then lunch", + "Secret: 2026-11-07T10:00Z.", + "secret: (2026-11-07)", + "SECRET=2026-11-07T10:00", + "Token: https://example.com/watch?v=abc123", + "the key to this is basic economics, a token gesture; his secret: he ate 400 calories", + "my password is hunter2 and the session was great", + "He said: key=value pairs are simple", + ]) + assert.equal(scrubText(plain, {}), plain); + assert.equal(scrubText("Secret: 2026hunter2hunter", {}), "Secret: [secret]"); + assert.equal(scrubText("password: 12345678", {}), "password: [secret]"); + assert.equal(scrubText("PASSWORD=hunter2!", {}), "PASSWORD=[secret]"); + assert.equal(scrubText("export ANTHROPIC_API_KEY='sk-ant-abcdefghijklmnopqrstuvwx'", {}), "export ANTHROPIC_API_KEY='[secret]'"); +}); diff --git a/common/lib/llm/callLogView.test.ts b/common/lib/llm/callLogView.test.ts @@ -0,0 +1,77 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { foldModelLog, type ModelCallRow, type ModelLogRunRow } from "./callLog"; +import { LIST_ITEMS, PAGE_ROWS, modelLogView, viewQueryOf } from "./callLogView"; + +// Run with: pnpm -C common exec tsx --test lib/llm/callLogView.test.ts +// +// The model log as the panel shows it (demo epic D3): runs picked by task, +// job, number, time or newest; groups by phase a page at a time; heads and a +// few items only in the list; counts per filter. + +const run = (n: number, task: string, at: string, jobId?: string): ModelLogRunRow => ({ v: 1, t: "run", run: n, at, task, ...(jobId ? { jobId } : {}) }); +const call = (id: string, phase: string, outcome: ModelCallRow["decision"]["outcome"], extra: Partial<ModelCallRow> = {}): ModelCallRow => ({ + v: 1, + t: "call", + id, + run: Number(id.split(".")[0]), + at: "2026-11-11T10:00:00.000Z", + task: "sweep", + phase, + model: "qwen3:8b", + route: "local", + promptChars: 10, + promptHead: "q", + answerChars: 1, + answerHead: "a", + seconds: 1, + decision: { outcome, why: "" }, + ...extra, +}); + +function log() { + const rows: object[] = [run(1, "sweep", "2026-11-11T10:00:00.000Z", "j1"), run(2, "narrate", "2026-11-11T11:00:00.000Z", "j2"), run(3, "sweep", "2026-11-11T12:00:00.000Z", "j3")]; + rows.push(call("1.1", "terms", "kept")); + for (let i = 2; i <= 60; i++) rows.push(call(`1.${i}`, "reading", i % 3 ? "kept" : "dropped", { items: Array.from({ length: 8 }, (_, k) => ({ text: `q${k}`, outcome: "kept" as const, why: "" })) })); + rows.push(call("1.61", "grouping", "kept")); + rows.push(call("2.1", "draft", "rewritten", { task: "narrate" })); + rows.push(call("3.1", "terms", "kept")); + return foldModelLog(rows.map((r) => JSON.stringify(r)).join("\n")); +} + +test("every run, groups in the sweep's order, a page each; heads and a few items in the list", () => { + const v = modelLogView(log()); + assert.equal(v.run, null); + assert.deepEqual(v.groups.map((g) => [g.phase, g.calls]), [["terms", 2], ["reading", 59], ["grouping", 1], ["draft", 1]]); + const reading = v.groups[1]!; + assert.equal(reading.rows.length, PAGE_ROWS); + assert.equal(reading.more, 59 - PAGE_ROWS); + assert.equal(reading.rows[0]!.items!.length, LIST_ITEMS); + assert.equal(reading.rows[0]!.itemsTotal, 8); + // A call is in each filter its decision or one of its items is in: every reading call kept items. + assert.deepEqual(v.counts, { all: 63, kept: 62, dropped: 20, rewritten: 1, "n/a": 0 }); +}); + +test("a phase's next page; the outcome filter", () => { + const page = modelLogView(log(), { phase: "reading", offset: 50 }); + assert.deepEqual(page.groups.map((g) => [g.phase, g.offset, g.rows.length, g.more]), [["reading", 50, 9, 0]]); + const dropped = modelLogView(log(), { outcome: "dropped" }); + assert.deepEqual(dropped.groups.map((g) => [g.phase, g.calls]), [["reading", 20]]); + assert.equal(dropped.counts.all, 63, "the counts are before the filter"); +}); + +test("the run: a task's newest, a job's, one by number, the one nearest a time; a job not yet run shows none", () => { + assert.equal(modelLogView(log(), { task: "sweep", latest: true }).run, 3); + assert.equal(modelLogView(log(), { task: "narrate", latest: true }).summary.calls, 1); + assert.equal(modelLogView(log(), { jobId: "j1" }).summary.calls, 61); + assert.equal(modelLogView(log(), { run: 3 }).summary.calls, 1); + assert.equal(modelLogView(log(), { near: "2026-11-11T10:00:02.000Z" }).run, 1); + assert.equal(modelLogView(log(), { jobId: "j-later" }).summary.calls, 0); +}); + +test("the query from a URL: whole numbers, an outcome by name, an ISO time", () => { + assert.deepEqual(viewQueryOf(new URLSearchParams("task=sweep&latest=1&outcome=dropped&phase=reading&offset=25&limit=10")), { task: "sweep", latest: true, outcome: "dropped", phase: "reading", offset: 25, limit: 10 }); + assert.throws(() => viewQueryOf(new URLSearchParams("outcome=maybe")), /"outcome" is one of/); + assert.throws(() => viewQueryOf(new URLSearchParams("offset=-1")), /whole number/); + assert.throws(() => viewQueryOf(new URLSearchParams("near=yesterday")), /ISO time/); +}); diff --git a/common/lib/llm/callLogView.ts b/common/lib/llm/callLogView.ts @@ -0,0 +1,152 @@ +// THE MODEL LOG AS A PANEL SHOWS IT (demo epic D3) — pure: a log (./callLog.ts +// foldModelLog) and a query → the runs, the run shown, the count header, and +// the calls grouped by phase, each group one page at a time. A row carries +// heads, never whole texts (those are fetched per row), and at most +// LIST_ITEMS of its items: the page never ships megabytes. umtool's panel, +// the editor's job page and `umtool model-log` all read this. + +import { + CALLS_MAX_BYTES, + CALLS_MAX_CALLS, + CALL_OUTCOMES, + callMatches, + phaseLabel, + phaseOrder, + summarizeCalls, + type CallOutcome, + type ModelCall, + type ModelLog, + type ModelLogRunRow, + type ModelLogSummary, +} from "./callLog"; + +export const PAGE_ROWS = 25; +export const MAX_PAGE_ROWS = 200; +export const LIST_ITEMS = 5; + +export type ModelLogViewQuery = { + // Only this task's runs (a media draft's panel: its task). + task?: string; + // The run of this job, else `run`, else (with `latest`) the newest run that + // matches `task`; none of them: every run. + jobId?: string; + run?: number; + latest?: boolean; + // The run that began nearest this time (a trace's run start: the run page). + near?: string; + outcome?: CallOutcome; + // One phase's page (a "Show more"): only that group, from `offset`. + phase?: string; + offset?: number; + limit?: number; +}; + +export type ModelLogViewRow = Omit<ModelCall, "items"> & { items: ModelCall["items"]; itemsTotal: number }; + +export type ModelLogViewGroup = { phase: string; label: string; calls: number; seconds: number; offset: number; rows: ModelLogViewRow[]; more: number }; + +export type ModelLogView = { + runs: ModelLogRunRow[]; + // The run shown; null: every run (the iteration's whole log). + run: number | null; + summary: ModelLogSummary; + // How many calls each filter would show (before the outcome filter). + 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 }); + +export function pickRun(log: ModelLog, q: Pick<ModelLogViewQuery, "task" | "jobId" | "run" | "latest" | "near">): number | null { + const runs = log.runs.filter((r) => !q.task || r.task === q.task); + if (q.jobId) return runs.filter((r) => r.jobId === q.jobId).at(-1)?.run ?? -1; + if (q.run !== undefined) return runs.some((r) => r.run === q.run) ? q.run : -1; + if (q.near) { + const t = Date.parse(q.near); + if (!Number.isFinite(t) || !runs.length) return runs.length ? null : -1; + return [...runs].sort((a, b) => Math.abs(Date.parse(a.at) - t) - Math.abs(Date.parse(b.at) - t))[0]!.run; + } + if (q.latest) { + // The newest run that made a call, else the newest at all. + const made = new Set(log.calls.map((c) => c.run)); + return [...runs].reverse().find((r) => made.has(r.run))?.run ?? runs.at(-1)?.run ?? null; + } + return null; +} + +export function modelLogView(log: ModelLog, q: ModelLogViewQuery = {}): ModelLogView { + const run = pickRun(log, q); + const scoped = log.calls.filter((c) => callMatches(c, { ...(q.task ? { task: q.task } : {}), ...(run !== null ? { run } : {}) })); + const counts = { all: scoped.length } as ModelLogView["counts"]; + for (const o of CALL_OUTCOMES) counts[o] = scoped.filter((c) => callMatches(c, { outcome: o })).length; + const shown = q.outcome ? scoped.filter((c) => callMatches(c, { outcome: q.outcome })) : scoped; + const limit = Math.max(1, Math.min(MAX_PAGE_ROWS, Math.floor(q.limit ?? PAGE_ROWS))); + const groups: ModelLogViewGroup[] = []; + for (const phase of phaseOrder(scoped.map((c) => c.phase))) { + if (q.phase && phase !== q.phase) continue; + const all = shown.filter((c) => c.phase === phase); + const offset = q.phase ? Math.max(0, Math.floor(q.offset ?? 0)) : 0; + const rows = all.slice(offset, offset + limit).map(listRow); + groups.push({ + phase, + label: phaseLabel(phase), + calls: all.length, + seconds: Math.round(all.reduce((s, c) => s + (c.seconds || 0), 0) * 10) / 10, + offset, + rows, + more: Math.max(0, all.length - offset - rows.length), + }); + } + return { + runs: log.runs.filter((r) => !q.task || r.task === q.task), + run, + summary: summarizeCalls(scoped), + 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)) }, + }; +} + +// A query from URL search params (the umtool and editor routes'); a bad +// value is an error a person can read. +export function viewQueryOf(sp: URLSearchParams): ModelLogViewQuery { + const q: ModelLogViewQuery = {}; + const str = (k: string) => sp.get(k)?.trim() || undefined; + const int = (k: string) => { + const v = str(k); + if (v === undefined) return undefined; + const n = Number(v); + if (!Number.isInteger(n) || n < 0) throw new Error(`"${k}" is a whole number`); + return n; + }; + const task = str("task"); + if (task) q.task = task; + const jobId = str("jobId"); + if (jobId) q.jobId = jobId; + const run = int("run"); + if (run !== undefined) q.run = run; + if (sp.get("latest") === "1" || sp.get("latest") === "true") q.latest = true; + const near = str("near"); + if (near) { + if (!Number.isFinite(Date.parse(near))) throw new Error('"near" is an ISO time'); + q.near = near; + } + const outcome = str("outcome"); + if (outcome) { + if (!(CALL_OUTCOMES as readonly string[]).includes(outcome)) throw new Error(`"outcome" is one of ${CALL_OUTCOMES.join(", ")}`); + q.outcome = outcome as CallOutcome; + } + const phase = str("phase"); + if (phase) q.phase = phase; + const offset = int("offset"); + if (offset !== undefined) q.offset = offset; + const limit = int("limit"); + if (limit !== undefined) q.limit = limit; + return q; +} diff --git a/common/lib/llm/index.ts b/common/lib/llm/index.ts @@ -10,3 +10,6 @@ export * from "./ollama"; export * from "./config"; export * from "./structured"; export * from "./agent"; +export * from "./callLog"; +export * from "./callLog-server"; +export * from "./callLogView"; diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts @@ -19,7 +19,8 @@ import { type MessagesResponse, } from "./anthropic"; import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig } from "./config"; -import type { Meter } from "./meter"; +import { CallSlot, lazyKeyRedactor, recordModelCall } from "./callLog-server"; +import type { Meter, Usage } from "./meter"; import { ollamaChat, OllamaError, PromptTooLargeError, promptEstimate } from "./ollama"; export const ANSWER_TOOL = "answer"; @@ -62,25 +63,71 @@ type Opts = { meter?: Meter; signal?: AbortSignal; maxTokens?: number; + // The model log (./callLog.ts): the call's phase and label, and a slot the + // caller says through what code did with the answer. + call?: StructuredCallMeta; +}; + +export type StructuredCallMeta = { phase?: string; label?: string; slot?: CallSlot }; + +// What one structured answer cost, summed over its attempts, and the text it +// last sent (the model log's record). +type Spent = { tokensIn: number; tokensOut: number; any: boolean; sent: string; redact?: (s: string) => string }; +const spend = (s: Spent, u: Usage | undefined) => { + if (!u) return; + const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0); + s.tokensIn += n(u.input_tokens) + n(u.cache_creation_input_tokens) + n(u.cache_read_input_tokens); + s.tokensOut += n(u.output_tokens); + s.any = true; }; export async function structuredAnswer<T>(o: Opts): Promise<T> { - return providerOf(o.model) === "api" ? claudeAnswer<T>(o) : localAnswer<T>(o); + const route = providerOf(o.model); + 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) => + recordModelCall( + { + ...(o.call?.phase ? { phase: o.call.phase } : {}), + ...(o.call?.label ? { label: o.call.label } : {}), + model: o.model, + route, + system: o.system, + prompt: spent.sent + images, + answer, + seconds: (Date.now() - t0) / 1000, + ...(spent.any ? { tokensIn: spent.tokensIn, tokensOut: spent.tokensOut } : {}), + ...(error !== undefined ? { error: (error as Error)?.message ?? String(error) } : {}), + ...(spent.redact ? { redact: spent.redact } : {}), + }, + o.call?.slot, + ); + try { + const out = route === "api" ? await claudeAnswer<T>(o, spent) : await localAnswer<T>(o, spent); + record(out); + return out; + } catch (err) { + record(null, err); + throw err; + } } -async function claudeAnswer<T>(o: Opts): Promise<T> { +async function claudeAnswer<T>(o: Opts, spent: Spent): Promise<T> { const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model)); + const configured = spent.redact; + spent.redact = (s) => client.redactText(configured ? configured(s) : s); const strict = isStrictModel(o.model); try { - return await claudeTry<T>(client, o, strict); + return await claudeTry<T>(client, o, strict, spent); } catch (err) { if (!strict && err instanceof AnthropicError && err.status === 400 && /tool_choice/.test(err.message)) - return claudeTry<T>(client, o, true); + return claudeTry<T>(client, o, true, spent); throw err; } } -async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): Promise<T> { +async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean, spent: Spent): Promise<T> { const tool = { name: ANSWER_TOOL, description: "Give the answer.", @@ -88,6 +135,7 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): ...(strict ? { strict: true } : {}), }; const text = strict ? `${o.user}\n\n${ASK}` : o.user; + spent.sent = text; let messages: { role: string; content: string | ContentBlock[] }[] = [ { role: "user", @@ -112,6 +160,7 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): }, { meter: o.meter, signal: o.signal }, ); + spend(spent, res.usage); const call = toolUsesOf(res).find((b) => b.name === ANSWER_TOOL); if (call && call.input && typeof call.input === "object") return call.input as T; // Append-only: the re-ask follows the answer as it came. @@ -133,7 +182,7 @@ export function structuredPromptEstimate(o: { system: string; user: string; sche }); } -async function localAnswer<T>(o: Opts): Promise<T> { +async function localAnswer<T>(o: Opts, spent: Spent): Promise<T> { const cfg = ollamaConfigOf(o.llm, o.model); let last = ""; for (let attempt = 0; attempt < 2; attempt++) { @@ -155,6 +204,7 @@ async function localAnswer<T>(o: Opts): Promise<T> { continue; } o.meter?.add(o.model, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }); + spend(spent, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }); const content = reply.message.content ?? ""; const value = content.trim() ? extractJsonObject(content) : null; if (value !== null && typeof value === "object") return value as T; diff --git a/common/lib/recordingClock-server.ts b/common/lib/recordingClock-server.ts @@ -46,6 +46,7 @@ import { savedVideoPath, type SavedVideoPointer } from "./savedVideo"; import { coerceMediaImport, MEDIA_IMPORT_FILENAME } from "./mediaImport"; import { readJsonFile } from "./jsonFile-server"; import { loadTranscribeOutcome } from "./transcribeOutcome-server"; +import "./childKillGuard"; export const recordingClockSidecar = sidecar(CLOCK_FILE, sidecarField(coerceRecordingClock), { indent: 2 }); diff --git a/common/lib/report/draft/tasks/clipsSuggest.ts b/common/lib/report/draft/tasks/clipsSuggest.ts @@ -26,6 +26,7 @@ // words.json), else the recording's cues from the corpus (`cuesOf`), spread // over their words. +import { recordSessionAnswer } from "../../../llm/callLog-server"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm"; @@ -203,6 +204,8 @@ export async function runClipsSuggest( log(`clips-suggest ${input.project} on ${input.model}: ${plural(items.length, "proposal")}, words from ${p.wordsFrom} (prompt ${SUGGEST_PROMPT_VERSION})`); if (input.answers !== undefined) { // The `code` route: a Claude Code session's answer, read as a model's is. + const all = suggestPrompt(items); + recordSessionAnswer({ phase: "labels", system: all.system, prompt: all.user, answer: input.answers, llm: deps.llm }); const r = parseSuggestAnswer(input.answers, items.map((i) => i.id)); if (!r.ok) throw new ClipsSuggestRefusal(`the session's answers are refused: ${r.error}`); fresh.push(...r.items); diff --git a/common/lib/report/draft/tasks/llmText.ts b/common/lib/report/draft/tasks/llmText.ts @@ -14,7 +14,9 @@ import { textOf, type LlmConfig, type Meter, + type StructuredCallMeta, } from "../../../llm"; +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; @@ -27,9 +29,46 @@ export async function plainAnswer(o: { meter: Meter; signal?: AbortSignal; maxTokens?: number; + // The model log (lib/llm/callLog.ts): the call's phase, label and slot. + call?: StructuredCallMeta; }): Promise<string> { + const route = providerOf(o.model); + const t0 = Date.now(); + let redact: ((s: string) => string) | undefined = lazyKeyRedactor(o.llm.anthropic); + const record = (answer: string, tokens: { tokensIn?: number; tokensOut?: number }, error?: unknown) => + recordModelCall( + { + ...(o.call?.phase ? { phase: o.call.phase } : {}), + ...(o.call?.label ? { label: o.call.label } : {}), + model: o.model, + route, + system: o.system, + prompt: o.user, + answer, + seconds: (Date.now() - t0) / 1000, + ...tokens, + ...(error !== undefined ? { error: (error as Error)?.message ?? String(error) } : {}), + ...(redact ? { redact } : {}), + }, + o.call?.slot, + ); + try { + const configured = redact; + return await plainAnswerOn(o, record, (r) => (redact = (s) => r(configured ? configured(s) : s))); + } catch (err) { + record("", {}, err); + throw err; + } +} + +async function plainAnswerOn( + o: Parameters<typeof plainAnswer>[0], + record: (answer: string, tokens: { tokensIn?: number; tokensOut?: number }) => void, + setRedact: (r: (s: string) => string) => void, +): Promise<string> { if (providerOf(o.model) === "api") { const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model)); + setRedact((s) => client.redactText(s)); const res = await client.messages( { model: o.model, @@ -40,7 +79,10 @@ export async function plainAnswer(o: { }, { meter: o.meter, signal: o.signal }, ); - return textOf(res); + const u = res.usage ?? {}; + const text = textOf(res); + record(text, { tokensIn: (Number(u.input_tokens) || 0) + (Number(u.cache_read_input_tokens) || 0) + (Number(u.cache_creation_input_tokens) || 0), tokensOut: Number(u.output_tokens) || 0 }); + return text; } const cfg = ollamaConfigOf(o.llm, o.model); const reply = await ollamaChat(cfg, { @@ -52,7 +94,9 @@ export async function plainAnswer(o: { signal: o.signal, }); o.meter.add(o.model, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }); - return reply.message.content ?? ""; + const text = reply.message.content ?? ""; + record(text, { tokensIn: reply.promptTokens, tokensOut: reply.evalTokens }); + return text; } // How many characters of user text fit a model's one call beside `system`: diff --git a/common/lib/report/draft/tasks/media.ts b/common/lib/report/draft/tasks/media.ts @@ -45,6 +45,8 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { structuredAnswer } from "../../../llm"; +import type { CallItem } from "../../../llm/callLog"; +import { CallSlot } from "../../../llm/callLog-server"; import { readIteration, readIterationFile, reportSourceOf } from "../../iterations"; import { applyDraft, @@ -296,8 +298,16 @@ async function askUnits<U extends MediaUnit, V, I extends MediaTaskInput>( return { value: null, hard: [(e as Error).message], soft: [] }; } }; - const ask = (system: string, user: string, schema: object) => - structuredAnswer<unknown>({ llm: deps.llm, model: ctx.input.model, system, user, schema, meter: h.meter, signal: deps.signal }); + const ask = (system: string, user: string, schema: object, label: string, slot: CallSlot) => + structuredAnswer<unknown>({ llm: deps.llm, model: ctx.input.model, system, user, schema, meter: h.meter, signal: deps.signal, call: { phase: "draft", label, slot } }); + // What code did with one unit's attempt (the model log): a clean value is + // kept, a hard problem drops it, soft ones keep it flagged. + const fate = (id: string, a: MediaAttempt<V>, k: number): CallItem => + a.hard.length + ? { text: id, outcome: "dropped", why: `${a.hard.join("; ")}${k === 0 ? " (asked again)" : ""}` } + : a.soft.length + ? { text: id, outcome: k === 0 ? "dropped" : "kept", why: `flagged: ${a.soft.join("; ")}${k === 0 ? " (asked again)" : ""}` } + : { text: id, outcome: "kept", why: "passes the checks" }; const b = spec.batch; // Computed once per unit (a batch: once for the whole), as narrate always did. const first = b ? { system: b.system(group, ctx), user: b.user(group, ctx) } : null; @@ -310,14 +320,17 @@ async function askUnits<U extends MediaUnit, V, I extends MediaTaskInput>( const list = out.get(u.id)!; const extra = list.length ? (spec.retry ?? refusedFor)(list.at(-1)!, u) : ""; let a: MediaAttempt<V>; + const slot = new CallSlot(); try { - a = judge(await ask(single.get(u.id)!.system, single.get(u.id)!.user + extra, spec.schema(u, ctx)), u); + a = judge(await ask(single.get(u.id)!.system, single.get(u.id)!.user + extra, spec.schema(u, ctx), `${u.label ?? u.id}${k ? ` · attempt ${k + 1}` : ""}`, slot), u); } catch (e) { if (deps.signal?.aborted) throw e; list.push({ value: null, hard: [(e as Error).message], soft: [] }); continue; } list.push(a); + const f = fate(u.id, a, k); + slot.decide(f.outcome, f.why); h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, ...a }]); if (!a.hard.length && !a.soft.length) pending = []; continue; @@ -328,19 +341,24 @@ async function askUnits<U extends MediaUnit, V, I extends MediaTaskInput>( const user = (k === 0 ? first!.user : b.user(pending, ctx)) + (failing.length ? (b.retry ?? batchRefusedFor)(failing) : ""); const system = k === 0 ? first!.system : b.system(pending, ctx); let answers: Record<string, unknown>; + const slot = new CallSlot(); try { - answers = b.split(await ask(system, user, b.schema(pending, ctx)), pending, ctx); + answers = b.split(await ask(system, user, b.schema(pending, ctx), `${pending.length} unit${pending.length === 1 ? "" : "s"}${k ? ` · attempt ${k + 1}` : ""}`, slot), pending, ctx); } catch (e) { if (deps.signal?.aborted) throw e; for (const u of pending) out.get(u.id)!.push({ value: null, hard: [(e as Error).message], soft: [] }); continue; } + const fates: CallItem[] = []; for (const u of pending) { const a: MediaAttempt<V> = answers[u.id] === undefined ? { value: null, hard: [`no draft for ${u.id} in the answer`], soft: [] } : judge(answers[u.id], u); + fates.push(fate(u.label ?? u.id, a, k)); out.get(u.id)!.push(a); h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, batch: pending.length, ...a }]); } + const nKept = fates.filter((f) => f.outcome === "kept").length; + slot.decide(nKept ? "kept" : "dropped", `${nKept} of ${fates.length} kept`, fates); pending = pending.filter((u) => { const last = out.get(u.id)!.at(-1)!; return last.hard.length > 0 || last.soft.length > 0; diff --git a/common/lib/report/draft/tasks/proposeGroups.ts b/common/lib/report/draft/tasks/proposeGroups.ts @@ -22,6 +22,7 @@ // It never writes the manifest or notes.json. An API model is held to // `maxUsd` (the ask's estimate checked first). +import { CallSlot, recordSessionAnswer } from "../../../llm/callLog-server"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm"; @@ -237,9 +238,13 @@ export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeG const base = { project: input.project, model: input.model }; const cancelled = (): ProposeGroupsOutcome => ({ ...base, status: "cancelled", proposals: null, file: null, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" }); let raw: unknown; + // What code did with the answer's groups (the model log). + const slot = new CallSlot(); if (input.answers !== undefined) { log(`propose-groups ${input.project}: a Claude Code session's answer (prompt ${GROUPS_PROMPT_VERSION})`); raw = input.answers; + const pr = groupsPrompt({ manifest, request, model: CODE_PRICED, llm: deps.llm }); + recordSessionAnswer({ phase: "groups", system: pr.system, prompt: pr.user, answer: raw, llm: deps.llm }, slot); } else { const pr = groupsPrompt({ manifest, request, model: input.model, llm: deps.llm }); log(`propose-groups ${input.project} on ${input.model}: one ask, ~${pr.tokens} prompt tokens (prompt ${GROUPS_PROMPT_VERSION})`); @@ -251,7 +256,7 @@ export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeG const ask = deps.ask ?? (<T,>(system: string, user: string, schema: object, model: string, maxTokens: number) => - structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens })); + structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens, call: { phase: "groups", slot } })); try { raw = await ask<unknown>(pr.system, pr.user, GROUPS_SCHEMA, input.model, 4096); } catch (e) { @@ -261,6 +266,7 @@ export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeG } const parsed = parseGroupsAnswer(raw); if (!parsed.ok) { + slot.decide("dropped", parsed.error); if (input.answers !== undefined) throw new ProposeGroupsRefusal(`the session's answer is refused: ${parsed.error}`); throw new StructuredAnswerError(`${input.model}: ${parsed.error}: ${JSON.stringify(raw ?? null).slice(0, 160)}`); } @@ -270,6 +276,10 @@ export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeG const checked = checkGroupProposals(fresh, { groups: parsed.groups }); for (const g of checked.groups) log(` proposed: §${g.section} ${g.ids.join(" ")} — ${g.claim}`); for (const r of checked.refused) log(` refused: ${JSON.stringify(r.group).slice(0, 120)} — ${r.why}`); + slot.decide(checked.groups.length ? "kept" : "dropped", `${checked.groups.length} group(s) proposed, ${checked.refused.length} refused`, [ + ...checked.groups.map((g) => ({ text: `§${g.section} ${g.ids.join(" ")} — ${g.claim}`, outcome: "kept" as const, why: "proposed" })), + ...checked.refused.map((r) => ({ text: JSON.stringify(r.group).slice(0, 200), outcome: "dropped" as const, why: r.why })), + ]); const proposals = groupProposalsDocOf({ at: now().toISOString(), model: input.model, request: request || null, checked }); const file = await writeGroupProposals(input.project, proposals); const usd = Math.round(meter.usd * 1e6) / 1e6; diff --git a/common/lib/report/draft/tasks/run.ts b/common/lib/report/draft/tasks/run.ts @@ -8,9 +8,12 @@ // or one that is not this task's to run. import { CancelledError, Meter, type ModelTally } from "../../../llm"; +import { currentJobContext } from "../../../jobContext"; +import { ModelLogWriter, modelLogFilesIn, processScrub, runWithModelLog } from "../../../llm/callLog-server"; import { addIterationUsage, appendIterationTurns, + iterationDir, readIteration, recordIterationStep, updateIteration, @@ -165,6 +168,21 @@ export async function runOnIteration( } } } + // The model log (demo epic D3): every model call the body makes, on any + // route, is recorded in the iteration's calls.jsonl under this run. + const storePaths = paths ?? getPaths(); + const modelLog = new ModelLogWriter({ + files: modelLogFilesIn(iterationDir(storePaths, article, n)), + task: o.step?.task ?? it.kind, + // The running job's own id (an iteration's jobId is written after its job starts). + ...((o.step?.jobId ?? currentJobContext()?.jobId ?? it.jobId) ? { jobId: o.step?.jobId ?? currentJobContext()?.jobId ?? it.jobId } : {}), + model: o.step?.model ?? o.trace?.model ?? it.model, + where: { article, iteration: n }, + scrub: processScrub(Object.values(storePaths).filter((v): v is string => typeof v === "string")), + now, + log, + }); + await modelLog.start(); let coverageOf: (() => IterationCoverage) | null = null; const handle: TaskHandle = { article, @@ -204,7 +222,7 @@ export async function runOnIteration( let summary: string; let patch: IterationPatch = {}; try { - const out = await body(handle); + const out = await runWithModelLog(modelLog, () => body(handle)); status = deps.signal?.aborted ? "cancelled" : out.status; summary = deps.signal?.aborted ? "cancelled" : out.summary; patch = out.patch ?? {}; @@ -222,6 +240,7 @@ export async function runOnIteration( } } + await modelLog.flush(); // The record of the run, whatever happened: turns, spend, the ending. if (turns.length) await appendIterationTurns(article, n, turns, paths).catch((e) => log(`turns not kept: ${(e as Error).message}`)); const tallies = meter.summary().byModel; diff --git a/common/lib/report/draft/tasks/sweep-agent.ts b/common/lib/report/draft/tasks/sweep-agent.ts @@ -188,6 +188,8 @@ function extractTool(h: TaskHandle, input: SweepAgentInput, rewrite: (t: string) user: `Directive: ${String(inp.directive ?? "")}\n\n${text}`, meter: h.meter, signal: ctx?.signal ?? h.deps.signal, + // The model log: the extractor's batch, handed back to the agent as it read. + call: { phase: "reading", label: `extract batch ${k} (${ids.length} recording${ids.length === 1 ? "" : "s"})` }, }); count.n++; // The batch, traced: its ids and the extractor's own lines. diff --git a/common/lib/report/draft/tasks/sweep-pipeline.ts b/common/lib/report/draft/tasks/sweep-pipeline.ts @@ -17,6 +17,8 @@ // `coverage` is what was enumerated and read. import { structuredAnswer, type LlmConfig, type Meter } from "../../../llm"; +import type { CallItem } from "../../../llm/callLog"; +import { CallSlot } from "../../../llm/callLog-server"; import type { Report } from "../../schema"; import { writeIterationFile } from "../../iterations"; import { mmss } from "../reportOps"; @@ -285,10 +287,22 @@ export async function sweepPipeline(input: SweepPipelineInput, deps: TaskDeps): ); } -async function ask<T>(h: TaskHandle, model: string, system: string, user: string, schema: object, what: string, traceCost = false): Promise<T> { +// The model log's phase of a pipeline step (lib/llm/callLog.ts PHASE_ORDER). +export const phaseOfStep = (what: string) => (what === "terms" ? "terms" : what.startsWith("extract") ? "reading" : what.startsWith("group") ? "grouping" : what); + +async function ask<T>(h: TaskHandle, model: string, system: string, user: string, schema: object, what: string, traceCost = false, slot?: CallSlot): Promise<T> { const t0 = Date.now(); const before = h.meter.usd; - const out = await structuredAnswer<T>({ llm: h.deps.llm as LlmConfig, model, system, user, schema, meter: h.meter as Meter, signal: h.deps.signal }); + const out = await structuredAnswer<T>({ + llm: h.deps.llm as LlmConfig, + model, + system, + user, + schema, + meter: h.meter as Meter, + signal: h.deps.signal, + call: { phase: phaseOfStep(what), label: what, ...(slot ? { slot } : {}) }, + }); h.turns([{ kind: "model", what, seconds: Math.round((Date.now() - t0) / 100) / 10, answer: out }]); if (traceCost) h.trace({ t: "cost", step: what, usd: h.meter.usd - before, model, total: h.meter.usd }); return out; @@ -323,13 +337,20 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T let terms: string[] = []; if (input.terms?.length) terms = input.terms.map((t) => t.trim()).filter(Boolean); else { - const ans = await ask<{ terms?: unknown }>(h, model, TERMS_SYSTEM, `Research question: ${question}`, TERMS_SCHEMA, "terms", true); + const termsSlot = new CallSlot(); + const ans = await ask<{ terms?: unknown }>(h, model, TERMS_SYSTEM, `Research question: ${question}`, TERMS_SCHEMA, "terms", true, termsSlot); const names = new Set(channels.flatMap((c) => [c.toLowerCase(), c.toLowerCase().replace(/-/g, " ")])); + const termItems: CallItem[] = []; for (const t of Array.isArray(ans.terms) ? ans.terms : []) { const v = String(t).replace(/["“”]/g, "").trim().toLowerCase(); if (v && v.length <= 40 && !terms.includes(v) && !names.has(v)) terms.push(v); + termItems.push({ + text: v || String(t), + ...(!v ? { outcome: "dropped", why: "empty" } : v.length > 40 ? { outcome: "dropped", why: "longer than 40 characters" } : names.has(v) ? { outcome: "dropped", why: "a channel's own name" } : terms.indexOf(v) >= 6 ? { outcome: "dropped", why: "past the sixth term" } : termItems.some((x) => x.text === v) ? { outcome: "dropped", why: "a repeat" } : { outcome: "kept", why: "searched" }), + } as CallItem); } terms = terms.slice(0, 6); + termsSlot.decide(terms.length ? "kept" : "dropped", terms.length ? `searched for ${terms.join(", ")}` : "no usable term", termItems); } if (!terms.length) return { status: "failed", summary: "no search terms" }; h.log(`terms: ${terms.join(", ")}`); @@ -470,8 +491,9 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const excerpt = ch.map(([s, t]) => `[${mmss(s)}] ${t}`).join("\n"); const user = `Research question: ${question}\n\nVideo: ${title} (${v.channel}, ${v.date})\n\nTranscript excerpt:\n${excerpt}`; let ans: { relevant?: unknown; items?: unknown }; + const slot = new CallSlot(); try { - ans = await ask(h, model, EXTRACT_SYSTEM, user, EXTRACT_SCHEMA, `extract ${v.id}@${ch[0]![0]}`); + ans = await ask(h, model, EXTRACT_SYSTEM, user, EXTRACT_SCHEMA, `extract ${v.id}@${ch[0]![0]}`, false, slot); } catch (e) { if (deps.signal?.aborted) throw e; event({ kind: "chunk-failed", video: v.id, at: ch[0]![0], error: (e as Error).message }); @@ -479,9 +501,14 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T h.log(` chunk failed: ${(e as Error).message}`); continue; } - if (!ans.relevant) continue; + if (!ans.relevant) { + slot.decide("dropped", "the model: the excerpt does not bear on the question"); + continue; + } nRelevant++; const items = Array.isArray(ans.items) ? ans.items.slice(0, MAX_ITEMS_PER_CHUNK) : []; + // What code did with each of the model's items (the model log). + const fates: CallItem[] = []; for (const raw of items as { quote?: unknown; claim?: unknown; on_topic?: unknown; strength?: unknown }[]) { let quote = String(raw.quote ?? "") .replace(/["“”]/g, "") @@ -514,6 +541,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T if (!why && kept.some((k) => k.video === v.id && (norm(k.quote).includes(key) || key.includes(norm(k.quote))))) why = "duplicate"; const at = sec ?? ch[0]![0]; batchLines.push(`${v.id} @ ${mmss(at)} “${quote}” — ${claim || "(no claim)"}${why ? ` [dropped: ${why}]` : ""}`); + fates.push({ text: quote ? `“${quote}” — ${claim || "(no claim)"}` : claim || "(empty)", outcome: why ? "dropped" : "kept", why: why ?? "verbatim in its window" }); if (why) { dropped.push({ video: v.id, quote, why }); event({ kind: "dropped", why, video: v.id, quote, claim }); @@ -534,6 +562,9 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T flags: lintClaim(claim, quote), }); } + const nKept = fates.filter((f) => f.outcome === "kept").length; + if (fates.length) slot.decide(nKept ? "kept" : "dropped", `${nKept} of ${fates.length} item${fates.length === 1 ? "" : "s"} kept`, fates); + else slot.decide("n/a", "relevant, but no items"); } } h.log(` read ${v.id} — kept so far ${kept.length}, dropped ${dropped.length}`); @@ -560,11 +591,13 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T .slice(0, MAX_CLAIMS_TOTAL) .sort((a, b) => a.date.localeCompare(b.date) || a.video.localeCompare(b.video) || a.sec - b.sec); const listing = pool.map((r, i) => `${i + 1}. (${r.date}) ${r.claim}`).join("\n"); - let best: { score: number; g: { title?: unknown; sections?: unknown } } | null = null; + let best: { score: number; g: { title?: unknown; sections?: unknown }; slot: CallSlot; why: string } | null = null; + const groupSlots: { slot: CallSlot; why: string }[] = []; for (let attempt = 0; attempt < 2; attempt++) { let g: { title?: unknown; sections?: unknown }; + const slot = new CallSlot(); try { - g = await ask(h, model, GROUP_SYSTEM, `Research question: ${question}\n\nFindings:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`, true); + g = await ask(h, model, GROUP_SYSTEM, `Research question: ${question}\n\nFindings:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`, true, slot); } catch (e) { if (deps.signal?.aborted) throw e; event({ kind: "group-failed", error: (e as Error).message }); @@ -576,9 +609,13 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const placed = new Set(secs.flatMap(nums)); const biggest = Math.max(0, ...secs.map((s) => new Set(nums(s)).size)); const score = placed.size - (secs.length > 1 && biggest > 0.7 * pool.length ? biggest : 0) * 0.5; - if (!best || score > best.score) best = { score, g }; + const why = `placed ${placed.size} of ${pool.length} findings in ${secs.length} section${secs.length === 1 ? "" : "s"}${secs.length > 1 && biggest > 0.7 * pool.length ? ` (one holds ${biggest})` : ""}`; + groupSlots.push({ slot, why }); + if (!best || score > best.score) best = { score, g, slot, why }; if (placed.size >= pool.length * 0.8 && biggest <= 0.7 * pool.length) break; } + for (const x of groupSlots) if (best && x.slot !== best.slot) x.slot.decide("dropped", `${x.why}; the other grouping was kept`); + best?.slot.decide("kept", best.why); const g = best?.g ?? { title: question, sections: [] }; const title = (String(g.title ?? "") || question).replace(/["“”#]/g, "").trim().slice(0, 90) || question.slice(0, 90); const raw = ((Array.isArray(g.sections) ? g.sections : []) as { heading?: unknown; findings?: unknown }[]) diff --git a/common/lib/report/draft/tasks/videoAssist.ts b/common/lib/report/draft/tasks/videoAssist.ts @@ -21,6 +21,7 @@ // It never writes the manifest, notes.json or a clip. An API model is held to // `maxUsd` (the ask's estimate checked first). +import { CallSlot, recordSessionAnswer } from "../../../llm/callLog-server"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm"; @@ -224,9 +225,13 @@ export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistD const meter = new Meter(); const base = { project: input.project, model: input.model, request, scope }; let raw: unknown; + // What code did with the answer's ops (the model log). + const slot = new CallSlot(); if (input.answers !== undefined) { log(`video-assist ${input.project}: a Claude Code session's answer (prompt ${ASSIST_PROMPT_VERSION})`); raw = input.answers; + const pr = assistPrompt({ manifest, request, scope, model: "claude-sonnet-5-5", llm: deps.llm }); + recordSessionAnswer({ phase: "assist", system: pr.system, prompt: pr.user, answer: raw, llm: deps.llm }, slot); } else { const pr = assistPrompt({ manifest, request, scope, model: input.model, llm: deps.llm }); log(`video-assist ${input.project} on ${input.model} (${scope}): one ask, ~${pr.tokens} prompt tokens (prompt ${ASSIST_PROMPT_VERSION})`); @@ -238,7 +243,7 @@ export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistD const ask = deps.ask ?? (<T,>(system: string, user: string, schema: object, model: string, maxTokens: number) => - structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens })); + structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens, call: { phase: "assist", label: request.slice(0, 80), slot } })); try { raw = await ask<unknown>(pr.system, pr.user, ASSIST_OPS_SCHEMA, input.model, 2048); } catch (e) { @@ -248,6 +253,7 @@ export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistD } const parsed = parseAssistAnswer(raw); if (!parsed.ok) { + slot.decide("dropped", parsed.error); if (input.answers !== undefined) throw new VideoAssistRefusal(`the session's answer is refused: ${parsed.error}`); throw new StructuredAnswerError(`${input.model}: ${parsed.error}: ${JSON.stringify(raw ?? null).slice(0, 160)}`); } @@ -257,6 +263,10 @@ export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistD const checked = checkAssistOps(fresh, parsed.ops, { request, scope }); for (const k of checked.ops) log(` proposed: ${k.diff}${k.warning ? ` (${k.warning})` : ""}`); for (const r of checked.refused) log(` refused: ${JSON.stringify(r.op).slice(0, 120)} — ${r.why}`); + slot.decide(checked.ops.length ? "kept" : "dropped", checked.ops.length ? `${plural(checked.ops.length, "edit")} proposed` : "no edit proposed", [ + ...checked.ops.map((k) => ({ text: k.diff, outcome: "kept" as const, why: k.warning ?? "proposed" })), + ...checked.refused.map((r) => ({ text: JSON.stringify(r.op).slice(0, 200), outcome: "dropped" as const, why: r.why })), + ]); const proposals = proposalsDocOf({ at: now().toISOString(), model: input.model, diff --git a/common/lib/report/iterations.test.ts b/common/lib/report/iterations.test.ts @@ -186,6 +186,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 @@ -80,8 +80,14 @@ export type IterationStepStatus = (typeof ITERATION_STEP_STATUSES)[number]; // draft/tasks/trace.ts) — one JSON object a line, like turns.jsonl. // `refresh.json`: a refresh's fetches, build and delta (umtool R4, // draft/refresh/types.ts RefreshFile). -export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl", "refresh.json"] as const; +// `calls.jsonl` / `calls-text.jsonl`: the model log, every model call of the +// iteration's runs and its steps (demo epic D3, lib/llm/callLog.ts) — +// 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). @@ -717,6 +723,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/common/lib/savedVideoWindow-server.ts b/common/lib/savedVideoWindow-server.ts @@ -54,6 +54,7 @@ import { isDriveNotAnswering, onDrive } from "./storageHealth"; import type { Paths } from "./paths"; import { clockForContainer } from "./recordingClock-read.mjs"; import { mapSpan, type RecordingClock } from "./recordingClock.mjs"; +import "./childKillGuard"; // A window cut from a container is seconds of re-encoding; a whole container // on a platter seeks once. Generous, so only a wedged ffmpeg reaches it — diff --git a/common/lib/storageVolumes.ts b/common/lib/storageVolumes.ts @@ -18,6 +18,7 @@ import { type LocationHealthState, } from "./storageHealth"; import { counterSampleMinimumMs, secondsText } from "./storageHealthTimings"; +import "./childKillGuard"; // STORAGE VOLUME PROBES — is this location's disk here, and if not, where? // diff --git a/common/publish/reportExports.ts b/common/publish/reportExports.ts @@ -114,6 +114,7 @@ import { storeHistoryGitDir, revisionExports, } from "./reportHistory"; +import "../lib/childKillGuard"; // A still or a screenshot in report.html: at most this wide, recompressed. export const EXPORT_IMAGE_MAX_WIDTH = 1200; diff --git a/common/publish/sourceAudit.ts b/common/publish/sourceAudit.ts @@ -31,6 +31,7 @@ import os from "node:os"; import path from "node:path"; import { gunzipSync } from "node:zlib"; import { runChildIntoLog } from "../jobs/runChild"; +import "../lib/childKillGuard"; /** A refusal: the step stops, publishes nothing, and says why. */ export class SourceRefusal extends Error { diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -70,6 +70,7 @@ import { type OnePostFetchInput, type OnePostFetchResult, } from "./fetchers"; +import "../lib/childKillGuard"; // "Are we still logged in?" — classified line by line in xGalleryDlSignals.ts // (pure, unit-tested on gallery-dl's real messages): a challenge, a login diff --git a/common/ytdlp/abortedBeforeLaunch.test.ts b/common/ytdlp/abortedBeforeLaunch.test.ts @@ -0,0 +1,85 @@ +// A run that is already cancelled launches nothing (lib/childKillGuard.ts says +// why execa must never be handed an aborted signal): the fake yt-dlp below +// leaves a file behind when it runs, and none is left. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/abortedBeforeLaunch.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { runAudioCheckedYtdlp } from "./audioCheckedDownload"; +import { runOneYtdlp } from "./runOneYtdlp"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "aborted-launch-")); +const RAN = path.join(ROOT, "ran"); +const YTDLP = path.join(ROOT, "fake-ytdlp.mjs"); +await writeFile(YTDLP, `#!/usr/bin/env node\nimport { writeFileSync } from "node:fs";\nwriteFileSync(${JSON.stringify(RAN)}, "ran");\n`); +await chmod(YTDLP, 0o755); +const ran = () => stat(RAN).then(() => true, () => false); +const aborted = () => { + const ac = new AbortController(); + ac.abort(); + return ac.signal; +}; + +test("runOneYtdlp: aborted before launch spawns nothing and logs nothing", async () => { + const said: string[] = []; + const out = await runOneYtdlp({ ytdlpBin: YTDLP, onLog: (l) => said.push(l), signal: aborted() }, ROOT, ["--version"]); + assert.deepEqual(out, { exitCode: null, stderrTail: "", archiveLine: null, formatLine: null }); + assert.deepEqual(said, []); + await new Promise((r) => setTimeout(r, 300)); + assert.equal(await ran(), false, "the fake yt-dlp never ran"); +}); + +test("runOneYtdlp: the same launch, not cancelled, does run (the fake is a real control)", async () => { + const out = await runOneYtdlp({ ytdlpBin: YTDLP, onLog: () => {}, signal: new AbortController().signal }, ROOT, ["--version"]); + assert.equal(out.exitCode, 0); + assert.equal(await ran(), true); + await rm(RAN, { force: true }); +}); + +test("the audio-checked download: aborted before launch is `aborted`, and yt-dlp never ran — over a channel directory that is gone, too", async () => { + for (const channelDir of [path.join(ROOT, "channel"), path.join(ROOT, "removed", "channel")]) { + if (channelDir.includes("/channel") && !channelDir.includes("removed")) await mkdir(path.join(channelDir, "data"), { recursive: true }); + const said: string[] = []; + const out = await runAudioCheckedYtdlp({ + paths: { ytdlpBin: YTDLP, ffmpegBin: "ffmpeg" } as unknown as Paths, + channelDir, + channelConfig: {} as ChannelConfig, + ytdlpArgs: ["--version"], + onLog: (l) => said.push(l), + signal: aborted(), + archiveMarker: "DLOM_ARCHIVE", + expectedVideoIdHint: "vid0000001", + }); + assert.equal(out.kind, "aborted"); + assert.ok(!said.some((l) => l.startsWith("$ ")), "no launch line"); + } + await new Promise((r) => setTimeout(r, 300)); + assert.equal(await ran(), false, "the fake yt-dlp never ran"); +}); + +test("the audio-checked download: cancelled by the log sink on the launch line, yt-dlp is not spawned", async () => { + const channelDir = path.join(ROOT, "channel-log"); + await mkdir(path.join(channelDir, "data"), { recursive: true }); + const ac = new AbortController(); + const out = await runAudioCheckedYtdlp({ + paths: { ytdlpBin: YTDLP, ffmpegBin: "ffmpeg" } as unknown as Paths, + channelDir, + channelConfig: {} as ChannelConfig, + ytdlpArgs: ["--version"], + onLog: (l) => { + if (l.startsWith("$ ")) ac.abort(); + }, + signal: ac.signal, + archiveMarker: "DLOM_ARCHIVE", + expectedVideoIdHint: "vid0000001", + }); + assert.equal(out.kind, "aborted"); + await new Promise((r) => setTimeout(r, 300)); + assert.equal(await ran(), false, "the fake yt-dlp never ran"); +}); diff --git a/common/ytdlp/audioCheckedDownload.ts b/common/ytdlp/audioCheckedDownload.ts @@ -53,6 +53,7 @@ import type { StreamVerdict } from "./ffmpegStreamClassify"; import { probeAudioStream } from "./ffmpegStreamProbe"; import { DLOM_PROBE_MARKER } from "../jobs/progressParsers"; import { jitterYtdlpSleeps } from "../lib/jitter"; +import "../lib/childKillGuard"; const STDERR_TAIL_BYTES = 64 * 1024; const DEFAULT_SIZE_GATE_BYTES = 1024 * 1024; // 1 MiB minimum growth between checks @@ -843,23 +844,35 @@ export async function runAudioCheckedYtdlp( // Derived AbortController: when the caller aborts, we first send // SIGCONT (in case the child is suspended) and then forward to execa. const launchAc = new AbortController(); + // The launched child's pid, once there is one: an abort that arrives + // before the spawn (the log sink below may cancel) has nothing to resume. + let launchedPid: number | undefined; const onParentAbort = () => { - if (child?.pid) { + if (launchedPid) { try { - process.kill(child.pid, "SIGCONT"); + process.kill(launchedPid, "SIGCONT"); } catch {} } launchAc.abort(); }; + // Already cancelled: nothing is launched. execa must never be handed a + // signal that is already aborted — it kills the child at once, and a + // child whose spawn failed (the channel directory removed under a + // cancelled job) has no pid: that kill reaches this process's own group + // (lib/childKillGuard.ts). if (opts.signal.aborted) { - launchAc.abort(); - } else { - opts.signal.addEventListener("abort", onParentAbort, { once: true }); + return { kind: "aborted", exitCode: null, stderrTail: "", archiveLine: null, videoDir: resolvedVideoDir }; } + opts.signal.addEventListener("abort", onParentAbort, { once: true }); // The fixed waits drawn once for this run (lib/jitter.mjs). const spawned = jitterYtdlpSleeps(opts.ytdlpArgs); opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`); + // (A log sink may cancel: asked again at the last moment before the spawn.) + if (launchAc.signal.aborted) { + opts.signal.removeEventListener?.("abort", onParentAbort); + return { kind: "aborted", exitCode: null, stderrTail: "", archiveLine: null, videoDir: resolvedVideoDir }; + } const child = execa(opts.paths.ytdlpBin, spawned, { cwd: opts.channelDir, cancelSignal: launchAc.signal, @@ -867,6 +880,7 @@ export async function runAudioCheckedYtdlp( buffer: false, reject: false, }); + launchedPid = child.pid; let stderrTail = ""; child.stderr?.on("data", (c: Buffer) => { @@ -1203,9 +1217,11 @@ export async function runAudioCheckedYtdlp( process.kill(child.pid, "SIGCONT"); } catch {} } - try { - child.kill("SIGTERM"); - } catch {} + if (child.pid) { + try { + child.kill("SIGTERM"); + } catch {} + } try { await exitPromise; } catch {} diff --git a/common/ytdlp/ffmpegStreamProbe.ts b/common/ytdlp/ffmpegStreamProbe.ts @@ -3,6 +3,7 @@ import { classifyFfmpegProbe, type StreamVerdict, } from "./ffmpegStreamClassify"; +import "../lib/childKillGuard"; export type ProbeAudioStreamOptions = { ffmpegBin: string; diff --git a/common/ytdlp/ffprobeDuration.ts b/common/ytdlp/ffprobeDuration.ts @@ -1,4 +1,5 @@ import { execa } from "execa"; +import "../lib/childKillGuard"; export type ProbeMediaDurationOptions = { ffprobeBin: string; diff --git a/common/ytdlp/metadataScan.ts b/common/ytdlp/metadataScan.ts @@ -49,6 +49,7 @@ import { type MetadataScanRun, } from "../controller/metadataScanStore"; import { jitterYtdlpSleeps } from "../lib/jitter"; +import "../lib/childKillGuard"; // yt-dlp's JSON-subset print template: one JSON object per entry, so the scan // parses lines instead of whole info jsons — and so nothing is ever written to diff --git a/common/ytdlp/runOneYtdlp.ts b/common/ytdlp/runOneYtdlp.ts @@ -13,6 +13,7 @@ import { execa } from "execa"; import type { Paths } from "../lib/paths"; import { observeYtdlpServiceOutcome } from "../lib/serviceCookies-server"; import { jitterYtdlpSleeps } from "../lib/jitter"; +import "../lib/childKillGuard"; export const STDERR_TAIL_BYTES = 64 * 1024; @@ -57,9 +58,17 @@ export async function runOneYtdlp( cwd: string, args: string[], ): Promise<AttemptOutcome> { + // Already cancelled: nothing is launched (and no request is made). execa + // handed an aborted signal kills the child at once, and one whose spawn + // failed — `cwd` removed under a cancelled job — has no pid: that kill + // reaches this process's own group (lib/childKillGuard.ts). The outcome is + // the one a child killed at launch gave: no exit code, the signal aborted. + if (opts.signal.aborted) return { exitCode: null, stderrTail: "", archiveLine: null, formatLine: null }; // The fixed waits drawn once for this run (lib/jitter.mjs). const spawned = jitterYtdlpSleeps(args); opts.onLog(`$ ${opts.ytdlpBin} ${spawned.join(" ")}\n`); + // (A log sink may cancel: asked again at the last moment before the spawn.) + if (opts.signal.aborted) return { exitCode: null, stderrTail: "", archiveLine: null, formatLine: null }; const child = execa(opts.ytdlpBin, spawned, { cwd, cancelSignal: opts.signal, diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -112,6 +112,7 @@ import { skippedShortIds, skipsAsShort, } from "../lib/skipShorts"; +import "../lib/childKillGuard"; export type YtdlpMode = | "store-playlist" @@ -2404,6 +2405,10 @@ async function runChildAndStream( cwd: string, args: string[], ): Promise<string> { + // Already cancelled: nothing is launched, no request counted (as + // runOneYtdlp; lib/childKillGuard.ts says why execa is never handed an + // aborted signal). The caller gates on the signal, as after a killed child. + if (opts.signal.aborted) return ""; const spawned = jitterYtdlpSleeps(args); opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`); if (opts.requestCounter) opts.requestCounter.n++; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,9 @@ # 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). 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 however its `&` and `=` are written — `\u0026`, `&`, `%26`, `%3D` — an `Authorization` value of any scheme, a `Bearer` value, a cookie line, a key that says what it is) loses its value whoever's it is, while a date or a time after `secret:` or `token:` is left as it is, and a failed call's message has its URLs and addresses removed. Links are kept. +- **Cancelling a job whose program never started no longer stops the editor.** A download cancelled after its channel directory was gone sent SIGTERM to the editor's whole process group: Node's `kill()` on a child that failed to spawn has no pid and signals the caller's own group. A kill on such a child is now a no-op in the editor, and umtool and the standalone scripts (the queue lock, `render-mode on -- <cmd>`, loudness, voice, TTS, diarization, `pnpm e2e:all`) check the child's pid before every kill; a sweep test holds them to it. - **A local media library's subtitles may use short cue timings (`01:02.500 --> 01:04.000`).** A Local Archive channel (New channel → Local Archive, or `pnpm ops local-media-configure`) scans a folder of recordings with their `.info.json` and `.vtt` or `.srt`, and imports them as records whose video stays in the library. A `.vtt` written with minutes and seconds only — what FFmpeg and hand-made subtitle files write — read as "no usable cues" and was held for review; it is now read, previewed with its cue count and imported byte for byte. The hours form every published site's captions are read with is unchanged and tried first, so no existing caption file reads differently (checked against 10,874 of the corpus's caption files: 0 cues differ); a short-form line is read only where it does not match, and only strictly: minutes and seconds 00–59, exactly three millisecond digits, hours optional, and a stamp whose hours are too long to be a number is not a cue. A recording whose file name holds a control character, `\` or `:` is now held for review in the preview, saying so, instead of being offered as new and refused at import. - **A published archive is a source: connect it once, sweep it, and fetch its cited clips with no local corpus.** A fresh clone pointed at jeralyzer.pages.dev could search it through the MCP and do nothing else: Create had no corpus to offer, and every clip of a channel the editor did not archive was a 404 `Channel "<slug>" not found`. An archive is now connected by its origin — `/sites` → **Connected archives**, or `pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev"}'` (`"dryRun": true` reads it and writes nothing; `pnpm ops get archives` lists them) — and kept in `settings.remoteArchives`. `TRANSCRIPT_SITE_URL`'s archive is offered without being connected, so a clone set up as AGENTS.md says starts with one. Create offers each connected archive as a sweep's source, preselected when this machine has no corpus of its own, the MCP's `list_sources` lists them and `generate` passes the choice. A sweep over an archive cites that archive's origin, whatever `generation.citationOrigin` says, and its revisions, drafts and refreshes inherit it. A clip window cited from one registers its channel **remote-only** on first need (`fetch-windows` and `fetch-window` take `"archive"`, and the MCP's `fetch_clip` names it): a `config.json` and nothing else, shown as "remote only" in the channel list, skipped by every sync, lane, scan and site build, and left out of the site form's channel picker. On a whole-recording platform (Rumble) a window means downloading the whole recording, which nobody planned for a channel that is not archived here: it is refused with the recording's length and estimated size until the ask carries `"allowWholeRecording": true`. The archive's documents are cached on disk by its build (512 MB by default), read one at a time and paced. `corpus.json` is spec 6 (the export's changelog): each channel names its platform and its page there; an older archive's platform is read from a record's `webpageUrl`. - **A connected archive is untrusted input.** umtool can connect one and is open on the LAN, and everything an archive serves is someone else's JSON. An archive on this machine or its network — loopback, private, link-local and CGNAT addresses in any spelling (decimal, hex, IPv4 carried inside IPv6), a `.local`/`.internal`/`.lan` name, or a name that resolves to one — is refused at connect, before anything is asked of it, unless the editor runs with `ARCHILYZER_ALLOW_PRIVATE_ARCHIVES=1` or the origin is `TRANSCRIPT_SITE_URL`'s or already in `settings.json`; the check is made once, at connect. Its documents are read on its own origin only: a redirect elsewhere is refused unfollowed, a manifest its `corpus.json` names on another origin is not followed, and no document past 32 MB is read or kept. A record's page URL is fetched only when its host is its channel's video platform's own domain or a subdomain (`evilyoutube.com` and `youtube.com.evil.example` are not YouTube); a URL carrying a backslash, whitespace or a control character is refused unparsed, because Node and yt-dlp's Python read its host differently; and what reaches yt-dlp is the URL the check parsed, never the archive's own string. A remote-only channel whose archive was removed from settings is refused before its record is read. diff --git a/editor/app/api/jobs/[id]/model-log/_locate.ts b/editor/app/api/jobs/[id]/model-log/_locate.ts @@ -0,0 +1,10 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { locateJobModelLog } from "yt-dlp-transcript-common/controller/jobModelLog"; + +// The model log of job `id` (demo epic D3): its own, or the iteration's its +// pointer names (only that job's run of it). Null: nothing recorded yet. +export async function locate(id: string) { + return locateJobModelLog(getPaths(), id); +} + +export const JOB_ID = /^[A-Za-z0-9_-]+$/; diff --git a/editor/app/api/jobs/[id]/model-log/call/route.ts b/editor/app/api/jobs/[id]/model-log/call/route.ts @@ -0,0 +1,19 @@ +import { NextResponse } from "next/server"; +import { readModelCallText, readModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; +import { JOB_ID, locate } from "../_locate"; + +export const dynamic = "force-dynamic"; + +// ONE CALL of a job's model log (demo epic D3): its row with every item and +// its whole text (each part kept to 40k characters), when the panel opens it. +// GET /api/jobs/<id>/model-log/call?id=<run.call> +export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + const call = new URL(request.url).searchParams.get("id")?.trim() ?? ""; + if (!JOB_ID.test(id) || !/^\d+\.\d+$/.test(call)) return NextResponse.json({ error: "Invalid id" }, { status: 400 }); + const at = await locate(id); + if (!at) return NextResponse.json({ error: "no model call recorded" }, { status: 404 }); + const row = (await readModelLog(at.files)).calls.find((c) => c.id === call); + if (!row) return NextResponse.json({ error: `no call ${call}` }, { status: 404 }); + return NextResponse.json({ call: row, text: await readModelCallText(at.files, call) }, { headers: { "cache-control": "no-store" } }); +} diff --git a/editor/app/api/jobs/[id]/model-log/route.ts b/editor/app/api/jobs/[id]/model-log/route.ts @@ -0,0 +1,32 @@ +import { NextResponse } from "next/server"; +import { readModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; +import { modelLogView, viewQueryOf } from "yt-dlp-transcript-common/lib/llm/callLogView"; +import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; +import { JOB_ID, locate } from "./_locate"; + +export const dynamic = "force-dynamic"; + +// A JOB'S MODEL LOG (demo epic D3; the record is common's lib/llm/callLog.ts): +// every model call the job made — what was asked (first lines), what came +// back, what code did with it — grouped by phase, one page a group, for the +// job page's panel. Ungated like the job's log beside it (./../log/route.ts +// says why); it carries no key, no header and no host path (the records are +// scrubbed when written). +// GET /api/jobs/<id>/model-log[?outcome=&phase=&offset=&limit=] +// -> { status, where: {article, n} | null, view: ModelLogView | null } +export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + if (!JOB_ID.test(id)) return NextResponse.json({ error: "Invalid id" }, { status: 400 }); + let q; + try { + q = viewQueryOf(new URL(request.url).searchParams); + } catch (e) { + return NextResponse.json({ error: (e as Error).message }, { status: 400 }); + } + const status = getRegistry().get(id)?.status ?? null; + const at = await locate(id); + if (!at) return NextResponse.json({ status, where: null, view: null }, { headers: { "cache-control": "no-store" } }); + // An iteration's log holds other runs: this job's only. + const view = modelLogView(await readModelLog(at.files), { ...q, ...(at.where ? { jobId: id } : {}) }); + return NextResponse.json({ status, where: at.where, view }, { headers: { "cache-control": "no-store" } }); +} diff --git a/editor/app/api/ops/_benchVerdicts.test.ts b/editor/app/api/ops/_benchVerdicts.test.ts @@ -9,7 +9,7 @@ import { jsonReply, startFakeOllama, type FakeOllama } from "yt-dlp-transcript-c import { enqueueVerdictBench, parseBenchVerdictsBody } from "yt-dlp-transcript-common/controller/benchVerdicts"; import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; -import { appendGenerationUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { appendGenerationUsage, isLocalUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; import { readBenchRun } from "yt-dlp-transcript-common/lib/report/draft/bench/index"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; @@ -107,8 +107,11 @@ test("an API and a local model: a bench-verdicts job on draft:local, every answe const [sonnet, qwen] = run.summary.score.models; assert.equal(sonnet!.agreed, 2); // the two CORROBORATED assert.equal(qwen!.agreed, 1); // the one NOT_FOUND - const rows = await readGenerationUsage(paths.generationUsageFile); + const all = await readGenerationUsage(paths.generationUsageFile); + const rows = all.filter((r) => !isLocalUsage(r)); assert.deepEqual(rows.map((r) => [r.model, r.task, r.jobId]), [["claude-sonnet-5-5", "bench-verdicts", out.result.jobId]]); + // The local model's calls: in the ledger at no cost (demo epic D3). + assert.deepEqual(all.filter(isLocalUsage).map((r) => [r.model, r.task, r.jobId, r.usd]), [["qwen3:8b", "bench-verdicts", out.result.jobId, 0]]); assert.ok(rows[0]!.usd > 0); assert.equal(api.requestHeaders.at(-1)!["x-api-key"], FAKE_KEY, "the key file's key"); }); diff --git a/editor/app/api/ops/_clipsSuggest.test.ts b/editor/app/api/ops/_clipsSuggest.test.ts @@ -11,7 +11,7 @@ import { planClipsSuggestJob, projectDirOf, umtoolOrigin, type ClipsSuggestJobDe import { readSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; import { GENERATION_PRESETS, sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; -import { appendGenerationUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { appendGenerationUsage, isLocalUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; import type { AskProposal } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; @@ -170,8 +170,10 @@ test("labels on the local model: draft:local through the arbiter, batches fitted assert.equal(doc!.model, "qwen3:8b"); assert.deepEqual(Object.keys(doc!.items).sort(), ["p002", "p003", "p004", "p005"]); assert.ok(ol.unloads.includes("qwen3:8b")); - // A local run spends nothing on the ledger. - assert.equal((await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id).length, 0); + // A local run spends nothing on the ledger; its calls are there at no cost (demo epic D3). + const mine = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); + assert.equal(mine.filter((r) => !isLocalUsage(r)).length, 0); + assert.ok(mine.length > 0 && mine.every((r) => r.model === "qwen3:8b" && r.usd === 0 && (r.calls ?? 0) > 0)); }); test("the code route: no model is asked; a session's answers are read as a model's and written as claude-code's", async () => { diff --git a/editor/app/api/ops/_generation.test.ts b/editor/app/api/ops/_generation.test.ts @@ -46,11 +46,24 @@ test("both reads are behind the token", async () => { test("generation-usage answers the day's ledger total and the daily cap", async () => { const get = await route("generation-usage"); const none = await callGet(get, "http://localhost/api/ops/generation-usage?day=2026-10-01"); - assert.deepEqual(none.body, { ok: true, day: "2026-10-01", usd: 0, jobs: 0, daily: 7 }); + assert.deepEqual(none.body, { ok: true, day: "2026-10-01", usd: 0, jobs: 0, daily: 7, models: [] }); await mkdir(path.dirname(usageFile), { recursive: true }); - await writeFile(usageFile, [row("2026-10-01", "j1", 1.25), row("2026-10-01", "j2", 0.5), row("2026-10-02", "j3", 9)].join("\n") + "\n"); + // A local job's row (demo epic D3): a model called at no cost — never in the + // spend or its jobs count, always in `models`. + const local = JSON.stringify({ ...JSON.parse(row("2026-10-01", "j4", 0)), model: "qwen3:8b", route: "local", calls: 5, inputTokens: 900, outputTokens: 80 }); + await writeFile(usageFile, [row("2026-10-01", "j1", 1.25), row("2026-10-01", "j2", 0.5), row("2026-10-02", "j3", 9), local].join("\n") + "\n"); const some = await callGet(get, "http://localhost/api/ops/generation-usage?day=2026-10-01"); - assert.deepEqual(some.body, { ok: true, day: "2026-10-01", usd: 1.75, jobs: 2, daily: 7 }); + assert.deepEqual(some.body, { + ok: true, + day: "2026-10-01", + usd: 1.75, + jobs: 2, + daily: 7, + models: [ + { model: "claude-sonnet-5-5", route: "api", calls: 0, jobs: 2, inputTokens: 2, outputTokens: 2 }, + { model: "qwen3:8b", route: "local", calls: 5, jobs: 1, inputTokens: 900, outputTokens: 80 }, + ], + }); const today = await callGet(get, "http://localhost/api/ops/generation-usage"); assert.equal(today.body.day, new Date().toISOString().slice(0, 10)); const bad = await callGet(get, "http://localhost/api/ops/generation-usage?day=yesterday"); @@ -68,15 +81,29 @@ test("iterations lists an article's iterations, and one with where its files are await updateIteration("synth-a", 1, { status: "done", ops: { applied: [{ op: "drop" }], refused: [] } }); const get = await route("iterations"); + // Its model log (demo epic D3): two local calls, counted per iteration. + const { ModelLogWriter, modelLogFilesIn, recordModelCall, runWithModelLog } = await import("yt-dlp-transcript-common/lib/llm/callLog-server"); + const { getPaths } = await import("yt-dlp-transcript-common/lib/paths"); + const { iterationDir } = await import("yt-dlp-transcript-common/lib/report/iterations"); + const w = new ModelLogWriter({ files: modelLogFilesIn(iterationDir(getPaths(), "synth-a", 1)), task: "sweep", scrub: {} }); + await runWithModelLog(w, async () => { + recordModelCall({ phase: "terms", model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 2 }); + recordModelCall({ phase: "reading", model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 3 }); + }); + await w.flush(); + const all = await callGet(get, "http://localhost/api/ops/iterations?article=synth-a"); assert.equal(all.status, 200); - const its = all.body.iterations as { n: number; status: string }[]; + const its = all.body.iterations as { n: number; status: string; calls: { calls: number; seconds: number; models: unknown[]; phases: { phase: string }[] } }[]; assert.deepEqual(its.map((i) => [i.n, i.status]), [[1, "done"]]); + assert.deepEqual([its[0]!.calls.calls, its[0]!.calls.seconds, its[0]!.calls.models], [2, 5, [{ model: "qwen3:8b", route: "local", calls: 2 }]]); + assert.deepEqual(its[0]!.calls.phases.map((p) => p.phase), ["terms", "reading"]); assert.deepEqual(all.body.current, { report: null, reportFrom: null, video: null }); const one = await callGet(get, "http://localhost/api/ops/iterations?article=synth-a&n=1"); assert.equal(one.status, 200); assert.equal((one.body.iteration as { kind: string }).kind, "sweep"); + assert.equal((one.body.calls as { calls: number }).calls, 2); const files = one.body.files as Record<string, string | null>; assert.equal(files["sweep.md"], path.join(String(one.body.dir), "sweep.md")); assert.equal(files["report.json"], null); diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts @@ -10,8 +10,9 @@ import { startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testi import { enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-common/controller/reportDraft"; import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; -import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; -import { createIteration, projectOf, readIteration, readIterationFile, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; +import { dayUsage, readGenerationUsage, usageModelsOf } from "yt-dlp-transcript-common/controller/generationUsage"; +import { modelLogFilesIn, readModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; +import { createIteration, iterationDir, projectOf, readIteration, readIterationFile, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; // Run with: @@ -288,3 +289,27 @@ test("a media draft (youtube, release 28 M6): a step on the done iteration, thro const notDone = await enqueueReportDraft({ task: "cut", article: "synth-basic", iteration: 9, model: "qwen3:8b", source }, deps()); assert.match((notDone.result as { error: string }).error, /has no iteration i9/); }); + +test("a local sweep (demo epic D3): its calls in the iteration's model log; the ledger lists its local model at no cost, and no Claude model", async () => { + const r = await run("sweep-pipeline"); + ol.push(...r.turns); + const spentBefore = await dayUsage(paths.generationUsageFile); + const out = await enqueueReportDraft({ task: "sweep", article: "synth-local-only", model: r.model, question: r.question, channels: r.channels, source }, deps()); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + assert.equal(getRegistry().get(out.result.jobId)!.queueKey, "draft:local"); + void out.result.stream.cancel(); + const jobId = out.result.jobId; + const done = await out.result.done; + assert.equal(done.status, "done", await readFile(getRegistry().get(jobId)!.logPath, "utf8")); + const log = await readModelLog(modelLogFilesIn(iterationDir(paths, "synth-local-only", out.iteration))); + assert.equal(log.runs[0]!.jobId, jobId); + assert.deepEqual([...new Set(log.calls.map((c) => c.phase))], ["terms", "reading", "grouping"]); + assert.ok(log.calls.every((c) => c.route === "local")); + const rows = (await readGenerationUsage(paths.generationUsageFile)).filter((x) => x.jobId === jobId); + assert.ok(rows.length > 0, "a local run is in the ledger"); + assert.ok(rows.every((x) => x.route === "local" && x.usd === 0 && x.article === "synth-local-only" && x.iteration === out.iteration && x.task === "sweep")); + const models = usageModelsOf(rows); + assert.deepEqual(models.map((m) => [m.model, m.route, m.calls]), [["qwen3:8b", "local", log.calls.length]]); + assert.ok(!models.some((m) => m.route === "api" || m.model.startsWith("claude")), "a local-only run lists no cloud model"); + assert.deepEqual(await dayUsage(paths.generationUsageFile), spentBefore, "the cap's total and jobs count are the API's alone"); +}); diff --git a/editor/app/api/ops/_videoAssist.test.ts b/editor/app/api/ops/_videoAssist.test.ts @@ -11,7 +11,7 @@ import { planVideoAssistJob, type AssistNoteReply, type VideoAssistJobDeps } fro import { readAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs"; import { GENERATION_PRESETS, sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; -import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; +import { isLocalUsage, readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; // Run with: @@ -99,7 +99,10 @@ test("on the local model (the default route): draft:local through the arbiter, o const { doc } = await readAssistProposals(dir); assert.deepEqual(doc!.diff, ["join 0.22 s → 0.15 s", "smear 0.5 → 0.3"]); assert.ok(ol.unloads.includes("qwen3:8b")); - assert.equal((await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id).length, 0); + // No spend; the local call is in the ledger at no cost (demo epic D3). + const mine = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); + assert.equal(mine.filter((r) => !isLocalUsage(r)).length, 0); + assert.deepEqual(mine.map((r) => [r.task, r.model, r.route, r.usd, r.calls]), [["video-assist", "qwen3:8b", "local", 0, 1]]); const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); assert.equal(m.render.transition, 0.22, "nothing applied"); }); diff --git a/editor/app/api/ops/generation-usage/route.ts b/editor/app/api/ops/generation-usage/route.ts @@ -1,26 +1,29 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; -import { dayUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { dayModels, dayUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; import { readRoute } from "../_read"; import { opsFail } from "../_lib"; export const dynamic = "force-dynamic"; // GET [?day=YYYY-MM-DD] -// -> { ok, day, usd, jobs, daily } +// -> { ok, day, usd, jobs, daily, models: [{model, route, calls, jobs, inputTokens, outputTokens}] } // // The day's Claude API spend on generation (release 27 S9): the usage // ledger's total for the UTC day (default today) — what the daily cap is // checked against (controller/generationUsage.ts) — and the cap itself // (`settings.generation.caps.daily`, 0 = none). The MCP's generation_policy -// and `archilyzer gen policy` show it beside the routes. Read only. +// and `archilyzer gen policy` show it beside the routes. `models`: every model +// the day's generation called and on which route ("api", or "local" with no +// cost, demo epic D3) — a local-only day lists no Claude model. Read only. const DAY = /^\d{4}-\d{2}-\d{2}$/; export async function GET(request: Request) { return readRoute(request, ["day"], async (q) => { const day = q.get("day")?.trim() || utcDay(); if (!DAY.test(day)) return opsFail('"day" must be a date YYYY-MM-DD (UTC)'); - const used = await dayUsage(getPaths().generationUsageFile, day); - return { ...used, daily: getSettings().generation.caps.daily }; + const file = getPaths().generationUsageFile; + const [used, models] = await Promise.all([dayUsage(file, day), dayModels(file, day)]); + return { ...used, daily: getSettings().generation.caps.daily, models }; }); } diff --git a/editor/app/api/ops/iterations/route.ts b/editor/app/api/ops/iterations/route.ts @@ -8,14 +8,21 @@ import { readIterations, } from "yt-dlp-transcript-common/lib/report/iterations"; import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { modelLogFilesIn, readModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; +import { summarizeCalls } from "yt-dlp-transcript-common/lib/llm/callLog"; import { readRoute } from "../_read"; import { opsFail } from "../_lib"; export const dynamic = "force-dynamic"; // GET ?article=<id>[&n=<n>] -// -> { ok, article, current, iterations: [iteration.json…], problems } -// -> with n: { ok, article, current, iteration, dir, files: {<name>: <path> | null} } +// -> { ok, article, current, iterations: [iteration.json… + calls], problems } +// -> with n: { ok, article, current, iteration, dir, files: {<name>: <path> | null}, calls } +// +// `calls` (demo epic D3): the iteration's model log counted — {calls, seconds, +// failed, models: [{model, route, calls}], phases: [{phase, calls, seconds}]} +// — read from calls.jsonl only (never the prompts); `umtool model-log` and +// the Model log panel show the calls themselves. // // An article's iterations (release 27 S9; lib/report/iterations.ts), read // only: every one with which is current, or one with where it lives on the @@ -36,7 +43,8 @@ export async function GET(request: Request) { if (read.iterations.length === 0 && read.problems.length === 0) { return opsFail(`"${article}" has no iterations`, 404); } - return { article, current: read.current, iterations: read.iterations, problems: read.problems }; + const iterations = await Promise.all(read.iterations.map(async (it) => ({ ...it, calls: await callsOf(paths, article, it.n) }))); + return { article, current: read.current, iterations, problems: read.problems }; } const n = Number(rawN); if (!Number.isInteger(n) || n < 1) return opsFail('"n" is an iteration number (1, 2, …)'); @@ -51,6 +59,12 @@ export async function GET(request: Request) { () => null, ); } - return { article, current: read.current, iteration: it, dir: iterationDir(paths, article, n), files }; + return { article, current: read.current, iteration: it, dir: iterationDir(paths, article, n), files, calls: await callsOf(paths, article, n) }; }); } + +async function callsOf(paths: ReturnType<typeof getPaths>, article: string, n: number) { + const { calls } = await readModelLog(modelLogFilesIn(iterationDir(paths, article, n))).catch(() => ({ calls: [] })); + const s = summarizeCalls(calls); + return { calls: s.calls, seconds: s.seconds, failed: s.failed, models: s.models, phases: s.phases }; +} diff --git a/editor/app/jobs/[id]/components/JobModelLog.tsx b/editor/app/jobs/[id]/components/JobModelLog.tsx @@ -0,0 +1,175 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import type { CallOutcome, ModelCall, ModelCallText } from "yt-dlp-transcript-common/lib/llm/callLog"; +import type { ModelLogView, ModelLogViewRow } from "yt-dlp-transcript-common/lib/llm/callLogView"; + +// A JOB'S MODEL LOG (demo epic D3; the record is common's lib/llm/callLog.ts): +// every model call the job made, grouped by phase — what was asked (its first +// lines), what came back, what code did with it and why, the seconds — each +// row opening to the whole prompt and answer, fetched for that row alone. The +// count header: calls, seconds, model and route. Filter: kept / dropped / +// rewritten. Live while the job runs (re-read every POLL_MS, as the log tail +// beside it is). umtool shows the same log on the run page, the iteration and +// the media draft. + +const POLL_MS = 1500; +const FILTERS: ("all" | CallOutcome)[] = ["all", "kept", "dropped", "rewritten"]; +const ROUTE: Record<string, string> = { local: "local", api: "Claude API", "claude-code": "Claude Code" }; +const TONE: Record<CallOutcome, string> = { kept: "text-green-700 dark:text-green-400", dropped: "text-red-700 dark:text-red-400", rewritten: "text-amber-700 dark:text-amber-400", "n/a": "text-muted-foreground" }; + +type Answer = { status: string | null; where: { article: string; n: number } | null; view: ModelLogView | null }; + +function Row({ jobId, row }: { jobId: string; row: ModelLogViewRow }) { + const [open, setOpen] = useState(false); + const [full, setFull] = useState<{ call: ModelCall; text: ModelCallText | null } | null>(null); + const [error, setError] = useState(""); + const toggle = async () => { + setOpen(!open); + if (open || full) return; + const r = await fetch(`/api/jobs/${jobId}/model-log/call?id=${encodeURIComponent(row.id)}`, { cache: "no-store" }).catch(() => null); + const b = r ? await r.json().catch(() => ({})) : {}; + if (r?.ok) setFull(b); + else setError(b.error ?? "the call could not be read"); + }; + const items = (open && full ? full.call.items : row.items) ?? []; + return ( + <li className="border-b last:border-b-0 py-1.5" data-call={row.id} data-call-outcome={row.decision.outcome}> + <button type="button" aria-expanded={open} onClick={() => void toggle()} className="grid w-full grid-cols-[56px_minmax(0,1.3fr)_minmax(0,1fr)_minmax(0,1fr)] gap-3 text-left text-xs hover:bg-muted/50"> + <span className="font-mono tabular-nums text-muted-foreground">{row.seconds.toFixed(1)} s</span> + <span className="min-w-0 whitespace-pre-line break-words"> + {row.label && <span className="block font-mono text-muted-foreground truncate">{row.label}</span>} + {row.promptHead || "(no prompt text)"} + </span> + <span className="min-w-0 whitespace-pre-line break-words font-mono text-muted-foreground">{row.error ? `failed: ${row.error}` : row.answerHead || "(empty)"}</span> + <span className="min-w-0"> + <span className={`font-mono ${TONE[row.decision.outcome]}`}>{row.decision.outcome}</span> + {row.decision.why && <span className="block text-muted-foreground">{row.decision.why}</span>} + </span> + </button> + {items.length > 0 && ( + <ul className="mt-1 ml-[68px] space-y-0.5 text-xs"> + {items.map((it, i) => ( + <li key={i} data-item-outcome={it.outcome}> + <span className={`font-mono ${TONE[it.outcome]}`}>{it.outcome}</span> {it.text} + {it.why && <span className="text-muted-foreground"> — {it.why}</span>} + </li> + ))} + {!open && row.itemsTotal > items.length && <li className="text-muted-foreground">+ {row.itemsTotal - items.length} more</li>} + </ul> + )} + {open && ( + <div className="mt-2 ml-[68px] space-y-2 text-xs" data-call-open=""> + {error && <p role="alert" className="text-red-700 dark:text-red-400">{error}</p>} + {full?.text && ( + <> + <p className="text-muted-foreground"> + <span className="font-mono">{row.model}</span> · {ROUTE[row.route] ?? row.route} · {row.promptChars.toLocaleString("en-US")} characters asked + {row.tokensIn !== undefined ? ` · ${row.tokensIn} tokens in, ${row.tokensOut ?? 0} out` : ""} + </p> + {full.text.system && ( + <details> + <summary className="cursor-pointer text-muted-foreground">System prompt</summary> + <pre className="max-h-72 overflow-auto whitespace-pre-wrap rounded border bg-muted/40 p-2 font-mono">{full.text.system}</pre> + </details> + )} + <pre className="max-h-72 overflow-auto whitespace-pre-wrap rounded border bg-muted/40 p-2 font-mono" data-call-prompt=""> + {full.text.prompt + (full.text.promptCut ? "\n… (cut at 40,000 characters)" : "")} + </pre> + <pre className="max-h-72 overflow-auto whitespace-pre-wrap rounded border bg-muted/40 p-2 font-mono">{full.text.answer || "(empty)"}</pre> + </> + )} + </div> + )} + </li> + ); +} + +export function JobModelLog({ jobId, initiallyRunning }: { jobId: string; initiallyRunning: boolean }) { + const [data, setData] = useState<Answer | null>(null); + const [filter, setFilter] = useState<"all" | CallOutcome>("all"); + const [running, setRunning] = useState(initiallyRunning); + // Rows a group shows (a page more each "Show more"). + const [limit, setLimit] = useState(25); + const busy = useRef(false); + + const load = useCallback(async () => { + if (busy.current) return; + busy.current = true; + try { + const q = `?limit=${limit}${filter === "all" ? "" : `&outcome=${filter}`}`; + const r = await fetch(`/api/jobs/${jobId}/model-log${q}`, { cache: "no-store" }); + if (!r.ok) return; + const b = (await r.json()) as Answer; + setData(b); + setRunning(b.status === "running" || b.status === "queued"); + } catch { + // the next tick asks again + } finally { + busy.current = false; + } + }, [jobId, filter, limit]); + + useEffect(() => { + void load(); + }, [load]); + useEffect(() => { + if (!running) return; + const t = window.setInterval(() => document.visibilityState === "visible" && void load(), POLL_MS); + return () => window.clearInterval(t); + }, [running, load]); + + const v = data?.view ?? null; + const s = v?.summary; + return ( + <section className="rounded border p-3 space-y-2" data-job-model-log={v && v.counts.all ? "calls" : "empty"}> + <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm"> + <h2 className="font-semibold">Model log</h2> + {s && s.calls > 0 && ( + <span className="text-muted-foreground" data-model-log-count={s.calls}> + {s.calls} {s.calls === 1 ? "call" : "calls"} · {s.seconds.toFixed(1)} s · {s.models.map((m) => `${m.model} (${ROUTE[m.route] ?? m.route})`).join(", ")} + {s.failed > 0 ? ` · ${s.failed} failed` : ""} + </span> + )} + {data?.where && <span className="text-xs text-muted-foreground font-mono">{data.where.article} i{data.where.n}</span>} + <span className="ml-auto flex gap-1"> + {FILTERS.map((f) => ( + <button key={f} type="button" aria-pressed={filter === f} onClick={() => setFilter(f)} className={`rounded border px-2 py-0.5 text-xs ${filter === f ? "bg-muted font-medium" : "border-transparent text-muted-foreground"}`}> + {f === "all" ? "All" : f[0]!.toUpperCase() + f.slice(1)} {v ? <span className="font-mono">{v.counts[f]}</span> : null} + </button> + ))} + </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 + ? "No model call yet. Each call appears here as it is made: what was asked, what came back, and what code kept or dropped." + : "This job recorded no model call."} + </p> + ) : ( + v.groups.map((g) => ( + <div key={g.phase} data-phase={g.phase}> + <h3 className="text-xs font-medium uppercase tracking-wide text-muted-foreground"> + {g.label} <span className="font-mono normal-case">{g.calls} · {g.seconds.toFixed(1)} s</span> + </h3> + <ul> + {g.rows.map((r) => ( + <Row key={r.id} jobId={jobId} row={r} /> + ))} + </ul> + {g.more > 0 && ( + <button type="button" className="text-xs underline text-muted-foreground" onClick={() => setLimit((n) => Math.min(200, n + 25))}> + Show more ({g.more} not shown) + </button> + )} + </div> + )) + )} + </section> + ); +} diff --git a/editor/app/jobs/[id]/page.tsx b/editor/app/jobs/[id]/page.tsx @@ -5,10 +5,14 @@ import { notFound } from "next/navigation"; import { getJobEntry } from "yt-dlp-transcript-common/jobs/listJobs"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { JobLogTail } from "./components/JobLogTail"; +import { JobModelLog } from "./components/JobModelLog"; import { jobKindLabel } from "../jobKindLabels"; export const dynamic = "force-dynamic"; +// The job kinds that call a model (their model log is shown under the log). +const MODEL_JOB_KINDS = new Set(["report-draft", "bench-verdicts", "frame-scan"]); + export async function generateMetadata({ params, }: { @@ -112,6 +116,13 @@ export default async function JobDetailPage({ job.status === "running" || job.status === "queued" } /> + {/* The model's side of a generation job (demo epic D3): every call it made. */} + {job.kind && MODEL_JOB_KINDS.has(job.kind) && ( + <JobModelLog + jobId={id} + initiallyRunning={job.status === "running" || job.status === "queued"} + /> + )} </div> ); } diff --git a/editor/e2e/report-draft.spec.ts b/editor/e2e/report-draft.spec.ts @@ -79,7 +79,7 @@ const run = async (name: string) => JSON.parse(await readFile(join(RUNS, `${name test.describe.configure({ mode: "serial" }); -test("a sweep draft: enqueued over ops, followed to done, its iteration read back", async ({ request }) => { +test("a sweep draft: enqueued over ops, followed to done, its iteration read back; its model log on the job page", async ({ request, page }) => { test.setTimeout(120_000); await setup(); const r = await run("sweep-agent"); @@ -110,6 +110,22 @@ test("a sweep draft: enqueued over ops, followed to done, its iteration read bac expect(ledger).toContain(body.jobId!); expect(ledger).not.toContain(FAKE_KEY); expect(api.remaining()).toBe(0); + + // The job page's model log (demo epic D3): the agent's turns and the + // extractor's batches, each opening to what was asked; no key anywhere. + const view = await (await request.get(`${baseUrl}/api/jobs/${body.jobId}/model-log`)).json(); + expect(view.where).toEqual({ article: "synth-e2e", n: 1 }); + expect(view.view.summary.calls).toBeGreaterThanOrEqual(6); + expect(view.view.groups.map((g: { phase: string }) => g.phase)).toEqual(expect.arrayContaining(["reading", "agent"])); + await page.goto(`${baseUrl}/jobs/${body.jobId}`); + const log = page.locator("[data-job-model-log]"); + await expect(log).toHaveAttribute("data-job-model-log", "calls"); + await expect(log.locator("[data-model-log-count]")).toHaveAttribute("data-model-log-count", String(view.view.summary.calls)); + await expect(log.locator("[data-phase=agent] [data-call]").first()).toBeVisible(); + await log.locator("[data-phase=agent] [data-call] button").first().click(); + await expect(log.locator("[data-call-open] [data-call-prompt]").first()).toContainText(r.question); + expect(await page.content()).not.toContain(FAKE_KEY); + if (process.env.E2E_MODEL_LOG_SHOTS) await page.screenshot({ path: join(process.env.E2E_MODEL_LOG_SHOTS, "editor-job-page.png"), fullPage: true }); }); test("a cancel mid-run: job cancel stops the draft and its iteration ends cancelled", async ({ request }) => { diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -92,6 +92,8 @@ import { currentSlot } from "./e2e/testPaths"; // the @serial project runs last (a whole run) // E2E_RACK_SHOTS=1 run the /channels rack screenshot audit // E2E_UI_OPS_SHOTS=<dir> social-channel.spec's Sync screenshots (UI notes #17) go there +// E2E_MODEL_LOG_SHOTS=<dir> report-draft.spec's screenshot of the job page's +// Model log panel goes there (demo epic D3) // E2E_FAKE_YTDLP_AUDIO_CHECK_MODE, E2E_FAKE_YTDLP_CHUNK_DELAY_MS, // E2E_FAKE_YTDLP_CORRUPT_AFTER_CHUNK, E2E_FAKE_YTDLP_CORRUPT_RUNS, // E2E_FAKE_YTDLP_DETERMINISTIC_CORRUPT, E2E_FAKE_YTDLP_RECOVER_ON_RESUME, diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts @@ -24,6 +24,8 @@ import { import { runTask, type TaskDeps } from "yt-dlp-transcript-common/lib/report/draft/tasks/index"; import type { TaskProgress } from "yt-dlp-transcript-common/lib/report/draft/tasks/types"; import { createCorpusTools, type CorpusTools } from "./callTool"; +import { modelLogFilesIn, readModelCallText, readModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; +import { iterationDir } from "yt-dlp-transcript-common/lib/report/iterations"; const RUNS = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft/runs"); const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft"); @@ -351,6 +353,28 @@ test("sweep-pipeline: terms, enumerate, windows, extract (a non-verbatim quote d assert.equal(trace.filter((e) => e.t === "finding").length, 2); assert.deepEqual(trace.at(-1)!.status, "done"); assert.deepEqual(after.coverage, { matched: 1, read: 1, partial: false, unreached: [] }); + + // The model log (demo epic D3): every call, its phase, what code did with it. + const files = modelLogFilesIn(iterationDir(paths, "synth-pipe", it.n)); + const log = await readModelLog(files); + assert.deepEqual(log.runs.map((x) => [x.task, x.model]), [["sweep", "qwen3:8b"]]); + assert.deepEqual(log.calls.map((c) => [c.phase, c.route, c.model]), [["terms", "local", "qwen3:8b"], ["reading", "local", "qwen3:8b"], ["grouping", "local", "qwen3:8b"], ["grouping", "local", "qwen3:8b"]]); + const [terms, extract, group, regroup] = log.calls; + // The second grouping ask (one section held every finding) met the fake's + // empty script: recorded as failed, the first one kept. + assert.match(regroup!.error ?? "", /no structured answer/); + assert.deepEqual(terms!.decision, { outcome: "kept", why: "searched for contest, judges" }); + assert.equal(extract!.label, "extract pie-stream-02@0"); + const lost = extract!.items!.find((x) => x.outcome === "dropped")!; + assert.equal(lost.why, "not verbatim in its window"); + assert.ok(lost.text.includes("I entered the contest and I won")); + assert.equal(extract!.items!.filter((x) => x.outcome === "kept").length, 2); + assert.equal(group!.decision.outcome, "kept"); + assert.match(group!.decision.why, /^placed 2 of 2 findings in \d section/); + assert.ok(log.calls.slice(0, 3).every((c) => c.seconds >= 0 && typeof c.tokensIn === "number")); + const text = (await readModelCallText(files, extract!.id))!; + assert.ok(text.system.startsWith("You read excerpts of an automatic transcript")); + assert.match(text.prompt, /^Research question: Did the baker enter the pie contest\?/); }); test("revise-report: ops over the parent's sweep.md — applied, refused with reasons; quotes untouched; a new quote checked", async () => { 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 @@ -715,7 +720,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/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1232,9 +1232,13 @@ export function usage() { "", "get generation-usage [<day>] is the day's Claude API spend on generation", " (the usage ledger's total for the UTC day, default today) and the daily", - " cap it is checked against: {day, usd, jobs, daily}.", + " cap it is checked against: {day, usd, jobs, daily}; and `models`, every", + " model the day's generation called and on which route (\"local\" at no", + " cost) — a local-only day lists no Claude model.", "get iterations <article> is an article's iterations (iteration.json each)", - " and which is current. (The MCP's generate reads one, with its files.)", + " and which is current, each with `calls`: its model log counted (calls,", + " seconds, failed, models and phases; `umtool model-log <article> <n>` the", + " calls). (The MCP's generate reads one, with its files.)", "", "get transcript <videoId> [--slug <slug>] reads one video's cues off disk", " with no index: a fresh cues.json, else what build-cues would write, else", diff --git a/scripts/diarize-sortformer.mjs b/scripts/diarize-sortformer.mjs @@ -124,7 +124,10 @@ engine.on("error", (err) => fail(`failed to run ${bin}: ${err.message}`, 3)); dec.stdout.pipe(engine.stdin); // The engine exiting early (bad model, unusable backend) closes the pipe under // ffmpeg. That is an expected race, not a crash to report. -engine.stdin.on("error", () => dec.kill("SIGTERM")); +engine.stdin.on("error", () => { + // (A child with no pid never started: Node would signal this process's own group — common/lib/childKillGuard.ts.) + if (dec.pid !== undefined) dec.kill("SIGTERM"); +}); let stdout = ""; engine.stdout.setEncoding("utf8"); @@ -164,6 +167,6 @@ engine.on("close", (code) => { // waiting for that close. Three of these accumulated during development, each // holding a decoder resident for hours. The engine's exit is therefore the // signal to tear the decoder down rather than wait for an EOF that cannot come. - if (dec.exitCode === null && !dec.killed) dec.kill("SIGKILL"); + if (dec.pid !== undefined && dec.exitCode === null && !dec.killed) dec.kill("SIGKILL"); finish(); }); diff --git a/scripts/e2e-all.mjs b/scripts/e2e-all.mjs @@ -236,7 +236,7 @@ async function main(argv) { process.on(sig, () => { for (const c of children) { try { - c.kill(sig); + if (c.pid !== undefined) c.kill(sig); } catch { /* already gone */ } diff --git a/scripts/queue-lock.mjs b/scripts/queue-lock.mjs @@ -425,7 +425,8 @@ function release(holder) { if (holder.exitCode != null || holder.signalCode != null) return resolve(); const hard = setTimeout(() => { try { - holder.kill("SIGKILL"); + // (A child with no pid never started: Node would signal this process's own group — common/lib/childKillGuard.ts.) + if (holder.pid !== undefined) holder.kill("SIGKILL"); } catch { /* already gone */ } @@ -438,7 +439,7 @@ function release(holder) { holder.stdin.end(); } catch { try { - holder.kill("SIGKILL"); + if (holder.pid !== undefined) holder.kill("SIGKILL"); } catch { /* already gone */ } @@ -589,7 +590,7 @@ function installSignalHandlers() { if (signalHits === 1) { if (activeForwardTerm && sig !== "SIGINT") { try { - child?.kill(sig); + if (child?.pid !== undefined) child.kill(sig); } catch { /* already gone */ } @@ -606,7 +607,7 @@ function installSignalHandlers() { } process.stderr.write("queue-lock: forcing shutdown\n"); try { - child?.kill("SIGKILL"); + if (child?.pid !== undefined) child.kill("SIGKILL"); } catch { /* already gone */ } @@ -698,7 +699,7 @@ async function holdLock(lock, name, cmd, timeoutMs, what, mode = {}) { const cleanup = () => { dropHolderFile(); try { - holder.kill("SIGKILL"); + if (holder.pid !== undefined) holder.kill("SIGKILL"); } catch { /* already gone */ } diff --git a/scripts/tts.mjs b/scripts/tts.mjs @@ -113,7 +113,8 @@ async function cleanup() { for (const sig of ["SIGTERM", "SIGINT"]) { process.on(sig, () => { - child?.kill("SIGTERM"); + // (A child with no pid never started: Node would signal this process's own group — common/lib/childKillGuard.ts.) + if (child?.pid !== undefined) child.kill("SIGTERM"); void cleanup().finally(() => process.exit(143)); }); } diff --git a/scripts/voice.mjs b/scripts/voice.mjs @@ -124,7 +124,8 @@ let child = null; const cleanup = () => rm(work, { recursive: true, force: true }).catch(() => {}); for (const sig of ["SIGTERM", "SIGINT"]) { process.on(sig, () => { - child?.kill("SIGTERM"); + // (A child with no pid never started: Node would signal this process's own group — common/lib/childKillGuard.ts.) + if (child?.pid !== undefined) child.kill("SIGTERM"); void cleanup().finally(() => process.exit(143)); }); } diff --git a/umtool/app/api/model-log/call/route.ts b/umtool/app/api/model-log/call/route.ts @@ -0,0 +1,17 @@ +import { readModelCall, sourceOf } from "@/lib/model-log"; +import { fail, ok } from "../../research/_respond"; + +export const dynamic = "force-dynamic"; + +// ONE CALL of the model log (demo epic D3): its row with every item and its +// whole text -- the system prompt, the prompt, the answer (each kept to 40k +// characters) -- fetched when the panel opens the row. +// GET /api/model-log/call?article=<id>&n=<n>&id=<run.call> (or job=<jobId>) +export async function GET(request: Request) { + try { + const sp = new URL(request.url).searchParams; + return ok(await readModelCall(sourceOf(sp), sp.get("id")?.trim() ?? "")); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/model-log/route.ts b/umtool/app/api/model-log/route.ts @@ -0,0 +1,27 @@ +import { viewQueryOf } from "yt-dlp-transcript-common/lib/llm/callLogView"; +import { ModelLogError, readModelLogView, sourceOf } from "@/lib/model-log"; +import { fail, ok } from "../research/_respond"; + +export const dynamic = "force-dynamic"; + +// THE MODEL LOG (demo epic D3): GET answers the panel's view -- the runs, the +// count header, the calls grouped by phase, one page a group -- of an +// iteration (`article`, `n`) or of a job with no iteration (`job`). Read only; +// the panel polls it while its run is live. +// GET /api/model-log?article=<id>&n=<n>[&task=&jobId=&run=&latest=1&outcome=&phase=&offset=&limit=] +// GET /api/model-log?job=<jobId>[&…] +// 404 no such iteration · 400 a bad query · 409 an iteration.json that does not read +export async function GET(request: Request) { + try { + const sp = new URL(request.url).searchParams; + let q; + try { + q = viewQueryOf(sp); + } catch (e) { + throw new ModelLogError((e as Error).message); + } + return ok(await readModelLogView(sourceOf(sp), q)); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/research/runs/[article]/[n]/page.tsx b/umtool/app/research/runs/[article]/[n]/page.tsx @@ -13,7 +13,8 @@ export const dynamic = "force-dynamic"; // A TRANSPARENT RUN (plans/umtool-redesign.md, R3; canvas "Transparent run"): // one sweep iteration of the article store, step by step -- live while it // runs, a replay when it is done (components/research/RunView.tsx). `?run=k` -// picks one of several runs. Read only. A static segment under /research, so +// picks one of several runs; `?view=model` opens the model log (every call +// the run made, demo epic D3) instead of the steps. Read only. A static segment under /research, so // it wins over the case page (`runs` is a reserved case id). export default async function RunPage({ params, @@ -37,7 +38,7 @@ export default async function RunPage({ <div className="flex h-full flex-col"> <AppRail active="research" /> {view ? ( - <RunView key={`${view.article}/${view.n}/${view.run}`} initial={view} /> + <RunView key={`${view.article}/${view.n}/${view.run}`} initial={view} initialPane={sp.view === "model" ? "model" : "steps"} /> ) : ( <> <AppHeader crumbs={[{ href: researchHref(), label: "Research" }, { href: runsHref(), label: "Runs" }, { label: `${article} i${n}` }]} /> diff --git a/umtool/app/settings/generation/page.tsx b/umtool/app/settings/generation/page.tsx @@ -1,5 +1,5 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { lastRunsByTask, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; import PolicyPanel from "@/components/articles/PolicyPanel"; import AppShell from "@/components/shell/AppShell"; import { Panel } from "@/components/ui/panel"; @@ -53,7 +53,7 @@ export default async function GenerationPage() { <main className="deck-main flex-1 p-4"> <div className="grid items-start gap-3 xl:grid-cols-[minmax(0,1fr)_360px]"> {policy ? ( - <PolicyPanel initial={policy} today={today} /> + <PolicyPanel initial={policy} today={today} lastRuns={lastRunsByTask(rows)} /> ) : ( <Panel title="Policy"> <p role="alert" className="m-0 text-[12.5px] text-reject-text" data-policy-error=""> diff --git a/umtool/bin/model-log.ts b/umtool/bin/model-log.ts @@ -0,0 +1,102 @@ +// `umtool model-log` -- the model log from a terminal (demo epic D3; the +// record is common's lib/llm/callLog.ts, the page's panel +// components/model-log/ModelLog.tsx). Run by bin/umtool.mjs through tsx, from +// umtool/ (the `@/` paths). Read only. +// +// umtool model-log <article> <n> [--phase P] [--outcome kept|dropped|rewritten|n/a] +// [--task T] [--run K] [--call <run.call>] [--json] +// umtool model-log --job <jobId> [the same] +// every model call of the iteration's runs (or the job's), by phase: +// the seconds, what code did and why, what was asked, what came back, +// and each item's fate; --call prints one call's whole text +// +// Every line printed for a person goes through `say`: a recorded prompt or +// 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 { 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"; + +const args = process.argv.slice(2); +const VALUED = ["--phase", "--outcome", "--task", "--run", "--call", "--job"]; +const has = (f: string) => args.includes(f); +const val = (f: string) => { + const i = args.indexOf(f); + return i >= 0 ? args[i + 1] : undefined; +}; +const json = has("--json"); +const positional = args.filter((a, i) => !a.startsWith("--") && !VALUED.includes(args[i - 1] ?? "")); +const USAGE = "usage: umtool model-log <article> <n> | --job <jobId> [--phase P] [--outcome kept|dropped|rewritten|n/a] [--task T] [--run K] [--call <run.call>] [--json]"; +const say = (line: string) => process.stdout.write(`${terminalSafe(line)}\n`); +const sayJson = (v: unknown) => process.stdout.write(`${terminalSafeJson(JSON.stringify(v, null, 2))}\n`); +const die = (msg: string, code = 2): never => { + console.error(terminalSafe(`umtool model-log: ${msg}`)); + process.exit(code); +}; + +const job = val("--job"); +const src: ModelLogSource = job ? { job } : { article: positional[0] ?? "", n: Number(positional[1]) }; +if (!job && (!positional[0] || !Number.isInteger(Number(positional[1])))) die(USAGE); +const outcome = val("--outcome"); +if (outcome && !(CALL_OUTCOMES as readonly string[]).includes(outcome)) die(`--outcome is one of ${CALL_OUTCOMES.join(", ")}`); +const runArg = val("--run"); +const run = runArg === undefined ? undefined : Number(runArg); +if (run !== undefined && !Number.isInteger(run)) die("--run is a run number (1, 2, …)"); +const where = "job" in src ? `job ${src.job}` : `${src.article} i${src.n}`; +const secs = (s: number) => `${s.toFixed(1)} s`; +const one = (s: string) => s.replace(/\s+/g, " ").trim(); + +try { + const id = val("--call"); + if (id) { + const { call, text } = await readModelCall(src, id); + if (json) { + sayJson({ call, text }); + process.exit(0); + } + say(`${where} · call ${call.id} · ${call.phase}${call.label ? ` · ${call.label}` : ""} · ${call.model} (${call.route}) · ${secs(call.seconds)} · ${call.decision.outcome}${call.decision.why ? `: ${call.decision.why}` : ""}`); + for (const it of call.items ?? []) say(` ${it.outcome.padEnd(9)} ${one(it.text)}${it.why ? ` — ${it.why}` : ""}`); + if (!text) say("\n(this call's text was not kept)"); + else { + if (text.system) say(`\n── system ──\n${text.system}`); + say(`\n── asked ──\n${text.prompt}${text.promptCut ? "\n… (cut at 40,000 characters)" : ""}`); + say(`\n── came back ──\n${text.answer}${text.answerCut ? "\n… (cut at 40,000 characters)" : ""}`); + } + process.exit(0); + } + // A job's calls in an iteration's log: only its run(s). + const ofJob = "job" in src ? await jobLogOf(src.job) : null; + const log = await readModelLog(ofJob ? ofJob.files : await modelLogFilesOf(src)); + const jobRuns = ofJob?.jobId ? new Set(log.runs.filter((r) => r.jobId === ofJob.jobId).map((r) => r.run)) : null; + const task = val("--task"); + const phase = val("--phase"); + const scoped = log.calls.filter((c) => (!jobRuns || jobRuns.has(c.run)) && callMatches(c, { ...(task ? { task } : {}), ...(run !== undefined ? { run } : {}) })); + 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, full: !!log.full, calls: shown }); + process.exit(0); + } + if (!scoped.length) { + say(`${where}: no model call recorded`); + 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))) { + const list: ModelCall[] = shown.filter((c) => c.phase === p); + say(`\n${phaseLabel(p)} · ${list.length} call${list.length === 1 ? "" : "s"} · ${secs(list.reduce((s, c) => s + c.seconds, 0))}`); + for (const c of list) { + say(` ${c.id.padEnd(6)} ${secs(c.seconds).padStart(7)} ${c.decision.outcome.padEnd(9)} ${c.label ?? ""}${c.decision.why ? ` — ${c.decision.why}` : ""}`); + say(` asked: ${one(c.promptHead).slice(0, 160)}`); + say(` back: ${c.error ? `FAILED ${one(c.error)}` : one(c.answerHead).slice(0, 160)}`); + for (const it of c.items ?? []) if (!outcome || it.outcome === outcome) say(` ${it.outcome.padEnd(9)} ${one(it.text).slice(0, 140)}${it.why ? ` — ${it.why}` : ""}`); + } + } + say(`\nthe whole text of one: umtool model-log ${"job" in src ? `--job ${src.job}` : `${src.article} ${src.n}`} --call <id>`); +} catch (e) { + die((e as Error).message, e instanceof ModelLogError && e.status === 400 ? 2 : 1); +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -991,6 +991,7 @@ const COMMANDS = { inbox: cmdInbox, schedule: () => tsxScript("schedule"), refresh: () => tsxScript("refresh"), + "model-log": () => tsxScript("model-log"), help: usage, }; diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx @@ -12,6 +12,7 @@ import { EditorJobProgress } from "@/components/ui/job-progress"; import ResearchSlot from "@/components/articles/ResearchSlot"; import { RefreshButton } from "@/components/articles/RefreshDialog"; import ExtractorSelect, { extractorBody } from "@/components/articles/ExtractorSelect"; +import ModelLog from "@/components/model-log/ModelLog"; import DeletePlan from "@/components/DeletePlan"; import { usd, type Today } from "@/components/articles/PolicyPanel"; import type { ArticleIterations, DraftJobView, IterationRow, PolicyView } from "@/lib/articles/generation"; @@ -154,7 +155,7 @@ function IterationCard({ comparing: boolean; onCompare: (on: boolean) => void; }) { - const [open, setOpen] = useState<"new" | "chain" | null>(null); + const [open, setOpen] = useState<"new" | "chain" | "log" | null>(null); const g = ctx.policy?.generation; const [copyModel, setCopyModel] = useState(() => ctx.allModels.find((m) => m !== it.model) ?? it.model); const [copyExtractor, setCopyExtractor] = useState(g?.models.extractor ?? ""); @@ -335,6 +336,17 @@ function IterationCard({ onDone={() => ctx.deleted(it.n)} /> )} + {/* The model log (demo epic D3): every call this iteration's runs and steps made. */} + <Button + size="sm" + variant="quiet" + aria-expanded={open === "log"} + aria-label={`Model log of ${it.label}`} + data-model-log-toggle={it.n} + onClick={() => setOpen(open === "log" ? null : "log")} + > + Model log{it.calls ? ` · ${it.calls.calls}` : ""} + </Button> {/* The run page (R3): a sweep's trace, step by step -- the row's quiet secondary action. */} {hasRunPage(it.kind) && ( <Link @@ -354,6 +366,7 @@ function IterationCard({ </div> {open === "new" && <NewIterationForm it={it} ctx={ctx} onDone={() => setOpen(null)} />} {open === "chain" && <ChainPanel article={ctx.article} n={it.n} label={it.label} />} + {open === "log" && <ModelLog className="mt-3 border-t border-[var(--color-line)] pt-3" source={{ article: ctx.article, n: it.n }} live={active || !!runningStep} pollMs={3000} />} </article> ); } diff --git a/umtool/components/articles/PolicyPanel.tsx b/umtool/components/articles/PolicyPanel.tsx @@ -4,6 +4,10 @@ import { useEffect, useState } from "react"; import { Button } from "@/components/ui/button"; import { badgeVariants } from "@/components/ui/badge"; import type { PolicyView } from "@/lib/articles/generation"; +import { plannedModelOf, type GenerationTask } from "yt-dlp-transcript-common/lib/generationSettings"; + +/** A task's last run, from the usage ledger (demo epic D3). */ +export type TaskLastRun = { at: string; jobId: string; models: string[]; route: "api" | "local" | "mixed" }; // THE GENERATION POLICY (release 27 S8): where each task runs (Claude Code, // the API, the local model), the presets that set all four at once, the @@ -22,10 +26,13 @@ export const usd = (v: number) => `$${v.toFixed(2)}`; export default function PolicyPanel({ initial, today: initialToday, + lastRuns = {}, onChange, }: { initial: PolicyView; today: Today | null; + /** Each task's last run (the ledger's newest job of it). */ + lastRuns?: Record<string, TaskLastRun>; onChange?: (p: PolicyView) => void; }) { const [policy, setPolicy] = useState(initial); @@ -86,27 +93,65 @@ export default function PolicyPanel({ </div> <div className="mt-3 grid gap-x-6 gap-y-2 sm:grid-cols-[auto_1fr]"> + {/* Per task (demo epic D3): the route, the model it will run on as the + policy stands, "no API key configured" when it would call the API + with none, and the model(s) of its last run in the ledger. */} <div className="micro pt-1">routes</div> - <div className="flex flex-wrap gap-x-4 gap-y-1"> - {policy.tasks.map((t) => ( - <label key={t} className="flex items-center gap-1.5"> - <span className="text-[var(--color-dim)]">{t}</span> - <select - aria-label={`route ${t}`} - className={field} - value={g.routes[t as keyof typeof g.routes]} - disabled={busy} - onChange={(e) => save({ routes: { ...g.routes, [t]: e.target.value } }, `route ${t}`)} - > - {policy.routes.map((r) => ( - <option key={r} value={r}> - {ROUTE_LABEL[r] ?? r} - </option> - ))} - </select> - </label> - ))} - </div> + <table className="w-full border-collapse text-left" data-policy-tasks=""> + <thead> + <tr className="text-[11px] text-[var(--color-dim)]"> + <th className="py-0.5 pr-3 font-normal">task</th> + <th className="py-0.5 pr-3 font-normal">route</th> + <th className="py-0.5 pr-3 font-normal">will run on</th> + <th className="py-0.5 font-normal">last run</th> + </tr> + </thead> + <tbody> + {policy.tasks.map((t) => { + const plan = plannedModelOf(g, t as GenerationTask); + const noKey = plan.needsKey && !policy.apiKey.configured; + const last = lastRuns[t]; + return ( + <tr key={t} data-task={t} data-task-route={plan.route} className="border-t border-[var(--color-line)]"> + <td className="py-0.5 pr-3 text-[var(--color-dim)]">{t}</td> + <td className="py-0.5 pr-3"> + <select + aria-label={`route ${t}`} + className={field} + value={g.routes[t as keyof typeof g.routes]} + disabled={busy} + onChange={(e) => save({ routes: { ...g.routes, [t]: e.target.value } }, `route ${t}`)} + > + {policy.routes.map((r) => ( + <option key={r} value={r}> + {ROUTE_LABEL[r] ?? r} + </option> + ))} + </select> + </td> + <td className="py-0.5 pr-3" data-task-model={plan.model ?? ""}> + {plan.model ? <span className="font-mono">{plan.model}</span> : <span className="text-[var(--color-dim)]">a Claude Code session</span>} + {noKey && ( + <span data-task-no-key="" className={`ml-2 ${badgeVariants({ variant: "blocking", size: "sm" })}`}> + no API key configured + </span> + )} + </td> + <td className="py-0.5" data-task-last={last ? last.models.join(" ") : ""}> + {last ? ( + <span title={`job ${last.jobId}`}> + <span className="font-mono">{last.models.join(", ")}</span> + <span className="text-[var(--color-dim)]"> · {last.at.slice(0, 10)}</span> + </span> + ) : ( + <span className="text-[var(--color-dim)]">none in the ledger</span> + )} + </td> + </tr> + ); + })} + </tbody> + </table> <div className="micro pt-1">models</div> <div className="flex flex-wrap gap-x-4 gap-y-1"> @@ -198,6 +243,8 @@ export default function PolicyPanel({ <span className={badgeVariants({ variant: policy.keyFile.exists ? "info" : "blocking", size: "sm" })}> {policy.keyFile.exists ? "file found" : "no file"} </span> + {policy.apiKey.from === "env" && <span className="text-[var(--color-dim)]">ANTHROPIC_API_KEY is set</span>} + {!policy.apiKey.configured && <span data-api-key-none="">no API key configured: an API route cannot run</span>} </div> </div> diff --git a/umtool/components/model-log/ModelLog.tsx b/umtool/components/model-log/ModelLog.tsx @@ -0,0 +1,380 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import type { CallOutcome, ModelCall, ModelCallText } from "yt-dlp-transcript-common/lib/llm/callLog"; +import type { ModelLogView, ModelLogViewGroup, ModelLogViewRow } from "yt-dlp-transcript-common/lib/llm/callLogView"; + +// --------------------------------------------------------------------------- +// THE MODEL LOG (demo epic D3; the record is common's lib/llm/callLog.ts): the +// model's side of a run -- every call, grouped by phase (terms → reading → +// meaning check → grouping, then any other), each row what was asked (its +// first lines), what came back, what code did with it and why, and the +// seconds. A row opens to the whole prompt and answer, fetched for that row +// alone; a group shows a page at a time. The count header: calls, seconds, +// the model(s) and route. Filter: kept / dropped / rewritten. +// +// LIVE while the host's run is: GET the view every `pollMs` while the tab is +// visible, one request at a time (the run page's own cadence). Works with no +// AI configured: with no call recorded it says what will appear. +// --------------------------------------------------------------------------- + +export type ModelLogSourceProp = { article: string; n: number } | { job: string }; + +const FILTERS: { key: "all" | CallOutcome; label: string }[] = [ + { key: "all", label: "All" }, + { key: "kept", label: "Kept" }, + { key: "dropped", label: "Dropped" }, + { key: "rewritten", label: "Rewritten" }, +]; + +const ROUTE_LABEL: Record<string, string> = { local: "local", api: "Claude API", "claude-code": "Claude Code" }; + +const secs = (s: number) => (s >= 60 ? `${Math.floor(s / 60)} min ${Math.round(s % 60)} s` : `${s.toFixed(1)} s`); + +function base(source: ModelLogSourceProp, extra: Record<string, string | number | undefined>): string { + const sp = new URLSearchParams(); + if ("job" in source) sp.set("job", source.job); + else { + sp.set("article", source.article); + sp.set("n", String(source.n)); + } + for (const [k, v] of Object.entries(extra)) if (v !== undefined && v !== "") sp.set(k, String(v)); + return sp.toString(); +} + +const OUTCOME_TONE: Record<CallOutcome, string> = { + kept: "text-kept-text", + dropped: "text-reject-text", + rewritten: "text-doubt-text", + "n/a": "text-muted-2", +}; + +function Outcome({ o }: { o: CallOutcome }) { + return <span className={cn("font-mono text-[11px]", OUTCOME_TONE[o])}>{o}</span>; +} + +function Pre({ children, className, ...props }: { children: string; className?: string } & Omit<React.ComponentProps<"pre">, "children">) { + return <pre {...props} className={cn("m-0 max-h-[340px] overflow-auto whitespace-pre-wrap break-words rounded-[2px] bg-reader px-3 py-2 font-mono text-[11.5px] leading-[1.45] text-reader-ink shadow-[inset_0_0_0_1px_var(--reader-edge)]", className)}>{children}</pre>; +} + +function Items({ items, total }: { items: ModelCall["items"]; total: number }) { + if (!items?.length) return null; + return ( + <ul className="m-0 grid list-none gap-0.5 p-0" data-call-items={total}> + {items.map((it, i) => ( + <li key={i} className="grid grid-cols-[70px_minmax(0,1fr)] gap-x-2 text-[12px]" data-item-outcome={it.outcome}> + <Outcome o={it.outcome} /> + <span className="min-w-0"> + <span className="text-text-2">{it.text}</span> + {it.why && <span className={cn("block text-[11.5px]", it.outcome === "dropped" ? "text-text" : "text-muted-2")} data-item-why="">{it.outcome === "kept" ? it.why : `why: ${it.why}`}</span>} + </span> + </li> + ))} + {total > items.length && <li className="text-[11.5px] text-muted-2">+ {total - items.length} more — open the call</li>} + </ul> + ); +} + +function CallRow({ row, source }: { row: ModelLogViewRow; source: ModelLogSourceProp }) { + const [open, setOpen] = useState(false); + const [full, setFull] = useState<{ call: ModelCall; text: ModelCallText | null } | null>(null); + const [error, setError] = useState(""); + const [showSystem, setShowSystem] = useState(false); + const toggle = async () => { + const next = !open; + setOpen(next); + if (!next || full) return; + try { + const r = await fetch(`/api/model-log/call?${base(source, { id: row.id })}`, { cache: "no-store" }); + const b = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + setFull(b); + } catch (e) { + setError((e as Error).message); + } + }; + const d = row.decision; + return ( + <li className="border-b border-seam last:border-b-0" data-call={row.id} data-call-outcome={d.outcome} data-call-phase={row.phase}> + <button + type="button" + aria-expanded={open} + aria-label={`call ${row.id}${row.label ? ` ${row.label}` : ""}`} + onClick={() => void toggle()} + className="grid w-full grid-cols-[52px_minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)] items-start gap-x-3 py-2 text-left hover:bg-panel max-md:grid-cols-[52px_minmax(0,1fr)]" + > + <span className="font-mono text-[11px] tabular-nums text-meter" data-call-seconds={row.seconds}> + {row.seconds.toFixed(1)} s + </span> + <span className="min-w-0"> + {row.label && <span className="block truncate font-mono text-[11px] text-muted-2">{row.label}</span>} + <span className="block whitespace-pre-line break-words text-[12px] text-text-2" data-call-asked=""> + {row.promptHead || "(no prompt text)"} + </span> + </span> + <span className="min-w-0 whitespace-pre-line break-words font-mono text-[11.5px] text-muted max-md:col-start-2" data-call-answer=""> + {row.error ? <span className="text-reject-text">failed: {row.error}</span> : row.answerHead || "(empty)"} + </span> + <span className="min-w-0 text-[12px] max-md:col-start-2" data-call-decision=""> + <Outcome o={d.outcome} /> + {d.why && <span className="block text-muted">{d.why}</span>} + </span> + </button> + {!open && row.itemsTotal > 0 && ( + <div className="pb-2 pl-[64px] max-md:pl-0"> + <Items items={row.items} total={row.itemsTotal} /> + </div> + )} + {open && ( + <div className="grid gap-2 pb-3 pl-[64px] max-md:pl-0" data-call-open=""> + {error && ( + <p role="alert" className="m-0 text-[12px] text-reject-text"> + {error} + </p> + )} + {!full && !error && <p className="m-0 text-[12px] text-muted-2">Reading the call…</p>} + {full && ( + <> + <div className="flex flex-wrap gap-x-3 text-[11.5px] text-muted-2"> + <span className="font-mono">{row.model}</span> + <span>{ROUTE_LABEL[row.route] ?? row.route}</span> + <span>{row.promptChars.toLocaleString("en-US")} characters asked</span> + {row.tokensIn !== undefined && ( + <span> + {row.tokensIn.toLocaleString("en-US")} tokens in · {(row.tokensOut ?? 0).toLocaleString("en-US")} out + </span> + )} + <span>{row.at.slice(11, 19)} UTC</span> + </div> + {full.text ? ( + <> + {full.text.system && ( + <div> + <button type="button" className={buttonVariants({ variant: "quiet", size: "sm" })} aria-expanded={showSystem} onClick={() => setShowSystem((x) => !x)}> + System prompt ({full.text.system.length.toLocaleString("en-US")} characters) + </button> + {showSystem && <Pre>{full.text.system}</Pre>} + </div> + )} + <section> + <span className="micro">Asked</span> + <Pre className="mt-1" data-call-prompt="">{full.text.prompt + (full.text.promptCut ? "\n… (cut at 40,000 characters)" : "")}</Pre> + </section> + <section> + <span className="micro">Came back</span> + <Pre className="mt-1">{(full.text.answer || "(empty)") + (full.text.answerCut ? "\n… (cut at 40,000 characters)" : "")}</Pre> + </section> + </> + ) : ( + <p className="m-0 text-[12px] text-muted-2">This call's text was not kept.</p> + )} + <Items items={full.call.items} total={full.call.items?.length ?? 0} /> + </> + )} + </div> + )} + </li> + ); +} + +function Group({ g, source, more }: { g: ModelLogViewGroup; source: ModelLogSourceProp; more: (g: ModelLogViewGroup) => Promise<void> }) { + const [busy, setBusy] = useState(false); + return ( + <section data-phase={g.phase} data-phase-calls={g.calls}> + <h3 className="micro mb-1 flex items-baseline gap-2"> + {g.label} + <span className="font-mono normal-case tracking-normal text-meter"> + {g.calls} {g.calls === 1 ? "call" : "calls"} · {secs(g.seconds)} + </span> + </h3> + {g.rows.length === 0 ? ( + <p className="m-0 text-[12px] text-muted-2">None matches the filter.</p> + ) : ( + <ul className="m-0 list-none p-0"> + {g.rows.map((r) => ( + <CallRow key={r.id} row={r} source={source} /> + ))} + </ul> + )} + {g.more > 0 && ( + <button + type="button" + disabled={busy} + className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "mt-1")} + onClick={async () => { + setBusy(true); + await more(g).finally(() => setBusy(false)); + }} + > + {g.more} more + </button> + )} + </section> + ); +} + +export default function ModelLog({ + source, + task, + jobId, + latest, + near, + live = false, + pollMs = 2500, + emptyText, + className, +}: { + source: ModelLogSourceProp; + /** Only this task's runs (a media draft's). */ + task?: string; + /** Only this job's run. */ + jobId?: string; + /** The newest run (of `task`). */ + latest?: boolean; + /** The run that began nearest this ISO time (the run page's trace run). */ + near?: string | null; + live?: boolean; + pollMs?: number; + /** What the empty state says will appear. */ + emptyText?: string; + className?: string; +}) { + const [view, setView] = useState<ModelLogView | null>(null); + const [error, setError] = useState(""); + const [filter, setFilter] = useState<"all" | CallOutcome>("all"); + // Rows a "N more" added, kept across polls (by phase). + const extra = useRef(new Map<string, ModelLogViewRow[]>()); + const inFlight = useRef(false); + + // The source by value: a host passes a fresh object each render. + const sourceKey = base(source, {}); + const query = useCallback( + (more: Record<string, string | number | undefined> = {}) => { + const sp = new URLSearchParams(sourceKey); + for (const [k, v] of Object.entries({ task, jobId, latest: latest ? 1 : undefined, near: near ?? undefined, outcome: filter === "all" ? undefined : filter, ...more })) if (v !== undefined && v !== "") sp.set(k, String(v)); + return sp.toString(); + }, + [sourceKey, task, jobId, latest, near, filter], + ); + + const load = useCallback(async () => { + if (inFlight.current) return; + inFlight.current = true; + try { + const r = await fetch(`/api/model-log?${query()}`, { cache: "no-store" }); + const b = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + setView(b as ModelLogView); + setError(""); + } catch (e) { + setError((e as Error).message); + } finally { + inFlight.current = false; + } + }, [query]); + + useEffect(() => { + extra.current.clear(); + void load(); + }, [load]); + + useEffect(() => { + if (!live) return; + const t = window.setInterval(() => { + if (document.visibilityState === "visible") void load(); + }, pollMs); + return () => window.clearInterval(t); + }, [live, pollMs, load]); + + // A run that just ended: one last read, so the final calls are shown. + const wasLive = useRef(live); + useEffect(() => { + if (wasLive.current && !live) void load(); + wasLive.current = live; + }, [live, load]); + + const more = useCallback( + async (g: ModelLogViewGroup) => { + const have = g.rows.length + (extra.current.get(g.phase)?.length ?? 0); + const r = await fetch(`/api/model-log?${query({ phase: g.phase, offset: have })}`, { cache: "no-store" }); + const b = (await r.json().catch(() => null)) as ModelLogView | null; + const page = b?.groups.find((x) => x.phase === g.phase); + if (!r.ok || !page) return; + extra.current.set(g.phase, [...(extra.current.get(g.phase) ?? []), ...page.rows]); + setView((v) => (v ? { ...v } : v)); + }, + [query], + ); + + const groups = (view?.groups ?? []).map((g) => { + const added = extra.current.get(g.phase) ?? []; + const seen = new Set(g.rows.map((r) => r.id)); + const rows = [...g.rows, ...added.filter((r) => !seen.has(r.id))]; + return { ...g, rows, more: Math.max(0, g.calls - rows.length) }; + }); + const s = view?.summary; + const empty = view && view.counts.all === 0; + + return ( + <div className={cn("grid gap-3", className)} data-model-log={empty ? "empty" : view ? "calls" : "loading"} data-model-log-live={live ? "" : undefined}> + <div className="flex flex-wrap items-center gap-x-3 gap-y-1"> + <span className="text-[12.5px] text-text-2" data-model-log-count={s?.calls ?? 0}> + {s ? ( + <> + <span className="font-mono text-meter">{s.calls}</span> {s.calls === 1 ? "call" : "calls"} · <span className="font-mono text-meter">{secs(s.seconds)}</span> + {s.models.length > 0 && ( + <> + {" "} + ·{" "} + <span data-model-log-models={s.models.map((m) => m.model).join(" ")}> + {s.models.map((m) => `${m.model} (${ROUTE_LABEL[m.route] ?? m.route})`).join(", ")} + </span> + </> + )} + {s.failed > 0 && <span className="text-reject-text"> · {s.failed} failed</span>} + </> + ) : ( + "Model log" + )} + </span> + <nav aria-label="Filter calls" className="ml-auto flex items-center gap-1"> + {FILTERS.map((f) => ( + <button + key={f.key} + type="button" + aria-pressed={filter === f.key} + data-filter={f.key} + onClick={() => setFilter(f.key)} + className={cn(buttonVariants({ variant: filter === f.key ? "pressed" : "quiet", size: "sm" }))} + > + {f.label} + {view && <span className="ml-1 font-mono text-[10.5px] text-muted-2">{view.counts[f.key]}</span>} + </button> + ))} + </nav> + </div> + {error && ( + <p role="alert" className="m-0 text-[12px] text-reject-text"> + {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 ?? + (live + ? "No model call yet. Each call appears here as it is made: what was asked, what came back, and what code kept or dropped." + : "No model call recorded. When a model works on this, each call appears here: what was asked, what came back, and what code kept or dropped.")} + </p> + ) : ( + groups.map((g) => <Group key={g.phase} g={g} source={source} more={more} />) + )} + </div> + ); +} diff --git a/umtool/components/projects/DraftPanel.tsx b/umtool/components/projects/DraftPanel.tsx @@ -3,6 +3,7 @@ import { useEffect, useState } from "react"; import { Button } from "@/components/ui/button"; import { EditorJobProgress, type EditorJob } from "@/components/ui/job-progress"; +import ModelLog from "@/components/model-log/ModelLog"; import type { DraftRowView, DraftRunSummary, ProjectIteration } from "@/lib/articles/projectDraft"; // DRAFT WITH <MODEL> (release 28 M9; the Media tab's section heads since P4b): @@ -117,6 +118,7 @@ export function DraftControl({ const [ended, setEnded] = useState<EditorJob | null>(null); const [error, setError] = useState(""); const [sending, setSending] = useState(false); + const [logOpen, setLogOpen] = useState(false); useEffect(() => { if (runningJob) setJobId(runningJob); @@ -211,6 +213,30 @@ export function DraftControl({ </p> )} {run && <RunLine run={run} />} + {/* The model log (demo epic D3): this task's calls -- the running job's, else its last run's. */} + {/* A button, not a <details>: the entries' <summary> is this row's only one (media-surfaces.spec). */} + <div className="text-[11.5px]" data-draft-model-log={row.task}> + <button + type="button" + className="cursor-pointer text-muted hover:text-text" + aria-expanded={logOpen} + aria-label={`Model log of ${row.label}`} + onClick={() => setLogOpen((x) => !x)} + > + {logOpen ? "▾" : "▸"} Model log + </button> + {logOpen && ( + <ModelLog + className="mt-2" + source={{ article: link.article, n: link.n }} + task={row.task} + {...(active && jobId ? { jobId } : { latest: true })} + live={active} + pollMs={2000} + emptyText={`No model call recorded for ${row.label} yet. When it is drafted, each call appears here: what was asked, what came back, and what the checks kept or refused.`} + /> + )} + </div> {error && ( <p role="alert" className="m-0 text-[11.5px] text-reject-text"> {error} diff --git a/umtool/components/research/RunView.tsx b/umtool/components/research/RunView.tsx @@ -15,6 +15,7 @@ import { runApi, runBoardApi, runHref, runsHref } from "@/lib/research/runs-href import type { RunCheck, RunCite, RunStep, RunView as View } from "@/lib/research/runs-types"; import { cn } from "@/lib/utils"; import SpendChart, { type SpendPoint } from "./SpendChart"; +import ModelLog from "@/components/model-log/ModelLog"; // --------------------------------------------------------------------------- // A TRANSPARENT RUN (plans/umtool-redesign.md, R3; canvas "Transparent run"): @@ -260,9 +261,24 @@ function Detail({ step }: { step: RunStep }) { ); } -export default function RunView({ initial }: { initial: View }) { +export type RunPane = "steps" | "model"; + +export default function RunView({ initial, initialPane = "steps" }: { initial: View; initialPane?: RunPane }) { const hydrated = useHydrated(); const [view, setView] = useState<View>(initial); + // The steps (the trace) or the model log (every call, demo epic D3); `?view=model` in the address. + const [pane, setPane] = useState<RunPane>(initialPane); + const choosePane = useCallback((p: RunPane) => { + setPane(p); + try { + const u = new URL(window.location.href); + if (p === "model") u.searchParams.set("view", "model"); + else u.searchParams.delete("view"); + window.history.replaceState(window.history.state, "", u); + } catch { + // the address is a convenience + } + }, []); const [litId, setLitId] = useState<string | null>(null); const [replaying, setReplaying] = useState(false); const [status, setStatus] = useState<{ text: string; tone: "ok" | "error"; href?: string } | null>(null); @@ -431,6 +447,19 @@ export default function RunView({ initial }: { initial: View }) { } actions={ <> + <nav aria-label="Run view" className="flex items-center gap-1" data-run-pane={pane}> + {(["steps", "model"] as const).map((p) => ( + <button + key={p} + type="button" + aria-pressed={pane === p} + onClick={() => choosePane(p)} + className={cn(buttonVariants({ variant: pane === p ? "pressed" : "quiet", size: "sm" }))} + > + {p === "steps" ? "Steps" : "Model log"} + </button> + ))} + </nav> {view.runs.length > 1 && ( <nav aria-label="Runs" className="flex items-center gap-1" data-run-picker=""> <span className="micro mr-1">Run</span> @@ -518,7 +547,11 @@ export default function RunView({ initial }: { initial: View }) { </div> } /> - {view.steps.length === 0 ? ( + {pane === "model" ? ( + <div className="min-h-0 flex-1 overflow-auto px-7 py-4 max-md:px-4" data-run-model-log=""> + <ModelLog source={{ article: view.article, n: view.n }} near={h.startedAt} live={view.live} pollMs={POLL_MS} /> + </div> + ) : view.steps.length === 0 ? ( <div className="px-7 pt-6 text-center text-[12.5px] text-text-2" data-empty=""> {view.live ? "The run has not written a step yet." : "This iteration recorded no run (no trace.jsonl, no turns.jsonl)."} </div> diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -101,6 +101,7 @@ Inbox cannot disagree about what is wrong with one. | `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase | | `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) | | `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | +| `model-log <article> <n> [--phase P] [--outcome kept|dropped|rewritten|n/a] [--task T] [--run K] [--call <id>] [--json]` · `model-log --job <jobId> […]` | the **model log** (the run page's, the Iterations tab's and a media draft's Model log panel): every model call of an iteration's runs and steps, or of a job with no iteration, on every route (local, the Claude API, a Claude Code session), grouped by phase — the seconds, what code did with the answer and why, the first lines asked and answered, and each item kept, dropped or rewritten with its reason; `--call` prints one call's system prompt, prompt and answer whole (each kept to 40,000 characters). Read only. **Exit 0 · 1 no such iteration or call · 2 usage** | | `refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]` · `refresh --check [<article>] [--force]` | the refresh's plan, `--yes` starts it; the daily check now ([refresh.md](refresh.md)) | | `clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]` | **quick clip**: a basic-mode project (`quick-clips/<slug>`, the footage alone), its window asked of the editor (fetch-windows, followed to its end; Rumble fetched whole), `--snap words` its edges snapped to the words heard (the editor's transcribe op), rendered as the take `clip` (`take <p> --id clip --full`: the heavy slot), then the mp4's path and the share line. `--json`: `{project, output, share: {platform, archive, text}, snapped?}`; `--progress ndjson`: events, the last `quick-clip` (the app's `POST /api/report/quick-clip` job). **Exit 0 · 1 failed (the editor, the render) · 2 usage** ([knobs.md](knobs.md#basic-output-the-footage-alone)) | | `provenance <project> [ls] [--json]` · `provenance <project> set [--site-origin URL] [--channel-slug S] [--channel "…"] [--json]` | the project's **provenance**: `siteOrigin` (the archive its QRs open), `channelSlug` (a clip with no channel is from it; `check` blocks without it), `channel` (the display name); `""` removes one. One write, one undo point; the Cut tab's Project › Provenance. The link policy is `link-policy` ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) | @@ -212,6 +213,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c | `corrections <project>` | what the report got wrong, as markdown | form · *project* | | `build <project> [--preset preview\|fast\|final] [--only ONLY] [--dry]` | the build's chain, printed (the Cut tab's Build runs it) | form · *project* | | `chain <article> <n> [--from FROM] [--dry] [--final] [--site-origin SITE-ORIGIN] [--draft-all] [--model MODEL] [--deck] [--stop-before-render] [--allow-whole-recording]` | an article iteration's pipeline to a video | form · queued · *corpus* | +| `model-log [<article>] [<n>] [--job JOB] [--phase PHASE] [--outcome kept\|dropped\|rewritten\|n/a] [--task TASK] [--run N] [--call CALL] [--json]` | the model's side of a run: every call, what was asked, what came back, what code did and why | form · *corpus* | | `index [--rebuild] [--prune] [--since N]` | the project index (the cache) | form · *corpus* | | `new <slug> [--folder FOLDER] [--from FROM] [--site-origin SITE-ORIGIN] [--seed chapters\|frames\|phrase\|reactions] [--target N] [--phrase PHRASE] [--channels CHANNELS] [--prefer PREFER] [--exclude EXCLUDE] [--max N] [--from-posts FROM-POSTS] [--brand BRAND]` | a new project (scaffold) | form · *corpus* | | `doctor` | the tools and the roots on this machine | form · *corpus* | diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -715,6 +715,7 @@ function startDraft(body) { patchIt(article, body.iteration, { research: { ...(r.research ?? {}), phase: "continued", continuedBy: [...(r.research?.continuedBy ?? []), n] } }); } } + if (task === "sweep" && !body.copyOf && Array.isArray(body.channels) && body.channels.includes("synth-kitchen")) return startRealSweep(article, n, id); const slow = /slow/.test(String(body.question ?? body.feedback ?? "")); const job = { id, article, n, task, autonomy: body.autonomy, status: "queued", at: Date.now(), log: [`report-draft ${task} ${article} i${n} (stub)`], timers: [] }; draftJobs.set(id, job); @@ -729,6 +730,45 @@ function startDraft(body) { return { jobId: id, iteration: n }; } +// A sweep over the synthetic draft corpus (`synth-kitchen`) runs FOR REAL +// (demo epic D3): the local pipeline over the MCP's tools, its model the fake +// ollama with the recorded run, each answer held a moment so the model log is +// seen live (e2e/fixtures/run-sweep.ts, a child under tsx). The pipeline marks +// the iteration running and done and writes its model log; the job follows +// the child. +function startRealSweep(article, n, id) { + const job = { id, article, n, task: "sweep", status: "queued", at: Date.now(), log: [`report-draft sweep ${article} i${n} (stub: the pipeline, the fake model)`], timers: [], child: null }; + draftJobs.set(id, job); + const args = [ + path.join(REPO, "umtool/e2e/fixtures/run-sweep.ts"), + "--article", article, "--n", String(n), "--articles", ARTICLES, + "--corpus", path.join(ARTICLES, "..", "synth-draft-corpus"), "--delay", "1500", + ]; + job.timers.push( + setTimeout(() => { + if (job.status !== "queued") return; + job.status = "running"; + const child = spawn(path.join(REPO, "node_modules/.bin/tsx"), args, { cwd: path.join(REPO, "umtool"), stdio: ["ignore", "pipe", "pipe"] }); + job.child = child; + let buf = ""; + const take = (d) => { + buf += d; + const lines = buf.split("\n"); + buf = lines.pop(); + job.log.push(...lines.filter(Boolean)); + }; + child.stdout.on("data", take); + child.stderr.on("data", take); + child.on("close", (code) => { + if (buf) job.log.push(buf); + if (job.status === "cancelled") return; + job.status = code === 0 ? "done" : "failed"; + }); + }, 300), + ); + return { jobId: id, iteration: n }; +} + // ─── a refresh (R4) ─── // The iteration a refresh refreshes: the one named, else the current report's, diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -26,7 +26,7 @@ import { SONG_DATA } from "../../song/paths.mjs"; import { songCapabilities } from "./song-capabilities.mjs"; import { makeSitesFixture } from "./sites-fixture.mjs"; import { makeIterationsFixture } from "./iterations-fixture.mjs"; -import { makeMediaDraftFixture } from "./media-draft-fixture.mjs"; +import { MODEL_LOG_MEDIA_ARTICLE, makeMediaDraftFixture } from "./media-draft-fixture.mjs"; import { makeMediaSurfacesFixture } from "./media-surfaces-fixture.mjs"; import { makeDeleteFixture } from "./delete-fixture.mjs"; import { makeDraftReviewFixture } from "./draft-review-fixture.mjs"; @@ -2603,6 +2603,8 @@ const { sites: SITES, articles: ARTICLES } = makeSitesFixture({ dest, reports, c makeIterationsFixture({ dest, articles: ARTICLES }); // Release 28: the media drafts' article (mdraft), one iteration per task. makeMediaDraftFixture({ dest, articles: ARTICLES }); +// The model log's own (demo epic D3, model-log.spec.ts): one done iteration to draft on. +makeMediaDraftFixture({ dest, articles: ARTICLES, article: MODEL_LOG_MEDIA_ARTICLE, iterations: [1] }); // Release 28 M9: "Draft with" and Draft everything (msurf), drafted canned by the stub. makeMediaSurfacesFixture({ dest, articles: ARTICLES, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // The release 27 follow-up's deletes: psi (in the making) and diff --git a/umtool/e2e/fixtures/media-draft-fixture.mjs b/umtool/e2e/fixtures/media-draft-fixture.mjs @@ -27,10 +27,15 @@ const put = (file, value) => { writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2) + "\n"); }; -export function makeMediaDraftFixture({ dest, articles }) { +// `article` and `iterations`: the same done iterations under another id (the +// model log's spec drafts on its own, demo epic D3: MODEL_LOG_MEDIA_ARTICLE). +export const MODEL_LOG_MEDIA_ARTICLE = "mlog-media"; + +export function makeMediaDraftFixture({ dest, articles, article = MEDIA_DRAFT_ARTICLE, iterations = Object.values(MEDIA_DRAFT_ITERATIONS) }) { + const MEDIA_DRAFT_ARTICLE = article; const report = JSON.parse(readFileSync(path.join(KIT, "reports", "basic.report.json"), "utf8")); const manifest = readFileSync(path.join(KIT, "manifests", "basic.video.manifest.json"), "utf8"); - for (const n of Object.values(MEDIA_DRAFT_ITERATIONS)) { + for (const n of iterations) { const dir = path.join(articles, MEDIA_DRAFT_ARTICLE, "iterations", String(n)); const project = path.join(dest, "gen-projects", MEDIA_DRAFT_ARTICLE, `i${n}`); put(path.join(dir, "iteration.json"), { diff --git a/umtool/e2e/fixtures/run-sweep.ts b/umtool/e2e/fixtures/run-sweep.ts @@ -0,0 +1,63 @@ +// A local sweep run FOR REAL over the synthetic draft corpus — what the e2e +// editor stub does with a `report-draft` sweep on `synth-kitchen` (demo epic +// D3: model-log.spec.ts watches its calls arrive). The pipeline is common's +// (sweep-pipeline), the corpus tools the MCP's over the test kit's synthetic +// corpus, the model the fake ollama scripted with the kit's recorded run +// (common/testing/draft/runs/sweep-pipeline.json), each answer held `--delay` +// ms so a page can see the run while it is live. Test-only; synthetic. +// +// tsx e2e/fixtures/run-sweep.ts --article <id> --n <i> --articles <dir> --corpus <dir> [--delay 1500] +// +// The last line printed is `@@report-draft {article, iteration, task, status, +// summary}`; the exit code is 0 when the sweep is done. + +import { existsSync } from "node:fs"; +import { mkdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; +import { ORIGIN, cuesOf, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; +import { startFakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs"; +import { runTask } from "yt-dlp-transcript-common/lib/report/draft/tasks/index"; + +const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); +const RUNS = path.resolve(/* turbopackIgnore: true */ HERE, "../../../common/testing/draft/runs"); + +const argv = process.argv.slice(2); +const flag = (name: string) => { + const i = argv.indexOf(`--${name}`); + return i < 0 ? undefined : argv[i + 1]; +}; +const article = flag("article") ?? ""; +const n = Number(flag("n")); +const articlesDir = flag("articles") ?? ""; +const corpusDir = flag("corpus") ?? ""; +const delay = Number(flag("delay") ?? "1500"); +if (!article || !Number.isInteger(n) || !articlesDir || !corpusDir) { + console.error("usage: run-sweep.ts --article <id> --n <i> --articles <dir> --corpus <dir> [--delay ms]"); + process.exit(2); +} + +const run = JSON.parse(await readFile(path.join(RUNS, "sweep-pipeline.json"), "utf8")) as { turns: unknown[] }; +const ol = await startFakeOllama(); +const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); +ol.push(...run.turns.map((t) => async () => (await wait(delay), t)) as never[]); +const dir = existsSync(path.join(corpusDir, "corpus.json")) ? corpusDir : await writeDraftCorpus(corpusDir); +const corpus = await createCorpusTools({ source: `local:${dir}` }); +const exportIndexDir = path.join(articlesDir, "..", ".export-index-run-sweep"); +await mkdir(exportIndexDir, { recursive: true }); +let code = 1; +try { + const res = await runTask( + { task: "sweep-pipeline", article, n, origin: ORIGIN }, + { llm: { ollama: { baseUrl: ol.url } }, corpus, cuesOf, paths: { articlesDir, exportIndexDir }, log: (l) => console.log(l) }, + ); + console.log(`@@report-draft ${JSON.stringify({ article, iteration: n, task: "sweep", status: res.status, summary: res.summary })}`); + code = res.status === "done" ? 0 : 1; +} catch (e) { + console.log(`@@report-draft ${JSON.stringify({ article, iteration: n, task: "sweep", status: "failed", summary: (e as Error).message })}`); +} finally { + await corpus.close(); + await ol.close(); +} +process.exit(code); diff --git a/umtool/e2e/model-log.spec.ts b/umtool/e2e/model-log.spec.ts @@ -0,0 +1,169 @@ +import { test, expect, type Page } from "@playwright/test"; +import { rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { RUN_ARTICLE } from "./fixtures/run-trace-fixture.mjs"; +import { MODEL_LOG_MEDIA_ARTICLE } from "./fixtures/media-draft-fixture.mjs"; +import { runHref } from "../lib/research/runs-hrefs"; +import { WARM_TIMEOUT, warm } from "./warm"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// THE MODEL LOG (demo epic D3): the model's side of the work, on screen. A +// local sweep runs FOR REAL in the editor stub (the pipeline over the +// synthetic corpus, its model the fake ollama with the recorded run, each +// answer held a moment — e2e/fixtures/run-sweep.ts): its calls appear on the +// run page while it runs, grouped by phase; the quote the code dropped shows +// its reason; a call opens to its whole prompt; the filter narrows to the +// dropped. The same log on the Iterations tab and on a media draft; with no +// call recorded, the panel says what will appear. +// --------------------------------------------------------------------------- + +const SWEEP = "mlog-sweep"; +const QUESTION = "Did the baker enter the pie contest?"; +// Screenshots for the lane's report (1366×768), when a directory is named. +const SHOTS = process.env.E2E_MODEL_LOG_SHOTS; +const shot = async (page: Page, name: string) => { + if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `${name}.png`) }); +}; + +const log = (page: Page) => page.locator("[data-model-log]").first(); +const calls = (page: Page) => log(page).locator("[data-call]"); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, [ + `${runHref(RUN_ARTICLE, 1)}?view=model`, + `/api/model-log?article=${RUN_ARTICLE}&n=1`, + `/api/model-log/call?article=${RUN_ARTICLE}&n=1&id=1.1`, + `/articles/${MODEL_LOG_MEDIA_ARTICLE}?tab=iterations`, + ]); +}); + +// The sweep's article is this spec's own: gone after it (projects.spec counts +// the store's sweep reports). +const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song"); +test.afterAll(() => rmSync(path.join(FIXTURE, "articles", SWEEP), { recursive: true, force: true })); + +test.use({ viewport: { width: 1366, height: 768 } }); + +test("a local sweep's calls appear live by phase; a dropped quote says why; a call opens to its whole prompt; the filter", async ({ page }) => { + test.setTimeout(120_000); + const made = await page.request.post("/api/articles/generate", { data: { task: "sweep", article: SWEEP, question: QUESTION, channels: ["synth-kitchen"], model: "qwen3:8b" } }); + expect(made.status(), await made.text()).toBe(200); + expect(await made.json()).toMatchObject({ ok: true, iteration: 1 }); + + await page.goto(`${runHref(SWEEP, 1)}?view=model`); + await expect(page.getByRole("navigation", { name: "Run view" })).toHaveAttribute("data-run-pane", "model"); + // LIVE: the run is going and its first calls are on the page. + await expect(async () => { + await expect(page.locator("[data-run-mode]")).toHaveAttribute("data-run-mode", "live", { timeout: 500 }); + await expect(log(page)).toHaveAttribute("data-model-log-live", "", { timeout: 500 }); + expect(await calls(page).count()).toBeGreaterThan(0); + }).toPass({ timeout: 30_000, intervals: [250] }); + await shot(page, "run-page-live"); + // It ends: every call, in the sweep's phases, the count header says so. + await expect(page.locator("[data-run-mode]")).toHaveAttribute("data-run-mode", "replay", { timeout: 60_000 }); + await expect(log(page).locator("[data-model-log-count]")).toHaveAttribute("data-model-log-count", "4", { timeout: 10_000 }); + await expect(log(page).locator("[data-phase]")).toHaveCount(3); + expect(await log(page).locator("[data-phase]").evaluateAll((els) => els.map((e) => e.getAttribute("data-phase")))).toEqual(["terms", "reading", "grouping"]); + await expect(log(page).locator("[data-model-log-models]")).toHaveAttribute("data-model-log-models", "qwen3:8b"); + await expect(log(page)).toContainText("qwen3:8b (local)"); + // The terms call: kept, and what was searched. + const terms = log(page).locator("[data-phase=terms] [data-call]"); + await expect(terms.locator("[data-call-decision]")).toContainText("searched for contest, judges"); + // The reading call: two quotes kept, one dropped, and why. + const reading = log(page).locator("[data-phase=reading] [data-call]"); + await expect(reading.locator("[data-item-outcome=kept]")).toHaveCount(2); + const dropped = reading.locator("[data-item-outcome=dropped]"); + await expect(dropped).toContainText("I entered the contest and I won"); + await expect(dropped.locator("[data-item-why]")).toHaveText("why: not verbatim in its window"); + // The second grouping ask met the fake's empty script: shown failed. + await expect(log(page).locator("[data-phase=grouping] [data-call]").nth(1).locator("[data-call-answer]")).toContainText("failed:"); + await shot(page, "run-page-done"); + + // The whole prompt, fetched for that row alone. + await reading.getByRole("button", { name: /^call 1\.\d+ extract pie-stream-02@0/ }).click(); + const open = reading.locator("[data-call-open]"); + await expect(open.locator("[data-call-prompt]")).toContainText(`Research question: ${QUESTION}`); + await expect(open.locator("[data-call-prompt]")).toContainText("Transcript excerpt:"); + await open.getByRole("button", { name: /^System prompt/ }).click(); + await expect(open).toContainText("You read excerpts of an automatic transcript"); + await shot(page, "run-page-call-open"); + + // The filter: only the calls code dropped something of. + await log(page).getByRole("button", { name: /^Dropped/ }).click(); + await expect(calls(page)).toHaveCount(1); + await expect(calls(page).first()).toHaveAttribute("data-call-phase", "reading"); + await log(page).getByRole("button", { name: /^All/ }).click(); + await expect(calls(page)).toHaveCount(4); + + // The steps are one press away, and the address keeps the pane. + await page.getByRole("button", { name: "Steps" }).click(); + await expect(page.getByRole("group", { name: "Steps" })).toBeVisible(); + expect(new URL(page.url()).searchParams.get("view")).toBeNull(); + + // The Iterations tab: the count on the toggle, the same log under it. + await page.goto(urls.articleHref({ site: "articles", id: SWEEP }, { tab: "iterations" })); + const toggle = page.locator("[data-iteration='1'] [data-model-log-toggle]"); + await expect(toggle).toHaveText("Model log · 4"); + await toggle.click(); + await expect(page.locator("[data-iteration='1'] [data-model-log-count]")).toHaveAttribute("data-model-log-count", "4"); + await shot(page, "iterations-tab"); +}); + +test("a media draft's model log: the task's calls, its drafted fields and what the checks did", async ({ page }) => { + test.setTimeout(120_000); + const r = await page.request.post("/api/articles/generate", { data: { task: "teaser", article: MODEL_LOG_MEDIA_ARTICLE, iteration: 1, model: "qwen3:8b" } }); + expect(r.status(), await r.text()).toBe(200); + await expect + .poll( + async () => { + const list = (await (await page.request.get(`/api/articles/iterations?article=${MODEL_LOG_MEDIA_ARTICLE}`)).json()) as { iterations: { n: number; steps: { task: string; status: string }[] }[] }; + return list.iterations.find((i) => i.n === 1)?.steps.find((s) => s.task === "teaser")?.status ?? "none"; + }, + { timeout: 60_000, intervals: [1000] }, + ) + .toBe("done"); + await page.goto(urls.articleHref({ site: "articles", id: MODEL_LOG_MEDIA_ARTICLE }, { tab: "iterations" })); + await page.locator("[data-media-link='1']").click(); + const section = page.locator("[data-draft-model-log='teaser']"); + await section.getByRole("button", { name: /^Model log of / }).click(); + const panel = section.locator("[data-model-log]"); + await expect(panel).toHaveAttribute("data-model-log", "calls"); + await expect(panel.locator("[data-phase='draft'] [data-call]").first()).toBeVisible(); + await expect(panel.locator("[data-model-log-models]")).toHaveAttribute("data-model-log-models", "qwen3:8b"); + await section.scrollIntoViewIfNeeded(); + await shot(page, "media-draft"); +}); + +test("no call recorded: the panel says what will appear (no AI needed)", async ({ page }) => { + await page.goto(`${runHref(RUN_ARTICLE, 1)}?view=model`); + await expect(log(page)).toHaveAttribute("data-model-log", "empty"); + await expect(log(page).locator("[data-model-log-empty]")).toContainText("No model call recorded. When a model works on this, each call appears here"); + await expect(log(page).locator("[data-model-log-count]")).toHaveAttribute("data-model-log-count", "0"); +}); + +test("settings: per task its route, the model it will run on, no API key when there is none, its last run's model", async ({ page }) => { + await page.goto(urls.generationPolicyHref()); + const policy = page.getByRole("region", { name: "generation policy" }); + const rows = policy.locator("[data-policy-tasks] tbody tr"); + await expect(rows).toHaveCount(17); + for (const t of ["sweep", "narrate", "frames", "revise-report"]) { + const row = policy.locator(`[data-task='${t}']`); + const route = await row.getByRole("combobox", { name: `route ${t}` }).inputValue(); + await expect(row).toHaveAttribute("data-task-route", route); + const model = await row.locator("[data-task-model]").getAttribute("data-task-model"); + if (route === "code") { + expect(model).toBe(""); + await expect(row.locator("[data-task-model]")).toHaveText("a Claude Code session"); + } else expect(model, `${t} on ${route}`).toMatch(route === "api" ? /^claude-/ : /^qwen/); + // No key on the e2e machine (its key file is never written): an API route says so. + const keyed = (await policy.locator("[data-key-file-exists]").getAttribute("data-key-file-exists")) === "yes"; + await expect(row.locator("[data-task-no-key]")).toHaveCount(route === "api" && !keyed ? 1 : 0); + } + // The ledger's fixture row: the sweep's last run was on Sonnet 5.5. + await expect(policy.locator("[data-task='sweep'] [data-task-last]")).toHaveAttribute("data-task-last", "claude-sonnet-5-5"); + await expect(policy.locator("[data-task='threads'] [data-task-last]")).toHaveText("none in the ledger"); + await shot(page, "settings-generation"); +}); diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts @@ -2,6 +2,7 @@ import { readFileSync, statSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { callCountOf } from "@/lib/model-log"; import { listPendingArticles } from "yt-dlp-transcript-common/lib/report/registry"; import { iterationLabel, @@ -180,6 +181,11 @@ export type PolicyView = { routes: readonly string[]; /** The key file's path (as configured, `~` kept) and whether a file is there. Never its content. */ keyFile: { path: string; exists: boolean }; + /** + * Whether an API key is there to use (demo epic D3): ANTHROPIC_API_KEY in + * this process's environment, else the key file. Never the key. + */ + apiKey: { configured: boolean; from: "env" | "file" | null }; /** The models a picker offers: Claude's priced ones, and the local route's. */ models: { api: string[]; local: string[] }; }; @@ -209,6 +215,11 @@ function keyFileExists(p: string): boolean { } } +function apiKeyOf(keyPath: string): PolicyView["apiKey"] { + if ((process.env.ANTHROPIC_API_KEY ?? "").trim()) return { configured: true, from: "env" }; + return keyFileExists(keyPath) ? { configured: true, from: "file" } : { configured: false, from: null }; +} + export async function readPolicy(): Promise<PolicyView> { const answer = await askEditor<{ value?: unknown }>("/api/ops/settings?key=generation"); const raw = (answer.value ?? {}) as Record<string, unknown>; @@ -224,6 +235,7 @@ export async function readPolicy(): Promise<PolicyView> { tasks: GENERATION_TASKS, routes: GENERATION_ROUTES, keyFile: { path: keyPath, exists: keyFileExists(keyPath) }, + apiKey: apiKeyOf(keyPath), models: { api, local }, }; } @@ -349,6 +361,8 @@ export type IterationRow = { currentVideo: boolean; /** A refresh's outcome (R4: iteration.json's `refresh`), else null. */ refresh: { status: string; summary: string } | null; + /** Its model log's count (demo epic D3: every call of its runs and steps), else null. */ + calls: { calls: number; seconds: number } | null; }; /** A project directory's id: its path under REPORTS_ROOT, posix, or null outside it. */ @@ -395,7 +409,7 @@ function refreshOutcomeOf(it: Iteration): IterationRow["refresh"] { return r && typeof r.status === "string" ? { status: r.status, summary: typeof r.summary === "string" ? r.summary : "" } : null; } -function rowOf(it: Iteration, hasReport: Map<number, boolean>, byN: Map<number, Iteration>, current: IterationsCurrent): IterationRow { +function rowOf(it: Iteration, hasReport: Map<number, boolean>, byN: Map<number, Iteration>, current: IterationsCurrent): Omit<IterationRow, "calls"> { let reportFrom: number | null = null; for (let at: number | null = it.n; at !== null; at = byN.get(at)?.parent ?? null) { if (hasReport.get(at)) { @@ -451,7 +465,8 @@ export async function readArticleIterations(article: string): Promise<ArticleIte const hasReport = new Map<number, boolean>(); for (const it of read.iterations) hasReport.set(it.n, (await readIterationFile(article, it.n, "report.json", paths)) !== null); const byN = new Map(read.iterations.map((it) => [it.n, it])); - const rows = read.iterations.map((it) => rowOf(it, hasReport, byN, read.current)).reverse(); + const rows = await Promise.all(read.iterations.map(async (it) => ({ ...rowOf(it, hasReport, byN, read.current), calls: await callCountOf(article, it.n) }))); + rows.reverse(); return { article, pending: !exists(path.join(/* turbopackIgnore: true */ paths.articlesDir, article, "report.json")), diff --git a/umtool/lib/childKill-sweep.test.mjs b/umtool/lib/childKill-sweep.test.mjs @@ -0,0 +1,79 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// Run with: node --test umtool/lib/childKill-sweep.test.mjs (part of `pnpm run test:scripts`) +// +// A KILL ON A CHILD THAT NEVER STARTED SIGNALS THE CALLER'S OWN PROCESS GROUP +// (common/lib/childKillGuard.ts: Node's kill does not look at the pid). common/ +// installs a guard on the prototype; umtool and the standalone scripts are +// processes of their own that never import it, so every `.kill()` on a child +// there checks the pid where it is called. This holds each one to it. + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const SKIP_DIRS = new Set(["node_modules", ".next", ".next-e2e-start", "e2e", "test-results", ".e2e-song", "public", "assets"]); + +function sources(dir, out = []) { + for (const e of readdirSync(dir, { withFileTypes: true })) { + if (e.name.startsWith(".") || SKIP_DIRS.has(e.name)) continue; + const p = path.join(dir, e.name); + if (e.isDirectory()) sources(p, out); + else if (/\.(mjs|cjs|js|ts|tsx|mts)$/.test(e.name) && !/\.test\.|\.d\.ts$/.test(e.name)) out.push(p); + } + return out; +} + +// A kill of a child: `<name>.kill(`, `<name>?.kill(`, or on a member chain +// (`this.child.kill(`, `job.child?.kill(`) — never `process.kill(pid)`, which +// takes a pid and refuses an undefined one. +const KILL = /(?<![\w$.?])([A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)*)\??\.kill\(/g; + +// Each kill on the line whose receiver has no `<receiver>.pid !== undefined` +// (or `?.pid`) on the same line. +function unguardedKills(line) { + const out = []; + for (const m of line.matchAll(KILL)) { + const receiver = m[1]; + if (receiver === "process") continue; + const chain = receiver + .split(/\??\./) + .map((part) => part.replace(/[$]/g, "\\$&")) + .join("\\??\\."); + out.push({ receiver, guarded: new RegExp(`(?<![\\w$])${chain}\\??\\.pid !== undefined`).test(line) }); + } + return out; +} + +test("the sweep's own matcher: a child's kill is found, a guarded one passes, process.kill is not a child's", () => { + const verdict = (line) => unguardedKills(line).map((k) => `${k.receiver}:${k.guarded}`); + assert.deepEqual(verdict("child.kill(sig);"), ["child:false"]); + assert.deepEqual(verdict("child?.kill('SIGTERM');"), ["child:false"]); + assert.deepEqual(verdict("this.child.kill();"), ["this.child:false"]); + assert.deepEqual(verdict("job.child?.kill();"), ["job.child:false"]); + assert.deepEqual(verdict("if (child.pid !== undefined) child.kill(sig);"), ["child:true"]); + assert.deepEqual(verdict("if (child?.pid !== undefined) child.kill(sig);"), ["child:true"]); + assert.deepEqual(verdict("if (job.child?.pid !== undefined) job.child.kill();"), ["job.child:true"]); + // Another child's pid is not this one's check. + assert.deepEqual(verdict("if (other.pid !== undefined) child.kill(sig);"), ["child:false"]); + assert.deepEqual(verdict("if (mychild.pid !== undefined) child.kill(sig);"), ["child:false"]); + assert.deepEqual(verdict("process.kill(pid, 'SIGTERM'); process.kill(-pgid);"), []); +}); + +test("umtool and the scripts check a child's pid at every kill", () => { + const unguarded = []; + let kills = 0; + for (const file of [...sources(path.join(ROOT, "umtool")), ...sources(path.join(ROOT, "scripts"))]) { + const lines = readFileSync(file, "utf8").split("\n"); + lines.forEach((line, i) => { + if (/^\s*(\/\/|\*|\/\*)/.test(line)) return; + for (const k of unguardedKills(line)) { + kills++; + if (!k.guarded) unguarded.push(`${path.relative(ROOT, file)}:${i + 1}: ${line.trim()}`); + } + }); + } + assert.ok(kills >= 10, `the sweep found the kills (${kills})`); + assert.deepEqual(unguarded, [], "check the pid on the line of the kill: `if (child.pid !== undefined) child.kill(sig)`"); +}); diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -847,6 +847,18 @@ export const GROUPS = [ ], }, { + cmd: "model-log", + usage: [ + " umtool model-log <article> <n> | --job <jobId> [--phase P] [--outcome kept|dropped|rewritten|n/a] [--task T] [--run K] [--json]", + " the model's side of a run: every call by phase -- seconds, what code did and why, what was", + " asked, what came back, each item's fate; --call <run.call> prints one call's whole text", + ], + docs: [ + ["`model-log <article> <n> [--phase P] [--outcome kept|dropped|rewritten|n/a] [--task T] [--run K] [--call <id>] [--json]` · `model-log --job <jobId> […]`", + "the **model log** (the run page's, the Iterations tab's and a media draft's Model log panel): every model call of an iteration's runs and steps, or of a job with no iteration, on every route (local, the Claude API, a Claude Code session), grouped by phase — the seconds, what code did with the answer and why, the first lines asked and answered, and each item kept, dropped or rewritten with its reason; `--call` prints one call's system prompt, prompt and answer whole (each kept to 40,000 characters). Read only. **Exit 0 · 1 no such iteration or call · 2 usage**"], + ], + }, + { cmd: "refresh", usage: [ " umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]", diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs @@ -223,6 +223,10 @@ export const VERBS = Object.freeze([ bool("--stop-before-render", "end before the voices: nothing voiced or built"), bool("--allow-whole-recording", "a remote-only channel's windows may download their whole recording (Rumble)"), ], Q), + form("model-log", "corpus", "the model's side of a run: every call, what was asked, what came back, what code did and why", [ + arg("article", { required: false }), num("n", { help: "the iteration" }), opt("--job", { help: "a job with no iteration" }), opt("--phase", { help: "terms, reading, meaning-check, grouping, draft, agent, …" }), + pick("--outcome", ["kept", "dropped", "rewritten", "n/a"]), opt("--task"), num("--run"), opt("--call", { help: "one call's whole text (run.call, e.g. 1.4)" }), bool("--json"), + ]), form("index", "corpus", "the project index (the cache)", [bool("--rebuild"), bool("--prune"), num("--since", { help: "ms" })], { confirm: { what: "prune the index's rows of projects no longer on disk", when: ["--prune"] } }), form("new", "corpus", "a new project (scaffold)", [ arg("slug", { help: "<slug> or <folder>/<slug>" }), opt("--folder"), opt("--from", { type: "ref", help: "a share URL or <channel>/<id> (a report.md: from a terminal)" }), opt("--site-origin"), diff --git a/umtool/lib/cli/verbs.test.mjs b/umtool/lib/cli/verbs.test.mjs @@ -207,7 +207,7 @@ test("a form's flags are flags the CLI still parses (a renamed flag fails here)" // the negation idiom of `--x` (bin/umtool.mjs window); ledger takes any `--<key>` of its schema. const files = [ ...readdirSync(`${UMTOOL}lib/report`).filter((f) => f.endsWith(".mjs") && !f.includes(".test.")).map((f) => `lib/report/${f}`), - "bin/umtool.mjs", "bin/schedule.ts", "bin/refresh.ts", "bin/inbox.ts", "lib/queue/cli.mjs", "lib/annotations/cli.mjs", "lib/phrase-finder/cli.mjs", "lib/ingredients/cli.mjs", + "bin/umtool.mjs", "bin/schedule.ts", "bin/refresh.ts", "bin/inbox.ts", "bin/model-log.ts", "lib/queue/cli.mjs", "lib/annotations/cli.mjs", "lib/phrase-finder/cli.mjs", "lib/ingredients/cli.mjs", ]; const src = files.map(read).join("\n"); const GENERIC = new Set(["ledger"]); diff --git a/umtool/lib/create/estimate.mjs b/umtool/lib/create/estimate.mjs @@ -30,7 +30,8 @@ export function spendHistory(rows, tasks = ["sweep", "research"]) { /** @type {Map<string, { task: string, at: string, usd: number, models: Map<string, number> }>} */ const jobs = new Map(); for (const r of rows) { - if (!r || !tasks.includes(r.task) || typeof r.usd !== "number" || !r.jobId) continue; + // A local row (route "local", demo epic D3) records calls, not spend. + if (!r || !tasks.includes(r.task) || typeof r.usd !== "number" || !r.jobId || r.route === "local") continue; const j = jobs.get(r.jobId) ?? { task: r.task, at: r.at ?? "", usd: 0, models: new Map() }; j.usd += r.usd; j.models.set(r.model, (j.models.get(r.model) ?? 0) + r.usd); diff --git a/umtool/lib/loudness.ts b/umtool/lib/loudness.ts @@ -92,7 +92,8 @@ async function runEbur128(abs: string): Promise<{ stderr: string; tookMs: number err += b.toString(); }); const timer = setTimeout(() => { - ff.kill("SIGKILL"); + // (A child with no pid never started: Node would signal this process's own group — common/lib/childKillGuard.ts.) + if (ff.pid !== undefined) ff.kill("SIGKILL"); reject(new Error(`ebur128 on ${labelFor(abs)} took longer than ${MEASURE_TIMEOUT_MS / 60000} minutes`)); }, MEASURE_TIMEOUT_MS); ff.on("error", (e) => { diff --git a/umtool/lib/model-log.ts b/umtool/lib/model-log.ts @@ -0,0 +1,86 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { readIteration, iterationDir } from "yt-dlp-transcript-common/lib/report/iterations"; +import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { modelLogFilesIn, readModelCallText, readModelLog, type ModelLogFiles } from "yt-dlp-transcript-common/lib/llm/callLog-server"; +import { modelLogView, type ModelLogView, type ModelLogViewQuery } from "yt-dlp-transcript-common/lib/llm/callLogView"; +import type { ModelCall, ModelCallText } from "yt-dlp-transcript-common/lib/llm/callLog"; +import { jobModelLogFiles, locateJobModelLog } from "yt-dlp-transcript-common/controller/jobModelLog"; +import { sitesPaths } from "@/lib/articles/sites"; + +// --------------------------------------------------------------------------- +// THE MODEL LOG, read (demo epic D3; the record is common's lib/llm/callLog.ts): +// an iteration's calls.jsonl -- its runs and every step on it, a media draft's +// among them -- or a job's with no iteration (`.generation/calls/<job>/`). +// READ ONLY: the editor's runs write it. The panel +// (components/model-log/ModelLog.tsx) and `umtool model-log` read through here. +// --------------------------------------------------------------------------- + +export class ModelLogError extends Error { + constructor( + message: string, + readonly status = 400, + ) { + super(message); + } +} + +export type ModelLogSource = { article: string; n: number } | { job: string }; + +export function sourceOf(sp: URLSearchParams): ModelLogSource { + const job = sp.get("job")?.trim(); + if (job) return { job }; + const article = sp.get("article")?.trim() ?? ""; + const n = Number(sp.get("n") ?? ""); + return { article, n }; +} + +/** A job's: its own log, or the iteration's its pointer names (then only its run). */ +export async function jobLogOf(job: string): Promise<{ files: ModelLogFiles; jobId?: string }> { + try { + const at = await locateJobModelLog(sitesPaths(), job); + if (at) return { files: at.files, ...(at.where ? { jobId: job } : {}) }; + return { files: jobModelLogFiles(getPaths(), job) }; + } catch (e) { + throw new ModelLogError((e as Error).message); + } +} + +export async function modelLogFilesOf(src: ModelLogSource): Promise<ModelLogFiles> { + if ("job" in src) return (await jobLogOf(src.job)).files; + if (!isReportId(src.article)) throw new ModelLogError(`not an article id: ${JSON.stringify(src.article)}`); + if (!Number.isInteger(src.n) || src.n < 1) throw new ModelLogError(`not an iteration number: ${JSON.stringify(src.n)} (1, 2, …)`); + const paths = sitesPaths(); + const it = await readIteration(src.article, src.n, paths).catch((e: Error) => { + throw new ModelLogError(`${src.article} i${src.n} cannot be read: ${e.message}`, 409); + }); + if (!it) throw new ModelLogError(`"${src.article}" has no iteration i${src.n}`, 404); + return modelLogFilesIn(iterationDir(paths, src.article, src.n)); +} + +export async function readModelLogView(src: ModelLogSource, q: ModelLogViewQuery): Promise<ModelLogView> { + if ("job" in src) { + const at = await jobLogOf(src.job); + return modelLogView(await readModelLog(at.files), { ...q, ...(at.jobId ? { jobId: at.jobId } : {}) }); + } + return modelLogView(await readModelLog(await modelLogFilesOf(src)), q); +} + +/** One call: its row (every item) and its whole text. */ +export async function readModelCall(src: ModelLogSource, id: string): Promise<{ call: ModelCall; text: ModelCallText | null }> { + if (!/^\d+\.\d+$/.test(id)) throw new ModelLogError(`not a call id: ${JSON.stringify(id)} (run.call, e.g. 1.4)`); + const files = await modelLogFilesOf(src); + const call = (await readModelLog(files)).calls.find((c) => c.id === id); + if (!call) throw new ModelLogError(`no call ${id}`, 404); + return { call, text: await readModelCallText(files, id) }; +} + +/** An iteration's call count and seconds, for a list (calls.jsonl only, never the texts). */ +export async function callCountOf(article: string, n: number): Promise<{ calls: number; seconds: number } | null> { + try { + const { calls } = await readModelLog(modelLogFilesIn(iterationDir(sitesPaths(), article, n))); + if (!calls.length) return null; + return { calls: calls.length, seconds: Math.round(calls.reduce((s, c) => s + (c.seconds || 0), 0) * 10) / 10 }; + } catch { + return null; + } +} diff --git a/umtool/lib/report/renderMode.mjs b/umtool/lib/report/renderMode.mjs @@ -308,7 +308,8 @@ async function renderModeChain(cmd, o) { say(` ${RENDER_MODE_REMINDER}`); }, onSignal: (sig) => { - child.kill(sig); + // (A child with no pid never started: Node would signal this process's own group — common/lib/childKillGuard.ts.) + if (child.pid !== undefined) child.kill(sig); }, }, () => exited, diff --git a/umtool/lib/research/model-log.test.ts b/umtool/lib/research/model-log.test.ts @@ -0,0 +1,133 @@ +import { test, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { CallSlot, ModelLogWriter, modelLogFilesIn, recordModelCall, runWithModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; + +// Run with: pnpm -C umtool exec tsx --test lib/research/model-log.test.ts +// +// `umtool model-log` (demo epic D3, the CLI twin of the Model log panel): an +// iteration's calls by phase with what code did and why, a filter, one call's +// whole text, --json; a job's calls followed through its pointer to the +// iteration it ran on. Over a temp article store (ARTICLES_DIR) and ledger dir. + +const UMTOOL = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); +const run = promisify(execFile); +let tmp: string; +let env: NodeJS.ProcessEnv; + +async function cli(...args: string[]): Promise<{ code: number; out: string; err: string }> { + try { + const r = await run(process.execPath, [path.join(UMTOOL, "bin/umtool.mjs"), "model-log", ...args], { cwd: UMTOOL, env }); + return { code: 0, out: r.stdout, err: r.stderr }; + } catch (e) { + const x = e as { code?: number; stdout?: string; stderr?: string }; + return { code: x.code ?? 1, out: x.stdout ?? "", err: x.stderr ?? "" }; + } +} + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-model-log-")); + const articles = path.join(tmp, "reports"); + const dir = path.join(articles, "mlog", "iterations", "1"); + await mkdir(dir, { recursive: true }); + const at = "2026-11-11T10:00:00.000Z"; + await writeFile(path.join(dir, "iteration.json"), JSON.stringify({ format: "archilyzer-iteration", version: 1, article: "mlog", n: 1, kind: "sweep", parent: null, copyOf: null, model: "qwen3:8b", question: "q", status: "done", usage: {}, steps: [], jobId: "job-7", createdAt: at, updatedAt: at })); + const w = new ModelLogWriter({ files: modelLogFilesIn(dir), task: "sweep", jobId: "job-7", model: "qwen3:8b", where: { article: "mlog", iteration: 1 }, scrub: {} }); + const slot = new CallSlot(); + await runWithModelLog(w, async () => { + recordModelCall({ phase: "terms", label: "terms", model: "qwen3:8b", route: "local", system: "Plan.", prompt: "Research question: pies?", answer: { terms: ["pie"] }, seconds: 1.5 }); + recordModelCall({ phase: "reading", label: "extract v1@0", model: "qwen3:8b", route: "local", system: "Read.", prompt: "Research question: pies?\n\nTranscript excerpt:\n[0:00] I made a pie", answer: { items: [] }, seconds: 4.25 }, slot); + slot.decide("kept", "1 of 2 items kept", [ + { text: "“I made a pie”", outcome: "kept", why: "verbatim in its window" }, + { text: "“I won the contest”", outcome: "dropped", why: "not verbatim in its window" }, + ]); + }); + await w.flush(); + // A second iteration whose model answered with terminal control sequences. + const dir2 = path.join(articles, "mlog", "iterations", "2"); + await mkdir(dir2, { recursive: true }); + await writeFile(path.join(dir2, "iteration.json"), JSON.stringify({ format: "archilyzer-iteration", version: 1, article: "mlog", n: 2, kind: "sweep", parent: null, copyOf: null, model: "qwen3:8b", question: "q", status: "done", usage: {}, steps: [], createdAt: at, updatedAt: at })); + const w2 = new ModelLogWriter({ files: modelLogFilesIn(dir2), task: "sweep", model: "qwen3:8b", where: { article: "mlog", iteration: 2 }, scrub: {} }); + const slot2 = new CallSlot(); + await runWithModelLog(w2, async () => { + recordModelCall({ phase: "reading", label: "extract \x1b[31mred", model: "qwen3:8b", route: "local", system: "Read.\x1b[2J", prompt: "asked \x1b]0;owned\x07 this\nsecond line\tkept", answer: "back \x1b[2J\x1b[H wiped \u009b31m and\rover", seconds: 1 }, slot2); + slot2.decide("dropped", "why \x1b[1mbold", [{ text: "item \x1b[5mblink", outcome: "dropped", why: "because \x07bell" }]); + }); + await w2.flush(); + // The job's pointer (what a report-draft job beside its iteration writes). + const usage = path.join(tmp, ".generation", "usage.jsonl"); + await mkdir(path.join(tmp, ".generation", "calls", "job-7"), { recursive: true }); + await writeFile(path.join(tmp, ".generation", "calls", "job-7", "where.json"), JSON.stringify({ v: 1, article: "mlog", n: 1 })); + env = { ...process.env, ARTICLES_DIR: articles, GENERATION_USAGE_FILE: usage }; + delete env.REPORTS_DIR; + delete env.CHANNELS_DIR; + delete env.SONG_DIR; +}); + +after(async () => { + await rm(tmp, { recursive: true, force: true }); +}); + +test("the calls by phase, what code did and why, each item's fate", async () => { + const r = await cli("mlog", "1"); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /^mlog i1 · 2 calls · 5\.8 s · qwen3:8b \(local, 2\)/); + assert.match(r.out, /\nTerms · 1 call · 1\.5 s\n/); + assert.match(r.out, /\nReading · 1 call · 4\.3 s\n/); + assert.match(r.out, /1\.2 +4\.3 s kept +extract v1@0 — 1 of 2 items kept/); + assert.match(r.out, /dropped +“I won the contest” — not verbatim in its window/); + assert.match(r.out, /asked: Research question: pies\?/); +}); + +test("--outcome dropped narrows to the calls that dropped something; --phase to one phase", async () => { + const d = await cli("mlog", "1", "--outcome", "dropped"); + assert.ok(!d.out.includes("Terms ·"), d.out); + assert.match(d.out, /dropped +“I won the contest”/); + assert.ok(!d.out.includes("I made a pie”"), "only the dropped items"); + const p = await cli("mlog", "1", "--phase", "terms"); + assert.ok(p.out.includes("Terms ·") && !p.out.includes("Reading ·")); +}); + +test("--call prints one call's whole text; --json the calls", async () => { + const c = await cli("mlog", "1", "--call", "1.2"); + assert.equal(c.code, 0, c.err); + assert.match(c.out, /── system ──\nRead\./); + assert.match(c.out, /── asked ──\nResearch question: pies\?\n\nTranscript excerpt:\n\[0:00\] I made a pie/); + const j = JSON.parse((await cli("mlog", "1", "--json")).out); + assert.equal(j.summary.calls, 2); + assert.deepEqual(j.calls.map((x: { phase: string }) => x.phase), ["terms", "reading"]); + assert.equal((await cli("mlog", "1", "--call", "9.9")).code, 1); +}); + +test("--job: a job's calls, through its pointer to the iteration it ran on", async () => { + const r = await cli("--job", "job-7"); + assert.equal(r.code, 0, r.err); + assert.match(r.out, /^job job-7 · 2 calls/); + const none = await cli("--job", "job-unknown"); + assert.match(none.out, /job job-unknown: no model call recorded/); + assert.equal((await cli("nope")).code, 2, "usage"); +}); + +test("a recorded text cannot drive the terminal: control sequences are printed as escapes, in the list and in --call; --json is JSON", async () => { + const raw = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/; + const list = await cli("mlog", "2"); + assert.equal(list.code, 0, list.err); + assert.ok(!raw.test(list.out), JSON.stringify(list.out)); + assert.match(list.out, /extract \\x1b\[31mred — why \\x1b\[1mbold/); + assert.match(list.out, /dropped +item \\x1b\[5mblink — because \\x07bell/); + const one = await cli("mlog", "2", "--call", "1.1"); + assert.equal(one.code, 0, one.err); + assert.ok(!raw.test(one.out), JSON.stringify(one.out)); + assert.match(one.out, /── system ──\nRead\.\\x1b\[2J/); + assert.match(one.out, /── asked ──\nasked \\x1b\]0;owned\\x07 this\nsecond line\tkept/, "newlines and tabs stay"); + assert.match(one.out, /── came back ──\nback \\x1b\[2J\\x1b\[H wiped \\x9b31m and\\x0dover/); + // --json: the text as recorded, in JSON's own escapes -- no raw control byte either. + const j = await cli("mlog", "2", "--call", "1.1", "--json"); + assert.ok(!raw.test(j.out)); + assert.equal(JSON.parse(j.out).text.answer, "back \x1b[2J\x1b[H wiped \u009b31m and\rover"); +}); diff --git a/umtool/lib/settings/spend.mjs b/umtool/lib/settings/spend.mjs @@ -18,7 +18,8 @@ export function daySpend(rows, day) { /** @type {Map<string, { jobId: string, at: string, task: string, article: string, iteration: number, models: string[], usd: number }>} */ const jobs = new Map(); for (const r of rows) { - if (!r || r.day !== day || typeof r.usd !== "number") continue; + // A local row (route "local", demo epic D3) is a model called, not spend. + if (!r || r.day !== day || typeof r.usd !== "number" || r.route === "local") continue; const j = jobs.get(r.jobId) ?? { jobId: r.jobId, at: r.at, task: r.task, article: r.article, iteration: r.iteration, models: [], usd: 0 }; j.usd += r.usd; if (!j.models.includes(r.model)) j.models.push(r.model); diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -19,6 +19,9 @@ import { dataRootRefusal } from "./lib/e2eEnvGuard.mjs"; // fixture's copy the app reads as SETTINGS_FILE // E2E_UMTOOL_EXTRA_KINDS set by projects.spec.ts on the CLI it runs: a kind // injected into the registry (lib/projects/kinds.mjs) +// E2E_MODEL_LOG_SHOTS a directory: model-log.spec.ts saves its +// screenshots of the Model log panel there (demo +// epic D3); unset, none is taken // E2E_MODE `start` (the default): the app runs under // `next start` from a build in .next-e2e-start that // scripts/e2e-stamp.mjs vouches for (rebuilt through