commit 4883a601c9f2a0e74b3df229ebb96768aa2b96c5
parent 7e1410ceae0d2d15ac8a90de503153b596e47380
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 07:13:53 -0500
umtool, editor: the Model log panel -- on the run page, the Iterations tab, each media draft and the job page; live while the run is (demo epic D3, item 2)
A list of the calls 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, the seconds, and each item's
fate; a row opens to the whole system prompt, prompt and answer, fetched for
that row alone (/api/model-log/call). A group shows 25 rows at a time; the
list never ships whole texts. The count header: calls, seconds, the
model(s) and route; the filter: kept / dropped / rewritten, each with its
count. With no call recorded it says what will appear (no AI needed).
- the run page (/research/runs/<article>/<n>): Steps | Model log, `?view=model`;
the run's own log by its start time, polled at the run page's cadence
- the article's Iterations tab: "Model log · N" on every iteration
- each media draft (the Media tab): the task's running job, else its last run
- the editor's job page (/jobs/<id>): a generation job's calls -- its own
log, or its iteration's through the `where.json` pointer the job's log
writes when an iteration's log runs inside it
The view is common's (lib/llm/callLogView.ts: runs picked by task, job,
number, time or newest; pages; counts), read by umtool's /api/model-log, the
editor's /api/jobs/<id>/model-log and the CLI to come.
e2e (umtool model-log.spec.ts): the editor stub runs a sweep on the
synthetic corpus FOR REAL (the local pipeline, the fake ollama with the
recorded run, each answer held 1.5 s: e2e/fixtures/run-sweep.ts); its calls
appear on the run page while it is live, the dropped quote says "not
verbatim in its window", the extract call opens to its prompt, Dropped
narrows to it; the Iterations tab's toggle; a teaser draft's log; the empty
state. The editor's report-draft.spec: an API sweep's job page lists its
agent turns and extractor batches, a turn opens to the question asked, and
the page holds no API key. Unit: the view (callLogView.test.ts), the job's
pointer and its locator (jobModelLog.test.ts).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
28 files changed, 1452 insertions(+), 18 deletions(-)
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -220,6 +220,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 |
+| `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/controller/jobModelLog.test.ts b/common/controller/jobModelLog.test.ts
@@ -0,0 +1,67 @@
+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();
+ }
+});
diff --git a/common/controller/jobModelLog.ts b/common/controller/jobModelLog.ts
@@ -5,12 +5,15 @@
// 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.
+// 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 { ModelLogWriter, modelLogFilesIn, processScrub, runWithModelLog, type LocalCallTally, type ModelLogFiles } from "../lib/llm/callLog-server";
+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";
@@ -25,6 +28,8 @@ export function jobModelLogFiles(paths: UsagePaths, jobId: string): ModelLogFile
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
@@ -41,10 +46,18 @@ export function modelLogged<R>(o: { paths: UsagePaths; task: string; model?: str
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 });
+ 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}`));
}
};
@@ -69,3 +82,26 @@ export async function appendLocalUsage(paths: UsagePaths, jobId: string, tally:
}));
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;
+ }
+ if (typeof w.article !== "string" || !Number.isInteger(w.n)) 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/lib/envVars.ts b/common/lib/envVars.ts
@@ -217,6 +217,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: "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/llm/callLog-server.ts b/common/lib/llm/callLog-server.ts
@@ -287,7 +287,10 @@ export class ModelLogWriter {
// 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 }>;
-type Ctx = { writer: ModelLogWriter; tally?: LocalCallTally };
+// `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>;
@@ -295,10 +298,18 @@ function storage(): 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 } = {}): T {
+export function runWithModelLog<T>(writer: ModelLogWriter | null, fn: () => T, o: { tally?: LocalCallTally; onInner?: (where: InnerLogWhere) => void } = {}): T {
if (!writer) return fn();
- const tally = o.tally ?? storage().getStore()?.tally;
- return storage().run({ writer, ...(tally ? { tally } : {}) }, 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 {
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,145 @@
+// 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 {
+ 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[];
+};
+
+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),
+ };
+}
+
+// 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
@@ -12,3 +12,4 @@ export * from "./structured";
export * from "./agent";
export * from "./callLog";
export * from "./callLog-server";
+export * from "./callLogView";
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/jobs/[id]/components/JobModelLog.tsx b/editor/app/jobs/[id]/components/JobModelLog.tsx
@@ -0,0 +1,170 @@
+"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 || 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.MODEL_LOG_SHOTS) await page.screenshot({ path: join(process.env.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/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/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/model-log/ModelLog.tsx b/umtool/components/model-log/ModelLog.tsx
@@ -0,0 +1,375 @@
+"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>
+ )}
+ {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/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -709,6 +709,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);
@@ -723,6 +724,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
@@ -25,7 +25,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";
@@ -2599,6 +2599,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,145 @@
+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.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");
+});
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,
@@ -349,6 +350,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 +398,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 +454,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/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;
+ }
+}