import { enumerateOf } from "yt-dlp-transcript-common/lib/report/draft/tasks/trace"; import type { RunBatch, RunCall, RunCheck, RunCite, RunCoverage, RunEnumeration, RunFinding, RunStep, RunSummary, RunView } from "./runs-types"; // --------------------------------------------------------------------------- // A TRANSPARENT RUN, projected (plans/umtool-redesign.md, R3). PURE: the // files' texts in, the page's view out (lib/research/runs.ts reads them). // // A run is read from its TRACE (trace.jsonl, common's draft/tasks/trace.ts): // scope, each turn (its cost, its enumerations, reads and extractor batches), // or a pipeline's terms, enumerations and read batches; then the findings, the // quote checks -- kept, refused, dropped and why -- and how it ended. // // A run made before the trace has only turns.jsonl: the model's responses // (with their spend) and its tool calls (inputs; results cut to nothing on an // import). That is projected the same way, turn by turn, and what it never // recorded -- the quote checks, the extractor's lines -- is a gap step that // says so. A turns file holding SEVERAL runs (an import keeps every attempt // of a stopgap run) is split at each start, and the runs are shown one at a // time, never summed. // --------------------------------------------------------------------------- type Json = Record; /** The iteration, as much of it as the page reads (its iteration.json). */ export type RunIteration = { kind?: string; status?: string; model?: string; question?: string; scope?: { channels?: string[]; from?: string; to?: string }; usage?: Record; minutes?: number; checks?: { name: string; ok: boolean; detail?: string }[]; coverage?: RunCoverage; createdAt?: string; endedAt?: string; error?: string; imported?: { extractor?: string; from?: string; run?: string }; }; export type RunReport = { title?: string; sections?: { title: string; claims?: { text: string; citations?: string[] }[] }[]; citations?: Record; }; export type RunInputs = { article: string; n: number; iteration: RunIteration; trace: string | null; turns: string | null; report: RunReport | null; board: { id: string; quotes: number } | null; /** The run asked for (1-based); the last when absent or out of range. */ want?: number | null; }; const str = (v: unknown): string | null => (typeof v === "string" && v ? v : null); const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null); const strs = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []); /** JSON lines, a torn or empty line skipped. */ export function parseLines(text: string | null): Json[] { if (!text) return []; const out: Json[] = []; for (const line of text.split("\n")) { if (!line.trim()) continue; try { const v = JSON.parse(line); if (v && typeof v === "object" && !Array.isArray(v)) out.push(v as Json); } catch { // a torn line (a run still writing) is skipped } } return out; } /** A model id as the header says it: `claude-sonnet-5-5` → Sonnet 5.5. */ export function prettyModel(id: string | null | undefined): string | null { if (!id) return null; const m = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?$/.exec(id); if (!m) return id; return `${m[1]![0]!.toUpperCase()}${m[1]!.slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}`; } /** A corpus handle as a person names it: a site build, the local corpus, a site's host, the hub. */ export function sourceLabelOf(handle: string | null | undefined): string | null { if (!handle) return null; const build = /\.export-builds\/([^/]+)\/out\/?$/.exec(handle); if (build) return `${build[1]} build`; if (handle.startsWith("local:")) return /export\/public\/?$/.test(handle) ? "local corpus" : `local · ${handle.slice(6).split("/").filter(Boolean).slice(-2).join("/")}`; if (handle.startsWith("remote:")) return handle.slice(7).replace(/^https?:\/\//, "").replace(/\/+$/, ""); if (handle.startsWith("hub:")) return "hub"; return handle; } const SHORT: Record = { enumerate_matches: "enumerate", extract_batch: "extract", search_transcripts: "search" }; const short = (name: string) => SHORT[name] ?? name; /** A turn's calls as the step's label: `enumerate ×2 · get_post`. */ export function summarizeCalls(names: readonly string[]): string { if (!names.length) return "answer"; const counts = new Map(); for (const n of names) counts.set(short(n), (counts.get(short(n)) ?? 0) + 1); return [...counts].map(([n, c]) => (c > 1 ? `${n} ×${c}` : n)).join(" · "); } const thousands = (n: number) => n.toLocaleString("en-US"); const plural = (n: number, one: string, many = `${one}s`) => `${thousands(n)} ${n === 1 ? one : many}`; function emptyStep(id: string, kind: RunStep["kind"], t: string, label: string): RunStep { return { id, kind, t, label, sub: null, usd: null, stepUsd: null, gap: false, detail: { facts: [], text: null, calls: [], enumerations: [], batches: [], reads: [], checks: [], findings: [], notes: [] }, }; } const citeOf = (v: unknown): RunCite => { const c = (v ?? {}) as Json; const out: RunCite = {}; for (const k of ["citation", "kind", "channel", "video", "url", "label", "quote"] as const) { const s = str(c[k]); if (s) out[k] = s; } for (const k of ["start", "end"] as const) { const x = num(c[k]); if (x !== null) out[k] = x; } return out; }; const checkOf = (e: Json): RunCheck => ({ quote: str(e.quote) ?? "", cite: citeOf(e.cite), ok: e.ok === true, reason: str(e.reason), stage: str(e.stage) ?? "check", dropped: e.dropped === true, claim: str(e.claim), round: num(e.round), }); const enumerationOf = (e: Json): RunEnumeration => ({ query: str(e.query) ?? "", n: num(e.n) ?? strs(e.ids).length, ids: strs(e.ids), partial: e.partial === true, unreached: strs(e.unreached), total: num(e.total), posts: num(e.posts) ?? 0, }); function checksStep(checks: RunCheck[], id = "checks"): RunStep { const s = emptyStep(id, "checks", "—", "quote checks"); const kept = checks.filter((c) => c.ok && c.stage === "final").length; const dropped = checks.filter((c) => c.dropped).length; const refused = checks.filter((c) => !c.ok && !c.dropped).length; s.sub = [`${thousands(kept)} kept`, `${thousands(dropped)} dropped`, refused ? `${thousands(refused)} refused` : ""].filter(Boolean).join(" · "); s.detail.checks = checks; return s; } function findingsStep(findings: RunFinding[], note?: string): RunStep { const s = emptyStep("findings", "findings", "—", "findings"); const sections = new Set(findings.map((f) => f.section)).size; const cites = findings.reduce((n, f) => n + f.cites.length, 0); s.sub = `${plural(findings.length, "finding")} · ${plural(sections, "section")} · ${plural(cites, "citation")}`; s.detail.findings = findings; if (note) s.detail.notes.push(note); return s; } /** The report's findings (the iteration's kept ones), as a step reads them. */ export function findingsOfReport(report: RunReport | null): RunFinding[] { if (!report) return []; const out: RunFinding[] = []; const cites = report.citations ?? {}; for (const s of report.sections ?? []) { for (const c of s.claims ?? []) { out.push({ section: s.title, claim: c.text, cites: (c.citations ?? []).map((id) => { const x = (cites[id] ?? {}) as Json; return citeOf({ ...x, citation: id, video: x.id }); }), }); } } return out; } // ─── The trace ─── /** The trace's runs, by their `run` number, each in order. */ export function traceRuns(events: Json[]): Map { const out = new Map(); for (const e of events) { const r = num(e.run) ?? 1; if (!out.has(r)) out.set(r, []); out.get(r)!.push(e); } return out; } type Built = { steps: RunStep[]; start: Json | null; scope: Json | null; end: Json | null; usd: number | null; checks: RunCheck[]; findings: RunFinding[]; startedAt: string | null; endedAt: string | null; }; export function stepsOfTrace(events: Json[]): Built { const steps: RunStep[] = []; const turns = new Map(); const batchSteps = new Map(); let start: Json | null = null; let scope: Json | null = null; let end: Json | null = null; let total: number | null = null; let enumN = 0; let termsStep: RunStep | null = null; let groupStep: RunStep | null = null; const checks: RunCheck[] = []; const findings: RunFinding[] = []; const keyOf = (e: Json) => (e.turn === undefined ? null : `${str(e.phase) ?? "agent"}:${num(e.turn) ?? 0}`); const turnOf = (e: Json): RunStep | null => { const k = keyOf(e); return k ? (turns.get(k) ?? null) : null; }; const bump = (s: RunStep, usd: number | null, t: number | null) => { if (usd !== null) s.stepUsd = (s.stepUsd ?? 0) + usd; if (t !== null) { s.usd = Math.max(s.usd ?? 0, t); total = Math.max(total ?? 0, t); } }; for (const e of events) { switch (e.t) { case "run": if (e.phase === "start") start = e; else if (e.phase === "end") end = e; break; case "scope": { scope = e; const s = emptyStep("scope", "scope", "—", "scope"); const ch = strs(e.channels); s.sub = [plural(ch.length, "channel"), sourceLabelOf(str(e.source))].filter(Boolean).join(" · "); s.detail.facts = scopeFacts(e, start); steps.push(s); break; } case "terms": { if (!termsStep) { termsStep = emptyStep("terms", "terms", "—", "search terms"); steps.push(termsStep); } const t = strs(e.terms); termsStep.sub = [termsStep.sub, t.join(", ")].filter(Boolean).join(" + "); if (e.extra) termsStep.detail.notes.push(`Phrases with no match; tried their words: ${t.join(", ")}`); break; } case "cost": { const step = str(e.step) ?? ""; const usd = num(e.usd); const t = num(e.total); const tm = /^(?:repair )?turn (\d+)$/.exec(step); if (tm && e.turn !== undefined) { const phase = str(e.phase) ?? "agent"; const n = num(e.turn) ?? Number(tm[1]); const id = `${phase === "repair" ? "r" : "t"}${n}`; const s = emptyStep(id, "turn", id, summarizeCalls(strs(e.calls))); if (phase === "repair") s.detail.notes.push("The repair round: the report tools only, the failing quotes' transcripts in the message."); s.detail.text = str(e.text); s.detail.facts.push(["model", str(e.model) ?? ""]); turns.set(`${phase}:${n}`, s); steps.push(s); bump(s, usd, t); } else if (/^batch \d+$/.test(step)) { const k = Number(step.slice(6)); const target = turnOf(e) ?? batchSteps.get(k) ?? null; if (target) bump(target, target.kind === "batch" ? null : usd, t); else if (t !== null) total = Math.max(total ?? 0, t); } else if (step === "terms" && termsStep) { bump(termsStep, usd, t); } else if (/^group/.test(step)) { if (!groupStep) { groupStep = emptyStep("group", "group", "—", "group and title"); steps.push(groupStep); } bump(groupStep, usd, t); } else if (t !== null) total = Math.max(total ?? 0, t); break; } case "enumerate": { const en = enumerationOf(e); const host = turnOf(e); if (host) { host.detail.enumerations.push(en); host.sub = enumSub(host.detail.enumerations); } else { enumN++; const s = emptyStep(`e${enumN}`, "enumerate", `e${enumN}`, "enumerate"); s.sub = enumSub([en]); s.detail.enumerations.push(en); s.usd = total; steps.push(s); } break; } case "read": { const host = turnOf(e); if (host) host.detail.reads.push({ tool: str(e.tool) ?? "", ids: strs(e.ids) }); break; } case "batch": { const b: RunBatch = { k: num(e.k) ?? 0, of: num(e.of), ids: strs(e.ids), lines: strs(e.lines), model: str(e.model), usd: num(e.usd), cut: e.cut === true, }; const host = turnOf(e); if (host) { host.detail.batches.push(b); host.sub = batchSub(host.detail.batches, host.detail.enumerations); } else { const s = emptyStep(`b${b.k}`, "batch", `b${b.k}`, `batch ${b.k}${b.of ? `/${b.of}` : ""}`); s.sub = `${plural(b.ids.length, "recording")} · ${plural(b.lines?.length ?? 0, "line")}`; s.detail.batches.push(b); s.stepUsd = b.usd; s.usd = total; batchSteps.set(b.k, s); steps.push(s); } break; } case "check": checks.push(checkOf(e)); break; case "finding": findings.push({ section: str(e.section) ?? "", claim: str(e.claim) ?? "", cites: Array.isArray(e.cites) ? e.cites.map(citeOf) : [] }); break; case "triage": { // R6: the cheap pass this sweep escalated -- its tiers, before this run. const owner = str(e.owner) ?? ""; const k = num(e.k) ?? 0; const cost = e.cost && typeof e.cost === "object" ? { tier0: num((e.cost as Json).tier0) ?? 0, tier1: num((e.cost as Json).tier1) ?? 0 } : null; const tri = { owner, k, href: `/series/${encodeURIComponent(owner)}/triage/${k}`, candidates: strs(e.candidates), flagged: strs(e.flagged), dismissed: num(e.dismissed) ?? 0, escalated: e.escalated === true, why: str(e.why), model: str(e.model), cost, }; const s = emptyStep("triage", "triage", "—", "triage first"); s.sub = `${plural(tri.candidates.length, "candidate")} · ${tri.flagged.length} flagged · ${tri.dismissed} dismissed${tri.escalated ? " · escalated" : ""}`; s.detail.triage = tri; s.detail.facts = [ ["tier 0 · code", `${plural(tri.candidates.length, "candidate")} (new by id) · $${(cost?.tier0 ?? 0).toFixed(2)}`], ["tier 1 · judge", `${tri.model ?? "?"} · ${tri.flagged.length} flagged, ${tri.dismissed} dismissed · $${(cost?.tier1 ?? 0).toFixed(2)}`], ["tier 2 · this run", "the sweep of the flagged recordings (its spend is this run's)"], ...(tri.why ? ([["escalated", tri.why]] as [string, string][]) : []), ]; steps.push(s); break; } case "note": { const host = turnOf(e) ?? steps.at(-1); if (host && str(e.text)) host.detail.notes.push(str(e.text)!); break; } } } // A pipeline's window checks, on the batch that read the recording. for (const s of batchSteps.values()) { const ids = new Set(s.detail.batches.flatMap((b) => b.ids)); s.detail.checks = checks.filter((c) => c.stage === "extract" && c.cite.video && ids.has(c.cite.video)); } if (findings.length) steps.push(findingsStep(findings)); if (checks.length) steps.push(checksStep(checks)); if (end) { const s = emptyStep("end", "end", "—", `ended · ${str(end.status) ?? "?"}`); s.sub = str(end.summary); s.usd = num(end.usd) ?? total; const cov = end.coverage as RunCoverage | undefined; s.detail.facts = [ ["status", str(end.status) ?? ""], ["minutes", String(num(end.minutes) ?? "")], ["spend", s.usd !== null ? `$${s.usd.toFixed(2)}` : ""], ...(cov ? ([["coverage", coverageLine(cov)]] as [string, string][]) : []), ]; steps.push(s); } const usd = end ? (num(end.usd) ?? total) : total; return { steps, start, scope, end, usd, checks, findings, startedAt: str(events[0]?.at), endedAt: end ? str(end.at) : null, }; } function enumSub(ens: RunEnumeration[]): string { const q = ens.map((e) => (e.query.length > 40 ? `${e.query.slice(0, 40)}…` : e.query)).filter(Boolean); const n = ens.reduce((s, e) => s + e.n, 0); return [`${q.length ? `“${q.join("”, “")}”` : "enumerate"}`, `${thousands(n)} matched`, ens.some((e) => e.partial) ? "PARTIAL" : ""].filter(Boolean).join(" · "); } function batchSub(bs: RunBatch[], ens: RunEnumeration[]): string { const ks = bs.map((b) => b.k).sort((a, b) => a - b); const of = Math.max(...bs.map((b) => b.of ?? 0)); const range = ks.length > 1 ? `${ks[0]}–${ks.at(-1)}` : `${ks[0]}`; const lines = bs.reduce((s, b) => s + (b.lines?.length ?? 0), 0); return [ens.length ? enumSub(ens) : "", `batch${ks.length > 1 ? "es" : ""} ${range}${of ? ` of ${of}` : ""}`, bs.every((b) => b.lines) ? plural(lines, "line") : ""].filter(Boolean).join(" · "); } export function coverageLine(c: RunCoverage): string { return [`${thousands(c.matched)} matched`, `${thousands(c.read)} read`, c.partial ? "PARTIAL" : "complete", c.unreached.length ? `not reached: ${c.unreached.join(", ")}` : ""].filter(Boolean).join(" · "); } function scopeFacts(e: Json, start: Json | null): [string, string][] { const out: [string, string][] = []; const add = (k: string, v: string | null | undefined) => { if (v) out.push([k, v]); }; add("question", str(e.question)); add("channels", strs(e.channels).join(", ")); if (e.from || e.to) add("dates", `${str(e.from) ?? "…"} – ${str(e.to) ?? "…"}`); add("corpus", sourceLabelOf(str(e.source))); add("model", str(e.model) ?? str(start?.model)); add("extractor", str(e.extractor) ?? str(start?.extractor)); const max = num(e.maxUsd); if (max !== null) add("budget", `$${max.toFixed(2)}`); const b = num(e.batchSize); if (b !== null) add("batch size", String(b)); const seed = e.seed as { chars?: number } | undefined; if (seed?.chars) add("seed", `a research board, ${thousands(seed.chars)} characters`); add("links on", str(e.origin)); return out; } // ─── turns.jsonl (a run before the trace) ─── const STARTED = /run started/i; /** * A turns file's runs. A note saying a run started (an import's) opens one; * a file with none splits where a response's turn goes back to 0 -- unless a * "repair round" note says that is the same run's repair. */ export function turnRuns(entries: Json[]): Json[][] { const marked = entries.some((e) => e.kind === "note" && STARTED.test(str(e.text) ?? "")); const hasWork = (xs: Json[]) => xs.some((x) => x.kind === "response" || x.kind === "model" || x.kind === "enumerate"); const runs: Json[][] = []; let cur: Json[] = []; let seenTurn = false; let repairPending = false; for (const e of entries) { let opens = false; if (marked) opens = e.kind === "note" && STARTED.test(str(e.text) ?? ""); else if (e.kind === "response" && num(e.turn) === 0 && seenTurn) { if (repairPending) repairPending = false; else opens = true; } // A start before any work (an import's own note first) opens nothing new. if (opens && hasWork(cur)) { runs.push(cur); cur = []; seenTurn = false; repairPending = false; } if (e.kind === "note" && /repair round/i.test(str(e.text) ?? "")) repairPending = true; if (e.kind === "response") seenTurn = true; cur.push(e); } if (cur.length) { if (runs.length && !hasWork(cur)) runs[runs.length - 1]!.push(...cur); else runs.push(cur); } return runs.length ? runs : [[]]; } function callSummary(name: string, input: unknown): string { const i = (input ?? {}) as Json; const parts: string[] = []; const q = str(i.query); if (q) parts.push(`“${q.length > 120 ? `${q.slice(0, 120)}…` : q}”`); const qs = strs(i.queries); if (qs.length) parts.push(`queries ${qs.join(", ").slice(0, 120)}`); const ids = strs(i.video_ids); if (ids.length) parts.push(plural(ids.length, "id")); const one = str(i.video_id) ?? str(i.post_id); if (one) parts.push(one); const ch = strs(i.channels); if (ch.length && name !== "extract_batch") parts.push(ch.join(", ")); else if (str(i.channel)) parts.push(str(i.channel)!); if (i.date_from || i.date_to) parts.push(`${str(i.date_from) ?? "…"}–${str(i.date_to) ?? "…"}`); const old = str(i.old_text); if (old) parts.push(`replace “${old.slice(0, 60)}${old.length > 60 ? "…" : ""}”`); if (name === "write_report") parts.push("the whole report"); return parts.join(" · "); } function turnSub(calls: { name: string; input: unknown; chars: number | null }[]): string | null { const en = calls.filter((c) => c.name === "enumerate_matches"); const ex = calls.filter((c) => c.name === "extract_batch"); const posts = calls.filter((c) => c.name === "get_post").map((c) => str((c.input as Json)?.post_id)).filter(Boolean); const reads = calls.filter((c) => c.name === "get_transcripts" || c.name === "get_transcript"); if (en.length) return en.map((c) => (c.chars !== null ? `${thousands(c.chars)}` : "?")).join(" + ") + " chars of ids"; if (ex.length) return `${plural(ex.reduce((s, c) => s + strs((c.input as Json)?.video_ids).length, 0), "id")} in ${plural(ex.length, "batch", "batches")}`; if (posts.length) return `post ${posts.join(", ")}`; if (reads.length) { const whole = calls.filter((c) => c.name === "get_transcript").map((c) => str((c.input as Json)?.video_id)).filter(Boolean); const chars = reads.reduce((s, c) => s + (c.chars ?? 0), 0); return [whole.length ? `${whole.join(", ")} read whole` : "", `${thousands(chars)} chars`].filter(Boolean).join(" · "); } if (calls.some((c) => c.name === "write_report")) return "the report written"; if (calls.some((c) => c.name === "edit_report")) return "the report edited"; return null; } export function stepsOfTurns(entries: Json[]): Built & { stopgap: Json | null; dropped: RunCheck[] } { const steps: RunStep[] = []; let total = 0; let anyUsd = false; let repair = false; let batchK = 0; let stopgap: Json | null = null; let current: RunStep | null = null; let pending: { name: string; input: unknown; chars: number | null }[] = []; const dropped: RunCheck[] = []; // The pipeline's own events. const enumerations: RunEnumeration[] = []; let extractAsks = 0; let extractIds = new Set(); let startedAt: string | null = null; let endedAt: string | null = null; const close = () => { if (current) current.sub = turnSub(pending) ?? current.sub; pending = []; }; for (const e of entries) { const at = str(e.at); if (at) { startedAt ??= at; endedAt = at; } if (e.kind === "note") { const text = str(e.text) ?? ""; if (STARTED.test(text)) stopgap = { ...((e.stopgap as Json | undefined) ?? {}), note: text }; if (/repair round/i.test(text)) repair = true; continue; } if (e.kind === "response") { close(); const turn = num(e.turn) ?? 0; // A turn 0 after turns already taken: the run's repair (an old run // kept no note for it). if (turn === 0 && steps.some((s) => s.kind === "turn")) repair = true; const id = `${repair ? "r" : "t"}${turn}`; const content = Array.isArray(e.content) ? (e.content as Json[]) : []; const names = content.filter((b) => b.type === "tool_use").map((b) => str(b.name) ?? ""); const s = emptyStep(id, "turn", id, summarizeCalls(names)); s.detail.text = content.filter((b) => b.type === "text").map((b) => str(b.text) ?? "").join("\n").trim() || null; const usd = num(e.usd); if (usd !== null) { // An imported stopgap run logged its RUNNING total on each turn // (common/bin/reports-import-local-runs.ts keeps it as it was); the // agent's own transcript logs each turn's spend. const step = stopgap ? Math.max(0, usd - total) : usd; total = stopgap ? Math.max(total, usd) : total + usd; anyUsd = true; s.stepUsd = step; s.usd = total; } if (repair) s.detail.notes.push("The repair round."); steps.push(s); current = s; continue; } if (e.kind === "tool") { const name = str(e.name) ?? ""; const chars = num(e.chars); const call: RunCall = { name, summary: callSummary(name, e.input), chars, error: e.error === true }; pending.push({ name, input: e.input, chars }); if (current) { current.detail.calls.push(call); const result = str(e.result); if (name === "enumerate_matches" && result) { const en = enumerateOf(result); current.detail.enumerations.push({ query: str((e.input as Json)?.query) ?? "", n: en.ids.length, ids: en.ids, partial: en.partial, unreached: en.unreached, total: en.total, posts: en.posts, }); } if (name === "extract_batch") { batchK++; current.detail.batches.push({ k: batchK, of: null, ids: strs((e.input as Json)?.video_ids), lines: null, model: null, usd: null, cut: false }); } if (name === "get_transcripts" || name === "get_transcript" || name === "get_post") { const i = (e.input ?? {}) as Json; const ids = name === "get_transcripts" ? strs(i.video_ids) : [str(i.video_id) ?? str(i.post_id) ?? ""].filter(Boolean); if (ids.length) current.detail.reads.push({ tool: name, ids }); } } continue; } // The pipeline (a local model): enumerate, model asks, dropped quotes. if (e.kind === "enumerate") { const en: RunEnumeration = { query: str(e.term) ?? "", n: num(e.videos) ?? 0, ids: [], partial: e.partial === true, unreached: [], total: null, posts: 0 }; enumerations.push(en); const s = emptyStep(`e${enumerations.length}`, "enumerate", `e${enumerations.length}`, "enumerate"); s.sub = enumSub([en]); s.detail.enumerations.push(en); steps.push(s); current = null; continue; } if (e.kind === "model") { const what = str(e.what) ?? ""; if (what.startsWith("extract")) { extractAsks++; const v = /^extract (\S+)@/.exec(what)?.[1]; if (v) extractIds.add(v); let s = steps.at(-1); if (!s || s.kind !== "batch") { s = emptyStep(`b${steps.filter((x) => x.kind === "batch").length + 1}`, "batch", "b", "extract"); s.t = s.id; steps.push(s); extractIds = new Set(v ? [v] : []); extractAsks = 1; } s.sub = `${plural(extractIds.size, "recording")} · ${plural(extractAsks, "excerpt")} judged`; s.detail.batches = [{ k: 1, of: null, ids: [...extractIds], lines: null, model: null, usd: null, cut: false }]; } else if (what === "terms") { const s = emptyStep("terms", "terms", "—", "search terms"); const t = strs((e.answer as Json)?.terms); s.sub = t.join(", ") || null; steps.push(s); } else if (what.startsWith("group")) { if (!steps.some((x) => x.kind === "group")) steps.push(emptyStep("group", "group", "—", "group and title")); } continue; } if (e.kind === "dropped") { const c: RunCheck = { quote: str(e.quote) ?? "", cite: { video: str(e.video) ?? undefined }, ok: false, reason: str(e.why), stage: /^quote check/.test(str(e.why) ?? "") ? "drop" : "extract", dropped: true, claim: str(e.claim), round: null }; dropped.push(c); const b = steps.at(-1); if (b?.kind === "batch") b.detail.checks.push(c); continue; } if (e.kind === "unread" || e.kind === "chunk-failed" || e.kind === "group-failed") { const host = steps.at(-1); host?.detail.notes.push(`${str(e.video) ?? ""} ${str(e.why) ?? str(e.error) ?? e.kind}`.trim()); } } close(); return { steps, start: null, scope: null, end: null, usd: anyUsd ? total : null, checks: dropped, findings: [], startedAt, endedAt, stopgap, dropped, }; } // ─── The view ─── const round2 = (n: number) => Math.round(n * 100) / 100; export function runView(inp: RunInputs): RunView { const it = inp.iteration; const status = it.status ?? "unknown"; const running = status === "running" || status === "queued"; const iterationUsd = round2(Object.values(it.usage ?? {}).reduce((s, u) => s + (u.usd ?? 0), 0)); const traceEvents = parseLines(inp.trace); const notes: string[] = []; const reportFindings = findingsOfReport(inp.report); const base = { article: inp.article, n: inp.n, label: `i${inp.n}`, kind: it.kind ?? "sweep", status, findings: reportFindings.reduce((s, f) => s + f.cites.filter((c) => c.quote).length, 0), board: inp.board, }; const iterationChecks = (it.checks ?? []).map((c) => ({ name: c.name, ok: c.ok, detail: c.detail ?? null })); if (traceEvents.length) { const byRun = traceRuns(traceEvents); const numbers = [...byRun.keys()].sort((a, b) => a - b); const run = inp.want && byRun.has(inp.want) ? inp.want : numbers.at(-1)!; const built = stepsOfTrace(byRun.get(run)!); const runs: RunSummary[] = numbers.map((r) => { const b = r === run ? built : stepsOfTrace(byRun.get(r)!); return { index: r, startedAt: b.startedAt, steps: b.steps.length, usd: b.usd === null ? null : round2(b.usd), status: b.end ? str(b.end.status) : r === numbers.at(-1) && running ? status : "stopped" }; }); if (numbers.length > 1) notes.push(`This iteration's trace holds ${numbers.length} runs; each is shown on its own.`); const sc = built.scope; const kept = built.checks.filter((c) => c.ok && c.stage === "final").length; const dropped = built.checks.filter((c) => c.dropped).length; const refused = built.checks.filter((c) => !c.ok && !c.dropped).length; const cov = (built.end?.coverage as RunCoverage | undefined) ?? (run === numbers.at(-1) ? (it.coverage ?? null) : null); const isLast = run === numbers.at(-1); return { ...base, live: running && isLast && !built.end, from: "trace", runs, run, header: { question: str(sc?.question) ?? it.question ?? null, title: isLast ? (inp.report?.title ?? null) : null, task: str(built.start?.task), model: str(built.start?.model) ?? str(sc?.model) ?? it.model ?? null, extractor: str(built.start?.extractor) ?? str(sc?.extractor), channels: sc ? strs(sc.channels) : (it.scope?.channels ?? []), dateFrom: str(sc?.from) ?? it.scope?.from ?? null, dateTo: str(sc?.to) ?? it.scope?.to ?? null, sourceLabel: sourceLabelOf(str(sc?.source)), startedAt: built.startedAt, endedAt: built.endedAt, minutes: num(built.end?.minutes), usd: built.usd === null ? null : round2(built.usd), iterationUsd, checks: isLast ? iterationChecks : [], coverage: cov ?? null, kept: built.end || kept ? kept : null, dropped: built.end || dropped ? dropped : null, refused, seed: (sc?.seed as { chars: number } | undefined) ?? null, error: isLast && status !== "done" ? (it.error ?? null) : null, summary: str(built.end?.summary), }, steps: built.steps, notes, ...(isLast ? {} : { findings: 0 }), }; } const entries = parseLines(inp.turns); const groups = turnRuns(entries); const count = entries.length ? groups.length : 0; const run = count === 0 ? 1 : inp.want && inp.want >= 1 && inp.want <= count ? inp.want : count; const built = stepsOfTurns(groups[run - 1] ?? []); const isLast = run === Math.max(count, 1); const sg = built.stopgap; const fromNote = (re: RegExp) => { const m = re.exec(str(sg?.note) ?? ""); return m ? m[1]! : null; }; const scope = emptyStep("scope", "scope", "—", "scope"); const channels = strs(sg?.channels).length ? strs(sg?.channels) : (it.scope?.channels ?? []); scope.sub = [plural(channels.length, "channel"), sourceLabelOf(str(sg?.source) ?? str(sg?.corpus))].filter(Boolean).join(" · "); const model = fromNote(/model (\S+?),/) ?? it.model ?? null; const extractor = fromNote(/extractor (\S+?)(?:,|$)/) ?? it.imported?.extractor ?? null; scope.detail.facts = [ ["question", str(sg?.question) ?? it.question ?? ""], ["channels", channels.join(", ")], ...((it.scope?.from || it.scope?.to ? [["dates", `${it.scope?.from ?? "…"} – ${it.scope?.to ?? "…"}`]] : []) as [string, string][]), ["model", model ?? ""], ...((extractor ? [["extractor", extractor]] : []) as [string, string][]), ...((fromNote(/cap (\$[\d.]+)/) ? [["budget", fromNote(/cap (\$[\d.]+)/)!]] : []) as [string, string][]), ].filter(([, v]) => v) as [string, string][]; const steps: RunStep[] = count ? [scope, ...built.steps] : []; if (count && isLast && reportFindings.length) steps.push(findingsStep(reportFindings, "From the iteration's report (what its last run kept).")); if (count) { if (built.dropped.length) { const s = checksStep(built.dropped); s.sub = `${thousands(built.dropped.length)} dropped · the kept ones were not traced`; steps.push(s); } else { const gap = emptyStep("checks", "checks", "—", "quote checks"); gap.gap = true; gap.sub = "kept / dropped not recorded"; gap.detail.notes.push("This run predates the trace (trace.jsonl): which quotes were checked, kept or dropped, and why, was never recorded."); if (isLast) for (const c of iterationChecks) gap.detail.facts.push([c.name, `${c.ok ? "ok" : "failed"}${c.detail ? ` — ${c.detail}` : ""}`]); steps.push(gap); } } if (count > 1) notes.push(`turns.jsonl holds ${count} run starts${it.imported ? " (an import keeps every attempt)" : ""}; each is shown on its own, never summed.`); if (count) notes.push("Projected from turns.jsonl: this run predates the trace, so the extractor's lines and the quote checks were not kept."); const runs: RunSummary[] = groups.slice(0, count).map((g, i) => { const b = i + 1 === run ? built : stepsOfTurns(g); return { index: i + 1, startedAt: b.startedAt, steps: b.steps.length + 2, usd: b.usd === null ? null : round2(b.usd), status: i + 1 === count ? status : "superseded" }; }); return { ...base, live: running && isLast, from: count ? "turns" : "none", runs, run, header: { question: str(sg?.question) ?? it.question ?? null, title: isLast ? (inp.report?.title ?? null) : null, task: null, model, extractor, channels, dateFrom: it.scope?.from ?? null, dateTo: it.scope?.to ?? null, sourceLabel: sourceLabelOf(str(sg?.source) ?? str(sg?.corpus)), startedAt: built.startedAt ?? it.createdAt ?? null, endedAt: isLast ? (it.endedAt ?? built.endedAt) : built.endedAt, minutes: isLast && count <= 1 ? (it.minutes ?? null) : minutesBetween(built.startedAt, built.endedAt), usd: built.usd === null ? null : round2(built.usd), iterationUsd, checks: isLast ? iterationChecks : [], coverage: isLast ? (it.coverage ?? null) : null, kept: null, dropped: built.dropped.length || null, refused: null, seed: null, error: isLast && status !== "done" ? (it.error ?? null) : null, summary: null, }, steps, notes, ...(isLast ? {} : { findings: 0 }), }; } function minutesBetween(a: string | null, b: string | null): number | null { if (!a || !b) return null; const d = (Date.parse(b) - Date.parse(a)) / 60_000; return Number.isFinite(d) && d >= 0 ? round2(d) : null; }