Archilyzer · Source

archilyzer

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

commit e9a7a44fe40a7d77a33dd27cc13e975a06e7f43a
parent 50b456765b142f4c8a7c9d765880a012fec79768
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 07:24:17 -0500

umtool, editor: `umtool model-log <article> <n>` -- the panel's CLI twin; `pnpm ops get iterations` counts each iteration's calls (demo epic D3, item 5)

umtool model-log <article> <n> | --job <jobId> [--phase P] [--outcome
kept|dropped|rewritten|n/a] [--task T] [--run K] [--call <run.call>] [--json]
prints every call by phase -- the seconds, what code did and why, the first
lines asked and answered, each item's fate -- and `--call` one call's whole
text; `--job` follows a job's pointer to the iteration it ran on. A verb
row, its help and docs/cli.md (generated).

GET /api/ops/iterations (pnpm ops get iterations) gives each iteration
`calls`: its model log counted -- calls, seconds, failed, models and phases
-- from calls.jsonl alone.

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

Diffstat:
MCOMMANDS.md | 4+++-
Meditor/app/api/ops/_generation.test.ts | 16+++++++++++++++-
Meditor/app/api/ops/iterations/route.ts | 22++++++++++++++++++----
Mscripts/archilyzer-ops.mjs | 4+++-
Aumtool/bin/model-log.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 1+
Mumtool/docs/cli.md | 2++
Mumtool/lib/cli/groups.mjs | 12++++++++++++
Mumtool/lib/cli/verbs.mjs | 4++++
Mumtool/lib/cli/verbs.test.mjs | 2+-
Aumtool/lib/research/model-log.test.ts | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 256 insertions(+), 8 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -342,7 +342,9 @@ get generation-usage [<day>] is the day's Claude API spend on generation 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/editor/app/api/ops/_generation.test.ts b/editor/app/api/ops/_generation.test.ts @@ -81,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/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/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1170,7 +1170,9 @@ export function usage() { " 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/umtool/bin/model-log.ts b/umtool/bin/model-log.ts @@ -0,0 +1,94 @@ +// `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 +import { CALL_OUTCOMES, callMatches, phaseLabel, phaseOrder, summarizeCalls, 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 die = (msg: string, code = 2): never => { + console.error(`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) { + console.log(JSON.stringify({ call, text }, null, 2)); + process.exit(0); + } + console.log(`${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 ?? []) console.log(` ${it.outcome.padEnd(9)} ${one(it.text)}${it.why ? ` — ${it.why}` : ""}`); + if (!text) console.log("\n(this call's text was not kept)"); + else { + if (text.system) console.log(`\n── system ──\n${text.system}`); + console.log(`\n── asked ──\n${text.prompt}${text.promptCut ? "\n… (cut at 40,000 characters)" : ""}`); + console.log(`\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) { + console.log(JSON.stringify({ source: src, runs: log.runs, summary, calls: shown }, null, 2)); + process.exit(0); + } + if (!scoped.length) { + console.log(`${where}: no model call recorded`); + process.exit(0); + } + console.log(`${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` : ""}`); + const runs = log.runs.filter((r) => scoped.some((c) => c.run === r.run)); + if (runs.length > 1) console.log(`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); + console.log(`\n${phaseLabel(p)} · ${list.length} call${list.length === 1 ? "" : "s"} · ${secs(list.reduce((s, c) => s + c.seconds, 0))}`); + for (const c of list) { + console.log(` ${c.id.padEnd(6)} ${secs(c.seconds).padStart(7)} ${c.decision.outcome.padEnd(9)} ${c.label ?? ""}${c.decision.why ? ` — ${c.decision.why}` : ""}`); + console.log(` asked: ${one(c.promptHead).slice(0, 160)}`); + console.log(` back: ${c.error ? `FAILED ${one(c.error)}` : one(c.answerHead).slice(0, 160)}`); + for (const it of c.items ?? []) if (!outcome || it.outcome === outcome) console.log(` ${it.outcome.padEnd(9)} ${one(it.text).slice(0, 140)}${it.why ? ` — ${it.why}` : ""}`); + } + } + console.log(`\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 @@ -987,6 +987,7 @@ const COMMANDS = { inbox: cmdInbox, schedule: () => tsxScript("schedule"), refresh: () => tsxScript("refresh"), + "model-log": () => tsxScript("model-log"), help: usage, }; diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -100,6 +100,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)) | @@ -204,6 +205,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]` | 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/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs @@ -840,6 +840,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 @@ -198,6 +198,10 @@ export const VERBS = Object.freeze([ arg("article"), num("n", { required: true, help: "the iteration" }), opt("--from", { help: "the step to start at" }), bool("--dry", "print it"), bool("--final"), opt("--site-origin"), bool("--draft-all", "Draft everything"), opt("--model"), bool("--deck"), ], 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/research/model-log.test.ts b/umtool/lib/research/model-log.test.ts @@ -0,0 +1,103 @@ +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(); + // 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"); +});