Archilyzer · Source

archilyzer

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

commit c37861b682b206da3561fdfea0ab9aae98aa6bae
parent f407a8231674eb5b662f0fbec17407a3978946a0
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 07:00:36 -0500

common: the model log -- every model call on every route recorded through ONE function, and local calls in the usage ledger (demo epic D3, item 1)

The record (common/lib/llm/callLog.ts, version 1): an iteration's calls.jsonl
holds a `run` row per run, a `call` row per model call (task, phase, label,
model, route local|api|claude-code, promptChars, the first lines asked and
answered, seconds, tokens in/out when the engine says, error, and the
decision kept|dropped|rewritten|n/a with why, plus each item's fate), and
`decision` rows code appends once it knows what it did with an answer;
calls-text.jsonl beside it keeps each call's system prompt, prompt and
answer, each capped at 40,000 characters, fetched per call. A later stage
adds a phase (the meaning check) and its decisions through the same
`call: {phase, slot}` option, never a new row kind.

The writer (callLog-server.ts): `recordModelCall` is the one function --
structuredAnswer on ollama and on the Claude API, each agent turn, the
sweep-agent's extractor (plainAnswer), and a Claude Code session's posted
answer (recordSessionAnswer) all go through it; it finds the run's writer in
an async context, so nothing records outside a run. runOnIteration opens one
per run (media drafts are steps: the same files, their own task); every
generation job with no iteration (verdicts, frames, clips-suggest,
video-assist, propose-groups, triage, bench, learn, refresh) runs inside its
own `.generation/calls/<jobId>/` log (controller/jobModelLog.ts).

What code did: the sweep pipeline's terms (each term kept, or dropped as a
channel's name, a repeat, past the sixth), each extract call's items (kept
verbatim, or dropped with the reason it already logs), the grouping kept and
the one not; a media draft's attempt per unit; the video assistant's and the
claim groups' proposed and refused ops.

The ledger: a job's local calls go to .generation/usage.jsonl when it ends,
route "local", cost 0, with their call count. API spend and the daily cap are
unchanged (dayUsage counts API rows only; umtool's spend lists skip local
rows). `pnpm ops get generation-usage` gains `models` -- every model the
day called and on which route -- and the editor test proves a local-only
sweep lists no Claude model.

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

Diffstat:
MCOMMANDS.md | 4+++-
Mcommon/controller/benchVerdicts.ts | 5+++--
Mcommon/controller/clipsSuggest.ts | 5+++--
Mcommon/controller/frameScan.ts | 5+++--
Mcommon/controller/generationUsage.ts | 35+++++++++++++++++++++++++++++++++--
Acommon/controller/jobModelLog.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/proposeGroups.ts | 5+++--
Mcommon/controller/reportDraft.ts | 3++-
Mcommon/controller/reportLearn.ts | 3++-
Mcommon/controller/reportRefresh.ts | 3++-
Mcommon/controller/reportTriage.ts | 3++-
Mcommon/controller/reportVerdicts.ts | 5+++--
Mcommon/controller/videoAssist.ts | 5+++--
Mcommon/lib/llm/agent.ts | 40++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/callLog-server.ts | 354+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/callLog.test.ts | 195+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/llm/callLog.ts | 252+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/llm/index.ts | 2++
Mcommon/lib/llm/structured.ts | 61++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/lib/report/draft/tasks/clipsSuggest.ts | 3+++
Mcommon/lib/report/draft/tasks/llmText.ts | 43+++++++++++++++++++++++++++++++++++++++++--
Mcommon/lib/report/draft/tasks/media.ts | 26++++++++++++++++++++++----
Mcommon/lib/report/draft/tasks/proposeGroups.ts | 12+++++++++++-
Mcommon/lib/report/draft/tasks/run.ts | 20+++++++++++++++++++-
Mcommon/lib/report/draft/tasks/sweep-agent.ts | 2++
Mcommon/lib/report/draft/tasks/sweep-pipeline.ts | 53+++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/lib/report/draft/tasks/videoAssist.ts | 12+++++++++++-
Mcommon/lib/report/iterations.ts | 5++++-
Meditor/app/api/ops/_benchVerdicts.test.ts | 7+++++--
Meditor/app/api/ops/_clipsSuggest.test.ts | 8+++++---
Meditor/app/api/ops/_generation.test.ts | 19++++++++++++++++---
Meditor/app/api/ops/_reportDraft.test.ts | 29+++++++++++++++++++++++++++--
Meditor/app/api/ops/_videoAssist.test.ts | 7+++++--
Meditor/app/api/ops/generation-usage/route.ts | 13++++++++-----
Mmcp/src/draftTasks.test.ts | 24++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 4+++-
Mumtool/lib/create/estimate.mjs | 3++-
Mumtool/lib/settings/spend.mjs | 3++-
38 files changed, 1284 insertions(+), 64 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -338,7 +338,9 @@ get coverage <slug> is what a channel holds by date: held, dated (by get generation-usage [<day>] is the day's Claude API spend on generation (the usage ledger's total for the UTC day, default today) and the daily - cap it is checked against: {day, usd, jobs, daily}. + cap it is checked against: {day, usd, jobs, daily}; and `models`, every + model the day's generation called and on which route ("local" at no + cost) — a local-only day lists no Claude model. get iterations <article> is an article's iterations (iteration.json each) and which is current. (The MCP's generate reads one, with its files.) diff --git a/common/controller/benchVerdicts.ts b/common/controller/benchVerdicts.ts @@ -29,6 +29,7 @@ // (`diskCuesOf`): a fact-check may cite channels no build carries. The log // ends `@@bench-verdicts {json}` with the run's id, status and spend. +import { modelLogged } from "./jobModelLog"; import { getSettings } from "../lib/settings"; import type { Paths } from "../lib/paths"; import type { GenerationSettings } from "../lib/generationSettings"; @@ -218,7 +219,7 @@ export async function enqueueVerdictBench( kind: BENCH_VERDICTS_JOB_KIND, queueKey: anyLocal ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, - fn: async (onLog, signal, _progress, ctx) => { + fn: modelLogged({ paths, task: "bench-verdicts" }, async (onLog, signal, _progress, ctx) => { const g = (deps.settings ?? getSettings)().generation; // Again at the job's turn: jobs ahead in the queue may have spent the day. const late = await benchDailyCapRefusal(opts, paths, g, deps.now?.()); @@ -229,7 +230,7 @@ export async function enqueueVerdictBench( { paths, gen: g, onLog, signal, jobId: ctx.jobId, gpu: true, ...(deps.now ? { now: deps.now } : {}), ...(deps.root ? { root: deps.root } : {}) }, ); if (out.summary.status === "cancelled" || signal.aborted) throw new Error("cancelled"); - }, + }), }); if (!result.ok) return { result }; return { result, run }; diff --git a/common/controller/clipsSuggest.ts b/common/controller/clipsSuggest.ts @@ -25,6 +25,7 @@ // {article: "", iteration: 0, task: "clips-suggest", kind, project, status, // summary, usd, suggestions | ask}`. +import { modelLogged } from "./jobModelLog"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; @@ -149,7 +150,7 @@ export async function enqueueClipsSuggest(body: ReportDraftBody, deps: ClipsSugg kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, - fn: async (onLog, signal, setProgress, ctx) => { + fn: modelLogged({ paths, task: "clips-suggest" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); @@ -225,7 +226,7 @@ export async function enqueueClipsSuggest(body: ReportDraftBody, deps: ClipsSugg ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (out.status === "failed") throw new Error(out.summary); - }, + }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; diff --git a/common/controller/frameScan.ts b/common/controller/frameScan.ts @@ -32,6 +32,7 @@ // usage ledger (task `frame-scan`, no article). The log ends // `@@frame-scan {json}` with the run's counts, spend, and events. +import { modelLogged } from "./jobModelLog"; import path from "node:path"; import { readFile } from "node:fs/promises"; import { getSettings } from "../lib/settings"; @@ -268,7 +269,7 @@ export async function enqueueFrameScan(raw: Record<string, unknown>, deps: Frame paths, channelSlug: body.slug, videoId: body.id, - fn: async (onLog, signal, setProgress, ctx) => { + fn: modelLogged({ paths, task: "frames" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; // Again at the job's turn: jobs ahead in the queue may have spent the day. const late = await capRefusal(); @@ -351,7 +352,7 @@ export async function enqueueFrameScan(raw: Record<string, unknown>, deps: Frame await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); } } - }, + }), }); if (!result.ok) return { result }; return { result, model, queueKey }; diff --git a/common/controller/generationUsage.ts b/common/controller/generationUsage.ts @@ -22,6 +22,11 @@ export type GenerationUsageRow = { cacheReadTokens: number; cacheWriteTokens: number; usd: number; + // "local": a local model's calls (demo epic D3) — cost 0, never counted + // against the cap; the ledger is the proof a run stayed local. Absent: an + // API row (every row before D3). + route?: "api" | "local"; + calls?: number; }; export const utcDay = (d: Date = new Date()) => d.toISOString().slice(0, 10); @@ -52,9 +57,11 @@ export async function readGenerationUsage(file: string): Promise<GenerationUsage return out; } -// The day's API spend: its total and how many jobs it took. +export const isLocalUsage = (r: Pick<GenerationUsageRow, "route">) => r.route === "local"; + +// The day's API spend: its total and how many jobs it took (local rows apart). export async function dayUsage(file: string, day: string = utcDay()): Promise<{ day: string; usd: number; jobs: number }> { - const rows = (await readGenerationUsage(file)).filter((r) => r.day === day); + const rows = (await readGenerationUsage(file)).filter((r) => r.day === day && !isLocalUsage(r)); const usd = Math.round(rows.reduce((s, r) => s + r.usd, 0) * 10_000) / 10_000; return { day, usd, jobs: new Set(rows.map((r) => r.jobId)).size }; } @@ -67,3 +74,27 @@ export function dailyCapRefusal(day: { day: string; usd: number }, daily: number "daily cap (settings.generation.caps.daily) — refused; it resets at midnight UTC" ); } + +// The models the day's generation called, on which route: what proves a run +// stayed local (a local-only day lists no Claude model). +export type UsageModel = { model: string; route: "api" | "local"; calls: number; jobs: number; inputTokens: number; outputTokens: number }; + +export async function dayModels(file: string, day: string = utcDay()): Promise<UsageModel[]> { + const rows = (await readGenerationUsage(file)).filter((r) => r.day === day); + return usageModelsOf(rows); +} + +export function usageModelsOf(rows: readonly GenerationUsageRow[]): UsageModel[] { + const by = new Map<string, UsageModel & { ids: Set<string> }>(); + for (const r of rows) { + const route = isLocalUsage(r) ? "local" : "api"; + const k = `${route}:${r.model}`; + const m = by.get(k) ?? { model: r.model, route, calls: 0, jobs: 0, inputTokens: 0, outputTokens: 0, ids: new Set<string>() }; + m.calls += typeof r.calls === "number" ? r.calls : 0; + m.inputTokens += r.inputTokens || 0; + m.outputTokens += r.outputTokens || 0; + m.ids.add(r.jobId); + by.set(k, m); + } + return [...by.values()].map(({ ids, ...m }) => ({ ...m, jobs: ids.size })).sort((a, b) => a.route.localeCompare(b.route) || b.jobs - a.jobs || a.model.localeCompare(b.model)); +} diff --git a/common/controller/jobModelLog.ts b/common/controller/jobModelLog.ts @@ -0,0 +1,70 @@ +// A GENERATION JOB'S MODEL LOG when it has no iteration (demo epic D3; the +// shape is lib/llm/callLog.ts): a verdict proposal, a frame scan, the clip +// finder, the video assistant, claim groups, a triage, the verdict bench, a +// learning pass. Its calls go to `<generation dir>/calls/<jobId>/` (beside +// the usage ledger: editor state, never the corpus). A job over an iteration +// records into the iteration's own files instead (tasks/run.ts opens that +// log inside this one, and the inner one wins); this one stays empty and +// is never created. +// +// SERVER-ONLY. + +import path from "node:path"; +import { ModelLogWriter, modelLogFilesIn, runWithModelLog, type LocalCallTally, type ModelLogFiles } from "../lib/llm/callLog-server"; +import { appendGenerationUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; +import type { Paths } from "../lib/paths"; + +type UsagePaths = Pick<Paths, "generationUsageFile">; + +export function jobModelLogDir(paths: UsagePaths, jobId: string): string { + if (!/^[A-Za-z0-9._-]+$/.test(jobId)) throw new Error(`not a job id: ${JSON.stringify(jobId)}`); + return path.join(path.dirname(paths.generationUsageFile), "calls", jobId); +} + +export function jobModelLogFiles(paths: UsagePaths, jobId: string): ModelLogFiles { + return modelLogFilesIn(jobModelLogDir(paths, jobId)); +} + +type JobFn<R> = (onLog: (line: string) => void, signal: AbortSignal, setProgress: any, ctx: { jobId: string }) => Promise<R>; + +// The job's `fn`, run inside its own model log; when it ends, its local calls +// go to the usage ledger (route "local", cost 0) — API spend is recorded by +// each job as before, never here. +export function modelLogged<R>(o: { paths: UsagePaths; task: string; model?: string }, fn: JobFn<R>): JobFn<R> { + return async (onLog, signal, setProgress, ctx) => { + const writer = new ModelLogWriter({ + files: jobModelLogFiles(o.paths, ctx.jobId), + task: o.task, + jobId: ctx.jobId, + ...(o.model ? { model: o.model } : {}), + log: onLog, + }); + const tally: LocalCallTally = new Map(); + try { + return await runWithModelLog(writer, () => fn(onLog, signal, setProgress, ctx), { tally }); + } finally { + await writer.flush(); + await appendLocalUsage(o.paths, ctx.jobId, tally).catch((e) => onLog(`local usage not recorded: ${(e as Error).message}`)); + } + }; +} + +export async function appendLocalUsage(paths: UsagePaths, jobId: string, tally: LocalCallTally, now: Date = new Date()): Promise<void> { + const rows: GenerationUsageRow[] = [...tally.values()].map((t) => ({ + at: now.toISOString(), + day: utcDay(now), + jobId, + article: t.article, + iteration: t.iteration, + task: t.task, + model: t.model, + inputTokens: t.tokensIn, + outputTokens: t.tokensOut, + cacheReadTokens: 0, + cacheWriteTokens: 0, + usd: 0, + route: "local", + calls: t.calls, + })); + await appendGenerationUsage(paths.generationUsageFile, rows); +} diff --git a/common/controller/proposeGroups.ts b/common/controller/proposeGroups.ts @@ -21,6 +21,7 @@ // `@@report-draft {article: "", iteration: 0, task: "propose-groups", // project, status, summary, usd, groups: {at, proposed, refused, file}}`. +import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; @@ -82,7 +83,7 @@ export async function enqueueProposeGroups(body: ReportDraftBody, deps: ReportDr kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, - fn: async (onLog, signal, setProgress, ctx) => { + fn: modelLogged({ paths, task: "propose-groups" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); @@ -158,7 +159,7 @@ export async function enqueueProposeGroups(body: ReportDraftBody, deps: ReportDr ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (out.status === "failed") throw new Error(out.summary); - }, + }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -60,6 +60,7 @@ // The corpus tools come in from the caller (`deps.corpusTools`): they are the // MCP's, and common cannot import the mcp package. +import { modelLogged } from "./jobModelLog"; import os from "node:os"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; @@ -741,7 +742,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, - fn: (onLog, signal, setProgress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal, setProgress }, deps), + fn: modelLogged({ paths, task: "report-draft" }, (onLog, signal, setProgress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal, setProgress }, deps)), }); if (!result.ok) { if (!isStepTask(body.task)) await updateIteration(body.article, n, { status: "failed", error: result.error }, paths).catch(() => {}); diff --git a/common/controller/reportLearn.ts b/common/controller/reportLearn.ts @@ -19,6 +19,7 @@ // when a pass is due — never proposed, terms changed, or a week since the last // (controller/reportTick.ts learnStep). +import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { getRegistry } from "../jobs/registry"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; @@ -140,7 +141,7 @@ export async function enqueueLearn(id: string, trigger: LearnTrigger, deps: Repo kind: REPORT_DRAFT_JOB_KIND, queueKey: plan.provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, - fn: (onLog, signal, _setProgress, ctx) => runLearnJob({ id, trigger, plan, maxUsd, jobId: ctx.jobId, onLog, signal }, deps), + fn: modelLogged({ paths, task: "learn" }, (onLog, signal, _setProgress, ctx) => runLearnJob({ id, trigger, plan, maxUsd, jobId: ctx.jobId, onLog, signal }, deps)), }); if (!result.ok) return { ok: false, error: result.error, plan }; return { ok: true, jobId: result.jobId, plan, result: result as Extract<StreamActionResult, { ok: true }> }; diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts @@ -21,6 +21,7 @@ // The iteration refreshed: `iteration` when given, else the current report's // (current.json), else the newest done iteration that carries a report. +import { modelLogged } from "./jobModelLog"; import { access, readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; @@ -261,7 +262,7 @@ export async function enqueueRefresh(body: ReportDraftBody, deps: ReportDraftDep kind: REPORT_DRAFT_JOB_KIND, queueKey: DRAFT_REFRESH_QUEUE, paths, - fn: (onLog, signal, setProgress, ctx) => runRefreshJob({ body, n: it.n, model: m.model, capUsd: m.capUsd, extractor: m.extractor, jobId: ctx.jobId, onLog, signal, setProgress }, deps), + fn: modelLogged({ paths, task: "refresh" }, (onLog, signal, setProgress, ctx) => runRefreshJob({ body, n: it.n, model: m.model, capUsd: m.capUsd, extractor: m.extractor, jobId: ctx.jobId, onLog, signal, setProgress }, deps)), }); if (!result.ok) { await updateIteration(body.article, it.n, { status: "failed", error: result.error }, paths).catch(() => {}); diff --git a/common/controller/reportTriage.ts b/common/controller/reportTriage.ts @@ -22,6 +22,7 @@ // `ids` (the candidates, named: no scan), `windows` ({id: [{start, end}]}), // `maxCandidates`, `model`, `maxUsd`, `source`/`build`. +import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { JobProgress } from "../jobs/registry"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; @@ -99,7 +100,7 @@ export async function enqueueTriage(body: ReportDraftBody, deps: ReportDraftDeps kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, - fn: (onLog, signal, setProgress, ctx) => runTriageJob({ body, k, model, provider, maxUsd, jobId: ctx.jobId, onLog, signal, setProgress }, deps), + fn: modelLogged({ paths, task: "triage" }, (onLog, signal, setProgress, ctx) => runTriageJob({ body, k, model, provider, maxUsd, jobId: ctx.jobId, onLog, signal, setProgress }, deps)), }); const mark = async (patch: Partial<TriageFile>) => { const cur = await readTriageFile(body.article, k, paths).catch(() => null); diff --git a/common/controller/reportVerdicts.ts b/common/controller/reportVerdicts.ts @@ -21,6 +21,7 @@ // through patchArticle, reject marks the proposal only // (lib/report/verdictProposals.ts). +import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; @@ -66,7 +67,7 @@ export async function enqueueVerdictProposals(body: ReportDraftBody, deps: Repor kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, - fn: async (onLog, signal, setProgress, ctx) => { + fn: modelLogged({ paths, task: "verdicts" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { // Again at the job's turn: jobs ahead in the queue may have spent the day. @@ -144,7 +145,7 @@ export async function enqueueVerdictProposals(body: ReportDraftBody, deps: Repor })}`, ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); - }, + }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; diff --git a/common/controller/videoAssist.ts b/common/controller/videoAssist.ts @@ -24,6 +24,7 @@ // `video-assist`). The log ends `@@report-draft {article: "", iteration: 0, // task: "video-assist", project, status, summary, usd, assist}`. +import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; @@ -136,7 +137,7 @@ export async function enqueueVideoAssist(body: ReportDraftBody, deps: VideoAssis kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, - fn: async (onLog, signal, setProgress, ctx) => { + fn: modelLogged({ paths, task: "video-assist" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); @@ -219,7 +220,7 @@ export async function enqueueVideoAssist(body: ReportDraftBody, deps: VideoAssis ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (out.status === "failed") throw new Error(out.summary); - }, + }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; diff --git a/common/lib/llm/agent.ts b/common/lib/llm/agent.ts @@ -24,6 +24,7 @@ import { toolUsesOf, type ContentBlock, } from "./anthropic"; +import { recordModelCall } from "./callLog-server"; import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig, type Provider } from "./config"; import type { Meter, Usage } from "./meter"; import { @@ -158,6 +159,33 @@ export function clip(v: unknown, max = TRANSCRIPT_RESULT_CHARS): unknown { const cut = (s: string, max: number) => s.length > max ? `${s.slice(0, max)}\n(cut at ${max} chars — narrow the call)` : s; +// A turn's new messages as the model log keeps them: the text sent, each tool +// result under the call it answers; an image or a server block by its kind. +export function messagesText(msgs: readonly { role: string; content?: unknown; tool_name?: unknown }[]): string { + const out: string[] = []; + for (const m of msgs) { + const c = m.content; + if (typeof c === "string") { + if (c.trim()) out.push(m.role === "tool" ? `[tool result: ${String(m.tool_name ?? "")}]\n${c}` : m.role === "user" ? c : `[${m.role}]\n${c}`); + continue; + } + if (!Array.isArray(c)) continue; + for (const b of c as ContentBlock[]) { + if (b.type === "text" && typeof b.text === "string") out.push(b.text); + else if (b.type === "tool_result") { + const inner = typeof b.content === "string" ? b.content : Array.isArray(b.content) ? (b.content as ContentBlock[]).map((x) => (typeof x.text === "string" ? x.text : `[${x.type}]`)).join("\n") : ""; + out.push(`[tool result]\n${inner}`); + } else out.push(`[${b.type}]`); + } + } + return out.join("\n\n"); +} + +// A turn's answer as the model log keeps it: its text, then each tool call. +function answerOf(text: string, calls: { name: string; input: unknown }[]): string { + return [text, ...calls.map((c) => `→ ${c.name} ${JSON.stringify(c.input ?? {})}`)].filter((x) => x && x.trim()).join("\n"); +} + function hasThinking(messages: { role: string; content: unknown }[]): boolean { return messages.some( (m) => @@ -323,13 +351,18 @@ async function runClaude(o: AgentOptions): Promise<AgentResult> { messagesTotal: messages.length, }); lastTools = toolsJson; + const fresh = messagesText(messages.slice(recorded)); recorded = messages.length; let res; const before = o.meter.usd; + const t0 = Date.now(); + const turnRecord = (answer: string, extra: { tokensIn?: number; tokensOut?: number; error?: string }) => + recordModelCall({ phase: "agent", label: `turn ${turn + 1}`, model: o.model, route: "api", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra }); try { res = await client.messages(body, { meter: o.meter, signal: o.signal }); } catch (err) { + turnRecord("", { error: (err as Error)?.message ?? String(err) }); if (isCancel(err, o.signal)) return run.finish(turn, lastText, "cancelled"); if (serverSearch && err instanceof AnthropicError && err.status === 400 && /web_search/.test(err.message)) { serverSearch = false; @@ -347,6 +380,7 @@ async function runClaude(o: AgentOptions): Promise<AgentResult> { const calls = toolUsesOf(res); const text = textOf(res); if (text) lastText = text; + turnRecord(answerOf(text, calls), { tokensIn: lastInput, tokensOut: Number(u.output_tokens) || 0 }); run.transcript.push({ kind: "response", turn, @@ -441,9 +475,14 @@ async function runLocal(o: AgentOptions): Promise<AgentResult> { let reply; const before = o.meter.usd; + const fresh = messagesText(messages.slice(turn === 0 ? 1 : recorded)); + const t0 = Date.now(); + const turnRecord = (answer: string, extra: { tokensIn?: number; tokensOut?: number; error?: string }) => + recordModelCall({ phase: "agent", label: `turn ${turn + 1}`, model: o.model, route: "local", ...(turn === 0 ? { system: o.system } : {}), prompt: fresh, answer, seconds: (Date.now() - t0) / 1000, ...extra }); try { reply = await ollamaChat(cfg, { model: o.model, messages, tools, signal: o.signal }); } catch (err) { + turnRecord("", { error: (err as Error)?.message ?? String(err) }); if (isCancel(err, o.signal)) return run.finish(turn, lastText, "cancelled"); throw err; } @@ -459,6 +498,7 @@ async function runLocal(o: AgentOptions): Promise<AgentResult> { recorded = messages.length; const calls = toolCallsOf(msg); if (msg.content) lastText = msg.content; + turnRecord(answerOf(msg.content ?? "", calls), { tokensIn: reply.promptTokens, tokensOut: reply.evalTokens }); run.transcript.push({ kind: "response", turn, diff --git a/common/lib/llm/callLog-server.ts b/common/lib/llm/callLog-server.ts @@ -0,0 +1,354 @@ +// THE MODEL LOG's writer and readers (demo epic D3; the shape is ./callLog.ts). +// +// A run opens a ModelLogWriter over its files and runs its body inside +// `runWithModelLog`; every model call under it — structuredAnswer on either +// provider, each turn of the agent loop, a Claude Code session's answer — goes +// through ONE function, `recordModelCall`, which finds the writer in the async +// context and appends the call. Outside a run (a test calling a task directly, +// a CLI run with no log) there is no writer and nothing is recorded. +// +// A RECORD NEVER FAILS THE RUN: every append is caught and the first failure +// logged once. Writes are queued one at a time, in order, per file, across +// every writer in the process (two media drafts on one iteration share its +// files), so a run's number and its call ids are allocated in order. +// +// SERVER-ONLY (node:async_hooks, node:fs). One storage and one queue per +// process, on globalThis (the house pattern: Next may load a module twice). + +import { AsyncLocalStorage } from "node:async_hooks"; +import { appendFile, mkdir, readFile } from "node:fs/promises"; +import { createReadStream } from "node:fs"; +import path from "node:path"; +import { createInterface } from "node:readline"; +import { + ANSWER_CAP_CHARS, + CALLS_FILE, + CALLS_TEXT_FILE, + MODEL_LOG_VERSION, + PROMPT_CAP_CHARS, + answerText, + boundDecision, + boundItems, + foldModelLog, + headOf, + outcomeOfItems, + type CallDecision, + type CallItem, + type CallOutcome, + type ModelCallRow, + type ModelCallText, + type ModelDecisionRow, + type ModelLog, + type ModelLogRunRow, + type ModelRoute, +} from "./callLog"; + +export type ModelLogFiles = { calls: string; text: string }; + +export const modelLogFilesIn = (dir: string): ModelLogFiles => ({ calls: path.join(dir, CALLS_FILE), text: path.join(dir, CALLS_TEXT_FILE) }); + +// ─── The per-file queue ─── + +const QUEUE_KEY = Symbol.for("archilyzer.modelLog.queues"); +function queues(): Map<string, Promise<unknown>> { + const g = globalThis as unknown as Record<symbol, Map<string, Promise<unknown>> | undefined>; + return (g[QUEUE_KEY] ??= new Map()); +} + +function enqueue<T>(file: string, op: () => Promise<T>): Promise<T> { + const q = queues(); + const prev = q.get(file) ?? Promise.resolve(); + const next = prev.then(op, op); + const tail = next.then( + () => undefined, + () => undefined, + ); + q.set(file, tail); + void tail.then(() => { + if (q.get(file) === tail) q.delete(file); + }); + return next; +} + +const compactJson = (v: unknown) => { + try { + return JSON.stringify(v) ?? ""; + } catch { + return String(v); + } +}; + +// ─── The writer ─── + +export type ModelCallEntry = { + phase?: string; + label?: string; + model: string; + route: ModelRoute; + // The text sent: the system prompt and the rest (the user turn, an agent + // turn's new messages). Never a header, a key or a URL. + system?: string; + prompt: string; + answer: unknown; + seconds: number; + tokensIn?: number; + tokensOut?: number; + error?: string; + decision?: CallDecision; + items?: CallItem[]; +}; + +// What a caller holds to say, once code has used an answer, what it did. +// Handed to structuredAnswer as `call.slot`; a no-op when nothing recorded. +export class CallSlot { + #writer: ModelLogWriter | null = null; + #id: Promise<string | null> | null = null; + bind(writer: ModelLogWriter, id: Promise<string | null>): void { + this.#writer = writer; + this.#id = id; + } + get recorded(): boolean { + return !!this.#writer; + } + // The call's decision (and its items'). Items alone: the decision is what + // they add up to. + decide(outcome: CallOutcome, why: string, items?: CallItem[]): void { + if (!this.#writer || !this.#id) return; + this.#writer.decide(this.#id, { outcome, why }, items); + } + items(items: CallItem[]): void { + if (!this.#writer || !this.#id || !items.length) return; + this.#writer.decide(this.#id, null, items); + } +} + +export class ModelLogWriter { + readonly files: ModelLogFiles; + readonly task: string; + readonly jobId: string | undefined; + readonly model: string | undefined; + // The article and iteration the log is of, when it is an iteration's. + readonly where: { article: string; iteration: number } | undefined; + private readonly now: () => Date; + private readonly log: ((line: string) => void) | undefined; + private run: number | null = null; + private seq = 0; + private failed = false; + private pending: Promise<unknown> = Promise.resolve(); + + constructor(o: { files: ModelLogFiles; task: string; jobId?: string; model?: string; where?: { article: string; iteration: number }; now?: () => Date; log?: (line: string) => void }) { + this.files = o.files; + this.where = o.where; + this.task = o.task; + this.jobId = o.jobId; + this.model = o.model; + this.now = o.now ?? (() => new Date()); + this.log = o.log; + } + + private fail(err: unknown) { + if (!this.failed) this.log?.(`model log not kept: ${(err as Error)?.message ?? String(err)}`); + this.failed = true; + } + + private queue<T>(op: () => Promise<T>): Promise<T | null> { + const p = enqueue(this.files.calls, op).catch((err) => { + this.fail(err); + return null; + }); + this.pending = Promise.all([this.pending, p]); + return p; + } + + // This run's number, allocated (with its `run` row) on the first write. + private async ensureRun(): Promise<number> { + if (this.run !== null) return this.run; + const text = await readFile(this.files.calls, "utf8").catch(() => ""); + const max = foldModelLog(text).runs.reduce((m, r) => Math.max(m, r.run), 0); + this.run = max + 1; + const row: ModelLogRunRow = { v: MODEL_LOG_VERSION, t: "run", run: this.run, at: this.now().toISOString(), task: this.task, ...(this.jobId ? { jobId: this.jobId } : {}), ...(this.model ? { model: this.model } : {}) }; + await mkdir(path.dirname(this.files.calls), { recursive: true }); + await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); + return this.run; + } + + // Starts the run now (its `run` row), so a page sees the run before its first call. + start(): Promise<number | null> { + return this.queue(() => this.ensureRun()); + } + + record(e: ModelCallEntry): Promise<string | null> { + const at = this.now().toISOString(); + return this.queue(async () => { + const run = await this.ensureRun(); + const id = `${run}.${++this.seq}`; + const clean = (s: string) => s; + const system = clean(e.system ?? ""); + const prompt = clean(e.prompt ?? ""); + const answer = clean(answerText(e.answer)); + const items = boundItems(e.items?.map((i) => ({ ...i, text: clean(i.text), why: clean(i.why) }))); + const decision = e.decision ? boundDecision({ ...e.decision, why: clean(e.decision.why) }) : items ? { outcome: outcomeOfItems(items), why: "" } : { outcome: "n/a" as const, why: e.error ? "the call failed" : "" }; + const row: ModelCallRow = { + v: MODEL_LOG_VERSION, + t: "call", + id, + run, + at, + task: this.task, + phase: e.phase || this.task, + ...(e.label ? { label: clean(e.label).slice(0, 120) } : {}), + model: e.model, + route: e.route, + promptChars: system.length + prompt.length, + promptHead: headOf(prompt || system), + answerChars: answer.length, + // A structured answer's head is its compact JSON (the whole text keeps it laid out). + answerHead: headOf(typeof e.answer === "string" || e.answer === undefined ? answer : clean(compactJson(e.answer))), + seconds: Math.round((Number.isFinite(e.seconds) ? e.seconds : 0) * 10) / 10, + ...(typeof e.tokensIn === "number" ? { tokensIn: e.tokensIn } : {}), + ...(typeof e.tokensOut === "number" ? { tokensOut: e.tokensOut } : {}), + ...(e.error ? { error: clean(e.error).slice(0, 600) } : {}), + decision, + ...(items ? { items } : {}), + }; + // The prompt cap is on the system and the rest together, the system first. + const sys = system.slice(0, PROMPT_CAP_CHARS); + const rest = prompt.slice(0, Math.max(0, PROMPT_CAP_CHARS - sys.length)); + const text: ModelCallText = { + v: MODEL_LOG_VERSION, + id, + system: sys, + prompt: rest, + ...(sys.length + rest.length < system.length + prompt.length ? { promptCut: true as const } : {}), + answer: answer.slice(0, ANSWER_CAP_CHARS), + ...(answer.length > ANSWER_CAP_CHARS ? { answerCut: true as const } : {}), + }; + // The text first: a row the list shows always has its text to expand. + await appendFile(this.files.text, `${JSON.stringify(text)}\n`); + await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); + return id; + }); + } + + decide(id: Promise<string | null>, decision: CallDecision | null, items?: CallItem[]): void { + const at = this.now().toISOString(); + void this.queue(async () => { + const call = await id; + if (!call) return; + const clean = (s: string) => s; + const b = boundItems(items?.map((i) => ({ ...i, text: clean(i.text), why: clean(i.why) }))); + const row: ModelDecisionRow = { + v: MODEL_LOG_VERSION, + t: "decision", + call, + at, + ...(decision ? { decision: boundDecision({ ...decision, why: clean(decision.why) }) } : {}), + ...(b ? { items: b } : {}), + }; + await appendFile(this.files.calls, `${JSON.stringify(row)}\n`); + }); + } + + // Every queued write, done (never rejects). + async flush(): Promise<void> { + let seen: Promise<unknown> | null = null; + while (seen !== this.pending) { + seen = this.pending; + await seen.catch(() => {}); + } + } +} + +// ─── The context ─── + +// A job's local calls, counted wherever they were recorded (its own log or an +// iteration's inside it): what the usage ledger is told when the job ends. +export type LocalCallTally = Map<string, { model: string; task: string; article: string; iteration: number; calls: number; tokensIn: number; tokensOut: number }>; + +type Ctx = { writer: ModelLogWriter; tally?: LocalCallTally }; +const ALS_KEY = Symbol.for("archilyzer.modelLog.context"); +function storage(): AsyncLocalStorage<Ctx> { + const g = globalThis as unknown as Record<symbol, AsyncLocalStorage<Ctx> | undefined>; + return (g[ALS_KEY] ??= new AsyncLocalStorage<Ctx>()); +} + +// A nested log takes the call (the innermost wins); the tally is the outer one's. +export function runWithModelLog<T>(writer: ModelLogWriter | null, fn: () => T, o: { tally?: LocalCallTally } = {}): T { + if (!writer) return fn(); + const tally = o.tally ?? storage().getStore()?.tally; + return storage().run({ writer, ...(tally ? { tally } : {}) }, fn); +} + +export function currentModelLog(): ModelLogWriter | null { + return storage().getStore()?.writer ?? null; +} + +// THE ONE RECORDING FUNCTION: every model call on every route comes here. +// Nothing is recorded outside a run's log; `slot` (when given) is bound to the +// call so the caller can say what code did with the answer. +export function recordModelCall(e: ModelCallEntry, slot?: CallSlot): void { + const ctx = storage().getStore(); + const w = ctx?.writer; + if (!w) return; + if (ctx.tally && e.route === "local") { + const key = `${e.model}\u0000${w.task}\u0000${w.where?.article ?? ""}\u0000${w.where?.iteration ?? 0}`; + const t = ctx.tally.get(key) ?? { model: e.model, task: w.task, article: w.where?.article ?? "", iteration: w.where?.iteration ?? 0, calls: 0, tokensIn: 0, tokensOut: 0 }; + t.calls++; + t.tokensIn += e.tokensIn ?? 0; + t.tokensOut += e.tokensOut ?? 0; + ctx.tally.set(key, t); + } + try { + const id = w.record(e); + slot?.bind(w, id); + } catch { + // a record never stops the run + } +} + +// A Claude Code session's answer (the `code` route): the request the plan +// handed it, and what it posted. Its seconds are the session's, unknown here. +export function recordSessionAnswer(e: { phase?: string; label?: string; system: string; prompt: string; answer: unknown }, slot?: CallSlot): void { + recordModelCall({ ...e, label: e.label ?? "a Claude Code session's answer", model: "claude-code", route: "claude-code", seconds: 0 }, slot); +} + +// ─── Reading ─── + +export async function readModelLog(files: ModelLogFiles): Promise<ModelLog> { + const text = await readFile(files.calls, "utf8").catch(() => null); + return foldModelLog(text); +} + +// One call's whole text, read line by line until its id (never the whole file +// into memory at once); null when it has none. +export async function readModelCallText(files: ModelLogFiles, id: string): Promise<ModelCallText | null> { + let stream: ReturnType<typeof createReadStream>; + try { + stream = createReadStream(files.text, { encoding: "utf8" }); + } catch { + return null; + } + const want = `"id":${JSON.stringify(id)}`; + try { + const rl = createInterface({ input: stream, crlfDelay: Infinity }); + for await (const line of rl) { + if (!line.includes(want)) continue; + try { + const r = JSON.parse(line) as ModelCallText; + if (r && r.v === MODEL_LOG_VERSION && r.id === id) { + rl.close(); + stream.destroy(); + return r; + } + } catch { + // a torn line + } + } + } catch (err) { + if ((err as NodeJS.ErrnoException).code === "ENOENT") return null; + throw err; + } finally { + stream.destroy(); + } + return null; +} diff --git a/common/lib/llm/callLog.test.ts b/common/lib/llm/callLog.test.ts @@ -0,0 +1,195 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { startFakeAnthropic, textTurn, toolTurn, toolUseBlock, turn } from "../../testing/llm/fakeAnthropic.mjs"; +import { jsonReply, reply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs"; +import { runAgent } from "./agent"; +import { + CALLS_FILE, + CALLS_TEXT_FILE, + PROMPT_CAP_CHARS, + callMatches, + foldModelLog, + headOf, + phaseOrder, + summarizeCalls, +} from "./callLog"; +import { CallSlot, ModelLogWriter, modelLogFilesIn, readModelCallText, readModelLog, recordModelCall, recordSessionAnswer, runWithModelLog } from "./callLog-server"; +import { Meter } from "./meter"; +import { structuredAnswer } from "./structured"; +import { plainAnswer } from "../report/draft/tasks/llmText"; + +// Run with: pnpm -C common exec tsx --test lib/llm/callLog.test.ts +// +// THE MODEL LOG (demo epic D3): every call on every route through ONE +// function, recorded in the run's files; a decision appended once code knows +// it; nothing recorded outside a run. + +const schema = { type: "object", properties: { terms: { type: "array", items: { type: "string" } } }, required: ["terms"] }; + +async function tmpLog(task = "sweep") { + const dir = await mkdtemp(path.join(os.tmpdir(), "model-log-")); + const files = modelLogFilesIn(dir); + const writer = new ModelLogWriter({ files, task, jobId: "job-1", model: "qwen3:8b" }); + return { dir, files, writer, done: () => rm(dir, { recursive: true, force: true }) }; +} + +test("the rows: a run row first, then each call; a decision folded into its call; ids in order", async () => { + const t = await tmpLog(); + try { + const slot = new CallSlot(); + await runWithModelLog(t.writer, async () => { + recordModelCall({ phase: "terms", model: "qwen3:8b", route: "local", system: "Plan.", prompt: "Research question: ovens?", answer: { terms: ["oven"] }, seconds: 1.234, tokensIn: 40, tokensOut: 6 }, slot); + slot.decide("kept", "searched for oven", [{ text: "oven", outcome: "kept", why: "searched" }]); + recordModelCall({ phase: "reading", label: "extract a@0", model: "qwen3:8b", route: "local", system: "Read.", prompt: "line one\nline two\nline three\nline four", answer: { items: [] }, seconds: 2 }); + }); + await t.writer.flush(); + const raw = (await readFile(t.files.calls, "utf8")).trim().split("\n").map((l) => JSON.parse(l)); + assert.deepEqual(raw.map((r) => r.t), ["run", "call", "decision", "call"]); + assert.deepEqual([raw[0].run, raw[0].task, raw[0].jobId, raw[0].model], [1, "sweep", "job-1", "qwen3:8b"]); + const log = await readModelLog(t.files); + assert.deepEqual(log.calls.map((c) => c.id), ["1.1", "1.2"]); + const [a, b] = log.calls; + assert.deepEqual([a!.phase, a!.route, a!.seconds, a!.tokensIn, a!.tokensOut], ["terms", "local", 1.2, 40, 6]); + assert.deepEqual(a!.decision, { outcome: "kept", why: "searched for oven" }); + assert.deepEqual(a!.items, [{ text: "oven", outcome: "kept", why: "searched" }]); + assert.deepEqual(b!.decision, { outcome: "n/a", why: "" }); + assert.equal(b!.promptHead, "line one\nline two\nline three…", "the list's head: the first three lines"); + assert.equal(b!.label, "extract a@0"); + // The whole text, one row, by id. + const text = await readModelCallText(t.files, "1.2"); + assert.equal(text!.system, "Read."); + assert.equal(text!.prompt, "line one\nline two\nline three\nline four"); + assert.match(text!.answer, /"items"/); + assert.equal(await readModelCallText(t.files, "9.9"), null); + // A second writer on the same files is run 2. + const w2 = new ModelLogWriter({ files: t.files, task: "narrate" }); + await runWithModelLog(w2, async () => recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 0 })); + await w2.flush(); + const again = await readModelLog(t.files); + assert.deepEqual(again.runs.map((r) => [r.run, r.task]), [[1, "sweep"], [2, "narrate"]]); + assert.equal(again.calls.at(-1)!.id, "2.1"); + assert.equal(again.calls.at(-1)!.phase, "narrate", "no phase: the task's name"); + } finally { + await t.done(); + } +}); + +test("nothing is recorded outside a run, and a slot outside one is a no-op", async () => { + const slot = new CallSlot(); + recordModelCall({ model: "qwen3:8b", route: "local", prompt: "p", answer: "a", seconds: 0 }, slot); + assert.equal(slot.recorded, false); + slot.decide("dropped", "nothing to say it to"); +}); + +test("caps: the prompt kept to 40k characters and said so; the row stays small", async () => { + const t = await tmpLog(); + try { + const big = "word ".repeat(20_000); + await runWithModelLog(t.writer, async () => recordModelCall({ model: "qwen3:8b", route: "local", system: "S", prompt: big, answer: big, seconds: 1 })); + await t.writer.flush(); + const [c] = (await readModelLog(t.files)).calls; + assert.equal(c!.promptChars, big.length + 1); + assert.ok(c!.promptHead.length <= 281); + const text = (await readModelCallText(t.files, c!.id))!; + assert.equal(text.system.length + text.prompt.length, PROMPT_CAP_CHARS); + assert.equal(text.promptCut, true); + assert.equal(text.answerCut, true); + assert.ok((await readFile(t.files.calls, "utf8")).length < 2_000, "calls.jsonl holds no whole prompt"); + } finally { + await t.done(); + } +}); + +test("the fold: a filter by outcome matches a call's items; phases in the sweep's order; the summary", () => { + const rows = [ + { v: 1, t: "run", run: 1, at: "x", task: "sweep" }, + { v: 1, t: "call", id: "1.1", run: 1, at: "x", task: "sweep", phase: "grouping", model: "qwen3:8b", route: "local", promptChars: 1, promptHead: "", answerChars: 1, answerHead: "", seconds: 3, decision: { outcome: "kept", why: "" } }, + { v: 1, t: "call", id: "1.2", run: 1, at: "x", task: "sweep", phase: "reading", model: "qwen3:8b", route: "local", promptChars: 1, promptHead: "", answerChars: 1, answerHead: "", seconds: 2, decision: { outcome: "n/a", why: "" } }, + { v: 1, t: "decision", call: "1.2", at: "x", items: [{ text: "q1", outcome: "kept", why: "verbatim" }, { text: "q2", outcome: "dropped", why: "not verbatim in its window" }] }, + { v: 2, t: "call", id: "future" }, + "not json", + ]; + const log = foldModelLog(rows.map((r) => (typeof r === "string" ? r : JSON.stringify(r))).join("\n")); + assert.equal(log.calls.length, 2, "a later version's row and a torn line are skipped"); + const reading = log.calls.find((c) => c.id === "1.2")!; + assert.equal(reading.decision.outcome, "kept", "items alone: the decision is what they add up to"); + assert.ok(callMatches(reading, { outcome: "dropped" })); + assert.ok(callMatches(reading, { outcome: "kept" })); + assert.ok(!callMatches(log.calls[0]!, { outcome: "dropped" })); + assert.deepEqual(phaseOrder(["grouping", "draft", "reading", "terms"]), ["terms", "reading", "grouping", "draft"]); + const s = summarizeCalls(log.calls); + assert.deepEqual([s.calls, s.seconds, s.models], [2, 5, [{ model: "qwen3:8b", route: "local", calls: 2 }]]); + assert.deepEqual(s.phases.map((p) => p.phase), ["reading", "grouping"]); + assert.equal(headOf(""), ""); +}); + +test("the one function on every route: structuredAnswer on ollama and on Claude, an agent's turns, the extractor, a Claude Code session", async () => { + const t = await tmpLog(); + const ol = await startFakeOllama({ turns: [jsonReply({ terms: ["oven"] }), reply("- a line"), reply("", { message: { role: "assistant", content: "done" } })] }); + const api = await startFakeAnthropic({ turns: [turn([toolUseBlock("answer", { terms: ["bread"] })]), toolTurn("lookup", { q: "oven" }), textTurn("all read")] }); + try { + const llm = { ollama: { baseUrl: ol.url }, anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }; + const meter = new Meter(); + const slot = new CallSlot(); + await runWithModelLog(t.writer, async () => { + await structuredAnswer({ llm, model: "qwen3:8b", system: "Plan.", user: "Ovens?", schema, meter, call: { phase: "terms", slot } }); + slot.decide("kept", "searched"); + await structuredAnswer({ llm, model: "claude-haiku-4-5", system: "Plan.", user: "Bread?", schema, meter, call: { phase: "terms", label: "api" } }); + await plainAnswer({ llm, model: "qwen3:8b", system: "Extract.", user: "the batch", meter, call: { phase: "reading" } }); + await runAgent({ + llm, + model: "claude-haiku-4-5", + system: "You research.", + user: "Go.", + meter, + tools: [{ name: "lookup", description: "look", inputSchema: { type: "object", properties: { q: { type: "string" } } }, run: async () => "the oven is hot" }], + }); + recordSessionAnswer({ phase: "assist", system: "Assist.", prompt: "make the joins 0.15 s", answer: { ops: [] } }); + }); + await t.writer.flush(); + const { calls } = await readModelLog(t.files); + assert.deepEqual( + calls.map((c) => [c.phase, c.route, c.model]), + [ + ["terms", "local", "qwen3:8b"], + ["terms", "api", "claude-haiku-4-5"], + ["reading", "local", "qwen3:8b"], + ["agent", "api", "claude-haiku-4-5"], + ["agent", "api", "claude-haiku-4-5"], + ["assist", "claude-code", "claude-code"], + ], + ); + assert.equal(calls[0]!.decision.outcome, "kept"); + assert.ok((calls[0]!.tokensIn ?? 0) > 0, "ollama's counts"); + assert.ok((calls[1]!.tokensIn ?? 0) > 0, "the API's usage"); + assert.match(calls[3]!.answerHead, /→ lookup/); + assert.match((await readModelCallText(t.files, calls[4]!.id))!.prompt, /\[tool result\]\nthe oven is hot/); + assert.equal((await readModelCallText(t.files, calls[3]!.id))!.system, "You research.", "turn 1 carries the system prompt"); + assert.match(calls[1]!.promptHead, /^Bread\?/); + } finally { + await ol.close(); + await api.close(); + await t.done(); + } +}); + +test("a failed call is recorded with its error, its decision n/a", async () => { + const t = await tmpLog(); + const ol = await startFakeOllama({ turns: [reply("not json"), reply("still not")] }); + try { + await runWithModelLog(t.writer, async () => { + await assert.rejects(structuredAnswer({ llm: { ollama: { baseUrl: ol.url } }, model: "qwen3:8b", system: "S", user: "U", schema })); + }); + await t.writer.flush(); + const [c] = (await readModelLog(t.files)).calls; + assert.match(c!.error ?? "", /no structured answer/); + assert.deepEqual(c!.decision, { outcome: "n/a", why: "the call failed" }); + assert.ok(CALLS_FILE && CALLS_TEXT_FILE); + } finally { + await ol.close(); + await t.done(); + } +}); diff --git a/common/lib/llm/callLog.ts b/common/lib/llm/callLog.ts @@ -0,0 +1,252 @@ +// THE MODEL LOG (demo epic D3) — every model call a job makes, on every route +// (a local model on ollama, the Claude API, a Claude Code session), as one +// record: what was asked, what came back, how long it took, and what CODE did +// with the answer and why. It is what the "Model log" panel shows and what +// `umtool model-log` prints. Pure (types, caps, the scrub, the fold): the +// writer and the readers are ./callLog-server.ts. +// +// WHERE. A run over an iteration writes its iteration's `calls.jsonl` and +// `calls-text.jsonl` (a media draft is a step on its iteration: the same +// files, its rows carry its `task`). A job with no iteration writes the same +// pair beside its output (callLog-server.ts `jobModelLogFiles`). +// +// THE ROWS (calls.jsonl — small; a list or a count reads only this file): +// {v, t: "run", run, at, task, jobId?, model?} a run began +// {v, t: "call", id, run, at, task, phase, label?, model, route, +// promptChars, promptHead, answerChars, answerHead, seconds, +// tokensIn?, tokensOut?, error?, decision, items?} one model call +// {v, t: "decision", call, at, decision?, items?} what code did with +// call `call`'s answer, +// appended once known +// and calls-text.jsonl, one row per call (the panel fetches it per row): +// {v, id, system, prompt, promptCut?, answer, answerCut?} +// +// A LATER STAGE only appends: a new `phase` (the meaning check's +// "meaning-check") and its `decision` — through structuredAnswer's `call` +// option and its CallSlot (callLog-server.ts), never a new row kind. +// +// A reader skips a line that does not parse and a row of an unknown version; +// a later version adds fields, never renames one. + +export const MODEL_LOG_VERSION = 1 as const; +export const CALLS_FILE = "calls.jsonl" as const; +export const CALLS_TEXT_FILE = "calls-text.jsonl" as const; + +// The caps: a prompt and an answer are kept to PROMPT_CAP_CHARS each (the +// rest is cut and said so); a head is the first lines a list row shows. +export const PROMPT_CAP_CHARS = 40_000; +export const ANSWER_CAP_CHARS = 40_000; +export const HEAD_CHARS = 280; +export const HEAD_LINES = 3; +export const WHY_CHARS = 400; +export const ITEM_TEXT_CHARS = 300; +export const MAX_ITEMS = 40; + +// `local`: ollama · `api`: the Claude API with a key · `claude-code`: a Claude +// Code session answered (the `code` route). +export const MODEL_ROUTES = ["local", "api", "claude-code"] as const; +export type ModelRoute = (typeof MODEL_ROUTES)[number]; + +export const CALL_OUTCOMES = ["kept", "dropped", "rewritten", "n/a"] as const; +export type CallOutcome = (typeof CALL_OUTCOMES)[number]; +export type CallDecision = { outcome: CallOutcome; why: string }; +// One item of an answer (an extracted quote, a drafted field) and its fate. +export type CallItem = CallDecision & { text: string }; + +// The phases a sweep goes through, in the order the panel lists them; any +// other phase follows them in the order it first appears. +export const PHASE_ORDER = ["terms", "reading", "meaning-check", "grouping"] as const; +const PHASE_LABELS: Record<string, string> = { terms: "Terms", reading: "Reading", "meaning-check": "Meaning check", grouping: "Grouping", agent: "Agent turns" }; +export const phaseLabel = (p: string) => PHASE_LABELS[p] ?? p.charAt(0).toUpperCase() + p.slice(1).replace(/-/g, " "); + +export type ModelLogRunRow = { v: 1; t: "run"; run: number; at: string; task: string; jobId?: string; model?: string }; + +export type ModelCallRow = { + v: 1; + t: "call"; + id: string; + run: number; + at: string; + task: string; + phase: string; + label?: string; + model: string; + route: ModelRoute; + promptChars: number; + promptHead: string; + answerChars: number; + answerHead: string; + seconds: number; + tokensIn?: number; + tokensOut?: number; + error?: string; + decision: CallDecision; + items?: CallItem[]; +}; + +export type ModelDecisionRow = { v: 1; t: "decision"; call: string; at: string; decision?: CallDecision; items?: CallItem[] }; + +export type ModelLogRow = ModelLogRunRow | ModelCallRow | ModelDecisionRow; + +export type ModelCallText = { v: 1; id: string; system: string; prompt: string; promptCut?: true; answer: string; answerCut?: true }; + +// ─── Text ─── + +const cutTo = (s: string, max: number) => (s.length > max ? s.slice(0, max) : s); + +// The first lines a list row shows: up to HEAD_LINES non-empty lines, at most +// HEAD_CHARS, an ellipsis when there was more. +export function headOf(text: string): string { + const lines = text.split("\n").map((l) => l.trimEnd()).filter((l) => l.trim()); + let head = lines.slice(0, HEAD_LINES).join("\n"); + const more = lines.length > HEAD_LINES || head.length > HEAD_CHARS; + head = cutTo(head, HEAD_CHARS); + return more ? `${head}…` : head; +} + +// An answer as the record keeps it: a string as it is, anything else as JSON. +export function answerText(answer: unknown): string { + if (typeof answer === "string") return answer; + if (answer === undefined) return ""; + try { + return JSON.stringify(answer, null, 1) ?? ""; + } catch { + return String(answer); + } +} + +export function boundDecision(d: CallDecision): CallDecision { + const outcome = (CALL_OUTCOMES as readonly string[]).includes(d.outcome) ? d.outcome : "n/a"; + return { outcome, why: cutTo(String(d.why ?? ""), WHY_CHARS) }; +} + +export function boundItems(items: readonly CallItem[] | undefined): CallItem[] | undefined { + if (!items?.length) return undefined; + return items.slice(0, MAX_ITEMS).map((i) => ({ ...boundDecision(i), text: cutTo(String(i.text ?? ""), ITEM_TEXT_CHARS) })); +} + +// The outcome a call's items add up to: kept when any was kept, rewritten +// when any was rewritten and none kept, else dropped. +export function outcomeOfItems(items: readonly CallItem[]): CallOutcome { + if (items.some((i) => i.outcome === "kept")) return "kept"; + if (items.some((i) => i.outcome === "rewritten")) return "rewritten"; + if (items.length && items.every((i) => i.outcome === "dropped")) return "dropped"; + return "n/a"; +} + +// ─── Reading ─── + +export type ModelCall = ModelCallRow; + +export type ModelLog = { + runs: ModelLogRunRow[]; + // Every call, its decision rows applied, in the order they were made. + calls: ModelCall[]; +}; + +const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v); + +// calls.jsonl's text → the runs and the calls (decisions folded in). +export function foldModelLog(text: string | null | undefined): ModelLog { + const runs: ModelLogRunRow[] = []; + const calls: ModelCall[] = []; + const byId = new Map<string, ModelCall>(); + for (const line of (text ?? "").split("\n")) { + if (!line.trim()) continue; + let r: unknown; + try { + r = JSON.parse(line); + } catch { + continue; // a torn line + } + if (!isObj(r) || r.v !== MODEL_LOG_VERSION) continue; + if (r.t === "run" && typeof r.run === "number") runs.push(r as ModelLogRunRow); + else if (r.t === "call" && typeof r.id === "string") { + const c = { ...(r as ModelCallRow) }; + if (!isObj(c.decision)) c.decision = { outcome: "n/a", why: "" }; + byId.set(c.id, c); + calls.push(c); + } else if (r.t === "decision" && typeof r.call === "string") { + const c = byId.get(r.call); + if (!c) continue; + const d = r as ModelDecisionRow; + if (d.items?.length) c.items = [...(c.items ?? []), ...d.items].slice(0, MAX_ITEMS); + if (d.decision) c.decision = d.decision; + else if (c.items?.length) c.decision = { outcome: outcomeOfItems(c.items), why: c.decision.why }; + } + } + return { runs, calls }; +} + +// What a filter asks for. `outcome` matches a call whose decision is it, or +// any of whose items is (a call that kept two quotes and dropped one is in +// both "kept" and "dropped"). +export type ModelLogQuery = { task?: string; run?: number; jobId?: string; phase?: string; outcome?: CallOutcome }; + +export function callMatches(c: ModelCall, q: ModelLogQuery): boolean { + if (q.task && c.task !== q.task) return false; + if (q.run !== undefined && c.run !== q.run) return false; + if (q.phase && c.phase !== q.phase) return false; + if (q.outcome && c.decision.outcome !== q.outcome && !(c.items ?? []).some((i) => i.outcome === q.outcome)) return false; + return true; +} + +// The runs a query's task and job name: by task, then by job. +export function runsOf(log: ModelLog, q: Pick<ModelLogQuery, "task" | "jobId">): ModelLogRunRow[] { + return log.runs.filter((r) => (!q.task || r.task === q.task) && (!q.jobId || r.jobId === q.jobId)); +} + +export function phaseOrder(phases: Iterable<string>): string[] { + const seen = [...new Set(phases)]; + const known = PHASE_ORDER.filter((p) => seen.includes(p)); + return [...known, ...seen.filter((p) => !(PHASE_ORDER as readonly string[]).includes(p))]; +} + +export type ModelLogSummary = { + calls: number; + seconds: number; + failed: number; + models: { model: string; route: ModelRoute; calls: number }[]; + phases: { phase: string; calls: number; seconds: number }[]; + outcomes: Record<CallOutcome, number>; + tokensIn: number; + tokensOut: number; +}; + +const round1 = (v: number) => Math.round(v * 10) / 10; + +export function summarizeCalls(calls: readonly ModelCall[]): ModelLogSummary { + const models = new Map<string, { model: string; route: ModelRoute; calls: number }>(); + const phases = new Map<string, { phase: string; calls: number; seconds: number }>(); + const outcomes: Record<CallOutcome, number> = { kept: 0, dropped: 0, rewritten: 0, "n/a": 0 }; + let seconds = 0; + let failed = 0; + let tokensIn = 0; + let tokensOut = 0; + for (const c of calls) { + seconds += c.seconds || 0; + if (c.error) failed++; + tokensIn += c.tokensIn ?? 0; + tokensOut += c.tokensOut ?? 0; + const mk = `${c.route}:${c.model}`; + const m = models.get(mk) ?? { model: c.model, route: c.route, calls: 0 }; + m.calls++; + models.set(mk, m); + const p = phases.get(c.phase) ?? { phase: c.phase, calls: 0, seconds: 0 }; + p.calls++; + p.seconds += c.seconds || 0; + phases.set(c.phase, p); + outcomes[c.decision.outcome] = (outcomes[c.decision.outcome] ?? 0) + 1; + } + const order = phaseOrder(phases.keys()); + return { + calls: calls.length, + seconds: round1(seconds), + failed, + models: [...models.values()].sort((a, b) => b.calls - a.calls), + phases: order.map((p) => ({ ...phases.get(p)!, seconds: round1(phases.get(p)!.seconds) })), + outcomes, + tokensIn, + tokensOut, + }; +} diff --git a/common/lib/llm/index.ts b/common/lib/llm/index.ts @@ -10,3 +10,5 @@ export * from "./ollama"; export * from "./config"; export * from "./structured"; export * from "./agent"; +export * from "./callLog"; +export * from "./callLog-server"; diff --git a/common/lib/llm/structured.ts b/common/lib/llm/structured.ts @@ -19,7 +19,8 @@ import { type MessagesResponse, } from "./anthropic"; import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig } from "./config"; -import type { Meter } from "./meter"; +import { CallSlot, recordModelCall } from "./callLog-server"; +import type { Meter, Usage } from "./meter"; import { ollamaChat, OllamaError, PromptTooLargeError, promptEstimate } from "./ollama"; export const ANSWER_TOOL = "answer"; @@ -62,25 +63,68 @@ type Opts = { meter?: Meter; signal?: AbortSignal; maxTokens?: number; + // The model log (./callLog.ts): the call's phase and label, and a slot the + // caller says through what code did with the answer. + call?: StructuredCallMeta; +}; + +export type StructuredCallMeta = { phase?: string; label?: string; slot?: CallSlot }; + +// What one structured answer cost, summed over its attempts, and the text it +// last sent (the model log's record). +type Spent = { tokensIn: number; tokensOut: number; any: boolean; sent: string }; +const spend = (s: Spent, u: Usage | undefined) => { + if (!u) return; + const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0); + s.tokensIn += n(u.input_tokens) + n(u.cache_creation_input_tokens) + n(u.cache_read_input_tokens); + s.tokensOut += n(u.output_tokens); + s.any = true; }; export async function structuredAnswer<T>(o: Opts): Promise<T> { - return providerOf(o.model) === "api" ? claudeAnswer<T>(o) : localAnswer<T>(o); + const route = providerOf(o.model); + const spent: Spent = { tokensIn: 0, tokensOut: 0, any: false, sent: o.user }; + const t0 = Date.now(); + const images = o.images?.length ? `\n\n[${o.images.length} image${o.images.length === 1 ? "" : "s"} sent with this prompt]` : ""; + const record = (answer: unknown, error?: unknown) => + recordModelCall( + { + ...(o.call?.phase ? { phase: o.call.phase } : {}), + ...(o.call?.label ? { label: o.call.label } : {}), + model: o.model, + route, + system: o.system, + prompt: spent.sent + images, + answer, + seconds: (Date.now() - t0) / 1000, + ...(spent.any ? { tokensIn: spent.tokensIn, tokensOut: spent.tokensOut } : {}), + ...(error !== undefined ? { error: (error as Error)?.message ?? String(error) } : {}), + }, + o.call?.slot, + ); + try { + const out = route === "api" ? await claudeAnswer<T>(o, spent) : await localAnswer<T>(o, spent); + record(out); + return out; + } catch (err) { + record(null, err); + throw err; + } } -async function claudeAnswer<T>(o: Opts): Promise<T> { +async function claudeAnswer<T>(o: Opts, spent: Spent): Promise<T> { const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model)); const strict = isStrictModel(o.model); try { - return await claudeTry<T>(client, o, strict); + return await claudeTry<T>(client, o, strict, spent); } catch (err) { if (!strict && err instanceof AnthropicError && err.status === 400 && /tool_choice/.test(err.message)) - return claudeTry<T>(client, o, true); + return claudeTry<T>(client, o, true, spent); throw err; } } -async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): Promise<T> { +async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean, spent: Spent): Promise<T> { const tool = { name: ANSWER_TOOL, description: "Give the answer.", @@ -88,6 +132,7 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): ...(strict ? { strict: true } : {}), }; const text = strict ? `${o.user}\n\n${ASK}` : o.user; + spent.sent = text; let messages: { role: string; content: string | ContentBlock[] }[] = [ { role: "user", @@ -112,6 +157,7 @@ async function claudeTry<T>(client: AnthropicClient, o: Opts, strict: boolean): }, { meter: o.meter, signal: o.signal }, ); + spend(spent, res.usage); const call = toolUsesOf(res).find((b) => b.name === ANSWER_TOOL); if (call && call.input && typeof call.input === "object") return call.input as T; // Append-only: the re-ask follows the answer as it came. @@ -133,7 +179,7 @@ export function structuredPromptEstimate(o: { system: string; user: string; sche }); } -async function localAnswer<T>(o: Opts): Promise<T> { +async function localAnswer<T>(o: Opts, spent: Spent): Promise<T> { const cfg = ollamaConfigOf(o.llm, o.model); let last = ""; for (let attempt = 0; attempt < 2; attempt++) { @@ -155,6 +201,7 @@ async function localAnswer<T>(o: Opts): Promise<T> { continue; } o.meter?.add(o.model, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }); + spend(spent, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }); const content = reply.message.content ?? ""; const value = content.trim() ? extractJsonObject(content) : null; if (value !== null && typeof value === "object") return value as T; diff --git a/common/lib/report/draft/tasks/clipsSuggest.ts b/common/lib/report/draft/tasks/clipsSuggest.ts @@ -26,6 +26,7 @@ // words.json), else the recording's cues from the corpus (`cuesOf`), spread // over their words. +import { recordSessionAnswer } from "../../../llm/callLog-server"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm"; @@ -203,6 +204,8 @@ export async function runClipsSuggest( log(`clips-suggest ${input.project} on ${input.model}: ${plural(items.length, "proposal")}, words from ${p.wordsFrom} (prompt ${SUGGEST_PROMPT_VERSION})`); if (input.answers !== undefined) { // The `code` route: a Claude Code session's answer, read as a model's is. + const all = suggestPrompt(items); + recordSessionAnswer({ phase: "labels", system: all.system, prompt: all.user, answer: input.answers }); const r = parseSuggestAnswer(input.answers, items.map((i) => i.id)); if (!r.ok) throw new ClipsSuggestRefusal(`the session's answers are refused: ${r.error}`); fresh.push(...r.items); diff --git a/common/lib/report/draft/tasks/llmText.ts b/common/lib/report/draft/tasks/llmText.ts @@ -14,7 +14,9 @@ import { textOf, type LlmConfig, type Meter, + type StructuredCallMeta, } from "../../../llm"; +import { recordModelCall } from "../../../llm/callLog-server"; // Characters a token takes in the ollama estimate (lib/llm/ollama.ts). const CHARS_PER_TOKEN = 3.5; @@ -27,7 +29,39 @@ export async function plainAnswer(o: { meter: Meter; signal?: AbortSignal; maxTokens?: number; + // The model log (lib/llm/callLog.ts): the call's phase, label and slot. + call?: StructuredCallMeta; }): Promise<string> { + const route = providerOf(o.model); + const t0 = Date.now(); + const record = (answer: string, tokens: { tokensIn?: number; tokensOut?: number }, error?: unknown) => + recordModelCall( + { + ...(o.call?.phase ? { phase: o.call.phase } : {}), + ...(o.call?.label ? { label: o.call.label } : {}), + model: o.model, + route, + system: o.system, + prompt: o.user, + answer, + seconds: (Date.now() - t0) / 1000, + ...tokens, + ...(error !== undefined ? { error: (error as Error)?.message ?? String(error) } : {}), + }, + o.call?.slot, + ); + try { + return await plainAnswerOn(o, record); + } catch (err) { + record("", {}, err); + throw err; + } +} + +async function plainAnswerOn( + o: Parameters<typeof plainAnswer>[0], + record: (answer: string, tokens: { tokensIn?: number; tokensOut?: number }) => void, +): Promise<string> { if (providerOf(o.model) === "api") { const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model)); const res = await client.messages( @@ -40,7 +74,10 @@ export async function plainAnswer(o: { }, { meter: o.meter, signal: o.signal }, ); - return textOf(res); + const u = res.usage ?? {}; + const text = textOf(res); + record(text, { tokensIn: (Number(u.input_tokens) || 0) + (Number(u.cache_read_input_tokens) || 0) + (Number(u.cache_creation_input_tokens) || 0), tokensOut: Number(u.output_tokens) || 0 }); + return text; } const cfg = ollamaConfigOf(o.llm, o.model); const reply = await ollamaChat(cfg, { @@ -52,7 +89,9 @@ export async function plainAnswer(o: { signal: o.signal, }); o.meter.add(o.model, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }); - return reply.message.content ?? ""; + const text = reply.message.content ?? ""; + record(text, { tokensIn: reply.promptTokens, tokensOut: reply.evalTokens }); + return text; } // How many characters of user text fit a model's one call beside `system`: diff --git a/common/lib/report/draft/tasks/media.ts b/common/lib/report/draft/tasks/media.ts @@ -45,6 +45,8 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { structuredAnswer } from "../../../llm"; +import type { CallItem } from "../../../llm/callLog"; +import { CallSlot } from "../../../llm/callLog-server"; import { readIteration, readIterationFile, reportSourceOf } from "../../iterations"; import { applyDraft, @@ -296,8 +298,16 @@ async function askUnits<U extends MediaUnit, V, I extends MediaTaskInput>( return { value: null, hard: [(e as Error).message], soft: [] }; } }; - const ask = (system: string, user: string, schema: object) => - structuredAnswer<unknown>({ llm: deps.llm, model: ctx.input.model, system, user, schema, meter: h.meter, signal: deps.signal }); + const ask = (system: string, user: string, schema: object, label: string, slot: CallSlot) => + structuredAnswer<unknown>({ llm: deps.llm, model: ctx.input.model, system, user, schema, meter: h.meter, signal: deps.signal, call: { phase: "draft", label, slot } }); + // What code did with one unit's attempt (the model log): a clean value is + // kept, a hard problem drops it, soft ones keep it flagged. + const fate = (id: string, a: MediaAttempt<V>, k: number): CallItem => + a.hard.length + ? { text: id, outcome: "dropped", why: `${a.hard.join("; ")}${k === 0 ? " (asked again)" : ""}` } + : a.soft.length + ? { text: id, outcome: k === 0 ? "dropped" : "kept", why: `flagged: ${a.soft.join("; ")}${k === 0 ? " (asked again)" : ""}` } + : { text: id, outcome: "kept", why: "passes the checks" }; const b = spec.batch; // Computed once per unit (a batch: once for the whole), as narrate always did. const first = b ? { system: b.system(group, ctx), user: b.user(group, ctx) } : null; @@ -310,14 +320,17 @@ async function askUnits<U extends MediaUnit, V, I extends MediaTaskInput>( const list = out.get(u.id)!; const extra = list.length ? (spec.retry ?? refusedFor)(list.at(-1)!, u) : ""; let a: MediaAttempt<V>; + const slot = new CallSlot(); try { - a = judge(await ask(single.get(u.id)!.system, single.get(u.id)!.user + extra, spec.schema(u, ctx)), u); + a = judge(await ask(single.get(u.id)!.system, single.get(u.id)!.user + extra, spec.schema(u, ctx), `${u.label ?? u.id}${k ? ` · attempt ${k + 1}` : ""}`, slot), u); } catch (e) { if (deps.signal?.aborted) throw e; list.push({ value: null, hard: [(e as Error).message], soft: [] }); continue; } list.push(a); + const f = fate(u.id, a, k); + slot.decide(f.outcome, f.why); h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, ...a }]); if (!a.hard.length && !a.soft.length) pending = []; continue; @@ -328,19 +341,24 @@ async function askUnits<U extends MediaUnit, V, I extends MediaTaskInput>( const user = (k === 0 ? first!.user : b.user(pending, ctx)) + (failing.length ? (b.retry ?? batchRefusedFor)(failing) : ""); const system = k === 0 ? first!.system : b.system(pending, ctx); let answers: Record<string, unknown>; + const slot = new CallSlot(); try { - answers = b.split(await ask(system, user, b.schema(pending, ctx)), pending, ctx); + answers = b.split(await ask(system, user, b.schema(pending, ctx), `${pending.length} unit${pending.length === 1 ? "" : "s"}${k ? ` · attempt ${k + 1}` : ""}`, slot), pending, ctx); } catch (e) { if (deps.signal?.aborted) throw e; for (const u of pending) out.get(u.id)!.push({ value: null, hard: [(e as Error).message], soft: [] }); continue; } + const fates: CallItem[] = []; for (const u of pending) { const a: MediaAttempt<V> = answers[u.id] === undefined ? { value: null, hard: [`no draft for ${u.id} in the answer`], soft: [] } : judge(answers[u.id], u); + fates.push(fate(u.label ?? u.id, a, k)); out.get(u.id)!.push(a); h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, batch: pending.length, ...a }]); } + const nKept = fates.filter((f) => f.outcome === "kept").length; + slot.decide(nKept ? "kept" : "dropped", `${nKept} of ${fates.length} kept`, fates); pending = pending.filter((u) => { const last = out.get(u.id)!.at(-1)!; return last.hard.length > 0 || last.soft.length > 0; diff --git a/common/lib/report/draft/tasks/proposeGroups.ts b/common/lib/report/draft/tasks/proposeGroups.ts @@ -22,6 +22,7 @@ // It never writes the manifest or notes.json. An API model is held to // `maxUsd` (the ask's estimate checked first). +import { CallSlot, recordSessionAnswer } from "../../../llm/callLog-server"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm"; @@ -237,9 +238,13 @@ export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeG const base = { project: input.project, model: input.model }; const cancelled = (): ProposeGroupsOutcome => ({ ...base, status: "cancelled", proposals: null, file: null, usd: meter.usd, byModel: meter.summary().byModel, summary: "cancelled" }); let raw: unknown; + // What code did with the answer's groups (the model log). + const slot = new CallSlot(); if (input.answers !== undefined) { log(`propose-groups ${input.project}: a Claude Code session's answer (prompt ${GROUPS_PROMPT_VERSION})`); raw = input.answers; + const pr = groupsPrompt({ manifest, request, model: CODE_PRICED, llm: deps.llm }); + recordSessionAnswer({ phase: "groups", system: pr.system, prompt: pr.user, answer: raw }, slot); } else { const pr = groupsPrompt({ manifest, request, model: input.model, llm: deps.llm }); log(`propose-groups ${input.project} on ${input.model}: one ask, ~${pr.tokens} prompt tokens (prompt ${GROUPS_PROMPT_VERSION})`); @@ -251,7 +256,7 @@ export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeG const ask = deps.ask ?? (<T,>(system: string, user: string, schema: object, model: string, maxTokens: number) => - structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens })); + structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens, call: { phase: "groups", slot } })); try { raw = await ask<unknown>(pr.system, pr.user, GROUPS_SCHEMA, input.model, 4096); } catch (e) { @@ -261,6 +266,7 @@ export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeG } const parsed = parseGroupsAnswer(raw); if (!parsed.ok) { + slot.decide("dropped", parsed.error); if (input.answers !== undefined) throw new ProposeGroupsRefusal(`the session's answer is refused: ${parsed.error}`); throw new StructuredAnswerError(`${input.model}: ${parsed.error}: ${JSON.stringify(raw ?? null).slice(0, 160)}`); } @@ -270,6 +276,10 @@ export async function runProposeGroups(input: ProposeGroupsInput, deps: ProposeG const checked = checkGroupProposals(fresh, { groups: parsed.groups }); for (const g of checked.groups) log(` proposed: §${g.section} ${g.ids.join(" ")} — ${g.claim}`); for (const r of checked.refused) log(` refused: ${JSON.stringify(r.group).slice(0, 120)} — ${r.why}`); + slot.decide(checked.groups.length ? "kept" : "dropped", `${checked.groups.length} group(s) proposed, ${checked.refused.length} refused`, [ + ...checked.groups.map((g) => ({ text: `§${g.section} ${g.ids.join(" ")} — ${g.claim}`, outcome: "kept" as const, why: "proposed" })), + ...checked.refused.map((r) => ({ text: JSON.stringify(r.group).slice(0, 200), outcome: "dropped" as const, why: r.why })), + ]); const proposals = groupProposalsDocOf({ at: now().toISOString(), model: input.model, request: request || null, checked }); const file = await writeGroupProposals(input.project, proposals); const usd = Math.round(meter.usd * 1e6) / 1e6; diff --git a/common/lib/report/draft/tasks/run.ts b/common/lib/report/draft/tasks/run.ts @@ -8,9 +8,12 @@ // or one that is not this task's to run. import { CancelledError, Meter, type ModelTally } from "../../../llm"; +import { currentJobContext } from "../../../jobContext"; +import { ModelLogWriter, modelLogFilesIn, runWithModelLog } from "../../../llm/callLog-server"; import { addIterationUsage, appendIterationTurns, + iterationDir, readIteration, recordIterationStep, updateIteration, @@ -165,6 +168,20 @@ export async function runOnIteration( } } } + // The model log (demo epic D3): every model call the body makes, on any + // route, is recorded in the iteration's calls.jsonl under this run. + const storePaths = paths ?? getPaths(); + const modelLog = new ModelLogWriter({ + files: modelLogFilesIn(iterationDir(storePaths, article, n)), + task: o.step?.task ?? it.kind, + // The running job's own id (an iteration's jobId is written after its job starts). + ...((o.step?.jobId ?? currentJobContext()?.jobId ?? it.jobId) ? { jobId: o.step?.jobId ?? currentJobContext()?.jobId ?? it.jobId } : {}), + model: o.step?.model ?? o.trace?.model ?? it.model, + where: { article, iteration: n }, + now, + log, + }); + await modelLog.start(); let coverageOf: (() => IterationCoverage) | null = null; const handle: TaskHandle = { article, @@ -204,7 +221,7 @@ export async function runOnIteration( let summary: string; let patch: IterationPatch = {}; try { - const out = await body(handle); + const out = await runWithModelLog(modelLog, () => body(handle)); status = deps.signal?.aborted ? "cancelled" : out.status; summary = deps.signal?.aborted ? "cancelled" : out.summary; patch = out.patch ?? {}; @@ -222,6 +239,7 @@ export async function runOnIteration( } } + await modelLog.flush(); // The record of the run, whatever happened: turns, spend, the ending. if (turns.length) await appendIterationTurns(article, n, turns, paths).catch((e) => log(`turns not kept: ${(e as Error).message}`)); const tallies = meter.summary().byModel; diff --git a/common/lib/report/draft/tasks/sweep-agent.ts b/common/lib/report/draft/tasks/sweep-agent.ts @@ -188,6 +188,8 @@ function extractTool(h: TaskHandle, input: SweepAgentInput, rewrite: (t: string) user: `Directive: ${String(inp.directive ?? "")}\n\n${text}`, meter: h.meter, signal: ctx?.signal ?? h.deps.signal, + // The model log: the extractor's batch, handed back to the agent as it read. + call: { phase: "reading", label: `extract batch ${k} (${ids.length} recording${ids.length === 1 ? "" : "s"})` }, }); count.n++; // The batch, traced: its ids and the extractor's own lines. diff --git a/common/lib/report/draft/tasks/sweep-pipeline.ts b/common/lib/report/draft/tasks/sweep-pipeline.ts @@ -17,6 +17,8 @@ // `coverage` is what was enumerated and read. import { structuredAnswer, type LlmConfig, type Meter } from "../../../llm"; +import type { CallItem } from "../../../llm/callLog"; +import { CallSlot } from "../../../llm/callLog-server"; import type { Report } from "../../schema"; import { writeIterationFile } from "../../iterations"; import { mmss } from "../reportOps"; @@ -285,10 +287,22 @@ export async function sweepPipeline(input: SweepPipelineInput, deps: TaskDeps): ); } -async function ask<T>(h: TaskHandle, model: string, system: string, user: string, schema: object, what: string, traceCost = false): Promise<T> { +// The model log's phase of a pipeline step (lib/llm/callLog.ts PHASE_ORDER). +export const phaseOfStep = (what: string) => (what === "terms" ? "terms" : what.startsWith("extract") ? "reading" : what.startsWith("group") ? "grouping" : what); + +async function ask<T>(h: TaskHandle, model: string, system: string, user: string, schema: object, what: string, traceCost = false, slot?: CallSlot): Promise<T> { const t0 = Date.now(); const before = h.meter.usd; - const out = await structuredAnswer<T>({ llm: h.deps.llm as LlmConfig, model, system, user, schema, meter: h.meter as Meter, signal: h.deps.signal }); + const out = await structuredAnswer<T>({ + llm: h.deps.llm as LlmConfig, + model, + system, + user, + schema, + meter: h.meter as Meter, + signal: h.deps.signal, + call: { phase: phaseOfStep(what), label: what, ...(slot ? { slot } : {}) }, + }); h.turns([{ kind: "model", what, seconds: Math.round((Date.now() - t0) / 100) / 10, answer: out }]); if (traceCost) h.trace({ t: "cost", step: what, usd: h.meter.usd - before, model, total: h.meter.usd }); return out; @@ -323,13 +337,20 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T let terms: string[] = []; if (input.terms?.length) terms = input.terms.map((t) => t.trim()).filter(Boolean); else { - const ans = await ask<{ terms?: unknown }>(h, model, TERMS_SYSTEM, `Research question: ${question}`, TERMS_SCHEMA, "terms", true); + const termsSlot = new CallSlot(); + const ans = await ask<{ terms?: unknown }>(h, model, TERMS_SYSTEM, `Research question: ${question}`, TERMS_SCHEMA, "terms", true, termsSlot); const names = new Set(channels.flatMap((c) => [c.toLowerCase(), c.toLowerCase().replace(/-/g, " ")])); + const termItems: CallItem[] = []; for (const t of Array.isArray(ans.terms) ? ans.terms : []) { const v = String(t).replace(/["“”]/g, "").trim().toLowerCase(); if (v && v.length <= 40 && !terms.includes(v) && !names.has(v)) terms.push(v); + termItems.push({ + text: v || String(t), + ...(!v ? { outcome: "dropped", why: "empty" } : v.length > 40 ? { outcome: "dropped", why: "longer than 40 characters" } : names.has(v) ? { outcome: "dropped", why: "a channel's own name" } : terms.indexOf(v) >= 6 ? { outcome: "dropped", why: "past the sixth term" } : termItems.some((x) => x.text === v) ? { outcome: "dropped", why: "a repeat" } : { outcome: "kept", why: "searched" }), + } as CallItem); } terms = terms.slice(0, 6); + termsSlot.decide(terms.length ? "kept" : "dropped", terms.length ? `searched for ${terms.join(", ")}` : "no usable term", termItems); } if (!terms.length) return { status: "failed", summary: "no search terms" }; h.log(`terms: ${terms.join(", ")}`); @@ -470,8 +491,9 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const excerpt = ch.map(([s, t]) => `[${mmss(s)}] ${t}`).join("\n"); const user = `Research question: ${question}\n\nVideo: ${title} (${v.channel}, ${v.date})\n\nTranscript excerpt:\n${excerpt}`; let ans: { relevant?: unknown; items?: unknown }; + const slot = new CallSlot(); try { - ans = await ask(h, model, EXTRACT_SYSTEM, user, EXTRACT_SCHEMA, `extract ${v.id}@${ch[0]![0]}`); + ans = await ask(h, model, EXTRACT_SYSTEM, user, EXTRACT_SCHEMA, `extract ${v.id}@${ch[0]![0]}`, false, slot); } catch (e) { if (deps.signal?.aborted) throw e; event({ kind: "chunk-failed", video: v.id, at: ch[0]![0], error: (e as Error).message }); @@ -479,9 +501,14 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T h.log(` chunk failed: ${(e as Error).message}`); continue; } - if (!ans.relevant) continue; + if (!ans.relevant) { + slot.decide("dropped", "the model: the excerpt does not bear on the question"); + continue; + } nRelevant++; const items = Array.isArray(ans.items) ? ans.items.slice(0, MAX_ITEMS_PER_CHUNK) : []; + // What code did with each of the model's items (the model log). + const fates: CallItem[] = []; for (const raw of items as { quote?: unknown; claim?: unknown; on_topic?: unknown; strength?: unknown }[]) { let quote = String(raw.quote ?? "") .replace(/["“”]/g, "") @@ -514,6 +541,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T if (!why && kept.some((k) => k.video === v.id && (norm(k.quote).includes(key) || key.includes(norm(k.quote))))) why = "duplicate"; const at = sec ?? ch[0]![0]; batchLines.push(`${v.id} @ ${mmss(at)} “${quote}” — ${claim || "(no claim)"}${why ? ` [dropped: ${why}]` : ""}`); + fates.push({ text: quote ? `“${quote}” — ${claim || "(no claim)"}` : claim || "(empty)", outcome: why ? "dropped" : "kept", why: why ?? "verbatim in its window" }); if (why) { dropped.push({ video: v.id, quote, why }); event({ kind: "dropped", why, video: v.id, quote, claim }); @@ -534,6 +562,9 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T flags: lintClaim(claim, quote), }); } + const nKept = fates.filter((f) => f.outcome === "kept").length; + if (fates.length) slot.decide(nKept ? "kept" : "dropped", `${nKept} of ${fates.length} item${fates.length === 1 ? "" : "s"} kept`, fates); + else slot.decide("n/a", "relevant, but no items"); } } h.log(` read ${v.id} — kept so far ${kept.length}, dropped ${dropped.length}`); @@ -560,11 +591,13 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T .slice(0, MAX_CLAIMS_TOTAL) .sort((a, b) => a.date.localeCompare(b.date) || a.video.localeCompare(b.video) || a.sec - b.sec); const listing = pool.map((r, i) => `${i + 1}. (${r.date}) ${r.claim}`).join("\n"); - let best: { score: number; g: { title?: unknown; sections?: unknown } } | null = null; + let best: { score: number; g: { title?: unknown; sections?: unknown }; slot: CallSlot; why: string } | null = null; + const groupSlots: { slot: CallSlot; why: string }[] = []; for (let attempt = 0; attempt < 2; attempt++) { let g: { title?: unknown; sections?: unknown }; + const slot = new CallSlot(); try { - g = await ask(h, model, GROUP_SYSTEM, `Research question: ${question}\n\nFindings:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`, true); + g = await ask(h, model, GROUP_SYSTEM, `Research question: ${question}\n\nFindings:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`, true, slot); } catch (e) { if (deps.signal?.aborted) throw e; event({ kind: "group-failed", error: (e as Error).message }); @@ -576,9 +609,13 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const placed = new Set(secs.flatMap(nums)); const biggest = Math.max(0, ...secs.map((s) => new Set(nums(s)).size)); const score = placed.size - (secs.length > 1 && biggest > 0.7 * pool.length ? biggest : 0) * 0.5; - if (!best || score > best.score) best = { score, g }; + const why = `placed ${placed.size} of ${pool.length} findings in ${secs.length} section${secs.length === 1 ? "" : "s"}${secs.length > 1 && biggest > 0.7 * pool.length ? ` (one holds ${biggest})` : ""}`; + groupSlots.push({ slot, why }); + if (!best || score > best.score) best = { score, g, slot, why }; if (placed.size >= pool.length * 0.8 && biggest <= 0.7 * pool.length) break; } + for (const x of groupSlots) if (best && x.slot !== best.slot) x.slot.decide("dropped", `${x.why}; the other grouping was kept`); + best?.slot.decide("kept", best.why); const g = best?.g ?? { title: question, sections: [] }; const title = (String(g.title ?? "") || question).replace(/["“”#]/g, "").trim().slice(0, 90) || question.slice(0, 90); const raw = ((Array.isArray(g.sections) ? g.sections : []) as { heading?: unknown; findings?: unknown }[]) diff --git a/common/lib/report/draft/tasks/videoAssist.ts b/common/lib/report/draft/tasks/videoAssist.ts @@ -21,6 +21,7 @@ // It never writes the manifest, notes.json or a clip. An API model is held to // `maxUsd` (the ask's estimate checked first). +import { CallSlot, recordSessionAnswer } from "../../../llm/callLog-server"; import { readFile } from "node:fs/promises"; import path from "node:path"; import { Meter, priceOf, providerOf, StructuredAnswerError, structuredAnswer, structuredPromptEstimate, type LlmConfig } from "../../../llm"; @@ -224,9 +225,13 @@ export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistD const meter = new Meter(); const base = { project: input.project, model: input.model, request, scope }; let raw: unknown; + // What code did with the answer's ops (the model log). + const slot = new CallSlot(); if (input.answers !== undefined) { log(`video-assist ${input.project}: a Claude Code session's answer (prompt ${ASSIST_PROMPT_VERSION})`); raw = input.answers; + const pr = assistPrompt({ manifest, request, scope, model: "claude-sonnet-5-5", llm: deps.llm }); + recordSessionAnswer({ phase: "assist", system: pr.system, prompt: pr.user, answer: raw }, slot); } else { const pr = assistPrompt({ manifest, request, scope, model: input.model, llm: deps.llm }); log(`video-assist ${input.project} on ${input.model} (${scope}): one ask, ~${pr.tokens} prompt tokens (prompt ${ASSIST_PROMPT_VERSION})`); @@ -238,7 +243,7 @@ export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistD const ask = deps.ask ?? (<T,>(system: string, user: string, schema: object, model: string, maxTokens: number) => - structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens })); + structuredAnswer<T>({ llm: deps.llm, model, system, user, schema, meter, ...(deps.signal ? { signal: deps.signal } : {}), maxTokens, call: { phase: "assist", label: request.slice(0, 80), slot } })); try { raw = await ask<unknown>(pr.system, pr.user, ASSIST_OPS_SCHEMA, input.model, 2048); } catch (e) { @@ -248,6 +253,7 @@ export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistD } const parsed = parseAssistAnswer(raw); if (!parsed.ok) { + slot.decide("dropped", parsed.error); if (input.answers !== undefined) throw new VideoAssistRefusal(`the session's answer is refused: ${parsed.error}`); throw new StructuredAnswerError(`${input.model}: ${parsed.error}: ${JSON.stringify(raw ?? null).slice(0, 160)}`); } @@ -257,6 +263,10 @@ export async function runVideoAssist(input: VideoAssistInput, deps: VideoAssistD const checked = checkAssistOps(fresh, parsed.ops, { request, scope }); for (const k of checked.ops) log(` proposed: ${k.diff}${k.warning ? ` (${k.warning})` : ""}`); for (const r of checked.refused) log(` refused: ${JSON.stringify(r.op).slice(0, 120)} — ${r.why}`); + slot.decide(checked.ops.length ? "kept" : "dropped", checked.ops.length ? `${plural(checked.ops.length, "edit")} proposed` : "no edit proposed", [ + ...checked.ops.map((k) => ({ text: k.diff, outcome: "kept" as const, why: k.warning ?? "proposed" })), + ...checked.refused.map((r) => ({ text: JSON.stringify(r.op).slice(0, 200), outcome: "dropped" as const, why: r.why })), + ]); const proposals = proposalsDocOf({ at: now().toISOString(), model: input.model, diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts @@ -80,7 +80,10 @@ export type IterationStepStatus = (typeof ITERATION_STEP_STATUSES)[number]; // draft/tasks/trace.ts) — one JSON object a line, like turns.jsonl. // `refresh.json`: a refresh's fetches, build and delta (umtool R4, // draft/refresh/types.ts RefreshFile). -export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl", "refresh.json"] as const; +// `calls.jsonl` / `calls-text.jsonl`: the model log, every model call of the +// iteration's runs and its steps (demo epic D3, lib/llm/callLog.ts) — +// appended by its writer only, never through writeIterationFile. +export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl", "refresh.json", "calls.jsonl", "calls-text.jsonl"] as const; export type IterationFile = (typeof ITERATION_FILES)[number]; // A revision needs something to revise (and feedback saying how); a refresh diff --git a/editor/app/api/ops/_benchVerdicts.test.ts b/editor/app/api/ops/_benchVerdicts.test.ts @@ -9,7 +9,7 @@ import { jsonReply, startFakeOllama, type FakeOllama } from "yt-dlp-transcript-c import { enqueueVerdictBench, parseBenchVerdictsBody } from "yt-dlp-transcript-common/controller/benchVerdicts"; import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; -import { appendGenerationUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { appendGenerationUsage, isLocalUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; import { readBenchRun } from "yt-dlp-transcript-common/lib/report/draft/bench/index"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; @@ -107,8 +107,11 @@ test("an API and a local model: a bench-verdicts job on draft:local, every answe const [sonnet, qwen] = run.summary.score.models; assert.equal(sonnet!.agreed, 2); // the two CORROBORATED assert.equal(qwen!.agreed, 1); // the one NOT_FOUND - const rows = await readGenerationUsage(paths.generationUsageFile); + const all = await readGenerationUsage(paths.generationUsageFile); + const rows = all.filter((r) => !isLocalUsage(r)); assert.deepEqual(rows.map((r) => [r.model, r.task, r.jobId]), [["claude-sonnet-5-5", "bench-verdicts", out.result.jobId]]); + // The local model's calls: in the ledger at no cost (demo epic D3). + assert.deepEqual(all.filter(isLocalUsage).map((r) => [r.model, r.task, r.jobId, r.usd]), [["qwen3:8b", "bench-verdicts", out.result.jobId, 0]]); assert.ok(rows[0]!.usd > 0); assert.equal(api.requestHeaders.at(-1)!["x-api-key"], FAKE_KEY, "the key file's key"); }); diff --git a/editor/app/api/ops/_clipsSuggest.test.ts b/editor/app/api/ops/_clipsSuggest.test.ts @@ -11,7 +11,7 @@ import { planClipsSuggestJob, projectDirOf, umtoolOrigin, type ClipsSuggestJobDe import { readSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; import { GENERATION_PRESETS, sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; -import { appendGenerationUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { appendGenerationUsage, isLocalUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; import type { AskProposal } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; @@ -170,8 +170,10 @@ test("labels on the local model: draft:local through the arbiter, batches fitted assert.equal(doc!.model, "qwen3:8b"); assert.deepEqual(Object.keys(doc!.items).sort(), ["p002", "p003", "p004", "p005"]); assert.ok(ol.unloads.includes("qwen3:8b")); - // A local run spends nothing on the ledger. - assert.equal((await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id).length, 0); + // A local run spends nothing on the ledger; its calls are there at no cost (demo epic D3). + const mine = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); + assert.equal(mine.filter((r) => !isLocalUsage(r)).length, 0); + assert.ok(mine.length > 0 && mine.every((r) => r.model === "qwen3:8b" && r.usd === 0 && (r.calls ?? 0) > 0)); }); test("the code route: no model is asked; a session's answers are read as a model's and written as claude-code's", async () => { diff --git a/editor/app/api/ops/_generation.test.ts b/editor/app/api/ops/_generation.test.ts @@ -46,11 +46,24 @@ test("both reads are behind the token", async () => { test("generation-usage answers the day's ledger total and the daily cap", async () => { const get = await route("generation-usage"); const none = await callGet(get, "http://localhost/api/ops/generation-usage?day=2026-10-01"); - assert.deepEqual(none.body, { ok: true, day: "2026-10-01", usd: 0, jobs: 0, daily: 7 }); + assert.deepEqual(none.body, { ok: true, day: "2026-10-01", usd: 0, jobs: 0, daily: 7, models: [] }); await mkdir(path.dirname(usageFile), { recursive: true }); - await writeFile(usageFile, [row("2026-10-01", "j1", 1.25), row("2026-10-01", "j2", 0.5), row("2026-10-02", "j3", 9)].join("\n") + "\n"); + // A local job's row (demo epic D3): a model called at no cost — never in the + // spend or its jobs count, always in `models`. + const local = JSON.stringify({ ...JSON.parse(row("2026-10-01", "j4", 0)), model: "qwen3:8b", route: "local", calls: 5, inputTokens: 900, outputTokens: 80 }); + await writeFile(usageFile, [row("2026-10-01", "j1", 1.25), row("2026-10-01", "j2", 0.5), row("2026-10-02", "j3", 9), local].join("\n") + "\n"); const some = await callGet(get, "http://localhost/api/ops/generation-usage?day=2026-10-01"); - assert.deepEqual(some.body, { ok: true, day: "2026-10-01", usd: 1.75, jobs: 2, daily: 7 }); + assert.deepEqual(some.body, { + ok: true, + day: "2026-10-01", + usd: 1.75, + jobs: 2, + daily: 7, + models: [ + { model: "claude-sonnet-5-5", route: "api", calls: 0, jobs: 2, inputTokens: 2, outputTokens: 2 }, + { model: "qwen3:8b", route: "local", calls: 5, jobs: 1, inputTokens: 900, outputTokens: 80 }, + ], + }); const today = await callGet(get, "http://localhost/api/ops/generation-usage"); assert.equal(today.body.day, new Date().toISOString().slice(0, 10)); const bad = await callGet(get, "http://localhost/api/ops/generation-usage?day=yesterday"); diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts @@ -10,8 +10,9 @@ import { startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testi import { enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-common/controller/reportDraft"; import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; -import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; -import { createIteration, projectOf, readIteration, readIterationFile, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; +import { dayUsage, readGenerationUsage, usageModelsOf } from "yt-dlp-transcript-common/controller/generationUsage"; +import { modelLogFilesIn, readModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; +import { createIteration, iterationDir, projectOf, readIteration, readIterationFile, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; // Run with: @@ -288,3 +289,27 @@ test("a media draft (youtube, release 28 M6): a step on the done iteration, thro const notDone = await enqueueReportDraft({ task: "cut", article: "synth-basic", iteration: 9, model: "qwen3:8b", source }, deps()); assert.match((notDone.result as { error: string }).error, /has no iteration i9/); }); + +test("a local sweep (demo epic D3): its calls in the iteration's model log; the ledger lists its local model at no cost, and no Claude model", async () => { + const r = await run("sweep-pipeline"); + ol.push(...r.turns); + const spentBefore = await dayUsage(paths.generationUsageFile); + const out = await enqueueReportDraft({ task: "sweep", article: "synth-local-only", model: r.model, question: r.question, channels: r.channels, source }, deps()); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + assert.equal(getRegistry().get(out.result.jobId)!.queueKey, "draft:local"); + void out.result.stream.cancel(); + const jobId = out.result.jobId; + const done = await out.result.done; + assert.equal(done.status, "done", await readFile(getRegistry().get(jobId)!.logPath, "utf8")); + const log = await readModelLog(modelLogFilesIn(iterationDir(paths, "synth-local-only", out.iteration))); + assert.equal(log.runs[0]!.jobId, jobId); + assert.deepEqual([...new Set(log.calls.map((c) => c.phase))], ["terms", "reading", "grouping"]); + assert.ok(log.calls.every((c) => c.route === "local")); + const rows = (await readGenerationUsage(paths.generationUsageFile)).filter((x) => x.jobId === jobId); + assert.ok(rows.length > 0, "a local run is in the ledger"); + assert.ok(rows.every((x) => x.route === "local" && x.usd === 0 && x.article === "synth-local-only" && x.iteration === out.iteration && x.task === "sweep")); + const models = usageModelsOf(rows); + assert.deepEqual(models.map((m) => [m.model, m.route, m.calls]), [["qwen3:8b", "local", log.calls.length]]); + assert.ok(!models.some((m) => m.route === "api" || m.model.startsWith("claude")), "a local-only run lists no cloud model"); + assert.deepEqual(await dayUsage(paths.generationUsageFile), spentBefore, "the cap's total and jobs count are the API's alone"); +}); diff --git a/editor/app/api/ops/_videoAssist.test.ts b/editor/app/api/ops/_videoAssist.test.ts @@ -11,7 +11,7 @@ import { planVideoAssistJob, type AssistNoteReply, type VideoAssistJobDeps } fro import { readAssistProposals } from "yt-dlp-transcript-common/lib/report/videoAssistProposals.mjs"; import { GENERATION_PRESETS, sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; -import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; +import { isLocalUsage, readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; // Run with: @@ -99,7 +99,10 @@ test("on the local model (the default route): draft:local through the arbiter, o const { doc } = await readAssistProposals(dir); assert.deepEqual(doc!.diff, ["join 0.22 s → 0.15 s", "smear 0.5 → 0.3"]); assert.ok(ol.unloads.includes("qwen3:8b")); - assert.equal((await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id).length, 0); + // No spend; the local call is in the ledger at no cost (demo epic D3). + const mine = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); + assert.equal(mine.filter((r) => !isLocalUsage(r)).length, 0); + assert.deepEqual(mine.map((r) => [r.task, r.model, r.route, r.usd, r.calls]), [["video-assist", "qwen3:8b", "local", 0, 1]]); const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); assert.equal(m.render.transition, 0.22, "nothing applied"); }); diff --git a/editor/app/api/ops/generation-usage/route.ts b/editor/app/api/ops/generation-usage/route.ts @@ -1,26 +1,29 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; -import { dayUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; +import { dayModels, dayUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; import { readRoute } from "../_read"; import { opsFail } from "../_lib"; export const dynamic = "force-dynamic"; // GET [?day=YYYY-MM-DD] -// -> { ok, day, usd, jobs, daily } +// -> { ok, day, usd, jobs, daily, models: [{model, route, calls, jobs, inputTokens, outputTokens}] } // // The day's Claude API spend on generation (release 27 S9): the usage // ledger's total for the UTC day (default today) — what the daily cap is // checked against (controller/generationUsage.ts) — and the cap itself // (`settings.generation.caps.daily`, 0 = none). The MCP's generation_policy -// and `archilyzer gen policy` show it beside the routes. Read only. +// and `archilyzer gen policy` show it beside the routes. `models`: every model +// the day's generation called and on which route ("api", or "local" with no +// cost, demo epic D3) — a local-only day lists no Claude model. Read only. const DAY = /^\d{4}-\d{2}-\d{2}$/; export async function GET(request: Request) { return readRoute(request, ["day"], async (q) => { const day = q.get("day")?.trim() || utcDay(); if (!DAY.test(day)) return opsFail('"day" must be a date YYYY-MM-DD (UTC)'); - const used = await dayUsage(getPaths().generationUsageFile, day); - return { ...used, daily: getSettings().generation.caps.daily }; + const file = getPaths().generationUsageFile; + const [used, models] = await Promise.all([dayUsage(file, day), dayModels(file, day)]); + return { ...used, daily: getSettings().generation.caps.daily, models }; }); } diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts @@ -24,6 +24,8 @@ import { import { runTask, type TaskDeps } from "yt-dlp-transcript-common/lib/report/draft/tasks/index"; import type { TaskProgress } from "yt-dlp-transcript-common/lib/report/draft/tasks/types"; import { createCorpusTools, type CorpusTools } from "./callTool"; +import { modelLogFilesIn, readModelCallText, readModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server"; +import { iterationDir } from "yt-dlp-transcript-common/lib/report/iterations"; const RUNS = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft/runs"); const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft"); @@ -351,6 +353,28 @@ test("sweep-pipeline: terms, enumerate, windows, extract (a non-verbatim quote d assert.equal(trace.filter((e) => e.t === "finding").length, 2); assert.deepEqual(trace.at(-1)!.status, "done"); assert.deepEqual(after.coverage, { matched: 1, read: 1, partial: false, unreached: [] }); + + // The model log (demo epic D3): every call, its phase, what code did with it. + const files = modelLogFilesIn(iterationDir(paths, "synth-pipe", it.n)); + const log = await readModelLog(files); + assert.deepEqual(log.runs.map((x) => [x.task, x.model]), [["sweep", "qwen3:8b"]]); + assert.deepEqual(log.calls.map((c) => [c.phase, c.route, c.model]), [["terms", "local", "qwen3:8b"], ["reading", "local", "qwen3:8b"], ["grouping", "local", "qwen3:8b"], ["grouping", "local", "qwen3:8b"]]); + const [terms, extract, group, regroup] = log.calls; + // The second grouping ask (one section held every finding) met the fake's + // empty script: recorded as failed, the first one kept. + assert.match(regroup!.error ?? "", /no structured answer/); + assert.deepEqual(terms!.decision, { outcome: "kept", why: "searched for contest, judges" }); + assert.equal(extract!.label, "extract pie-stream-02@0"); + const lost = extract!.items!.find((x) => x.outcome === "dropped")!; + assert.equal(lost.why, "not verbatim in its window"); + assert.ok(lost.text.includes("I entered the contest and I won")); + assert.equal(extract!.items!.filter((x) => x.outcome === "kept").length, 2); + assert.equal(group!.decision.outcome, "kept"); + assert.match(group!.decision.why, /^placed 2 of 2 findings in \d section/); + assert.ok(log.calls.slice(0, 3).every((c) => c.seconds >= 0 && typeof c.tokensIn === "number")); + const text = (await readModelCallText(files, extract!.id))!; + assert.ok(text.system.startsWith("You read excerpts of an automatic transcript")); + assert.match(text.prompt, /^Research question: Did the baker enter the pie contest\?/); }); test("revise-report: ops over the parent's sweep.md — applied, refused with reasons; quotes untouched; a new quote checked", async () => { diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1166,7 +1166,9 @@ export function usage() { "", "get generation-usage [<day>] is the day's Claude API spend on generation", " (the usage ledger's total for the UTC day, default today) and the daily", - " cap it is checked against: {day, usd, jobs, daily}.", + " cap it is checked against: {day, usd, jobs, daily}; and `models`, every", + " model the day's generation called and on which route (\"local\" at no", + " cost) — a local-only day lists no Claude model.", "get iterations <article> is an article's iterations (iteration.json each)", " and which is current. (The MCP's generate reads one, with its files.)", "", diff --git a/umtool/lib/create/estimate.mjs b/umtool/lib/create/estimate.mjs @@ -30,7 +30,8 @@ export function spendHistory(rows, tasks = ["sweep", "research"]) { /** @type {Map<string, { task: string, at: string, usd: number, models: Map<string, number> }>} */ const jobs = new Map(); for (const r of rows) { - if (!r || !tasks.includes(r.task) || typeof r.usd !== "number" || !r.jobId) continue; + // A local row (route "local", demo epic D3) records calls, not spend. + if (!r || !tasks.includes(r.task) || typeof r.usd !== "number" || !r.jobId || r.route === "local") continue; const j = jobs.get(r.jobId) ?? { task: r.task, at: r.at ?? "", usd: 0, models: new Map() }; j.usd += r.usd; j.models.set(r.model, (j.models.get(r.model) ?? 0) + r.usd); diff --git a/umtool/lib/settings/spend.mjs b/umtool/lib/settings/spend.mjs @@ -18,7 +18,8 @@ export function daySpend(rows, day) { /** @type {Map<string, { jobId: string, at: string, task: string, article: string, iteration: number, models: string[], usd: number }>} */ const jobs = new Map(); for (const r of rows) { - if (!r || r.day !== day || typeof r.usd !== "number") continue; + // A local row (route "local", demo epic D3) is a model called, not spend. + if (!r || r.day !== day || typeof r.usd !== "number" || r.route === "local") continue; const j = jobs.get(r.jobId) ?? { jobId: r.jobId, at: r.at, task: r.task, article: r.article, iteration: r.iteration, models: [], usd: 0 }; j.usd += r.usd; if (!j.models.includes(r.model)) j.models.push(r.model);