// A SWEEP'S TRACE — trace.jsonl beside turns.jsonl (umtool R3, "Transparent // agent runs"; plans/umtool-redesign.md). turns.jsonl is the model's // transcript, written once the run ends; the trace is what the run DID, in // order, appended as it happens, so a page can follow a run live and replay it // when it is done: // // {t: "run", phase: "start", task, model, extractor?} // {t: "scope", source, channels, from?, to?, question, seed?: {chars}} // {t: "terms", terms, topic?, dropped?} the pipeline's search terms (and the ones code dropped) // {t: "enumerate", query, n, ids, partial, unreached, total?} // {t: "read", tool, ids} text read outside a batch // {t: "batch", k, of, ids, lines, model, usd} the extractor's own lines // {t: "cost", step, usd, model, total, turn?, calls?} // {t: "check", quote, cite, ok, reason?, stage, dropped?} // {t: "finding", section, claim, cites} // {t: "select", scope, terms, rare, candidates, read} what the pipeline reads and why (demo D2) // {t: "meaning", video, sec, quote, answer, action, why, from?, to?, seconds} an item's meaning check (D2) // {t: "note", text} // {t: "run", phase: "end", status, summary, usd, minutes, coverage?} // // A REFRESH (umtool R4, draft/refresh) adds its stages' own: // {t: "fetch", channel, action, status, jobId?, reason?, ids?} // one editor action of stage 1 // {t: "build", site, status, jobIds?, reason?} the local build it waited on // {t: "delta", status, matched, newIds, changed, drifted, deleted, partial, // unreached} stage 2's answer // and an enumeration may carry `counts` (each id's matching lines), so the // next refresh can tell a recording whose transcript changed. // // A TRIAGE (umtool R6, draft/triage) — its own run's trace, and the first // line after the start of a sweep it escalated to — adds: // {t: "triage", owner, k, candidates, flagged, dismissed, escalated?, why?, // cost?: {tier0, tier1}, model?} the tiers in one line // and its `cost` lines name their `tier` (1: the judge; 2: the sweep). // // Every line also carries `at` (ISO time) and `run` (1 for the file's first // run; a resumed job's run is 2, …). An agent's events carry `turn` and // `phase` ("agent" or "repair") so a step can be put on the turn that made it. // // A TRACE WRITE NEVER FAILS THE RUN: every append is caught, and the first // failure is logged once. The writes are queued, one at a time, in order, and // take no lock (one writer per run: the job's process); an iteration deleted // mid-run answers ENOENT, which is caught like any other. // // SERVER-ONLY (node:fs). import { appendFile, readFile } from "node:fs/promises"; import { getPaths } from "../../../paths"; import { iterationFile, type IterationCoverage } from "../../iterations"; import type { Report } from "../../schema"; import type { StorePaths } from "./types"; export const TRACE_FILE = "trace.jsonl" as const; // Caps, so one event stays a line a page can read. export const TRACE_MAX_IDS = 2000; export const TRACE_MAX_LINES = 300; export const TRACE_LINE_CHARS = 600; export const TRACE_QUOTE_CHARS = 1200; export type TraceCite = { citation?: string; kind?: string; channel?: string; video?: string; start?: number; end?: number; url?: string; label?: string; quote?: string; }; export type CheckStage = "extract" | "check" | "strict" | "final" | "drop" | "triage"; // What a task hands the tracer: the event, without `at` and `run`. export type TraceInput = | { t: "run"; phase: "start"; task: string; model: string; extractor?: string; jobId?: string } | { t: "run"; phase: "end"; status: string; summary: string; usd: number; minutes: number; coverage?: IterationCoverage } | { t: "scope"; source: string; channels: string[]; from?: string; to?: string; question: string; model: string; extractor?: string; origin?: string; maxUsd?: number; batchSize?: number; seed?: { chars: number }; // A sweep restricted to these recordings (umtool R4). ids?: string[]; } | { t: "terms"; terms: string[]; extra?: boolean; topic?: string; dropped?: { term: string; why: string }[]; asked?: "again" } | { t: "meaning"; video: string; sec: number; quote: string; answer: { speaker: string; stance: string; sentence: string; fix: string | null }; action: "keep" | "rewrite" | "mark" | "drop"; why: string; from?: string; to?: string; seconds: number; } | { t: "select"; scope: number; terms: { term: string; videos: number; partial: boolean; idf: number; nominates: boolean }[]; rare: string[]; candidates: number; read: { id: string; date: string; score: number; hits: Record; why: "top" | "spread" }[]; } | { t: "enumerate"; query: string; n: number; ids: string[]; partial: boolean; unreached: string[]; total?: number; posts?: number; counts?: Record; turn?: number; phase?: string; error?: string } | { t: "read"; tool: string; ids: string[]; turn?: number; phase?: string } | { t: "batch"; k: number; of: number; ids: string[]; lines: string[]; model: string; usd: number; cut?: boolean; turn?: number; phase?: string } | { t: "cost"; step: string; usd: number; model: string; total: number; turn?: number; phase?: string; calls?: string[]; text?: string; tier?: number } | { t: "check"; quote: string; cite: TraceCite; ok: boolean; reason?: string; stage: CheckStage; dropped?: boolean; claim?: string; round?: number } | { t: "finding"; section: string; claim: string; cites: TraceCite[] } | { t: "note"; text: string; turn?: number; phase?: string } // A triage's tiers (umtool R6): its candidates (ids), the flagged ids, how // many lines and windows it dismissed, whether it escalated and why, and // what each tier spent. | { t: "triage"; owner: string; k: number; candidates: string[]; flagged: string[]; dismissed: number; escalated?: boolean; why?: string; cost?: { tier0: number; tier1: number }; model?: string; } // A refresh's stages (umtool R4). | { t: "fetch"; channel: string; action: string; status: TraceStepStatus; jobId?: string; reason?: string; ids?: string[] } | { t: "build"; site: string | null; status: TraceStepStatus; jobIds?: string[]; reason?: string } | { t: "delta"; status: string; matched: number; newIds: string[]; changed: string[]; drifted: string[]; deleted: string[]; partial: boolean; unreached: string[]; }; // How one of a refresh's editor steps went. export type TraceStepStatus = "queued" | "running" | "done" | "failed" | "cancelled" | "skipped" | "refused" | "waiting"; export type TraceEvent = TraceInput & { at: string; run: number }; export type RunTracer = { // This run's number in the file (1, 2, …). readonly run: number; emit(e: TraceInput): void; // Every queued write, done (never rejects). flush(): Promise; }; // A tracer that writes nothing (a task with no trace). export const NO_TRACE: RunTracer = { run: 0, emit: () => {}, flush: async () => {} }; const cut = (s: string, max: number) => (s.length > max ? `${s.slice(0, max)}…` : s); // One event, its lists and texts cut to the caps. export function boundEvent(e: TraceInput): TraceInput { const o = { ...e } as Record; if (Array.isArray(o.ids)) o.ids = (o.ids as string[]).slice(0, TRACE_MAX_IDS); for (const k of ["newIds", "changed", "drifted", "deleted", "candidates", "flagged"]) if (Array.isArray(o[k])) o[k] = (o[k] as string[]).slice(0, TRACE_MAX_IDS); if (o.counts && typeof o.counts === "object") { const entries = Object.entries(o.counts as Record); if (entries.length > TRACE_MAX_IDS) o.counts = Object.fromEntries(entries.slice(0, TRACE_MAX_IDS)); } if (Array.isArray(o.lines)) { const lines = (o.lines as string[]).map((l) => cut(l, TRACE_LINE_CHARS)); o.lines = lines.length > TRACE_MAX_LINES ? [...lines.slice(0, TRACE_MAX_LINES), `(+${lines.length - TRACE_MAX_LINES} more lines)`] : lines; } if (typeof o.quote === "string") o.quote = cut(o.quote, TRACE_QUOTE_CHARS); if (typeof o.text === "string") o.text = cut(o.text, TRACE_LINE_CHARS); if (typeof o.claim === "string") o.claim = cut(o.claim, TRACE_LINE_CHARS); if (typeof o.reason === "string") o.reason = cut(o.reason, TRACE_LINE_CHARS); if (Array.isArray(o.cites)) o.cites = (o.cites as TraceCite[]).map((c) => (c.quote ? { ...c, quote: cut(c.quote, TRACE_QUOTE_CHARS) } : c)); if (o.cite && typeof (o.cite as TraceCite).quote === "string") o.cite = { ...(o.cite as TraceCite), quote: cut((o.cite as TraceCite).quote!, TRACE_QUOTE_CHARS) }; return o as TraceInput; } // The runs a trace file already holds (its `run` start lines). export function runStartsOf(text: string): number { let n = 0; for (const line of text.split("\n")) { if (!line.includes('"run"')) continue; try { const e = JSON.parse(line) as { t?: unknown; phase?: unknown }; if (e.t === "run" && e.phase === "start") n++; } catch { // a torn line is skipped, never fatal } } return n; } // Open the trace of iteration `n` of `article` for a new run (appending) — // or, given `file`, that trace (a triage run's, umtool R6). export async function openTrace(o: { article: string; n: number; paths?: StorePaths; now?: () => Date; log?: (line: string) => void; file?: string; }): Promise { const now = o.now ?? (() => new Date()); let file: string; try { file = o.file ?? iterationFile(o.paths ?? getPaths(), o.article, o.n, TRACE_FILE); } catch (e) { o.log?.(`trace not kept: ${(e as Error).message}`); return NO_TRACE; } const before = await readFile(file, "utf8").catch(() => ""); const run = runStartsOf(before) + 1; let queue: Promise = Promise.resolve(); let failed = false; return { run, emit(e) { let line: string; try { const { t, ...rest } = boundEvent(e); line = `${JSON.stringify({ t, at: now().toISOString(), run, ...rest })}\n`; } catch (err) { if (!failed) o.log?.(`trace not kept: ${(err as Error).message}`); failed = true; return; } queue = queue.then(() => appendFile(file, line).catch((err: Error) => { if (!failed) o.log?.(`trace not kept: ${err.message}`); failed = true; }), ); }, flush: () => queue, }; } // ─── Reading what the corpus tools answered (pure; the tests use them) ─── const ENUM_ROW = /^- (\S+) \| (video|post|audio) \| /; // The whole row: id | kind | channel | date | N match(es) | title[ | mirrors]. const ENUM_FULL = /^- (\S+) \| (video|post|audio) \| (.*?) \| ([^|]*?) \| (\d+) match\(es\) \| (.*)$/; // One row of enumerate_matches' answer, as far as it reads. export type EnumeratedRow = { id: string; kind: "video" | "post" | "audio"; channel: string | null; date: string | null; matches: number | null; title: string | null }; // enumerate_matches' answer: its rows' ids, whether the scan was capped, and // the channels a capped scan never reached; `rows` each row as it reads (its // channel's name, date, matching lines and title). export function enumerateOf(text: string): { ids: string[]; videos: number; posts: number; partial: boolean; unreached: string[]; stopped?: string; total: number | null; rows: EnumeratedRow[] } { const ids: string[] = []; const rows: EnumeratedRow[] = []; let videos = 0; let posts = 0; for (const raw of text.split("\n")) { const line = raw.trim(); const m = ENUM_ROW.exec(line); if (!m) continue; ids.push(m[1]!); if (m[2] === "post") posts++; else videos++; const f = ENUM_FULL.exec(line); rows.push({ id: m[1]!, kind: m[2] as EnumeratedRow["kind"], channel: f ? f[3]!.trim() : null, date: f ? f[4]!.trim() || null : null, matches: f ? Number(f[5]) : null, title: f ? f[6]!.replace(/ \| ⧉ .*$/, "").trim() : null, }); } const partial = /COVERAGE PARTIAL/.test(text); const unreached: string[] = []; // The list ends the sentence (its last name carries the full stop); a name // may hold parentheses ("TheQuartering (Rumble)") — read to the line's end. const nr = /NEVER REACHED \(\d+\): (.*?)\.?$/m.exec(text); if (nr) for (const c of nr[1]!.split(", ")) if (c.trim()) unreached.push(c.trim()); // The channel the cap stopped inside (read in part). const st = /stopped inside (.+?) at page (\d+)\/(\d+)/.exec(text); const stopped = st ? `${st[1]!.trim()} (stopped at page ${st[2]} of ${st[3]})` : undefined; const total = /^(\d+) match\(es\) for /m.exec(text) ?? /\(complete set: [^;]+; (\d+) match\(es\)/.exec(text); return { ids, videos, posts, partial, unreached, ...(stopped ? { stopped } : {}), total: total ? Number(total[1]) : null, rows }; } // Each row's matching lines, by id (a row whose count does not read is left // out); undefined when none reads. export function countsOf(rows: readonly EnumeratedRow[]): Record | undefined { const out: Record = {}; let any = false; for (const r of rows) { if (r.matches === null) continue; out[r.id] = r.matches; any = true; } return any ? out : undefined; } // The ids a corpus read names (get_transcripts' video_ids, get_transcript's // video_id, get_post's post_id, get_thread's), or none. export function idsReadBy(tool: string, input: unknown): string[] { const i = (input ?? {}) as Record; const str = (v: unknown) => (typeof v === "string" && v ? [v] : []); if (tool === "get_transcripts" || tool === "extract_batch") return Array.isArray(i.video_ids) ? i.video_ids.filter((x): x is string => typeof x === "string") : []; if (tool === "get_transcript") return str(i.video_id); if (tool === "get_post") return str(i.post_id); if (tool === "get_thread") return str(i.post_id ?? i.thread_id); return []; } // An answer as lines, empty lines dropped. export function linesOf(text: string): string[] { return text .split("\n") .map((l) => l.trimEnd()) .filter((l) => l.trim()); } // ─── Coverage, accumulated as a run reads ─── export class CoverageTally { readonly matched = new Set(); readonly read = new Set(); partial = false; readonly unreached = new Set(); enumerated(ids: readonly string[], partial: boolean, unreached: readonly string[]): void { for (const id of ids) this.matched.add(id); if (partial) this.partial = true; for (const c of unreached) this.unreached.add(c); } readIds(ids: readonly string[]): void { for (const id of ids) this.read.add(id); } value(): IterationCoverage { return { matched: this.matched.size, read: this.read.size, partial: this.partial, unreached: [...this.unreached].sort() }; } } // ─── A finished report, traced ─── // A report citation as the trace names it. export function citeOfCitation(id: string, c: unknown): TraceCite { const x = (c ?? {}) as Record; const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined); const str = (v: unknown) => (typeof v === "string" && v ? v : undefined); const out: TraceCite = { citation: id }; const kind = str(x.kind); if (kind) out.kind = kind; const channel = str(x.channel); if (channel) out.channel = channel; const video = str(x.id); if (video) out.video = video; const start = num(x.start); if (start !== undefined) out.start = start; const end = num(x.end); if (end !== undefined) out.end = end; const url = str(x.url) ?? str(x.href); if (url) out.url = url; const label = str(x.label); if (label) out.label = label; const quote = str(x.quote); if (quote) out.quote = quote; return out; } // The report a run made: one `finding` per claim (its section, its words, its // cites with their quotes) and one kept `check` per quoted citation. export function traceReport(trace: (e: TraceInput) => void, report: Report): void { const citations = (report.citations ?? {}) as Record; for (const s of report.sections) { for (const c of s.claims ?? []) { trace({ t: "finding", section: s.title, claim: c.text, cites: (c.citations ?? []).map((id) => citeOfCitation(id, citations[id])) }); } } for (const [id, c] of Object.entries(citations)) { const cite = citeOfCitation(id, c); if (!cite.quote) continue; const { quote, ...rest } = cite; trace({ t: "check", quote, cite: rest, ok: true, stage: "final", reason: "verbatim (strict)" }); } }