// 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, countsOf, 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, article: string, n: number): Promise => (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, // umtool R4: each row as it reads (a refresh compares the matching lines). rows: [{ id: "a1", kind: "video", channel: "C", date: "2024-01-01", matches: 1, title: "T" }], }); assert.deepEqual(countsOf(enumerateOf(PARTIAL).rows), { "pie-stream-02": 2, "bread-day-01": 1, "17": 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] as { phase?: string }).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; 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"); });