commit e02f68d5a074704bb64ab9125c02706a8d94d459
parent f9d4bff7e04eb1c77bdb91cdc4d89356cbfdbb7b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 07:08:53 -0400
common: a sweep's trace.jsonl (scope, enumerations, batches with the extractor's lines, every quote check kept or dropped with why, findings, cost per step, the run's start and end) and the iteration's coverage {matched, read, partial, unreached}
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
10 files changed, 838 insertions(+), 28 deletions(-)
diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts
@@ -60,6 +60,8 @@ export { pickCorpusBuild, listCorpusBuilds, siteOriginOf, NoCorpusBuildError, ty
export { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
export { checkQuotes, convertSweepText, dropFailedFindings, type QuoteProblem } from "./quotes";
export { projectDirOf } from "./project";
+// umtool R3: a sweep's trace (trace.jsonl).
+export { TRACE_FILE, enumerateOf, openTrace, runStartsOf, type TraceCite, type TraceEvent, type TraceInput } from "./trace";
export type TaskInput =
| ({ task: "sweep-agent" } & SweepAgentInput)
diff --git a/common/lib/report/draft/tasks/quotes.ts b/common/lib/report/draft/tasks/quotes.ts
@@ -156,10 +156,15 @@ export function describeProblems(problems: readonly QuoteProblem[], max = 40): s
// The findings citing a failed quote, dropped: a finding goes when one of its
// links cites the problem's recording and its quoted words hold one of the
-// failed quote's fragments. Answers the new markdown and what went.
-export function dropFailedFindings(md: string, problems: readonly QuoteProblem[]): { md: string; dropped: string[] } {
+// failed quote's fragments. Answers the new markdown and what went: `dropped`
+// as lines, `items` as the finding's claim with the problem that took it (a
+// sweep's trace shows each dropped quote and why).
+export type DroppedFinding = { claim: string; problem: QuoteProblem };
+
+export function dropFailedFindings(md: string, problems: readonly QuoteProblem[]): { md: string; dropped: string[]; items: DroppedFinding[] } {
const doc: SweepDoc = parseSweep(md);
const dropped: string[] = [];
+ const items: DroppedFinding[] = [];
for (const section of doc.sections) {
for (const f of findingsOf(section)) {
const links = [...evidenceOf(f).matchAll(new RegExp(LINK_RE.source, "g"))]
@@ -178,8 +183,9 @@ export function dropFailedFindings(md: string, problems: readonly QuoteProblem[]
if (!hit) continue;
section.body.splice(section.body.indexOf(f), 1);
dropped.push(`${f.claim.slice(0, 80)} — ${hit.why}`);
+ items.push({ claim: f.claim, problem: hit });
}
}
- if (!dropped.length) return { md, dropped };
- return { md: renderSweep(doc), dropped };
+ if (!dropped.length) return { md, dropped, items };
+ return { md: renderSweep(doc), dropped, items };
}
diff --git a/common/lib/report/draft/tasks/run.ts b/common/lib/report/draft/tasks/run.ts
@@ -19,6 +19,8 @@ import {
type IterationPatch,
} from "../../iterations";
import { ArticleRegistryError } from "../../registry";
+import type { IterationCoverage } from "../../iterations";
+import { NO_TRACE, openTrace, type RunTracer, type TraceInput } from "./trace";
import type { StorePaths, TaskDeps, TaskProgress, TaskResult, TaskStatus } from "./types";
export class TaskInputError extends Error {}
@@ -44,6 +46,11 @@ export type TaskHandle = {
turns(entries: readonly unknown[]): void;
check(c: IterationCheck): void;
checks: IterationCheck[];
+ // The run's trace (trace.jsonl, ./trace.ts) when the task keeps one, else a
+ // no-op. Never throws, never waits.
+ trace(e: TraceInput): void;
+ // The iteration's coverage, read when the run ends (whatever ended it).
+ setCoverage(read: () => IterationCoverage): void;
};
export function usageOf(t: ModelTally) {
@@ -74,6 +81,10 @@ export async function runOnIteration(
maxUsd?: number;
kinds?: readonly Iteration["kind"][];
step?: { task: string; model: string; jobId?: string };
+ // Keep a trace (trace.jsonl): the run's start and end are written here,
+ // the task writes the rest through `h.trace` (umtool R3).
+ // `model` defaults to the iteration's.
+ trace?: { task: string; model?: string; extractor?: string };
},
body: (h: TaskHandle) => Promise<TaskOutcome>,
): Promise<TaskResult> {
@@ -127,6 +138,13 @@ export async function runOnIteration(
if (o.step) await record("running");
else await updateIteration(article, n, { status: "running", error: undefined }, paths, started);
+ // The trace: opened after the iteration is running (so its first line is
+ // never older than the status a page reads beside it).
+ const tracer: RunTracer = o.trace ? await openTrace({ article, n, paths, now, log }).catch(() => NO_TRACE) : NO_TRACE;
+ if (o.trace) {
+ tracer.emit({ t: "run", phase: "start", task: o.trace.task, model: o.trace.model || it.model, ...(o.trace.extractor ? { extractor: o.trace.extractor } : {}), ...(it.jobId ? { jobId: it.jobId } : {}) });
+ }
+ let coverageOf: (() => IterationCoverage) | null = null;
const handle: TaskHandle = {
article,
n,
@@ -149,6 +167,16 @@ export async function runOnIteration(
else checks.push(c);
},
checks,
+ trace: (e) => {
+ try {
+ tracer.emit(e);
+ } catch {
+ // a trace never stops the task
+ }
+ },
+ setCoverage: (read) => {
+ coverageOf = read;
+ },
};
let status: TaskStatus;
@@ -181,12 +209,26 @@ export async function runOnIteration(
await addIterationUsage(article, n, model, usageOf(t), paths, now());
}
const minutes = await record(status, summary);
+ let coverage: IterationCoverage | undefined;
+ try {
+ coverage = coverageOf ? (coverageOf as () => IterationCoverage)() : undefined;
+ } catch {
+ coverage = undefined;
+ }
+ // The trace ends BEFORE the status does: a page that reads the iteration
+ // ended finds the trace's end already written.
+ if (o.trace) {
+ const usd = Math.round(meter.usd * 10_000) / 10_000;
+ tracer.emit({ t: "run", phase: "end", status, summary: summary.slice(0, 1000), usd, minutes: o.step ? minutes : round2((now().getTime() - started.getTime()) / 60_000), ...(coverage ? { coverage } : {}) });
+ await tracer.flush();
+ }
if (!o.step) {
await updateIteration(
article,
n,
(cur) => ({
...patch,
+ ...(coverage ? { coverage } : {}),
status,
minutes: round2((now().getTime() - started.getTime()) / 60_000),
...(checks.length ? { checks: [...(cur.checks ?? []).filter((c) => !checks.some((x) => x.name === c.name)), ...checks] } : {}),
diff --git a/common/lib/report/draft/tasks/sweep-agent.ts b/common/lib/report/draft/tasks/sweep-agent.ts
@@ -9,8 +9,15 @@
// convert, the strict quote check, ONE bounded repair round (the report tools
// only, the transcript ±45 s inline, an allowance of min($0.25, cap/4)), and a
// finding whose quote still fails is dropped.
+//
+// The run is TRACED (trace.jsonl, ./trace.ts; umtool R3): its scope, every
+// enumeration (ids, partial, the channels never reached), every read, every
+// extractor batch with the lines it returned, each turn's cost, every quote
+// check — the ones dropped too, with why — and the findings it kept. The
+// iteration's `coverage` is what it enumerated and read.
import { providerOf, runAgent, type AgentTool } from "../../../llm";
+import type { Report } from "../../schema";
import { iterationLabel, readIterationFile, writeIterationFile } from "../../iterations";
import {
CLAIM_QUOTES_RULE,
@@ -26,9 +33,10 @@ import {
} from "../authoringRules";
import { plainAnswer, userCharsFor } from "./llmText";
import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
-import { checkQuotes, convertSweepText, describeProblems, dropFailedFindings, titleOfSweep } from "./quotes";
+import { checkQuotes, convertSweepText, describeProblems, dropFailedFindings, titleOfSweep, type QuoteProblem } from "./quotes";
import { reportFile } from "./reportFile";
import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
+import { CoverageTally, enumerateOf, idsReadBy, linesOf, traceReport, type TraceCite } from "./trace";
import type { TaskDeps, TaskResult } from "./types";
// The corpus reads the agent may make (no fetch_clip, enqueue, notes or jobs:
@@ -124,7 +132,11 @@ const REPAIR_SYSTEM = [
"For each problem: correct the quote to the transcript's exact words shown with it (and the second in the link to that line's second); a fragment's fix is the whole sentence given with it; or remove the finding. Never invent words. Edit the report only, then stop.",
].join("\n");
-function extractTool(h: TaskHandle, input: SweepAgentInput, rewrite: (t: string) => Promise<string>, count: { n: number }): AgentTool {
+// Where the agent is (the turn its tool calls belong to), and what it has
+// enumerated and read: the trace's and the coverage's.
+type Watch = { turn: number; phase: "agent" | "repair"; batches: number; cov: CoverageTally };
+
+function extractTool(h: TaskHandle, input: SweepAgentInput, rewrite: (t: string) => Promise<string>, count: { n: number }, watch: Watch): AgentTool {
const batch = input.batchSize ?? 10;
return {
name: "extract_batch",
@@ -145,6 +157,9 @@ function extractTool(h: TaskHandle, input: SweepAgentInput, rewrite: (t: string)
run: async (inp: { video_ids?: unknown; queries?: unknown; directive?: unknown; channel?: unknown }, ctx) => {
const ids = Array.isArray(inp.video_ids) ? inp.video_ids.filter((x): x is string => typeof x === "string") : [];
if (!ids.length) throw new Error("extract_batch needs video_ids");
+ const k = ++watch.batches;
+ const { turn, phase } = watch;
+ const before = h.meter.usd;
const args: Record<string, unknown> = {
video_ids: ids,
queries: Array.isArray(inp.queries) ? inp.queries : [],
@@ -167,14 +182,28 @@ function extractTool(h: TaskHandle, input: SweepAgentInput, rewrite: (t: string)
signal: ctx?.signal ?? h.deps.signal,
});
count.n++;
+ // The batch, traced: its ids and the extractor's own lines.
+ const usd = h.meter.usd - before;
+ watch.cov.readIds(ids);
+ const of = Math.max(k, Math.ceil(watch.cov.matched.size / Math.max(batch, 1)));
+ h.trace({ t: "batch", k, of, ids, lines: linesOf(out), model: input.extractorModel, usd, ...(note ? { cut: true } : {}), turn, phase });
+ h.trace({ t: "cost", step: `batch ${k}`, usd, model: input.extractorModel, total: h.meter.usd, turn, phase });
return out + note;
},
};
}
export async function sweepAgent(input: SweepAgentInput, deps: TaskDeps): Promise<TaskResult> {
- return runOnIteration({ article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["sweep"] }, (h) =>
- sweepAgentBody(h, input),
+ return runOnIteration(
+ {
+ article: input.article,
+ n: input.n,
+ deps,
+ maxUsd: input.maxUsd,
+ kinds: ["sweep"],
+ trace: { task: "sweep-agent", ...(input.model ? { model: input.model } : {}), extractor: input.extractorModel },
+ },
+ (h) => sweepAgentBody(h, input),
);
}
@@ -197,6 +226,22 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
const file = reportFile({ article: h.article, n: h.n, paths: h.paths, ...(seed ? { initial: seed } : {}) });
if (seed) await file.set(seed); // sweep.md holds it from the first turn, as a run cut short keeps it
const extracts = { n: 0 };
+ const watch: Watch = { turn: 0, phase: "agent", batches: 0, cov: new CoverageTally() };
+ h.setCoverage(() => watch.cov.value());
+ h.trace({
+ t: "scope",
+ source: deps.corpus.source,
+ channels,
+ ...(from ? { from } : {}),
+ ...(to ? { to } : {}),
+ question,
+ model,
+ extractor: input.extractorModel,
+ origin,
+ maxUsd: input.maxUsd,
+ batchSize: batch,
+ ...(seed ? { seed: { chars: seed.length } } : {}),
+ });
h.log(`${iterationLabel(h.n)} sweep on ${model} (extractor ${input.extractorModel}), corpus ${deps.corpus.source}, links on ${origin}${seed ? `, seeded (${seed.length} chars)` : ""}`);
const request =
@@ -209,21 +254,39 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
t.name === "get_transcripts"
? { ...t, run: async (i: unknown, c: { signal?: AbortSignal }) => rewrite(await t.run(i, c)) }
: t,
- );
+ )
+ .map((t) => watched(h, t, watch));
const web = input.web === false ? [] : (deps.web ?? []);
- const tools = [...corpusTools, extractTool(h, input, rewrite, extracts), ...file.tools, ...web];
+ const tools = [...corpusTools, extractTool(h, input, rewrite, extracts, watch), ...file.tools, ...web];
const isApi = providerOf(model) === "api";
const maxTurns = input.maxTurns ?? 150;
// The job's progress: every model turn, the repair round's included.
let turnsTaken = 0;
const onEvent = (e: Parameters<NonNullable<Parameters<typeof runAgent>[0]["onEvent"]>>[0]) => {
if (e.type === "turn") {
+ watch.turn = e.turn;
+ h.trace({
+ t: "cost",
+ step: `${watch.phase === "repair" ? "repair " : ""}turn ${e.turn}`,
+ usd: e.usd,
+ model,
+ total: h.meter.usd,
+ turn: e.turn,
+ phase: watch.phase,
+ calls: e.calls,
+ ...(e.text.trim() ? { text: e.text.trim() } : {}),
+ });
turnsTaken++;
h.progress({ metric: "turns", current: turnsTaken, total: Math.max(turnsTaken, maxTurns) });
h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`);
}
- else if (e.type === "wrap-up") h.log(`budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`);
- else if (e.type === "note") h.log(e.text);
+ else if (e.type === "wrap-up") {
+ h.log(`budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`);
+ h.trace({ t: "note", text: `budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`, turn: e.turn, phase: watch.phase });
+ } else if (e.type === "note") {
+ h.log(e.text);
+ h.trace({ t: "note", text: e.text, turn: e.turn, phase: watch.phase });
+ }
};
const run = await runAgent({
llm: deps.llm,
@@ -241,12 +304,13 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
h.turns(run.transcript);
if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" };
h.log(`agent ended: ${run.stopReason}${extracts.n ? `, ${extracts.n} extract batch(es)` : ""}`);
+ h.trace({ t: "note", text: `agent ended: ${run.stopReason}`, turn: watch.turn, phase: watch.phase });
if (!file.text().trim()) {
return { status: "failed", summary: `no report was written (the agent stopped: ${run.stopReason})` };
}
- const finish = await convertAndCheck(h, file, { origin, resolver });
+ const finish = await convertAndCheck(h, file, { origin, resolver, round: 1 });
let { problems } = finish;
if (finish.convertProblems) {
return { status: "failed", summary: `the report does not convert: ${finish.convertProblems.slice(0, 3).join("; ")}` };
@@ -254,6 +318,9 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
if (problems.length && !deps.signal?.aborted) {
h.log(`${problems.length} quote problem(s) — one repair round`);
+ watch.phase = "repair";
+ watch.turn = 0;
+ h.trace({ t: "note", text: `${problems.length} quote problem(s) — one repair round`, phase: "repair" });
const allowance = Math.min(REPAIR_ALLOWANCE_USD, input.maxUsd * 0.25);
const repair = await runAgent({
llm: deps.llm,
@@ -271,7 +338,7 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
});
h.turns([{ kind: "note", turn: 0, at: (deps.now?.() ?? new Date()).toISOString(), text: "repair round" }, ...repair.transcript]);
if (repair.stopReason === "cancelled") return { status: "failed", summary: "cancelled" };
- const again = await convertAndCheck(h, file, { origin, resolver });
+ const again = await convertAndCheck(h, file, { origin, resolver, round: 2 });
if (again.convertProblems) {
return { status: "failed", summary: `the repaired report does not convert: ${again.convertProblems.slice(0, 3).join("; ")}` };
}
@@ -282,11 +349,14 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
if (problems.length) {
const d = dropFailedFindings(file.text(), problems);
dropped = d.dropped;
+ for (const item of d.items) {
+ h.trace({ t: "check", quote: item.problem.quote, cite: citeOfProblem(item.problem), ok: false, reason: item.problem.why, stage: "drop", dropped: true, claim: item.claim });
+ }
if (dropped.length) {
await file.set(d.md);
h.log(`dropped ${dropped.length} finding(s) whose quote still fails`);
}
- const last = await convertAndCheck(h, file, { origin, resolver });
+ const last = await convertAndCheck(h, file, { origin, resolver, round: 3 });
if (last.convertProblems) return { status: "failed", summary: `the report does not convert: ${last.convertProblems[0]}` };
problems = last.problems;
}
@@ -305,6 +375,7 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
}
if (!citations) return { status: "failed", summary: "the report cites nothing" };
await writeIterationFile(h.article, h.n, "report.json", report, h.paths);
+ traceReport(h.trace, report as Report);
const claims = report.sections.reduce((s, x) => s + (x.claims?.length ?? 0), 0);
return {
status: "done",
@@ -316,7 +387,7 @@ async function sweepAgentBody(h: TaskHandle, input: SweepAgentInput): Promise<Ta
async function convertAndCheck(
h: TaskHandle,
file: ReturnType<typeof reportFile>,
- o: { origin: string; resolver: ReturnType<typeof slugResolver> },
+ o: { origin: string; resolver: ReturnType<typeof slugResolver>; round: number },
): Promise<{ report?: Awaited<ReturnType<typeof convertOnly>>; problems: Awaited<ReturnType<typeof checkQuotes>>; convertProblems?: string[] }> {
const fixed = await rewriteLinks(file.text(), o.resolver, o.origin);
if (fixed.fixed) {
@@ -331,7 +402,59 @@ async function convertAndCheck(
});
h.check({ name: "convert", ok: c.ok, ...(c.ok ? (c.warnings.length ? { detail: c.warnings.slice(0, 3).join("; ") } : {}) : { detail: c.problems.slice(0, 3).join("; ") }) });
if (!c.ok) return { problems: [], convertProblems: c.problems };
- return { report: c.report, problems: await checkQuotes(c.report, h.deps) };
+ const problems = await checkQuotes(c.report, h.deps);
+ // Every refused quote, traced with why (a later round may fix or drop it).
+ for (const p of problems) h.trace({ t: "check", quote: p.quote, cite: citeOfProblem(p), ok: false, reason: p.why, stage: "check", round: o.round });
+ return { report: c.report, problems };
+}
+
+export function citeOfProblem(p: QuoteProblem): TraceCite {
+ return { citation: p.citation, channel: p.channel, video: p.id, ...(p.second !== undefined ? { start: p.second } : {}) };
+}
+
+// A corpus tool, watched: an enumeration's ids and coverage, a read's ids.
+function watched(h: TaskHandle, t: AgentTool, w: Watch): AgentTool {
+ return {
+ ...t,
+ run: async (input: unknown, ctx: { signal?: AbortSignal }) => {
+ const { turn, phase } = w;
+ let out: string;
+ try {
+ out = await t.run(input, ctx);
+ } catch (e) {
+ h.trace({ t: "note", text: `${t.name} failed: ${(e as Error).message}`, turn, phase });
+ throw e;
+ }
+ try {
+ if (t.name === "enumerate_matches") {
+ const e = enumerateOf(out);
+ w.cov.enumerated(e.ids, e.partial, e.unreached);
+ const q = (input as { query?: unknown } | null)?.query;
+ h.trace({
+ t: "enumerate",
+ query: typeof q === "string" ? q : "",
+ n: e.ids.length,
+ ids: e.ids,
+ partial: e.partial,
+ unreached: e.unreached,
+ ...(e.total !== null ? { total: e.total } : {}),
+ ...(e.posts ? { posts: e.posts } : {}),
+ turn,
+ phase,
+ });
+ } else {
+ const ids = idsReadBy(t.name, input);
+ if (ids.length) {
+ w.cov.readIds(ids);
+ h.trace({ t: "read", tool: t.name, ids, turn, phase });
+ }
+ }
+ } catch {
+ // watching never stops the tool
+ }
+ return out;
+ },
+ };
}
async function convertOnly(h: TaskHandle, file: ReturnType<typeof reportFile>) {
diff --git a/common/lib/report/draft/tasks/sweep-pipeline.ts b/common/lib/report/draft/tasks/sweep-pipeline.ts
@@ -10,8 +10,14 @@
// the strict quote check (a finding that fails it is dropped, never fixed).
// Every prompt fits the local cap; one that would not is never sent (the
// ollama module refuses it) and that chunk is logged as failed.
+//
+// The run is TRACED (trace.jsonl, ./trace.ts; umtool R3): the scope, the
+// terms, each term's enumeration, each read batch with the model's lines,
+// every quote kept or dropped and why, the findings; the iteration's
+// `coverage` is what was enumerated and read.
import { structuredAnswer, type LlmConfig, type Meter } from "../../../llm";
+import type { Report } from "../../schema";
import { writeIterationFile } from "../../iterations";
import { mmss } from "../reportOps";
import { strictNormalize } from "../../../citations/verify";
@@ -19,6 +25,7 @@ import { fragmentOf, fullSentenceFor } from "../../../citations/fragment";
import { momentHref } from "./links";
import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes";
import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
+import { CoverageTally, enumerateOf, traceReport } from "./trace";
import type { TaskDeps, TaskResult } from "./types";
export const CHUNK_CHARS = 7000; // one model call's transcript text (~2k tokens)
@@ -268,15 +275,18 @@ type Kept = {
};
export async function sweepPipeline(input: SweepPipelineInput, deps: TaskDeps): Promise<TaskResult> {
- return runOnIteration({ article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["sweep"] }, (h) =>
- pipelineBody(h, input),
+ return runOnIteration(
+ { article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["sweep"], trace: { task: "sweep-pipeline", ...(input.model ? { model: input.model } : {}) } },
+ (h) => pipelineBody(h, input),
);
}
-async function ask<T>(h: TaskHandle, model: string, system: string, user: string, schema: object, what: string): Promise<T> {
+async function ask<T>(h: TaskHandle, model: string, system: string, user: string, schema: object, what: string, traceCost = false): 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 });
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;
}
@@ -294,12 +304,15 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
if (!channels.length) throw new TaskInputError("a sweep needs its channels");
const event = (e: Record<string, unknown>) => h.turns([e]);
h.log(`pipeline sweep on ${model}, corpus ${deps.corpus.source}, links on ${origin}`);
+ const cov = new CoverageTally();
+ h.setCoverage(() => cov.value());
+ h.trace({ t: "scope", source: deps.corpus.source, channels, ...(since ? { from: since } : {}), ...(until ? { to: until } : {}), question, model, origin });
// 1. terms (the model, unless given)
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");
+ const ans = await ask<{ terms?: unknown }>(h, model, TERMS_SYSTEM, `Research question: ${question}`, TERMS_SCHEMA, "terms", true);
const names = new Set(channels.flatMap((c) => [c.toLowerCase(), c.toLowerCase().replace(/-/g, " ")]));
for (const t of Array.isArray(ans.terms) ? ans.terms : []) {
const v = String(t).replace(/["“”]/g, "").trim().toLowerCase();
@@ -309,6 +322,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
}
if (!terms.length) return { status: "failed", summary: "no search terms" };
h.log(`terms: ${terms.join(", ")}`);
+ h.trace({ t: "terms", terms });
// 2. enumerate (code)
const found = new Map<string, EnumeratedVideo>();
@@ -323,6 +337,22 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
});
if (text.includes("COVERAGE PARTIAL")) partial.push(term);
const vids = parseEnumerate(text, term);
+ const e = enumerateOf(text);
+ cov.enumerated(
+ vids.map((v) => v.id),
+ e.partial,
+ e.unreached,
+ );
+ h.trace({
+ t: "enumerate",
+ query: term,
+ n: vids.length,
+ ids: vids.map((v) => v.id),
+ partial: e.partial,
+ unreached: e.unreached,
+ ...(e.total !== null ? { total: e.total } : {}),
+ ...(e.posts ? { posts: e.posts } : {}),
+ });
for (const v of vids) {
const had = found.get(v.id);
if (had) Object.assign(had.hits, v.hits);
@@ -343,6 +373,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
}
if (extra.length) {
h.log(`phrases with no match; trying words: ${extra.join(", ")}`);
+ h.trace({ t: "terms", terms: extra, extra: true });
await enumerate(extra);
const hitNow = new Set([...found.values()].flatMap((v) => Object.keys(v.hits)));
terms = [...terms.filter((t) => hit.has(t)), ...extra.filter((w) => hitNow.has(w))].slice(0, 8);
@@ -369,9 +400,13 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
// The job's progress: the recordings gone through, of the worklist.
let visited = 0;
h.progress({ metric: "entries", current: 0, total: todo.length });
+ const batches = Math.ceil(todo.length / READ_BATCH);
for (let b = 0; b < todo.length; b += READ_BATCH) {
deps.signal?.throwIfAborted();
const batch = todo.slice(b, b + READ_BATCH);
+ // The batch's trace: what the model returned, kept or dropped.
+ const batchLines: string[] = [];
+ const batchUsd = h.meter.usd;
const text = await deps.corpus.call("get_transcripts", {
video_ids: batch.map((v) => v.id),
queries: terms.slice(0, 8),
@@ -383,10 +418,12 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
const p = parsed.get(v.id);
if (!p || !p.lines.length) {
event({ kind: "unread", video: v.id, why: "no windows returned" });
+ batchLines.push(`${v.id}: no windows returned`);
h.progress({ metric: "entries", current: ++visited, total: todo.length });
continue;
}
readIds.push(v.id);
+ cov.readIds([v.id]);
const title = p.title || v.title;
// The channel slug: off a moment_base in the archive's form, else asked.
let slug: string | null = null;
@@ -417,6 +454,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
} catch (e) {
if (deps.signal?.aborted) throw e;
event({ kind: "chunk-failed", video: v.id, at: ch[0]![0], error: (e as Error).message });
+ batchLines.push(`${v.id} @ ${mmss(ch[0]![0])}: the model's answer failed — ${(e as Error).message}`);
h.log(` chunk failed: ${(e as Error).message}`);
continue;
}
@@ -453,11 +491,15 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
else if (raw.on_topic === false || (Number(raw.strength) || 2) < 2) why = "model: not on topic";
const key = norm(quote);
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}]` : ""}`);
if (why) {
dropped.push({ video: v.id, quote, why });
event({ kind: "dropped", why, video: v.id, quote, claim });
+ h.trace({ t: "check", quote, cite: { channel: slug, video: v.id, start: at }, ok: false, reason: why, stage: "extract", dropped: true, claim });
continue;
}
+ h.trace({ t: "check", quote, cite: { channel: slug, video: v.id, start: at }, ok: true, reason: "verbatim in its window", stage: "extract", claim });
kept.push({
video: v.id,
title,
@@ -476,6 +518,10 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
h.log(` read ${v.id} — kept so far ${kept.length}, dropped ${dropped.length}`);
h.progress({ metric: "entries", current: ++visited, total: todo.length });
}
+ const k = b / READ_BATCH + 1;
+ const usd = h.meter.usd - batchUsd;
+ h.trace({ t: "batch", k, of: batches, ids: batch.map((v) => v.id), lines: batchLines, model, usd });
+ h.trace({ t: "cost", step: `batch ${k}`, usd, model, total: h.meter.usd });
}
if (!kept.length) {
h.check({ name: "evidence", ok: false, detail: `${nEnum} matched, ${readIds.length} read, ${dropped.length} quote(s) dropped` });
@@ -497,7 +543,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
for (let attempt = 0; attempt < 2; attempt++) {
let g: { title?: unknown; sections?: unknown };
try {
- g = await ask(h, model, GROUP_SYSTEM, `Research question: ${question}\n\nFindings:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`);
+ g = await ask(h, model, GROUP_SYSTEM, `Research question: ${question}\n\nFindings:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`, true);
} catch (e) {
if (deps.signal?.aborted) throw e;
event({ kind: "group-failed", error: (e as Error).message });
@@ -582,6 +628,9 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
h.check({ name: "convert", ok: c.ok, ...(c.ok ? {} : { detail: c.problems.slice(0, 3).join("; ") }) });
if (!c.ok) return { status: "failed", summary: `the report does not convert: ${c.problems[0]}` };
const problems = await checkQuotes(c.report, deps);
+ for (const p of problems) {
+ h.trace({ t: "check", quote: p.quote, cite: { citation: p.citation, channel: p.channel, video: p.id, ...(p.second !== undefined ? { start: p.second } : {}) }, ok: false, reason: p.why, stage: "strict", round: round + 1 });
+ }
if (!problems.length) {
report = c.report;
break;
@@ -592,6 +641,10 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
dropped.push({ video: "", quote: "", why: `quote check: ${why}` });
event({ kind: "dropped", why: `quote check: ${why}` });
}
+ for (const item of d.items) {
+ const p = item.problem;
+ h.trace({ t: "check", quote: p.quote, cite: { citation: p.citation, channel: p.channel, video: p.id, ...(p.second !== undefined ? { start: p.second } : {}) }, ok: false, reason: `quote check: ${p.why}`, stage: "drop", dropped: true, claim: item.claim });
+ }
if (!d.dropped.length) break;
// Re-render from what is left: the coverage counts the drop.
const left = new Set(
@@ -624,6 +677,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
: "no claim flagged",
});
await writeIterationFile(h.article, h.n, "report.json", report, h.paths);
+ traceReport(h.trace, report as Report);
return {
status: "done",
summary: `“${title}”: ${cited.length} claim(s) in ${secs.length} section(s) from ${new Set(cited.map((r) => r.video)).size} video(s); ${dropped.length} dropped, ${flagged.length} flagged`,
diff --git a/common/lib/report/draft/tasks/trace.test.ts b/common/lib/report/draft/tasks/trace.test.ts
@@ -0,0 +1,189 @@
+// A sweep's trace (umtool R3): the event shapes, the corpus answers it reads,
+// the run numbering, a write that fails without failing the run, and the run's
+// start, end and coverage as runOnIteration keeps them. The sweeps' own traces,
+// end to end over the corpus tools, are mcp/src/draftTasks.test.ts. Temp
+// stores only.
+
+import { after, 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 { createIteration, iterationFile, readIteration } from "../../iterations";
+import { runOnIteration } from "./run";
+import {
+ CoverageTally,
+ TRACE_MAX_IDS,
+ TRACE_MAX_LINES,
+ boundEvent,
+ citeOfCitation,
+ enumerateOf,
+ idsReadBy,
+ linesOf,
+ openTrace,
+ runStartsOf,
+ traceReport,
+ type TraceEvent,
+} from "./trace";
+
+const tmp = await mkdtemp(path.join(os.tmpdir(), "trace-"));
+after(() => rm(tmp, { recursive: true, force: true }));
+let k = 0;
+const store = () => {
+ k++;
+ return { articlesDir: path.join(tmp, `reports-${k}`), exportIndexDir: path.join(tmp, `idx-${k}`) };
+};
+const readTrace = async (paths: ReturnType<typeof store>, article: string, n: number): Promise<TraceEvent[]> =>
+ (await readFile(iterationFile(paths, article, n, "trace.jsonl"), "utf8"))
+ .trim()
+ .split("\n")
+ .map((l) => JSON.parse(l));
+
+// What enumerate_matches answers (mcp/src/server.ts handleEnumerateMatches).
+const PARTIAL =
+ "⚠ COVERAGE PARTIAL — the scan hit its page/video cap before the corpus was exhausted. The 3 match(es) below are a SAMPLE.\n" +
+ "The sample is biased by CHANNEL ORDER, not random — fully scanned (1): Synth Kitchen; NEVER REACHED (2): synth-other, synth-third.\n\n" +
+ '3 match(es) for "contest" — a PARTIAL worklist:\n\n' +
+ "- pie-stream-02 | video | Synth Kitchen | 2024-03-02 | 2 match(es) | Pie stream\n" +
+ "- bread-day-01 | video | Synth Kitchen | 2024-01-10 | 1 match(es) | Bread day\n" +
+ "- 17 | post | Synth Social | 2024-02-01 | 1 match(es) | a post\n\n" +
+ "(complete set: NO — capped; 3 match(es); 1 batch(es) of 10; scanned 4 page(s) across 1 channel(s))";
+
+test("enumerateOf: the rows' ids, partial, the channels never reached, the total", () => {
+ const e = enumerateOf(PARTIAL);
+ assert.deepEqual(e.ids, ["pie-stream-02", "bread-day-01", "17"]);
+ assert.equal(e.videos, 2);
+ assert.equal(e.posts, 1);
+ assert.equal(e.partial, true);
+ assert.deepEqual(e.unreached, ["synth-other", "synth-third"]);
+ assert.equal(e.total, 3);
+ const whole = enumerateOf('1 match(es) for "x" — the complete worklist:\n\n- a1 | video | C | 2024-01-01 | 1 match(es) | T\n\n(complete set: yes; 1 match(es); …)');
+ assert.deepEqual(whole, { ids: ["a1"], videos: 1, posts: 0, partial: false, unreached: [], total: 1 });
+ assert.deepEqual(enumerateOf('No matches for "x".(complete set: yes; 0 match(es); 0 batch(es) of 10)').ids, []);
+});
+
+test("idsReadBy and linesOf: what a read names; an answer's lines", () => {
+ assert.deepEqual(idsReadBy("get_transcripts", { video_ids: ["a", 3, "b"] }), ["a", "b"]);
+ assert.deepEqual(idsReadBy("get_transcript", { video_id: "a" }), ["a"]);
+ assert.deepEqual(idsReadBy("get_post", { post_id: "17" }), ["17"]);
+ assert.deepEqual(idsReadBy("list_channels", {}), []);
+ assert.deepEqual(linesOf("### Pie\n\n[0:10|10] hello \n"), ["### Pie", "[0:10|10] hello"]);
+});
+
+test("boundEvent: ids, lines and quotes are cut to the caps", () => {
+ const ids = Array.from({ length: TRACE_MAX_IDS + 5 }, (_, i) => `v${i}`);
+ const lines = Array.from({ length: TRACE_MAX_LINES + 2 }, (_, i) => `line ${i} ${"x".repeat(i === 0 ? 900 : 1)}`);
+ const b = boundEvent({ t: "batch", k: 1, of: 1, ids, lines, model: "m", usd: 0 }) as { ids: string[]; lines: string[] };
+ assert.equal(b.ids.length, TRACE_MAX_IDS);
+ assert.equal(b.lines.length, TRACE_MAX_LINES + 1);
+ assert.equal(b.lines.at(-1), "(+2 more lines)");
+ assert.ok(b.lines[0]!.length <= 601);
+ const c = boundEvent({ t: "check", quote: "q".repeat(5000), cite: { video: "v" }, ok: false, reason: "r", stage: "drop" }) as { quote: string };
+ assert.ok(c.quote.length <= 1201);
+});
+
+test("CoverageTally: distinct ids matched and read, partial sticks, unreached sorted", () => {
+ const c = new CoverageTally();
+ c.enumerated(["a", "b"], false, []);
+ c.enumerated(["b", "c"], true, ["z", "y"]);
+ c.readIds(["a", "a", "q"]);
+ assert.deepEqual(c.value(), { matched: 3, read: 2, partial: true, unreached: ["y", "z"] });
+});
+
+test("openTrace: lines are {t, at, run, …} in order; a second run is run 2", async () => {
+ const paths = store();
+ await createIteration("tr", { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["c"] } }, paths);
+ const at = new Date("2026-10-14T10:00:00.000Z");
+ const t1 = await openTrace({ article: "tr", n: 1, paths, now: () => at });
+ assert.equal(t1.run, 1);
+ t1.emit({ t: "run", phase: "start", task: "sweep-agent", model: "m" });
+ t1.emit({ t: "enumerate", query: "contest", n: 2, ids: ["a", "b"], partial: false, unreached: [] });
+ await t1.flush();
+ const t2 = await openTrace({ article: "tr", n: 1, paths, now: () => at });
+ assert.equal(t2.run, 2);
+ t2.emit({ t: "run", phase: "start", task: "sweep-agent", model: "m" });
+ await t2.flush();
+ const lines = await readTrace(paths, "tr", 1);
+ assert.deepEqual(Object.keys(lines[1]!).slice(0, 3), ["t", "at", "run"]);
+ assert.deepEqual(lines.map((l) => [l.t, l.run]), [["run", 1], ["enumerate", 1], ["run", 2]]);
+ assert.equal(lines[0]!.at, at.toISOString());
+ assert.equal(runStartsOf((await readFile(iterationFile(paths, "tr", 1, "trace.jsonl"), "utf8")) + "{torn\n"), 2);
+});
+
+test("openTrace: a write that fails never throws, and is logged once", async () => {
+ const paths = store();
+ const logged: string[] = [];
+ // No such iteration: the directory is not there, every append fails.
+ const t = await openTrace({ article: "nope", n: 4, paths, log: (l) => logged.push(l) });
+ t.emit({ t: "note", text: "a" });
+ t.emit({ t: "note", text: "b" });
+ await t.flush();
+ assert.equal(logged.length, 1);
+ assert.match(logged[0]!, /^trace not kept: /);
+});
+
+test("runOnIteration with a trace: the run's start and end lines, the body's events between, coverage kept on the iteration", async () => {
+ const paths = store();
+ await createIteration("cov", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["c"] } }, paths);
+ const out = await runOnIteration({ article: "cov", n: 1, deps: { paths } as never, kinds: ["sweep"], trace: { task: "sweep-pipeline" } }, async (h) => {
+ const c = new CoverageTally();
+ h.setCoverage(() => c.value());
+ h.trace({ t: "scope", source: "local:/x", channels: ["c"], question: "q", model: "qwen3:8b" });
+ c.enumerated(["a", "b", "c"], true, ["d"]);
+ c.readIds(["a"]);
+ h.trace({ t: "check", quote: "said it", cite: { video: "a" }, ok: false, reason: "not verbatim in its window", stage: "extract", dropped: true });
+ return { status: "failed", summary: "no verbatim evidence found" };
+ });
+ assert.equal(out.status, "failed");
+ const lines = await readTrace(paths, "cov", 1);
+ assert.deepEqual(lines.map((l) => l.t), ["run", "scope", "check", "run"]);
+ assert.deepEqual([lines[0]!.phase, (lines[0] as { model?: string }).model, (lines[0] as { task?: string }).task], ["start", "qwen3:8b", "sweep-pipeline"]);
+ const end = lines.at(-1) as Extract<TraceEvent, { t: "run"; phase: "end" }>;
+ assert.equal(end.phase, "end");
+ assert.equal(end.status, "failed");
+ assert.deepEqual(end.coverage, { matched: 3, read: 1, partial: true, unreached: ["d"] });
+ const it = (await readIteration("cov", 1, paths))!;
+ assert.deepEqual(it.coverage, { matched: 3, read: 1, partial: true, unreached: ["d"] });
+ // A task with no trace writes none.
+ await createIteration("cov", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["c"] } }, paths);
+ await runOnIteration({ article: "cov", n: 2, deps: { paths } as never, kinds: ["sweep"] }, async (h) => {
+ h.trace({ t: "note", text: "never written" });
+ return { status: "done", summary: "ok" };
+ });
+ await assert.rejects(readFile(iterationFile(paths, "cov", 2, "trace.jsonl"), "utf8"), /ENOENT/);
+ assert.equal((await readIteration("cov", 2, paths))!.coverage, undefined);
+});
+
+test("traceReport: a finding per claim with its cites, a kept check per quoted citation", () => {
+ const events: unknown[] = [];
+ traceReport((e) => events.push(e), {
+ format: "archilyzer-report",
+ version: 1,
+ id: "r",
+ kind: "sweep",
+ title: "T",
+ citations: {
+ c1: { kind: "video", channel: "synth-kitchen", id: "pie-stream-02", start: 10, end: 14, quote: "I did not enter the contest this year", label: "Pie stream" },
+ c2: { kind: "post", channel: "synth-social", id: "17", url: "https://x.example/17" },
+ },
+ sections: [{ id: "s1", title: "The contest", claims: [{ id: "k1", text: "She did not enter.", citations: ["c1", "c2"] }] }],
+ } as never);
+ assert.deepEqual(events[0], {
+ t: "finding",
+ section: "The contest",
+ claim: "She did not enter.",
+ cites: [
+ citeOfCitation("c1", { kind: "video", channel: "synth-kitchen", id: "pie-stream-02", start: 10, end: 14, quote: "I did not enter the contest this year", label: "Pie stream" }),
+ { citation: "c2", kind: "post", channel: "synth-social", video: "17", url: "https://x.example/17" },
+ ],
+ });
+ assert.deepEqual(events[1], {
+ t: "check",
+ quote: "I did not enter the contest this year",
+ cite: { citation: "c1", kind: "video", channel: "synth-kitchen", video: "pie-stream-02", start: 10, end: 14, label: "Pie stream" },
+ ok: true,
+ stage: "final",
+ reason: "verbatim (strict)",
+ });
+ assert.equal(events.length, 2, "a citation with no quote has no check");
+});
diff --git a/common/lib/report/draft/tasks/trace.ts b/common/lib/report/draft/tasks/trace.ts
@@ -0,0 +1,286 @@
+// 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} the pipeline's search terms
+// {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: "note", text}
+// {t: "run", phase: "end", status, summary, usd, minutes, coverage?}
+//
+// 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";
+
+// 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 };
+ }
+ | { t: "terms"; terms: string[]; extra?: boolean }
+ | { t: "enumerate"; query: string; n: number; ids: string[]; partial: boolean; unreached: string[]; total?: number; posts?: number; 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 }
+ | { 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 };
+
+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<void>;
+};
+
+// 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<string, unknown>;
+ if (Array.isArray(o.ids)) o.ids = (o.ids as string[]).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).
+export async function openTrace(o: {
+ article: string;
+ n: number;
+ paths?: StorePaths;
+ now?: () => Date;
+ log?: (line: string) => void;
+}): Promise<RunTracer> {
+ const now = o.now ?? (() => new Date());
+ let file: string;
+ try {
+ 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<void> = 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) \| /;
+
+// enumerate_matches' answer: its rows' ids, whether the scan was capped, and
+// the channels a capped scan never reached.
+export function enumerateOf(text: string): { ids: string[]; videos: number; posts: number; partial: boolean; unreached: string[]; total: number | null } {
+ const ids: string[] = [];
+ let videos = 0;
+ let posts = 0;
+ for (const raw of text.split("\n")) {
+ const m = ENUM_ROW.exec(raw.trim());
+ if (!m) continue;
+ ids.push(m[1]!);
+ if (m[2] === "post") posts++;
+ else videos++;
+ }
+ const partial = /COVERAGE PARTIAL/.test(text);
+ const unreached: string[] = [];
+ const nr = /NEVER REACHED \(\d+\): ([^;\n)]+)/.exec(text);
+ // The list ends the sentence: its last name carries the full stop.
+ if (nr) for (const c of nr[1]!.trim().replace(/\.$/, "").split(",")) if (c.trim()) unreached.push(c.trim());
+ const total = /^(\d+) match\(es\) for /m.exec(text) ?? /\(complete set: [^;]+; (\d+) match\(es\)/.exec(text);
+ return { ids, videos, posts, partial, unreached, total: total ? Number(total[1]) : null };
+}
+
+// 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<string, unknown>;
+ 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<string>();
+ readonly read = new Set<string>();
+ partial = false;
+ readonly unreached = new Set<string>();
+
+ 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<string, unknown>;
+ 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<string, unknown>;
+ 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)" });
+ }
+}
diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts
@@ -8,6 +8,9 @@
// transcripts/reports/<id>/iterations/<n>/report.json the report it made
// transcripts/reports/<id>/iterations/<n>/sweep.md the sweep's text
// transcripts/reports/<id>/iterations/<n>/turns.jsonl the model turns
+// transcripts/reports/<id>/iterations/<n>/trace.jsonl a sweep's steps as
+// they happen (umtool
+// R3, tasks/trace.ts)
// transcripts/reports/<id>/iterations/<n>/proposals.json a research run's
// acquisitions (S11)
// transcripts/reports/<id>/iterations/current.json which iteration
@@ -67,7 +70,9 @@ export type IterationStepStatus = (typeof ITERATION_STEP_STATUSES)[number];
// The files writeIterationFile may write (iteration.json is written by
// create/update only). A later slice adds a name here, never a path.
// `seed.md`: a seeded sweep's starting report (a research board, umtool R2).
-export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md"] as const;
+// `trace.jsonl`: a sweep's structured trace, appended as it runs (umtool R3,
+// draft/tasks/trace.ts) — one JSON object a line, like turns.jsonl.
+export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl"] as const;
export type IterationFile = (typeof ITERATION_FILES)[number];
// A revision needs something to revise.
@@ -122,6 +127,20 @@ export const iterationScopeSchema = z.looseObject({
});
export type IterationScope = z.infer<typeof iterationScopeSchema>;
+// What a sweep enumerated and read (umtool R3): the coverage rule
+// (mcp/src/instructions.ts, "State the plan") as data. `matched`: the distinct
+// recordings and posts the enumerations returned; `read`: the distinct ones
+// whose text was read; `partial`: an enumeration hit its cap (COVERAGE
+// PARTIAL); `unreached`: the channels a capped scan never reached. Optional:
+// an iteration written before R3 has none, and a reader ignores it if absent.
+export const iterationCoverageSchema = z.looseObject({
+ matched: z.number().int().nonnegative(),
+ read: z.number().int().nonnegative(),
+ partial: z.boolean(),
+ unreached: z.array(z.string()),
+});
+export type IterationCoverage = z.infer<typeof iterationCoverageSchema>;
+
// Loose: a key a later slice adds survives an update by code that predates it.
export const iterationSchema = z.looseObject({
format: z.literal(ITERATION_FORMAT),
@@ -145,6 +164,7 @@ export const iterationSchema = z.looseObject({
ops: z.looseObject({ applied: z.array(z.unknown()), refused: z.array(z.unknown()) }).optional(),
minutes: z.number().nonnegative().optional(),
checks: z.array(iterationCheckSchema).optional(),
+ coverage: iterationCoverageSchema.optional(),
steps: z.array(iterationStepSchema),
// The video project (projectOf), once one is made.
projectDir: z.string().min(1).optional(),
@@ -631,17 +651,17 @@ function fileText(name: IterationFile, data: string | Uint8Array | object, id: s
}
if (typeof data !== "string" && !(data instanceof Uint8Array)) throw new ArticleRegistryError(`${name} is text`);
const text = typeof data === "string" ? data : Buffer.from(data).toString("utf8");
- if (name === "turns.jsonl") assertJsonLines(text);
+ if (name === "turns.jsonl" || name === "trace.jsonl") assertJsonLines(text, name);
return text;
}
-function assertJsonLines(text: string): void {
+function assertJsonLines(text: string, name: string): void {
for (const [i, line] of text.split("\n").entries()) {
if (!line.trim()) continue;
try {
JSON.parse(line);
} catch {
- throw new ArticleRegistryError(`turns.jsonl line ${i + 1} is not JSON`);
+ throw new ArticleRegistryError(`${name} line ${i + 1} is not JSON`);
}
}
}
@@ -649,7 +669,7 @@ function assertJsonLines(text: string): void {
// WRITE ONE FILE OF AN ITERATION — a name from ITERATION_FILES, replaced
// whole. report.json must parse as a report of this article (its problems
// are the checks' to name; makeCurrent refuses a report with any); proposals.json
-// must be JSON; turns.jsonl one JSON value a line. Answers the file's path.
+// must be JSON; turns.jsonl and trace.jsonl one JSON value a line. Answers the file's path.
export async function writeIterationFile(
id: string,
n: number,
diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts
@@ -28,6 +28,13 @@ import { createCorpusTools, type CorpusTools } from "./callTool";
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");
const run = async (name: string) => JSON.parse(await readFile(path.join(RUNS, `${name}.json`), "utf8"));
+// A sweep's trace.jsonl (umtool R3), one event a line.
+const traceOf = async (article: string, n: number) =>
+ ((await readIterationFile(article, n, "trace.jsonl", paths)) ?? "")
+ .trim()
+ .split("\n")
+ .filter(Boolean)
+ .map((l) => JSON.parse(l) as Record<string, any>);
let tmp: string;
let corpus: CorpusTools;
@@ -154,6 +161,48 @@ test("sweep-agent: the plan, the corpus tools, extract_batch, the report file; t
// The job's progress: every model turn, the repair round's counted on (release 28 F3).
assert.deepEqual(d.progressed.map((p) => p.current), [1, 2, 3, 4, 5, 6]);
assert.ok(d.progressed.every((p) => p.metric === "turns" && p.total === 150));
+
+ // The trace (umtool R3): every line {t, at, run}; the run's start and end
+ // around the scope, the enumeration, the batch with the extractor's own
+ // lines, each turn's cost, the refused quote and the findings it kept.
+ const trace = await traceOf("synth-contest", it.n);
+ assert.ok(trace.every((e) => typeof e.t === "string" && typeof e.at === "string" && e.run === 1));
+ assert.deepEqual([trace[0]!.t, trace[0]!.phase, trace[0]!.task, trace[0]!.model, trace[0]!.extractor], ["run", "start", "sweep-agent", r.model, r.extractorModel]);
+ const end = trace.at(-1)!;
+ assert.deepEqual([end.t, end.phase, end.status], ["run", "end", "done"]);
+ const scope = trace.find((e) => e.t === "scope")!;
+ assert.deepEqual([scope.question, scope.channels, scope.model, scope.extractor, scope.seed], [r.question, r.channels, r.model, r.extractorModel, undefined]);
+ assert.match(scope.source, /^local:/);
+ const en = trace.find((e) => e.t === "enumerate")!;
+ assert.equal(en.query, "contest");
+ assert.equal(en.turn, 0);
+ assert.equal(en.partial, false);
+ assert.deepEqual(en.unreached, []);
+ assert.equal(en.n, en.ids.length);
+ assert.ok(en.ids.includes("pie-stream-02"));
+ const batch = trace.find((e) => e.t === "batch")!;
+ assert.deepEqual([batch.k, batch.of, batch.ids, batch.model, batch.turn], [1, Math.max(1, Math.ceil(en.ids.length / 10)), ["pie-stream-02", "bread-day-01"], r.extractorModel, 1]);
+ assert.ok(batch.lines.includes("[0:15|15] the judges were friends of mine so it felt wrong"), "the extractor's lines, not a count");
+ assert.ok(batch.usd > 0);
+ const costs = trace.filter((e) => e.t === "cost");
+ assert.deepEqual(costs.filter((c) => c.phase === "agent" && /^turn /.test(c.step)).map((c) => c.turn), [0, 1, 2, 3]);
+ assert.ok(costs.some((c) => c.step === "repair turn 0" && c.phase === "repair"));
+ assert.ok(costs.some((c) => c.step === "batch 1" && c.model === r.extractorModel));
+ for (let i = 1; i < costs.length; i++) assert.ok(costs[i]!.total >= costs[i - 1]!.total, "the running total only grows");
+ const refused = trace.filter((e) => e.t === "check" && !e.ok);
+ assert.equal(refused.length, 1);
+ assert.deepEqual([refused[0]!.stage, refused[0]!.round, refused[0]!.cite.video, refused[0]!.quote], ["check", 1, "pie-stream-02", "the judges were friends of mine so it felt right"]);
+ assert.match(refused[0]!.reason, /not verbatim/);
+ const kept = trace.filter((e) => e.t === "check" && e.ok);
+ assert.equal(kept.length, 3);
+ assert.ok(kept.every((c) => c.stage === "final"));
+ const findings = trace.filter((e) => e.t === "finding");
+ assert.equal(findings.length, 3);
+ assert.deepEqual(findings.map((f) => f.section), ["The contest", "The contest", "The bakery"]);
+ assert.equal(findings[1]!.cites[0].quote, "the judges were friends of mine so it felt wrong");
+ // Coverage, as data: what was enumerated and read.
+ assert.deepEqual(after.coverage, { matched: en.ids.length, read: 2, partial: false, unreached: [] });
+ assert.deepEqual(end.coverage, after.coverage);
});
test("sweep-agent: a quote the repair round does not fix is dropped, and the iteration is still done", async () => {
@@ -167,6 +216,27 @@ test("sweep-agent: a quote the repair round does not fix is dropped, and the ite
assert.ok(!md.includes("so it felt right"), "the failing finding is gone");
const after = (await readIteration("synth-drop", it.n, paths))!;
assert.match(after.checks!.find((c) => c.name === "quotes")!.detail!, /1 finding\(s\) dropped/);
+ // The dropped quote is in the trace, with why (umtool R3: invisible before).
+ const trace = await traceOf("synth-drop", it.n);
+ const drop = trace.find((e) => e.t === "check" && e.dropped)!;
+ assert.deepEqual([drop.stage, drop.ok, drop.quote, drop.cite.video], ["drop", false, "the judges were friends of mine so it felt right", "pie-stream-02"]);
+ assert.match(drop.reason, /not verbatim within 90 s/);
+ assert.match(drop.claim, /She gives her reason/);
+ assert.equal(trace.filter((e) => e.t === "finding").length, 2);
+});
+
+test("sweep-agent: a seeded sweep (a research board, R2) traces its seed", async () => {
+ await drainFake();
+ const r = await run("sweep-agent");
+ api.push(...r.turns);
+ const it = await createIteration("synth-seeded", { kind: "sweep", model: r.model, question: r.question, scope: { channels: r.channels } }, paths);
+ const seed = '# The board\n\n## The contest\n\n- She did not enter: "I did not enter the contest this year" — [Pie stream @ 0:10](' + ORIGIN + "/?v=synth-kitchen%2Fpie-stream-02&t=10)\n";
+ await writeIterationFile("synth-seeded", it.n, "seed.md", seed, paths);
+ const out = await runTask({ task: "sweep-agent", article: "synth-seeded", n: it.n, extractorModel: r.extractorModel, origin: ORIGIN, maxUsd: 5 }, deps());
+ assert.equal(out.status, "done", out.summary);
+ assert.match(api.requests.at(-7).messages[0].content, /THE REPORT FILE ALREADY HOLDS THE OPERATOR'S RESEARCH BOARD/);
+ const scope = (await traceOf("synth-seeded", it.n)).find((e) => e.t === "scope")!;
+ assert.deepEqual(scope.seed, { chars: seed.trim().length });
});
test("sweep-agent: a fragment quote goes to the repair round with its full sentence, and the fix is kept (release 28 Q2)", async () => {
@@ -263,6 +333,24 @@ test("sweep-pipeline: terms, enumerate, windows, extract (a non-verbatim quote d
const after = (await readIteration("synth-pipe", it.n, paths))!;
assert.equal(after.usage["qwen3:8b"]!.usd, 0);
assert.equal(after.usage["qwen3:8b"]!.calls, 3);
+
+ // The trace (umtool R3): scope, terms, an enumeration per term, the read
+ // batch with the model's lines, the quote dropped in its window and why,
+ // the findings; coverage on the iteration.
+ const trace = await traceOf("synth-pipe", it.n);
+ assert.deepEqual([trace[0]!.t, trace[0]!.phase, trace[0]!.task, trace[0]!.model], ["run", "start", "sweep-pipeline", "qwen3:8b"]);
+ assert.deepEqual(trace.find((e) => e.t === "terms")!.terms, ["contest", "judges"]);
+ assert.deepEqual(trace.filter((e) => e.t === "enumerate").map((e) => e.query), ["contest", "judges"]);
+ const batch = trace.find((e) => e.t === "batch")!;
+ assert.deepEqual([batch.k, batch.of, batch.ids], [1, 1, ["pie-stream-02"]]);
+ assert.ok(batch.lines.some((l: string) => l.includes("[dropped: not verbatim in its window]")));
+ const drop = trace.find((e) => e.t === "check" && e.dropped)!;
+ assert.deepEqual([drop.stage, drop.reason, drop.cite.video], ["extract", "not verbatim in its window", "pie-stream-02"]);
+ assert.ok(drop.quote.includes("I entered the contest and I won"));
+ assert.equal(trace.filter((e) => e.t === "check" && e.stage === "final").length, 2);
+ 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: [] });
});
test("revise-report: ops over the parent's sweep.md — applied, refused with reasons; quotes untouched; a new quote checked", async () => {
diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts
@@ -421,7 +421,7 @@ export function renderIterationSummary(
if (o.dir) {
const present = Object.entries(o.files ?? {}).filter(([, p]) => p) as [string, string][];
lines.push(`Where (the editor's disk): ${o.dir}`);
- for (const [name, p] of present) if (name !== "turns.jsonl") lines.push(` - ${name}: ${p}`);
+ for (const [name, p] of present) if (name !== "turns.jsonl" && name !== "trace.jsonl") lines.push(` - ${name}: ${p}`);
}
if (it.projectDir) lines.push(`Video project: ${it.projectDir}`);
if (it.kind === "research") {