commit 8b942fbac24a262feb69ab2ff297696cecd48564
parent d4bb57d0d4577d1aa786d577060c59aba2a94e65
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 09:42:20 -0400
Merge ux/integration (R3, 484dca2f) into ux/p4a2
The plan: R3's record, then P4a-2's; one status row per phase (R3 LIVE,
P4a-2 shipped on the branch).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
41 files changed, 4062 insertions(+), 79 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] 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<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/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -14,6 +14,10 @@
- **A board exports as cited markdown.** **Copy as cited markdown** (`c`) and **Download .md**: the case's title, its notes as the summary, a `##` per section, each quote as a finding — the claim, the quote in quotes, `[title @ m:ss](link)` — with our note under it, and a `## Coverage` paragraph (the scope, what was searched and read, what is pinned, drifted and unchecked). It converts as a /sweep report.
- **Hand off a board, plan first.** **Draft an article from this board** shows the plan — the article, the question, the channels, the model and the most it may spend — and on **Start the sweep** asks the editor for a `report-draft` sweep seeded with the board's markdown. **Start a video from this board** shows the clips — one per quote, its window the quote's cue span — and on **Create the project** scaffolds a report-video project under the reports root. A board with a quote from a local-only channel never becomes an article. The API (`/api/research/cases`, documented in its route) is what Create will use.
- **A sweep can start from a seed.** `pnpm ops report-draft --json '{"task": "sweep", …, "seed": "<markdown>"}'` keeps the markdown as the iteration's `seed.md`; the sweep agent's report starts from it, checks its quotes, and extends it. A seed is a new sweep's, on a Claude model (a local model is refused: its pipeline writes the report from scratch). Needs a restart of the editor.
+- **A sweep keeps a trace: `trace.jsonl`.** Every `report-draft` sweep — the API agent's and the local pipeline's — appends what it does beside `turns.jsonl`, one JSON line per step, as it happens: the scope (corpus, channels, dates, question, model, extractor, a board's seed), each enumeration (the ids, whether the scan was capped, the channels it never reached), each read, each extractor batch with the lines it returned, each turn's cost and the running total, every quote check — the quotes refused and the ones **dropped, with why**, which nothing recorded before — the findings it kept, and how the run ended. A trace that cannot be written never fails the run. `iteration.json` gains `coverage {matched, read, partial, unreached}`: the coverage rule as data. Needs a restart of the editor.
+- **umtool shows how a sweep ran: `/research/runs/<article>/<n>`.** The question, the model and extractor, the scope, the time, the spend and the checks; the steps as one lit list (scope, each turn or batch, findings, the quote checks kept and dropped, the end) with the running spend on each; the lit step's detail (its ids, the extractor's own lines, the quotes kept and dropped with the reason); a cumulative spend chart. A running sweep's page follows it live; a finished one replays (`r`). A run from before the trace is read from `turns.jsonl`, turn by turn, and says what was never recorded; a file holding several run starts (an import keeps every attempt) shows each as its own run, never summed. **Agent runs** on `/research` lists every sweep. Needs a restart of umtool.
+- **A run's findings open as a board.** **Open as a board** (`b`) on a run makes the research case `<article>-run<n>` (or adds to it) with the run's kept quotes, each in its section with its finding as the claim line and marked **by agent**; the board links back to the run. A second open adds nothing twice and keeps your edits.
+- **Run a sweep on a case's scope.** A board's **Run a sweep on this scope** plans a `report-draft` sweep over the case's query, channels and dates — the model, the extractor and the most it may spend shown first — and on **Start the sweep** opens the run's page. A policy routing sweeps to Claude Code runs the API agent here, and the plan says so.
- **umtool drafts each section of a report video with a model you pick.** A video project made from an article's iteration has a **draft** section: for the cut, the on-screen titles, the teaser, the flips, the threads, the narration and the YouTube text, **Draft with** and a model (the generation policy's models, the task's route chosen first), **force** (re-drafts only what a model drafted; what you wrote or edited is never replaced), and for a per-entry task the entries to draft. The job's progress shows while it runs; when it ends the page shows what it wrote, skipped and had refused by a check, the **drafted by** badge with **Approve** and **Reject**, and any draft kept aside with **Use this**. A project not made from an iteration says so and offers none. The article's Iterations tab gains the same drafts beside **Narrate**. Needs a restart of umtool.
- **Draft everything.** One button on the Iterations tab (or `umtool chain <article> <n> --draft-all [--model M]`) runs the chain with every media draft in it, on the model you choose: the cut, on-screen, teaser, flips, threads and narration after the manifest, then the voices, a fast build and the podcast, then the YouTube text, whose chapters are re-muxed so `out/youtube.txt` is written. A draft the editor refuses or that fails is marked failed and the chain carries on; one with nothing to draft, or flips and threads with no on-screen deck (or with the other panel on), is skipped. It does not attach the video to the article: review the drafts first. Started again, it resumes after the last draft that ran. Needs a restart of umtool.
- **A site's Delete shows its plan before anything goes.** On `/sites`, **Delete** lists what would be removed (the site, its publish state and last bundle, its staging), how much, what is kept and what refuses; **Confirm delete** removes it. A site with a deploy target, a recorded deploy or reports of its own is refused unless you tick the box and press **Delete with force**; a site whose directory is a link, or a publish stage running, is refused outright. The delete is `pnpm ops delete-site`'s, so it now removes the build state too.
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") {
diff --git a/plans/umtool-redesign.md b/plans/umtool-redesign.md
@@ -356,7 +356,8 @@ P0 design ─► P1 foundation ─┬─► P3 inbox/work/tools/URLs ─┬─
| P5 create + settings | `ux/p5` → `main` `20ee628a` | LIVE 2026-10-14 (umtool ZfQXZuNF…) |
| P4a-2 article-rooted merge | `ux/p4a2` | shipped on the branch |
| P4a-3 song pieces | — | after P4a-2 |
-| R3, P4b, P6 | — | after R2 / P4a / all |
+| R3 transparent runs | `ux/r3` → `ux/integration` `6362cf40` | LIVE 2026-10-14 |
+| P4b, P6 | — | after P4a / all |
### P2a, as shipped
@@ -1556,6 +1557,188 @@ built (40 s) and restarted (`scripts/p5-umtool.sh`). Live: `/?from=the-quarterin
`/settings/generation`, `/settings/system`, `/work`, `/research` 200; decisions API 828 rows, notes' hrefs intact.
For P6's audit: `/settings/system`'s index and storage panels carry explanatory sentences the copy rule would cut.
+### R3, as shipped
+
+**What.** Transparent agent runs: a sweep records what it did as it does it, and umtool shows it step by step —
+live while it runs, a replay when it is done — with the quote checks that used to be invisible (kept, refused,
+dropped, and why). Old runs, which have only `turns.jsonl`, are projected the same way. A run's kept findings
+open as a research board, and a board's scope can start a run. Read-only on the corpus and the article store
+from umtool; the editor writes the trace.
+
+- **`trace.jsonl`** (`common/lib/report/draft/tasks/trace.ts`; `ITERATION_FILES` + `trace.jsonl`): one JSON object a
+ line, `{t, at, run, …}`, appended as the run goes (a queue of `appendFile`s, no lock: one writer per run; a failed
+ write is logged once and never fails the run). `run` is 1 for the file's first run, 2 for a resumed job's, ….
+ Events: `run {phase: start, task, model, extractor}`, `scope {source, channels, from, to, question, model,
+ extractor, origin, maxUsd, batchSize, seed: {chars}}`, `terms` (the pipeline's), `enumerate {query, n, ids,
+ partial, unreached, total, posts}` (read off `enumerate_matches`' own answer: its rows, COVERAGE PARTIAL, NEVER
+ REACHED), `read {tool, ids}`, `batch {k, of, ids, lines, model, usd, cut}` (the extractor's returned LINES),
+ `cost {step, usd, model, total, turn, calls, text}`, `check {quote, cite, ok, reason, stage, dropped, claim,
+ round}` (stages: `extract` — the pipeline's window check, every quote kept or dropped; `check`/`strict` — a
+ strict round's refusals; `drop` — a finding dropped, with the problem that took it; `final` — every quote kept),
+ `finding {section, claim, cites}`, `note`, `run {phase: end, status, summary, usd, minutes, coverage}`. An
+ agent's events carry `turn` and `phase` (`agent` | `repair`), so a step is put on the turn that made it. Caps:
+ 2,000 ids, 300 lines of 600 characters, quotes 1,200.
+- **Where it is written.** `runOnIteration` takes `trace: {task, model?, extractor?}`: it opens the trace once the
+ iteration is running, writes the start, hands the task `h.trace(e)` and `h.setCoverage(read)`, and writes the end
+ — and flushes — BEFORE the final status update, so a page that reads the iteration ended finds the trace's end
+ already there. `sweep-agent.ts` wraps the corpus tools (an enumeration's ids and coverage, a read's ids), the
+ extractor (`batch` with its lines and its cost), the agent's turn events (`cost` per turn, the repair round's as
+ `repair turn N`), each strict round's refusals, the drops (`dropFailedFindings` now also answers `items`: the
+ claim and the problem), and the kept report (`traceReport`). `sweep-pipeline.ts` the same over its own steps.
+- **`iteration.json` gains `coverage {matched, read, partial, unreached}`** (`iterationCoverageSchema`, optional;
+ readers ignore it if absent): distinct ids enumerated, distinct ids read (a batch, `get_transcripts`,
+ `get_transcript`, `get_post`), any capped scan, the channels never reached. Set on every ending, done or not.
+- **`/research/runs/<article>/<n>`** (`components/research/RunView.tsx`, `SpendChart.tsx`; canvas "Transparent
+ run"): the head — `<article> i<n>` as the title, `Run · replay`/`Run · live`, the question under it, then sweep ·
+ model · extractor · channels · dates · corpus · when · minutes · spend this run (and on the iteration when they
+ differ) · kept / dropped · the iteration's checks · status, and the notes; actions: the run picker (`Run 1 2 3`,
+ `?run=k`), **Replay** (`r`), **Open as a board** (`b`, the one filled action). Then ONE lit list, **Steps**:
+ scope, each turn (`t0`…, a repair's `r0`…) or a pipeline's enumerations and batches (`e1`, `b1`), findings,
+ quote checks, the end — each with its sub-line and the running spend in Meter. Beside it: three lanes (Batches,
+ Findings, Coverage), the lit step's detail (facts; the model's words; the calls; each enumeration with its ids
+ and partial / never reached; each batch with its ids and the extractor's lines on the READER surface; the
+ findings with their quotes; the checks grouped Dropped / Refused by a strict check / Kept, each quote on the
+ reader with its cite and **why**), and **Spend by step, cumulative**: a step line in Meter, an 8 px marker per
+ step, the lit step's in Signal, the endpoint labelled, three recessive gridlines; a crosshair snapping to the
+ nearest step with a tooltip (total strong, step secondary); a click on a column lights that step (the list is
+ its table view). **Live**: `GET /api/research/runs/<a>/<n>` every 2.5 s while the iteration is queued or running
+ and the tab is visible, one request at a time; the newest step is lit as it lands until the operator moves the
+ light. **Replay**: the steps lit one after another (650 ms) from the first; any key or click stops it.
+- **The turns.jsonl projection** (`lib/research/runs-view.ts`, pure, unit-tested): each response is a turn step
+ with its calls (inputs in a line; results were cut to nothing on an import), enumerations parsed where a
+ result survives, `extract_batch` calls as batches whose lines are null ("not kept"), and a **gap** step for the
+ quote checks ("kept / dropped not recorded", the iteration's own checks listed). A pipeline's `dropped` turns
+ are real checks. **Several run starts**: a "run started" note opens a run (an import's); a file without them
+ splits where a response's turn goes back to 0, unless a "repair round" note says it is the repair. Each run is
+ shown alone, its spend its own: an imported stopgap run logged its RUNNING total on each turn (the importer
+ kept it), so its step cost is the difference; the agent's own transcript logs each turn's. The iteration's
+ report is the last run's: findings and "Open as a board" are offered on the last run only.
+- **`/research/runs`**: every sweep iteration of the article store, newest first (model, status, `turns` when it
+ predates the trace, spend), each linking its run; **Agent runs** in Research's head reaches it.
+- **Open as a board** (`lib/research/runs-board.ts`, `POST /api/research/runs/<a>/<n>/board`): the case
+ `<article>-run<n>` (piece `c:<article>-run<n>`; `runBoardId` cuts the article so it stays a piece segment) is made
+ — titled with the report's title, its scope the iteration's channels and dates, its query the question — or
+ brought up to date. Its quotes are every quoted citation of the iteration's report, in the report's sections,
+ the finding as the claim line, through R2's `addQuote` (the same snapshot shape as a pin), each `by: "agent"`
+ (kept by `cleanQuote`; the slip says **by agent**); the case carries `run {article, n, at}` and its side panel
+ links **From run**. The cite's link is a moment link on the run's origin (its trace's scope, else its
+ sweep.md's links); its source is the run's corpus when offered, else the one serving that origin, else the
+ local corpus — so the board's Re-verify reads it like any pin. A second open adds what is new (`sameCite`) and
+ never touches the operator's claims, notes, sections or order. A run with no report is a 409.
+- **Run a sweep on this scope** (a board's side panel; `POST /api/research/cases/<id>/handoff {to: "sweep"}`):
+ R2's article hand-off without the seed (`planArticle(…, {seeded: false})` → `planScopeSweep` /
+ `confirmScopeSweep`): the case's query (else its title), its channels (else the quoted ones), dates and source;
+ the policy's sweep route — the API agent with the policy's extractor and cap, or the local model (no cap); a
+ route to Claude Code (a session's, not a job's) runs the API agent, and the plan says so. Local-only channels
+ are refused (a sweep makes an article). The dialog shows the corpus, the model and extractor and the cap;
+ confirmed, it answers the run's page, and the case records it (`what: "a sweep on the scope: <a> i<n>, job …"`).
+- **Hrefs** (`lib/research/runs-hrefs.ts`, pure): `runHref(article, n, {run?})`, `runsHref()`, `runApi`,
+ `runBoardApi`, `runBoardId`, `hasRunPage(kind)` (sweeps).
+
+**Not wired here, left to the owners** (their files): the Iterations tab's iteration row (`components/articles/
+IterationsTab.tsx`, P4a-2) and the Running list's report-draft row (`lib/activity.ts` `editorItem`'s `href`,
+P2b's) should link `runHref(article, n)` when `hasRunPage(kind)` — `lib/activity.ts` already has the place
+(`{article, n, task}`), and a sweep row's href becomes `runHref(place.article, place.n)`.
+
+| sha | what |
+|---|---|
+| `767f2681` | common: `trace.jsonl` (`tasks/trace.ts`), `runOnIteration`'s `trace` and `setCoverage`, both sweeps traced, `dropFailedFindings`' `items`, `iterationCoverageSchema`, `ITERATION_FILES` + `trace.jsonl`; `trace.test.ts` (8); `mcp/src/draftTasks.test.ts` asserts each sweep's trace and coverage, the dropped quote and why, and a seeded sweep's `scope.seed` (+1 test) |
+| `751b2eff` | umtool: the run page and `/research/runs`, the APIs, `runs-view.ts` (trace + turns projections), `runs-board.ts`, `runs-hrefs.ts`, the scope sweep (`planScopeSweep`/`confirmScopeSweep`, `to: "sweep"`), `by: "agent"` and `run` on a case, the board's button and From run, the run fixture, `runs.test.ts` (7) |
+| `2351d34e` | `e2e/run-trace.spec.ts` (6); **Agent runs** on Research; a Claude Code-routed scope sweep runs the API agent (plan says so); `boards.test.ts` +1 |
+| `15c4b813` | the replay assertion watches every frame; `[Unreleased]` bullets |
+| `d35e0c51` | `data-board-busy` on the board; `board.spec` waits for it before each move |
+
+**Gates.**
+
+| Gate | Result |
+|---|---|
+| repo-wide `tsc --noEmit` | clean at `767f2681` (common, mcp, editor, umtool), `751b2eff` (umtool) and `2351d34e` (repo-wide, exit 0); umtool's at every later commit |
+| common `pnpm --filter yt-dlp-transcript-common test` (`SETTINGS_FILE` at the primary's, read only) | **4104/4104** (+8: `trace.test.ts`) |
+| mcp `pnpm --filter yt-dlp-transcript-mcp test` | **364/364** (+1: the seeded sweep's trace; the sweep tests assert their traces) |
+| umtool unit (`node --test umtool/lib/*.test.mjs umtool/lib/*/*.test.mjs umtool/report-to-video/*.test.mjs`) | 834 tests, 832 pass, 2 skipped, 0 fail |
+| `pnpm --filter umtool test` | **24/24** (new: `runs.test.ts` 7 — the trace projection, live and torn lines, two trace runs, turns-only with two starts and running totals, the unmarked split, the small words, open as a board end to end with re-verify; `boards.test.ts` +1 — the scope sweep) |
+| editor unit `pnpm --filter editor test` | 297/297 |
+| `pnpm run test:scripts` (reads the capped build) | 985 tests, 983 pass, 2 skipped, 0 fail |
+| `pnpm archilyzer docs cli --check` | clean |
+| capped umtool `next build` (corpus linked, `MemoryMax=5G`, heavy slot) | exit 0; compiled 12.3 s, 44.6 s wall, 1.46 GB max RSS. The run page's and the board route's traces: 938 / 932 files, none from `transcripts/`, `export/public`, `.e2e-song` or `.env*`; the link removed |
+| capped editor `next build` (common changed) | exit 0; compiled 39.4 s, 1:13.6 wall, 2.36 GB max RSS |
+| editor e2e, the report-draft specs (`report-draft.spec.ts`, `ops-api.spec.ts`; `export/public` linked from the primary) | **17 passed, 0 failed**, 30 s |
+| full umtool e2e, run 1 (`2351d34e`) | 413 tests: 405 passed, 2 failed, 6 skipped, 8.3 min. Reds: `run-trace.spec` replay (asserted a 650 ms step with backed-off retries — now watched per frame, `15c4b813`) and `running.spec:185` (the drafts decision read empty once; green in every run since) |
+| `research` + `run-trace` + `running` specs | 21/21 |
+| full umtool e2e, run 2 (`15c4b813`) | 404 passed, 3 failed, 6 skipped, 7.8 min: `board.spec` 102/163/185 — an R2 race surfaced by the loaded machine (below), then `board`+`run-trace`+`running` 16/16 and 13/16 |
+| `board.spec` × 3 (`d35e0c51`) | 7/7, 7/7, 7/7 |
+| full umtool e2e, run 3 (`d35e0c51`) | **413 tests: 407 passed, 0 failed, 6 skipped** (the song-data skips), 7.9m; `run-trace.spec` 6/6 |
+
+**Screenshots and keys.** Job scratch `r3-shots/`: `/research/runs/piratesoftware-ai-friends/1?run=1` (the fallback on
+REAL data: the iteration's two files copied read-only into a scratch article store, run 1 of 3, `t4` lit) and the
+fixture's traced run (`runfix`, the quote checks lit; the batch lit with the chart's tooltip), 1366×768 and
+1440×900, dark and light; `dev/` holds the working shots (run 3 with the hover, the turns-only and live runs, the
+index). Against the canvas's Transparent run: the same two columns (the 330 px step list with `t`, label and
+sub-line, and the running spend in Meter; the detail pane), the three lanes (Batches, Findings, Coverage), the
+ids as mono chips, the spend chart as a Meter step line with the lit step's dot in Signal and the endpoint
+labelled, the gap step in italics. The real run's numbers match the canvas's (t0 $0.04 … t7 $0.64). Differences:
+the title is `<article> i<n>` with the question under it (the head's h1 truncates a long line; the question
+wraps), the run picker and the notes in the head, the extractor's lines on the reader surface, the checks
+grouped in the detail, Replay and Open as a board in the head, the key legend at the foot. **Keyboard only**
+(reduced motion): the rail's 11 stops, the trail's two links, Replay, Open as a board (each the 2 px Signal
+ring), the step list ONE stop (the lit line, dashed 1 px), then the footer's link; `j`/`k`, `Home`/`End` move the
+light and the detail follows; `r` replays to the end and stops; `b` opens the board.
+
+**Found and left.**
+- **R2's board refused a move pressed while the previous one was answering** (`busy`): the case file is written
+ before the answer lands, so a spec — or a fast operator — pressing `alt+j` twice saw the second dropped. On a
+ loaded machine `board.spec` went red 2 runs in 3. The board now says `data-board-busy` while it waits and the
+ spec waits for it; queueing the key instead of dropping it is left for R2's owner to judge.
+- **An imported stopgap run's spend per turn is a running total** (the importer kept the stopgap's own field); the
+ projection takes differences when the run has a stopgap note. The iteration's `usage` for such an import is
+ only its last attempt's (`$0.33` on piratesoftware-ai-friends while its first run alone shows `$1.83`); the head
+ says both when they differ.
+- **The trace is the editor's to write**: runs already in the store have none, and nothing back-fills one. A
+ run started before the editor restart writes none either.
+- **Open as a board takes the iteration's report** (the last run's), so it is offered on the last run only. A cite's
+ link needs the run's origin: an old run's comes from its sweep.md's links; a run with neither gets no link
+ (the board shows the cite without one).
+- **The live page polls the whole view** every 2.5 s (a trace of a few hundred lines is a few tens of KB); a
+ cursor (`?from=<line>`) is the next step if traces grow large.
+- **A scope sweep from a board with no channels** is refused with what to do; a case whose scope names a hub's
+ `<site>:<slug>` keys sweeps the slugs (R2's rule).
+- **Not wired** (above): the Iterations tab and the Running list link the run page through `runHref` once their
+ owners take it.
+
+**Follow-up (review, 2026-10-14).**
+- **Rulings:** a scope sweep under a policy routing sweeps to Claude Code runs the API agent, said in the plan —
+ accepted.
+- **The question is the run page's title**, as on the canvas: the `<h1>` (Archivo), clamped to two lines with the
+ full text in `title` (AppHeader's new additive `clamp`), and `<article> · i<n>` is a crumb in the trail, linking
+ the article's iterations. The `below` row keeps the micro line, the meta and the notes.
+- **Board moves queue, never drop** (`components/research/BoardView.tsx`): an `alt+j`/`alt+k` pressed while the
+ last move is still answering is queued and applied after it, in order, computed on the case that move left
+ (`docRef`, updated from each answer); a move that fails drops the ones behind it and says why.
+ `data-board-busy` stays (a request answering or moves queued). `board.spec` now presses two moves at once and
+ expects both, in order (`q2 q3 q1`), with no waits between them.
+- **The Running list links a sweep's run page** (`lib/activity.ts` `placeHref`): a report-draft row placed on an
+ iteration whose task has a run page (`hasRunPage`: a sweep, not a research proposal) links
+ `runHref(article, n)`; any other placed job its article's iterations, as before. The rail lists active jobs
+ only, so a finished draft has no row to link. `running.spec`: the existing running sweep row now links
+ `/research/runs/zeta/7`; a new test places one row by its iteration's `jobId` (the run fixture's live sweep,
+ `jobId: e2e-run-live`) and one by its log (a narration step), and follows the first to the live run page.
+ The Iterations tab is not touched (P4a-2).
+- **Merged `ux/integration` `8675bc57` (P5)** at `e7d59eb1`; one conflict, this plan (P5's records kept, R3's after
+ them, one status row per phase); `pnpm install` up to date.
+
+| sha | what |
+|---|---|
+| `e7d59eb1` | merge `ux/integration` `8675bc57` (P5) |
+| `0f4d05a0` | the question as the title (AppHeader `clamp`), the run in the trail; board moves queued; a sweep's Running row links its run page; `board.spec`, `run-trace.spec`, `running.spec` (+1) |
+
+Gates at `0f4d05a0`: repo-wide tsc clean; common 4104/4104 (`SETTINGS_FILE` at the primary's; a first run beside
+the chain's builds had 1 failure, gone on the rerun); mcp 364/364; umtool unit 843 tests, 841 pass, 2 skipped, 0
+fail; `pnpm --filter umtool test` 24/24; editor unit 297/297; test:scripts 994, 992 pass, 2 skipped, 0 fail; capped
+umtool build exit 0 (24.1 s compile, 1:06.9 wall, 1.47 GB); capped editor build exit 0 (27.4 s, 1:05.0, 2.37 GB);
+`board` + `run-trace` + `running` specs 17/17; full umtool e2e **433 tests: 427 passed, 0 failed, 6 skipped**
+(the song-data skips), 7.8 min. Screenshots: job scratch `r3-shots/followup/` (the real fallback and the fixture
+trace with the question as the title, dark and light, 1366×768).
+
### P4a-2, as shipped
**What.** An article and the video project it claims are one page: the article's address (`/articles/<id>`,
diff --git a/umtool/app/api/research/cases/[id]/handoff/route.ts b/umtool/app/api/research/cases/[id]/handoff/route.ts
@@ -1,5 +1,5 @@
import { CaseError } from "@/lib/research/cases.mjs";
-import { confirmArticle, confirmVideo, planArticle, planVideo } from "@/lib/research/handoff";
+import { confirmArticle, confirmScopeSweep, confirmVideo, planArticle, planScopeSweep, planVideo } from "@/lib/research/handoff";
import { fail, ok } from "../../../_respond";
export const dynamic = "force-dynamic";
@@ -10,25 +10,32 @@ export const dynamic = "force-dynamic";
// { to: "article", confirm: true, … } -> { href, jobId, iteration }
// { to: "video", slug?, title? } -> { plan: VideoPlan }
// { to: "video", confirm: true, … } -> { href }
+// { to: "sweep", article?, model?, question? } -> { plan: ArticlePlan } (seeded: false)
+// { to: "sweep", confirm: true, … } -> { href (the run's page), jobId, iteration }
// An article is a seeded report-draft sweep the editor runs (it spends: the
// plan says on what model, under which cap); a video is a project scaffolded
-// under the reports root (it writes one).
+// under the reports root (it writes one); a sweep (R3) is the article's
+// sweep over the case's scope with no seed, on the policy's sweep route.
export async function POST(request: Request, ctx: { params: Promise<{ id: string }> }) {
try {
const { id } = await ctx.params;
const b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
- if (!b || typeof b !== "object" || Array.isArray(b)) throw new CaseError('expected a JSON object: { to: "article" | "video", confirm? }');
+ if (!b || typeof b !== "object" || Array.isArray(b)) throw new CaseError('expected a JSON object: { to: "article" | "video" | "sweep", confirm? }');
const s = (k: string) => (typeof b[k] === "string" && (b[k] as string).trim() ? (b[k] as string).trim() : undefined);
const confirm = b.confirm === true;
if (b.to === "article") {
const over = { ...(s("article") ? { article: s("article") } : {}), ...(s("model") ? { model: s("model") } : {}), ...(s("question") ? { question: s("question") } : {}) };
return ok(confirm ? await confirmArticle(id, over) : { plan: (await planArticle(id, over)).plan });
}
+ if (b.to === "sweep") {
+ const over = { ...(s("article") ? { article: s("article") } : {}), ...(s("model") ? { model: s("model") } : {}), ...(s("question") ? { question: s("question") } : {}) };
+ return ok(confirm ? await confirmScopeSweep(id, over) : { plan: (await planScopeSweep(id, over)).plan });
+ }
if (b.to === "video") {
const over = { ...(s("slug") ? { slug: s("slug") } : {}), ...(s("title") ? { title: s("title") } : {}) };
return ok(confirm ? await confirmVideo(id, over) : { plan: await planVideo(id, over) });
}
- throw new CaseError('to is "article" or "video"');
+ throw new CaseError('to is "article", "video" or "sweep"');
} catch (e) {
return fail(e);
}
diff --git a/umtool/app/api/research/cases/route.ts b/umtool/app/api/research/cases/route.ts
@@ -49,10 +49,14 @@ export const dynamic = "force-dynamic";
// quote's words. -> { results: [{ id, verify }], case: CaseView }
// GET /api/research/cases/<id>/export.md[?download=1]
// the board as cited markdown in the house format (text/markdown)
-// POST /api/research/cases/<id>/handoff { to: "article" | "video", confirm?, ... }
+// POST /api/research/cases/<id>/handoff { to: "article" | "video" | "sweep", confirm?, ... }
// without confirm -> { plan } (ArticlePlan | VideoPlan; writes nothing)
-// with confirm: true -> { href } (article: { href, jobId, iteration })
-// article: { article?, model?, question? } video: { slug?, title? }
+// with confirm: true -> { href } (article, sweep: { href, jobId, iteration })
+// article, sweep: { article?, model?, question? } video: { slug?, title? }
+// sweep (R3): the case's scope with no seed, on the policy's sweep
+// route; its href is the run's page, /research/runs/<article>/<n>
+// (a quote may carry `by: "agent"` and a case `run: { article, n, at }`:
+// a run's findings opened as a board, POST /api/research/runs/<a>/<n>/board)
// ---------------------------------------------------------------------------
export async function GET() {
diff --git a/umtool/app/api/research/runs/[article]/[n]/board/route.ts b/umtool/app/api/research/runs/[article]/[n]/board/route.ts
@@ -0,0 +1,18 @@
+import { openRunBoard } from "@/lib/research/runs-board";
+import { fail, ok } from "../../../../_respond";
+
+export const dynamic = "force-dynamic";
+
+// OPEN A RUN AS A BOARD (lib/research/runs-board.ts): POST makes, or brings up
+// to date, the research case `<article>-run<n>` holding the run's kept findings
+// as quotes (`by: "agent"`). Writes umtool's own state only.
+// POST -> { id, href, created, added, already, skipped }
+// 409 the run kept no findings yet (or a case.json that does not read)
+export async function POST(_request: Request, ctx: { params: Promise<{ article: string; n: string }> }) {
+ try {
+ const { article, n } = await ctx.params;
+ return ok(await openRunBoard(decodeURIComponent(article), Number(n)));
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/api/research/runs/[article]/[n]/route.ts b/umtool/app/api/research/runs/[article]/[n]/route.ts
@@ -0,0 +1,21 @@
+import { readRunView } from "@/lib/research/runs";
+import { fail, ok } from "../../../_respond";
+
+export const dynamic = "force-dynamic";
+
+// A TRANSPARENT RUN (plans/umtool-redesign.md, R3): GET answers the run's view
+// (lib/research/runs-types.ts RunView) -- read from the iteration's
+// trace.jsonl, or projected from its turns.jsonl for a run before the trace.
+// `?run=<k>` picks one of several runs (the last by default). Read only; the
+// page polls it while the run is live.
+// GET /api/research/runs/<article>/<n>[?run=<k>] -> RunView
+// 404 no such iteration · 400 a bad address · 409 an iteration.json that does not read
+export async function GET(request: Request, ctx: { params: Promise<{ article: string; n: string }> }) {
+ try {
+ const { article, n } = await ctx.params;
+ const run = Number(new URL(request.url).searchParams.get("run") ?? "");
+ return ok(await readRunView(decodeURIComponent(article), Number(n), Number.isInteger(run) && run > 0 ? run : null));
+ } catch (e) {
+ return fail(e);
+ }
+}
diff --git a/umtool/app/research/page.tsx b/umtool/app/research/page.tsx
@@ -5,6 +5,7 @@ import { buttonVariants } from "@/components/ui/button";
import { listCases } from "@/lib/research/boards";
import { scopeFrom, scopeOf } from "@/lib/research/corpus";
import { researchArchiveHref } from "@/lib/research/hrefs";
+import { runsHref } from "@/lib/research/runs-hrefs";
import { listSources } from "@/lib/research/sources";
import type { ScopeSummary } from "@/lib/research/types";
@@ -40,9 +41,14 @@ export default async function ResearchPage({ searchParams }: { searchParams: Pro
active="research"
crumbs={[{ label: "research" }]}
actions={
- <Link href={researchArchiveHref({ source: scope.source === sources[0].handle ? undefined : scope.source })} className={buttonVariants({ variant: "outline", size: "sm" })}>
- Archive inventory
- </Link>
+ <>
+ <Link href={runsHref()} prefetch={false} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Agent runs
+ </Link>
+ <Link href={researchArchiveHref({ source: scope.source === sources[0].handle ? undefined : scope.source })} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Archive inventory
+ </Link>
+ </>
}
/>
<ResearchView
diff --git a/umtool/app/research/runs/[article]/[n]/page.tsx b/umtool/app/research/runs/[article]/[n]/page.tsx
@@ -0,0 +1,56 @@
+import Link from "next/link";
+import AppHeader from "@/components/shell/AppHeader";
+import AppRail from "@/components/shell/AppRail";
+import RunView from "@/components/research/RunView";
+import { EmptyState } from "@/components/ui/empty-state";
+import { researchHref } from "@/lib/research/hrefs";
+import { readRunView } from "@/lib/research/runs";
+import { runsHref } from "@/lib/research/runs-hrefs";
+import type { RunView as View } from "@/lib/research/runs-types";
+
+export const dynamic = "force-dynamic";
+
+// A TRANSPARENT RUN (plans/umtool-redesign.md, R3; canvas "Transparent run"):
+// one sweep iteration of the article store, step by step -- live while it
+// runs, a replay when it is done (components/research/RunView.tsx). `?run=k`
+// picks one of several runs. Read only. A static segment under /research, so
+// it wins over the case page (`runs` is a reserved case id).
+export default async function RunPage({
+ params,
+ searchParams,
+}: {
+ params: Promise<{ article: string; n: string }>;
+ searchParams: Promise<Record<string, string | string[] | undefined>>;
+}) {
+ const { article: raw, n } = await params;
+ const sp = await searchParams;
+ const article = decodeURIComponent(raw);
+ const want = Number(typeof sp.run === "string" ? sp.run : "");
+ let view: View | null = null;
+ let error: { status: number; message: string } | null = null;
+ try {
+ view = await readRunView(article, Number(n), Number.isInteger(want) && want > 0 ? want : null);
+ } catch (e) {
+ error = { status: (e as { status?: number }).status ?? 500, message: (e as Error).message };
+ }
+ return (
+ <div className="flex h-full flex-col">
+ <AppRail active="research" />
+ {view ? (
+ <RunView key={`${view.article}/${view.n}/${view.run}`} initial={view} />
+ ) : (
+ <>
+ <AppHeader crumbs={[{ href: researchHref(), label: "research" }, { href: runsHref(), label: "runs" }, { label: `${article} i${n}` }]} />
+ <div className="px-7 pt-6">
+ <EmptyState title={error?.status === 404 ? `No run ${article} i${n}` : "This run cannot be read"}>
+ <span role="alert">{error?.message}</span>{" "}
+ <Link prefetch={false} href={runsHref()} className="ink-link">
+ Every run
+ </Link>
+ </EmptyState>
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/app/research/runs/page.tsx b/umtool/app/research/runs/page.tsx
@@ -0,0 +1,55 @@
+import Link from "next/link";
+import AppShell from "@/components/shell/AppShell";
+import { EmptyState } from "@/components/ui/empty-state";
+import { LitList } from "@/components/ui/lit-list";
+import { LitLine } from "@/components/ui/lit-line";
+import { researchHref } from "@/lib/research/hrefs";
+import { listRuns } from "@/lib/research/runs";
+import { runHref } from "@/lib/research/runs-hrefs";
+
+export const dynamic = "force-dynamic";
+
+// EVERY SWEEP RUN (plans/umtool-redesign.md, R3): the article store's sweep
+// iterations, newest first, each linking its run page. Read only.
+export default async function RunsPage() {
+ const rows = await listRuns().catch(() => []);
+ const live = rows.filter((r) => r.status === "running" || r.status === "queued").length;
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell
+ active="research"
+ crumbs={[{ href: researchHref(), label: "research" }, { label: "runs" }]}
+ note={`${rows.length} ${rows.length === 1 ? "sweep" : "sweeps"}${live ? ` · ${live} running` : ""}`}
+ />
+ <div className="min-h-0 flex-1 overflow-auto px-7 pb-6 pt-3">
+ {rows.length === 0 ? (
+ <EmptyState title="No sweep has run yet" />
+ ) : (
+ <LitList label="Runs" global>
+ {rows.map((r) => (
+ <LitLine
+ key={`${r.article}/${r.n}`}
+ id={`${r.article}/${r.n}`}
+ data-run-row={`${r.article}/${r.n}`}
+ className="grid grid-cols-[minmax(0,1fr)_120px_96px_70px] items-baseline gap-x-4 text-[13px]"
+ >
+ <span className="min-w-0">
+ <Link prefetch={false} href={runHref(r.article, r.n)} className="font-mono text-[12.5px] text-text no-underline hover:underline">
+ {r.article} i{r.n}
+ </Link>
+ <small className="block truncate text-[12px] text-muted-2">{r.question ?? "—"}</small>
+ </span>
+ <span className="truncate font-mono text-[11.5px] text-muted-2">{r.model}</span>
+ <span className="font-mono text-[11.5px] text-muted-2">
+ {r.status}
+ {r.from === "turns" ? " · turns" : r.from === "none" ? " · no record" : ""}
+ </span>
+ <span className="text-right font-mono text-[11.5px] tabular-nums text-meter">${r.usd.toFixed(2)}</span>
+ </LitLine>
+ ))}
+ </LitList>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx
@@ -22,6 +22,7 @@ import {
researchHref,
} from "@/lib/research/hrefs";
import HandoffDialog from "./HandoffDialog";
+import { runHref } from "@/lib/research/runs-hrefs";
import QuoteSlip, { quoteLineId } from "./QuoteSlip";
// ---------------------------------------------------------------------------
@@ -109,7 +110,7 @@ export default function BoardView({ initial }: { initial: CaseView }) {
const [listKey, setListKey] = useState(0);
const [ask, setAsk] = useState<Ask | null>(null);
const [askText, setAskText] = useState("");
- const [handoff, setHandoff] = useState<"article" | "video" | null>(null);
+ const [handoff, setHandoff] = useState<"article" | "video" | "sweep" | null>(null);
const [notes, setNotes] = useState(initial.case.notes);
const dragging = useRef<string | null>(null);
const doc = view.case;
@@ -132,18 +133,26 @@ export default function BoardView({ initial }: { initial: CaseView }) {
el?.scrollIntoView({ block: "nearest" });
}, [listKey]);
+ // The case as the last answer left it: a queued move is computed on it, not
+ // on the render that queued it.
+ const docRef = useRef(doc);
+ docRef.current = doc;
+
const arrange = useCallback(
- async (next: { sections: unknown; order: unknown } | null, keep: string | null) => {
- if (!next) return;
+ async (next: { sections: unknown; order: unknown } | null, keep: string | null): Promise<boolean> => {
+ if (!next) return true;
setBusy(true);
try {
const v = await call<CaseView>(researchCaseApi(doc.id), "PATCH", next);
+ docRef.current = v.case;
refocus.current = keep;
if (keep) setLitId(keep);
setView(v);
setListKey((k) => k + 1);
+ return true;
} catch (e) {
fail(e);
+ return false;
} finally {
setBusy(false);
}
@@ -151,6 +160,40 @@ export default function BoardView({ initial }: { initial: CaseView }) {
[doc.id],
);
+ // MOVES ARE QUEUED, never dropped: an alt+j/k pressed while the last move
+ // is still answering is applied after it, in order, on the case that move
+ // left. A move that fails drops the ones queued behind it (and says why).
+ const moves = useRef<{ kind: "quote" | "section"; id: string; dir: number }[]>([]);
+ const moving = useRef(false);
+ const [queued, setQueued] = useState(0);
+ const pumpMoves = useCallback(async () => {
+ if (moving.current) return;
+ moving.current = true;
+ try {
+ while (moves.current.length) {
+ const m = moves.current.shift()!;
+ setQueued(moves.current.length);
+ const d = docRef.current;
+ const ok =
+ m.kind === "quote"
+ ? await arrange(moveQuote(d, m.id, m.dir), quoteLineId(m.id))
+ : await arrange(moveSection(d, m.id, m.dir), sectionLineId(m.id));
+ if (!ok) moves.current = [];
+ }
+ } finally {
+ moving.current = false;
+ setQueued(0);
+ }
+ }, [arrange]);
+ const queueMove = useCallback(
+ (m: { kind: "quote" | "section"; id: string; dir: number }) => {
+ moves.current.push(m);
+ setQueued(moves.current.length);
+ void pumpMoves();
+ },
+ [pumpMoves],
+ );
+
const patchQuote = useCallback(
async (qid: string, body: Record<string, unknown>) => {
setBusy(true);
@@ -294,10 +337,10 @@ export default function BoardView({ initial }: { initial: CaseView }) {
if (document.querySelector("dialog[open]")) return;
if (e.altKey) {
const dir = e.code === "KeyJ" || e.key === "ArrowDown" ? 1 : e.code === "KeyK" || e.key === "ArrowUp" ? -1 : 0;
- if (!dir || busy) return;
+ if (!dir) return;
e.preventDefault();
- if (litQuote) void arrange(moveQuote(doc, litQuote.id, dir), quoteLineId(litQuote.id));
- else if (litSection) void arrange(moveSection(doc, litSection.id, dir), sectionLineId(litSection.id));
+ if (litQuote) queueMove({ kind: "quote", id: litQuote.id, dir });
+ else if (litSection) queueMove({ kind: "section", id: litSection.id, dir });
return;
}
const focusField = (f: string) => {
@@ -393,7 +436,7 @@ export default function BoardView({ initial }: { initial: CaseView }) {
/>
<div className="grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)_300px]">
<div className="flex min-h-0 min-w-0 flex-col">
- <div className="min-h-0 flex-1 overflow-auto px-7 pb-4 pt-2">
+ <div className="min-h-0 flex-1 overflow-auto px-7 pb-4 pt-2" data-board-busy={busy || queued > 0 ? "" : undefined}>
{doc.quotes.length === 0 && doc.sections.length === 0 ? (
<EmptyState title="No quotes on this board yet">
<Link prefetch={false} href={researchFromCaseHref(doc)} className="ink-link">
@@ -472,6 +515,9 @@ export default function BoardView({ initial }: { initial: CaseView }) {
<button type="button" disabled={!hydrated || !doc.quotes.length} className={`${buttonVariants({ variant: "outline" })} justify-start`} onClick={() => setHandoff("video")}>
Start a video from this board
</button>
+ <button type="button" data-run-sweep="" disabled={!hydrated} className={`${buttonVariants({ variant: "outline" })} justify-start`} onClick={() => setHandoff("sweep")}>
+ Run a sweep on this scope
+ </button>
</div>
{view.localOnly > 0 && <p className="mt-2 text-[12px] text-doubt-text">{view.localOnly} local-only: no article (it could be published); a video stays local.</p>}
</div>
@@ -490,6 +536,16 @@ export default function BoardView({ initial }: { initial: CaseView }) {
<dd className="m-0 break-all font-mono text-[11px] text-text-2">{view.stored}</dd>
<dt className="text-muted">Piece</dt>
<dd className="m-0 font-mono text-[11px] text-text-2">{view.piece}</dd>
+ {doc.run && (
+ <>
+ <dt className="text-muted">From run</dt>
+ <dd className="m-0 text-text-2" data-case-run="">
+ <Link prefetch={false} href={runHref(doc.run.article, doc.run.n)} className="ink-link font-mono text-[11.5px]">
+ {doc.run.article} i{doc.run.n}
+ </Link>
+ </dd>
+ </>
+ )}
</dl>
<div className="grid gap-1.5">
<Link prefetch={false} href={researchFromCaseHref(doc)} className={`${buttonVariants({ variant: "outline", size: "sm" })} justify-self-start`}>
@@ -516,7 +572,7 @@ export default function BoardView({ initial }: { initial: CaseView }) {
<span className="micro">Made from it</span>
{doc.handoffs.map((h, i) => (
<Link prefetch={false} key={`${h.href}-${i}`} href={h.href} className="ink-link">
- {h.to === "article" ? "Article" : "Video"} · {h.what ?? h.href} · {h.at.slice(0, 10)}
+ {h.to === "video" ? "Video" : h.what?.startsWith("a sweep on the scope") ? "Sweep" : "Article"} · {h.what ?? h.href} · {h.at.slice(0, 10)}
</Link>
))}
</div>
diff --git a/umtool/components/research/HandoffDialog.tsx b/umtool/components/research/HandoffDialog.tsx
@@ -42,11 +42,23 @@ function ArticleBody({ p }: { p: ArticlePlan }) {
{p.dateFrom ?? "…"} – {p.dateTo ?? "…"}
</Row>
)}
- <Row k="Seed">
- the board as cited markdown: {p.seed.quotes} {p.seed.quotes === 1 ? "quote" : "quotes"}, {p.seed.chars.toLocaleString("en-US")} characters
- </Row>
+ {p.seeded !== false ? (
+ <Row k="Seed">
+ the board as cited markdown: {p.seed.quotes} {p.seed.quotes === 1 ? "quote" : "quotes"}, {p.seed.chars.toLocaleString("en-US")} characters
+ </Row>
+ ) : (
+ <Row k="Corpus">
+ <span className="break-all font-mono text-[11.5px]">{p.source || "the local corpus"}</span>
+ </Row>
+ )}
<Row k="Runs on">
- {p.model ? <span className="font-mono">{p.model}</span> : "the editor cannot be asked"}
+ {p.model ? <span className="font-mono">{p.model}</span> : p.policyError ? "the editor cannot be asked" : "—"}
+ {p.extractor ? (
+ <>
+ {" "}
+ · extractor <span className="font-mono">{p.extractor}</span>
+ </>
+ ) : null}
{p.capUsd !== null ? (
<>
{" "}
@@ -90,7 +102,7 @@ export default function HandoffDialog({
onDone,
}: {
caseId: string;
- to: "article" | "video" | null;
+ to: "article" | "video" | "sweep" | null;
onClose: () => void;
onDone: (href: string, what: string) => void;
}) {
@@ -116,7 +128,7 @@ export default function HandoffDialog({
setError(null);
try {
const r = await post<{ href: string }>(researchCaseHandoffApi(caseId), { to, confirm: true, ...(plan.to === "article" ? { article: plan.article } : { slug: plan.slug }) });
- onDone(r.href, plan.to === "article" ? `The sweep for ${plan.article} is queued` : `Project ${plan.slug} written`);
+ onDone(r.href, plan.to === "article" ? `The sweep for ${plan.article} is queued${to === "sweep" ? ": its run page follows it" : ""}` : `Project ${plan.slug} written`);
} catch (e) {
setError((e as Error).message);
} finally {
@@ -124,7 +136,7 @@ export default function HandoffDialog({
}
};
- const title = to === "article" ? "Draft an article from this board" : "Start a video from this board";
+ const title = to === "article" ? "Draft an article from this board" : to === "sweep" ? "Run a sweep on this scope" : "Start a video from this board";
const blocked = !plan || plan.refusals.length > 0 || (plan.to === "article" && !!plan.policyError);
return (
<Dialog open={to !== null} onClose={onClose} title={title} data-handoff={to ?? ""}>
@@ -159,7 +171,7 @@ export default function HandoffDialog({
Cancel
</button>
<button type="button" data-confirm="" disabled={blocked || working} className={buttonVariants({ variant: "go" })} onClick={confirm}>
- {working ? "Working…" : plan?.to === "article" ? `Start the sweep${plan.capUsd !== null ? ` (up to $${plan.capUsd.toFixed(2)})` : ""}` : "Create the project"}
+ {working ? "Working…" : plan?.to === "article" ? `Start the sweep${plan.capUsd !== null ? ` (up to $${plan.capUsd.toFixed(2)})` : plan.model && !plan.model.startsWith("claude-") ? " (local model)" : ""}` : "Create the project"}
</button>
</div>
</Dialog>
diff --git a/umtool/components/research/QuoteSlip.tsx b/umtool/components/research/QuoteSlip.tsx
@@ -185,6 +185,11 @@ export default function QuoteSlip({
/>
</div>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-muted-2">
+ {q.by === "agent" && (
+ <span data-by="agent" className="font-mono text-[11px] text-text-2" title="Kept by an agent's sweep (its strict quote check passed); not a person's pin">
+ by agent
+ </span>
+ )}
{c.kind !== "post" &&
(q.speakerChecked ? (
<span data-speaker="checked" className="text-muted">Speaker checked</span>
diff --git a/umtool/components/research/RunView.tsx b/umtool/components/research/RunView.tsx
@@ -0,0 +1,622 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useRef, useState } from "react";
+import AppHeader from "@/components/shell/AppHeader";
+import { buttonVariants } from "@/components/ui/button";
+import { KeyHint } from "@/components/ui/kbd";
+import { LitList, type LitDetail } from "@/components/ui/lit-list";
+import { LitLine } from "@/components/ui/lit-line";
+import { useHydrated } from "@/components/ui/use-hydrated";
+import { ARTICLES_KEY } from "@/lib/articles/key.mjs";
+import { articleHref } from "@/lib/hrefs";
+import { researchCaseHref, researchHref } from "@/lib/research/hrefs";
+import { runApi, runBoardApi, runHref, runsHref } from "@/lib/research/runs-hrefs";
+import type { RunCheck, RunCite, RunStep, RunView as View } from "@/lib/research/runs-types";
+import { cn } from "@/lib/utils";
+import SpendChart, { type SpendPoint } from "./SpendChart";
+
+// ---------------------------------------------------------------------------
+// A TRANSPARENT RUN (plans/umtool-redesign.md, R3; canvas "Transparent run"):
+// the head -- the question, the model and extractor, the scope, the time, the
+// spend, the checks -- then ONE lit list of the run's steps (scope, each turn
+// or batch, findings, the quote checks kept and dropped, the end) with the
+// running spend on each, and beside it the lit step's detail: the ids, the
+// extractor's own lines on the reader surface, the quotes kept and dropped
+// with why, and the spend chart.
+//
+// LIVE while the run is (the view's `live`): GET the view every POLL_MS while
+// the tab is visible, one request at a time; the lit line follows the newest
+// step until the operator moves it. REPLAY when it is done: `r` (or Replay)
+// lights the steps one after another from the first.
+// ---------------------------------------------------------------------------
+
+export const POLL_MS = 2500;
+const REPLAY_MS = 650;
+
+const money = (v: number | null | undefined) => (typeof v === "number" ? `$${v.toFixed(2)}` : "—");
+const thousands = (n: number) => n.toLocaleString("en-US");
+const mmss = (s: number) => {
+ const t = Math.floor(s);
+ const h = Math.floor(t / 3600);
+ const m = Math.floor((t % 3600) / 60);
+ const ss = String(t % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
+};
+
+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);
+ return m ? `${m[1]![0]!.toUpperCase()}${m[1]!.slice(1)} ${m[2]}${m[3] ? `.${m[3]}` : ""}` : id;
+}
+
+function when(iso: string | null): string {
+ if (!iso) return "";
+ const d = new Date(iso);
+ return Number.isNaN(d.getTime()) ? "" : `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
+}
+
+function citeLine(c: RunCite): string {
+ return [c.label ?? null, c.channel && c.video ? `${c.channel}/${c.video}` : (c.video ?? null), typeof c.start === "number" ? mmss(c.start) : null, c.citation ?? null].filter(Boolean).join(" · ");
+}
+
+function Ids({ ids, max = 160 }: { ids: string[]; max?: number }) {
+ const [all, setAll] = useState(false);
+ const shown = all ? ids : ids.slice(0, max);
+ return (
+ <div className="flex flex-wrap gap-1" data-ids="">
+ {shown.map((id, i) => (
+ <code key={`${id}-${i}`} className="rounded-[2px] border border-seam px-[5px] py-px font-mono text-[11px] text-text-2">
+ {id}
+ </code>
+ ))}
+ {ids.length > shown.length && (
+ <button type="button" className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => setAll(true)}>
+ + {thousands(ids.length - shown.length)} more
+ </button>
+ )}
+ </div>
+ );
+}
+
+/** Source words (the extractor's lines, a quote): the reader surface. */
+function Paper({ children, className, ...props }: React.ComponentProps<"div">) {
+ return (
+ <div className={cn("rounded-[2px] bg-reader px-3.5 py-2.5 text-reader-ink shadow-[inset_0_0_0_1px_var(--reader-edge)]", className)} {...props}>
+ {children}
+ </div>
+ );
+}
+
+function CheckRow({ c }: { c: RunCheck }) {
+ const tone = c.ok ? "kept" : c.dropped ? "dropped" : "refused";
+ return (
+ <li data-check={tone} className="grid grid-cols-[76px_minmax(0,1fr)] gap-x-3 border-b border-seam py-2 last:border-b-0">
+ <span
+ className={cn(
+ "font-mono text-[11px]",
+ tone === "kept" ? "text-kept-text" : tone === "dropped" ? "text-reject-text" : "text-doubt-text",
+ )}
+ >
+ {tone}
+ {c.round ? ` · r${c.round}` : ""}
+ </span>
+ <div className="grid min-w-0 gap-1">
+ {c.quote && (
+ <Paper className="py-1.5">
+ <p className="m-0 font-serif text-[14px] leading-[1.4]">“{c.quote}”</p>
+ <div className="mt-1 truncate font-mono text-[10.5px] text-reader-dim">{citeLine(c.cite)}</div>
+ </Paper>
+ )}
+ {c.claim && <p className="m-0 text-[12px] text-text-2">claim: {c.claim}</p>}
+ {c.reason && (
+ <p className={cn("m-0 text-[12px]", c.ok ? "text-muted-2" : "text-text")} data-check-reason="">
+ {c.ok ? c.reason : `why: ${c.reason}`}
+ </p>
+ )}
+ </div>
+ </li>
+ );
+}
+
+function Checks({ checks }: { checks: RunCheck[] }) {
+ const dropped = checks.filter((c) => c.dropped);
+ const refused = checks.filter((c) => !c.ok && !c.dropped);
+ const kept = checks.filter((c) => c.ok && c.stage === "final");
+ const extractKept = checks.filter((c) => c.ok && c.stage === "extract");
+ const group = (title: string, list: RunCheck[], key: string) =>
+ list.length > 0 && (
+ <section data-check-group={key}>
+ <h3 className="micro mb-1">
+ {title} <span className="font-mono normal-case tracking-normal text-meter">{list.length}</span>
+ </h3>
+ <ul className="m-0 list-none p-0">
+ {list.map((c, i) => (
+ <CheckRow key={`${key}-${i}`} c={c} />
+ ))}
+ </ul>
+ </section>
+ );
+ return (
+ <div className="grid gap-4">
+ {group("Dropped", dropped, "dropped")}
+ {group("Refused by a strict check", refused, "refused")}
+ {group("Kept", kept, "kept")}
+ {!kept.length && group("Kept in their windows", extractKept, "extract")}
+ </div>
+ );
+}
+
+function Detail({ step }: { step: RunStep }) {
+ const d = step.detail;
+ return (
+ <div className="grid gap-4" data-detail={step.id}>
+ <span className="micro">
+ {step.t !== "—" ? `${step.t} · ` : ""}
+ {step.label}
+ {step.stepUsd !== null ? ` · ${money(step.stepUsd)} this step` : ""}
+ </span>
+ {d.facts.length > 0 && (
+ <dl className="m-0 grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1 text-[12.5px]">
+ {d.facts.map(([k, v]) => (
+ <div key={k} className="contents">
+ <dt className="text-muted">{k}</dt>
+ <dd className="m-0 min-w-0 break-words text-text-2">{v}</dd>
+ </div>
+ ))}
+ </dl>
+ )}
+ {d.text && <p className="m-0 max-w-[72ch] whitespace-pre-wrap text-[12.5px] text-text-2" data-model-text="">{d.text}</p>}
+ {d.calls.length > 0 && (
+ <ul className="m-0 grid list-none gap-0.5 p-0 font-mono text-[11.5px] text-text-2" data-calls="">
+ {d.calls.map((c, i) => (
+ <li key={i} className="truncate">
+ <span className={c.error ? "text-reject-text" : "text-text"}>{c.name}</span>
+ {c.summary ? ` ${c.summary}` : ""}
+ {c.chars !== null ? <span className="text-muted-2"> → {thousands(c.chars)} chars</span> : null}
+ {c.error ? <span className="text-reject-text"> (error)</span> : null}
+ </li>
+ ))}
+ </ul>
+ )}
+ {d.enumerations.map((e, i) => (
+ <section key={`en-${i}`} data-enumeration="" className="grid gap-1.5">
+ <span className="text-[12.5px] text-text-2">
+ enumerate {e.query ? `“${e.query}”` : ""} · <b className="font-mono font-medium text-meter">{thousands(e.n)}</b> matched
+ {e.total !== null && e.total !== e.n ? ` of ${thousands(e.total)}` : ""}
+ {e.posts ? ` (${e.posts} posts)` : ""}
+ {e.partial ? <span className="text-doubt-text"> · COVERAGE PARTIAL</span> : null}
+ {e.unreached.length ? <span className="text-doubt-text"> · never reached: {e.unreached.join(", ")}</span> : null}
+ </span>
+ {e.ids.length > 0 && <Ids ids={e.ids} />}
+ </section>
+ ))}
+ {d.batches.map((b, i) => (
+ <section key={`b-${i}`} data-batch={b.k} className="grid gap-1.5">
+ <span className="text-[12.5px] text-text-2">
+ batch {b.k}
+ {b.of ? ` of ${b.of}` : ""} · {b.ids.length} ids{b.model ? ` · ${prettyModel(b.model)}` : ""}
+ {b.usd !== null ? ` · ${money(b.usd)}` : ""}
+ {b.cut ? <span className="text-doubt-text"> · cut at the extractor's input cap</span> : null}
+ </span>
+ <Ids ids={b.ids} max={60} />
+ {b.lines === null ? (
+ <p className="m-0 text-[12px] text-muted-2" data-lines-missing="">The extractor's lines were not kept (a run before the trace).</p>
+ ) : b.lines.length ? (
+ <Paper data-batch-lines="" className="max-h-[260px] overflow-auto">
+ {b.lines.map((l, k) => (
+ <p key={k} className="m-0 whitespace-pre-wrap font-serif text-[13.5px] leading-[1.45]">
+ {l}
+ </p>
+ ))}
+ </Paper>
+ ) : (
+ <p className="m-0 text-[12px] text-muted-2">The extractor returned nothing for this batch.</p>
+ )}
+ </section>
+ ))}
+ {d.reads.length > 0 && (
+ <section className="grid gap-1.5">
+ <span className="text-[12.5px] text-text-2">read</span>
+ {d.reads.map((r, i) => (
+ <div key={i} className="grid gap-1">
+ <span className="font-mono text-[11px] text-muted-2">{r.tool}</span>
+ <Ids ids={r.ids} max={40} />
+ </div>
+ ))}
+ </section>
+ )}
+ {d.findings.length > 0 && (
+ <ol className="m-0 grid list-none gap-3 p-0" data-findings="">
+ {d.findings.map((f, i) => (
+ <li key={i} className="grid gap-1">
+ <span className="micro">{f.section}</span>
+ <p className="m-0 text-[13px] text-text">{f.claim}</p>
+ {f.cites.filter((c) => c.quote).map((c, k) => (
+ <Paper key={k} className="py-1.5">
+ <p className="m-0 font-serif text-[14px] leading-[1.4]">“{c.quote}”</p>
+ <div className="mt-1 truncate font-mono text-[10.5px] text-reader-dim">{citeLine(c)}</div>
+ </Paper>
+ ))}
+ </li>
+ ))}
+ </ol>
+ )}
+ {d.checks.length > 0 && <Checks checks={d.checks} />}
+ {d.notes.map((n, i) => (
+ <p key={i} className="m-0 text-[12px] text-muted">
+ {n}
+ </p>
+ ))}
+ </div>
+ );
+}
+
+export default function RunView({ initial }: { initial: View }) {
+ const hydrated = useHydrated();
+ const [view, setView] = useState<View>(initial);
+ const [litId, setLitId] = useState<string | null>(null);
+ const [replaying, setReplaying] = useState(false);
+ const [status, setStatus] = useState<{ text: string; tone: "ok" | "error"; href?: string } | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [updated, setUpdated] = useState<string | null>(null);
+ const listRef = useRef<HTMLDivElement>(null);
+ const follow = useRef(initial.live);
+ const inflight = useRef(false);
+
+ // Live: poll while the run is, and while the tab is visible.
+ useEffect(() => {
+ if (!view.live) return;
+ let live = true;
+ const tick = async () => {
+ if (inflight.current || document.visibilityState === "hidden") return;
+ inflight.current = true;
+ try {
+ const r = await fetch(runApi(view.article, view.n, { run: view.run }), { cache: "no-store" });
+ const next = r.ok ? ((await r.json()) as View) : null;
+ if (live && next?.steps) {
+ setView(next);
+ setUpdated(new Date().toISOString());
+ }
+ } catch {
+ // the next tick asks again
+ } finally {
+ inflight.current = false;
+ }
+ };
+ const timer = window.setInterval(tick, POLL_MS);
+ const onVisible = () => {
+ if (document.visibilityState === "visible") void tick();
+ };
+ document.addEventListener("visibilitychange", onVisible);
+ return () => {
+ live = false;
+ window.clearInterval(timer);
+ document.removeEventListener("visibilitychange", onVisible);
+ };
+ }, [view.live, view.article, view.n, view.run]);
+
+ const lineOf = useCallback((id: string) => listRef.current?.querySelector<HTMLElement>(`[data-lit-line][data-lit-id="${CSS.escape(id)}"]`) ?? null, []);
+
+ // Following a live run: the newest step is lit as it lands (a click lights
+ // without taking focus), until the operator moves the light.
+ const lastId = view.steps.at(-1)?.id ?? null;
+ useEffect(() => {
+ if (!follow.current || !lastId) return;
+ lineOf(lastId)?.click();
+ }, [lastId, lineOf]);
+
+ const onLight = useCallback(
+ (d: LitDetail) => {
+ setLitId(d.id);
+ if (d.id !== lastId) follow.current = false;
+ else if (view.live) follow.current = true;
+ },
+ [lastId, view.live],
+ );
+
+ // Replay: light every step in turn from the first.
+ useEffect(() => {
+ if (!replaying) return;
+ const ids = view.steps.map((s) => s.id);
+ let i = 0;
+ follow.current = false;
+ const go = () => {
+ const el = lineOf(ids[i]!);
+ if (el) {
+ el.focus({ preventScroll: true });
+ el.scrollIntoView({ block: "nearest" });
+ }
+ i++;
+ if (i >= ids.length) setReplaying(false);
+ };
+ go();
+ const timer = window.setInterval(go, REPLAY_MS);
+ const stop = (e: Event) => {
+ if (e instanceof KeyboardEvent && (e.key === "r" || e.key === "R")) return;
+ setReplaying(false);
+ };
+ window.addEventListener("pointerdown", stop);
+ window.addEventListener("keydown", stop);
+ return () => {
+ window.clearInterval(timer);
+ window.removeEventListener("pointerdown", stop);
+ window.removeEventListener("keydown", stop);
+ };
+ }, [replaying, view.steps, lineOf]);
+
+ const openBoard = useCallback(async () => {
+ setBusy(true);
+ setStatus(null);
+ try {
+ const r = await fetch(runBoardApi(view.article, view.n), { method: "POST" });
+ const j = (await r.json().catch(() => null)) as { error?: string; id?: string; href?: string; created?: boolean; added?: number; already?: number } | null;
+ if (!r.ok || !j?.href) throw new Error(j?.error ?? `HTTP ${r.status}`);
+ setStatus({
+ tone: "ok",
+ href: j.href,
+ text: `${j.created ? "Board made" : "Board updated"}: ${j.added ?? 0} ${j.added === 1 ? "quote" : "quotes"} added${j.already ? `, ${j.already} already on it` : ""}`,
+ });
+ setView((v) => ({ ...v, board: { id: j.id!, quotes: (v.board?.quotes ?? 0) + (j.added ?? 0) } }));
+ } catch (e) {
+ setStatus({ tone: "error", text: (e as Error).message });
+ } finally {
+ setBusy(false);
+ }
+ }, [view.article, view.n]);
+
+ // Keys: r replays, b opens the board. Never while typing or with a modifier.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;
+ if ((e.target as HTMLElement | null)?.closest?.("input, textarea, select, [contenteditable], dialog")) return;
+ if (e.key === "r" && !view.live && view.steps.length) {
+ e.preventDefault();
+ setReplaying((x) => !x);
+ } else if (e.key === "b" && view.findings > 0 && !busy) {
+ e.preventDefault();
+ void openBoard();
+ }
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [view.live, view.steps.length, view.findings, busy, openBoard]);
+
+ const h = view.header;
+ const lit = view.steps.find((s) => s.id === litId) ?? view.steps[0] ?? null;
+ const points: SpendPoint[] = view.steps.filter((s) => s.usd !== null && s.kind !== "end").map((s) => ({ id: s.id, t: s.t === "—" ? s.kind : s.t, label: s.label, usd: s.usd! }));
+ const batches = view.steps.flatMap((s) => s.detail.batches);
+ const findingSteps = view.steps.find((s) => s.kind === "findings");
+ const sections = findingSteps ? new Set(findingSteps.detail.findings.map((f) => f.section)).size : 0;
+ const cov = h.coverage;
+ const checkNames = h.checks.map((c) => (
+ <span key={c.name} className="whitespace-nowrap" title={c.detail ?? undefined}>
+ {c.name} <span className={c.ok ? "text-kept-text" : "text-reject-text"}>{c.ok ? "ok" : "failed"}</span>
+ </span>
+ ));
+ const meta: React.ReactNode[] = [
+ view.kind,
+ [prettyModel(h.model), h.extractor ? `${prettyModel(h.extractor)} extractor` : null].filter(Boolean).join(" · "),
+ h.channels.join(", "),
+ h.dateFrom || h.dateTo ? `${h.dateFrom ?? "…"} – ${h.dateTo ?? "…"}` : null,
+ h.sourceLabel,
+ when(h.startedAt),
+ h.minutes !== null ? `${h.minutes} min` : null,
+ ].filter(Boolean);
+
+ return (
+ <>
+ <AppHeader
+ crumbs={[
+ { href: researchHref(), label: "research" },
+ { href: runsHref(), label: "runs" },
+ { href: articleHref({ site: ARTICLES_KEY, id: view.article }, { tab: "iterations" }), label: `${view.article} · ${view.label}` },
+ { label: h.question ?? h.title ?? `${view.article} ${view.label}` },
+ ]}
+ clamp
+ meta={
+ <span className="micro" data-run-mode={view.live ? "live" : "replay"}>
+ Run · {view.live ? "live" : "replay"}
+ {view.live && updated ? ` · updated ${updated.slice(11, 19)}` : ""}
+ {view.from === "turns" ? " · from turns.jsonl" : ""}
+ </span>
+ }
+ actions={
+ <>
+ {view.runs.length > 1 && (
+ <nav aria-label="Runs" className="flex items-center gap-1" data-run-picker="">
+ <span className="micro mr-1">Run</span>
+ {view.runs.map((r) => (
+ <Link
+ key={r.index}
+ prefetch={false}
+ href={runHref(view.article, view.n, { run: r.index })}
+ aria-current={r.index === view.run ? "page" : undefined}
+ title={[when(r.startedAt), r.usd !== null ? money(r.usd) : null, r.status].filter(Boolean).join(" · ")}
+ className={cn(
+ buttonVariants({ variant: r.index === view.run ? "outline" : "quiet", size: "sm" }),
+ "font-mono",
+ r.index === view.run && "border-muted text-text",
+ )}
+ >
+ {r.index}
+ </Link>
+ ))}
+ </nav>
+ )}
+ <button
+ type="button"
+ disabled={!hydrated || view.live || !view.steps.length}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ onClick={() => setReplaying((x) => !x)}
+ data-replay={replaying ? "on" : "off"}
+ >
+ {replaying ? "Stop" : "Replay"} <kbd>r</kbd>
+ </button>
+ <button type="button" disabled={!hydrated || busy || view.findings === 0} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void openBoard()} data-open-board="">
+ {view.board ? "Update the board" : "Open as a board"} <kbd>b</kbd>
+ </button>
+ </>
+ }
+ below={
+ <div className="grid gap-1.5 pt-1">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[12.5px] text-muted" data-run-meta="">
+ {meta.map((m, i) => (
+ <span key={i}>
+ {i > 0 && <span className="mr-2 text-seam-2">·</span>}
+ {m}
+ </span>
+ ))}
+ <span>
+ <span className="mr-2 text-seam-2">·</span>
+ <span className="font-mono text-meter" data-run-usd={h.usd ?? ""}>{money(h.usd)}</span> this run
+ {view.runs.length > 1 || (h.usd !== null && Math.abs((h.usd ?? 0) - h.iterationUsd) >= 0.01) ? (
+ <>
+ {" "}· <span className="font-mono text-meter">{money(h.iterationUsd)}</span> on the iteration
+ </>
+ ) : null}
+ </span>
+ {(h.kept !== null || h.dropped !== null) && (
+ <span data-run-checks="">
+ <span className="mr-2 text-seam-2">·</span>
+ {h.kept !== null ? `${h.kept} kept` : ""}
+ {h.kept !== null && h.dropped !== null ? " · " : ""}
+ {h.dropped !== null ? <span className={h.dropped ? "text-reject-text" : undefined}>{h.dropped} dropped</span> : null}
+ </span>
+ )}
+ {checkNames.length > 0 && (
+ <span className="flex flex-wrap gap-x-2">
+ <span className="text-seam-2">·</span>
+ {checkNames}
+ </span>
+ )}
+ <span>
+ <span className="mr-2 text-seam-2">·</span>
+ <span className={view.status === "failed" ? "text-reject-text" : view.status === "done" ? "text-text-2" : "text-signal-text"} data-run-status={view.status}>
+ {view.status}
+ </span>
+ </span>
+ </div>
+ {(view.notes.length > 0 || h.error) && (
+ <div className="grid gap-0.5 text-[12px] text-muted-2" data-run-notes="">
+ {view.notes.map((n) => (
+ <p key={n} className="m-0">
+ {n}
+ </p>
+ ))}
+ {h.error && <p className="m-0 text-reject-text">{h.error}</p>}
+ </div>
+ )}
+ </div>
+ }
+ />
+ {view.steps.length === 0 ? (
+ <div className="px-7 pt-6 text-center text-[12.5px] text-text-2" data-empty="">
+ {view.live ? "The run has not written a step yet." : "This iteration recorded no run (no trace.jsonl, no turns.jsonl)."}
+ </div>
+ ) : (
+ <div className="grid min-h-0 flex-1 grid-cols-[330px_minmax(0,1fr)] overflow-hidden">
+ <div ref={listRef} className="min-h-0 overflow-auto border-r border-seam pb-4 pt-2">
+ <LitList label="Steps" global initial={initial.live ? Math.max(0, initial.steps.length - 1) : 0} onLight={onLight}>
+ {view.steps.map((s) => (
+ <LitLine
+ key={s.id}
+ id={s.id}
+ data-step={s.kind}
+ data-gap={s.gap ? "" : undefined}
+ className="grid grid-cols-[34px_minmax(0,1fr)_auto] items-baseline gap-x-2.5 py-[7px]"
+ >
+ <span className="font-mono text-[11px] tabular-nums text-muted-2">{s.t}</span>
+ <span className={cn("min-w-0 font-mono text-[12px] font-medium", s.gap && "italic text-muted-2")}>
+ {s.label}
+ {s.sub && <small className="block truncate font-sans text-[11px] font-normal text-muted-2">{s.sub}</small>}
+ </span>
+ <span className="font-mono text-[11.5px] tabular-nums text-meter" data-step-usd={s.usd ?? ""}>
+ {s.gap ? "—" : s.usd !== null ? money(s.usd) : ""}
+ </span>
+ </LitLine>
+ ))}
+ </LitList>
+ </div>
+ <div className="grid min-h-0 content-start gap-[18px] overflow-auto px-[26px] py-[18px]">
+ <div className="grid grid-cols-3 gap-2.5" data-lanes="">
+ <div className="rounded-[3px] border border-seam bg-panel px-3 py-2.5">
+ <span className="micro mb-1.5 block">Batches</span>
+ <p className="m-0 text-[12.5px] text-text-2">
+ {batches.length ? (
+ <>
+ <span className="font-mono text-meter">{batches.length}</span>
+ {batches.some((b) => b.of) ? ` of ${Math.max(...batches.map((b) => b.of ?? 0))}` : ""} returned
+ {batches.every((b) => b.lines) ? ` · ${thousands(batches.reduce((n, b) => n + (b.lines?.length ?? 0), 0))} lines` : " · lines not kept"}
+ </>
+ ) : (
+ "none"
+ )}
+ </p>
+ </div>
+ <div className="rounded-[3px] border border-seam bg-panel px-3 py-2.5">
+ <span className="micro mb-1.5 block">Findings</span>
+ <p className="m-0 text-[12.5px] text-text-2" data-lane-findings="">
+ {findingSteps ? `${findingSteps.detail.findings.length} findings · ${sections} sections · ${view.findings} quotes` : view.live ? "not yet" : "none kept"}
+ </p>
+ </div>
+ <div className="rounded-[3px] border border-seam bg-panel px-3 py-2.5">
+ <span className="micro mb-1.5 block">Coverage</span>
+ <p className="m-0 text-[12.5px] text-text-2" data-lane-coverage="">
+ {cov ? (
+ <>
+ <span className="font-mono text-meter">{thousands(cov.matched)}</span> matched · <span className="font-mono text-meter">{thousands(cov.read)}</span> read ·{" "}
+ {cov.partial ? <span className="text-doubt-text">partial</span> : "complete"}
+ {cov.unreached.length ? ` · not reached: ${cov.unreached.join(", ")}` : ""}
+ </>
+ ) : (
+ "not recorded (a run before the trace)"
+ )}
+ </p>
+ </div>
+ </div>
+ {lit && <Detail step={lit} />}
+ <section>
+ <span className="micro">Spend by step, cumulative</span>
+ <SpendChart
+ points={points}
+ lit={lit?.id ?? null}
+ onPick={(id) => {
+ const el = lineOf(id);
+ el?.focus({ preventScroll: true });
+ el?.scrollIntoView({ block: "nearest" });
+ }}
+ />
+ </section>
+ </div>
+ </div>
+ )}
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-seam px-7 py-2 text-[11.5px] text-muted-2">
+ <KeyHint keys={["j", "k"]}>step</KeyHint>
+ <KeyHint keys={["r"]}>replay</KeyHint>
+ <KeyHint keys={["b"]}>open as a board</KeyHint>
+ <Link prefetch={false} href={articleHref({ site: ARTICLES_KEY, id: view.article }, { tab: "iterations" })} className="ink-link text-[12px]">
+ {view.article} · iterations
+ </Link>
+ {view.board && (
+ <Link prefetch={false} href={researchCaseHref(view.board.id)} className="ink-link text-[12px]" data-run-board={view.board.id}>
+ Board · {view.board.quotes} {view.board.quotes === 1 ? "quote" : "quotes"}
+ </Link>
+ )}
+ {status && (
+ <span role={status.tone === "error" ? "alert" : "status"} data-run-status-line="" className={`ml-auto text-[12px] ${status.tone === "error" ? "text-reject-text" : "text-text-2"}`}>
+ {status.text}
+ {status.href && (
+ <>
+ {" · "}
+ <Link prefetch={false} href={status.href} className="ink-link">
+ Open the board
+ </Link>
+ </>
+ )}
+ </span>
+ )}
+ </div>
+ </>
+ );
+}
diff --git a/umtool/components/research/SpendChart.tsx b/umtool/components/research/SpendChart.tsx
@@ -0,0 +1,133 @@
+"use client";
+
+import { useMemo, useRef, useState } from "react";
+
+// ---------------------------------------------------------------------------
+// A run's spend, step by step, CUMULATIVE (canvas "Transparent run", the
+// `.spark`): one series, so no legend -- the heading names it. A step line in
+// Meter (measurement only), 2 px; an 8 px marker per step; the lit step's
+// marker in Signal (the interaction colour: it is the step the list has lit);
+// the endpoint labelled with the total. Recessive grid: three hairlines with
+// their dollar labels.
+//
+// The hover layer: a crosshair snaps to the nearest step and a tooltip gives
+// the total (strong) and the step (secondary). Its hit target is the step's
+// whole column, not the dot. The same values are in the step list on the
+// left (its right column), so nothing here is reachable by hover only. A
+// click on a column lights that step (onPick).
+// ---------------------------------------------------------------------------
+
+export type SpendPoint = { id: string; t: string; label: string; usd: number };
+
+const W = 640;
+const H = 130;
+const L = 44;
+const R = 64;
+const T = 10;
+const B = 24;
+
+const money = (v: number) => `$${v.toFixed(2)}`;
+
+export default function SpendChart({ points, lit, onPick }: { points: SpendPoint[]; lit: string | null; onPick?: (id: string) => void }) {
+ const [hover, setHover] = useState<number | null>(null);
+ const ref = useRef<SVGSVGElement>(null);
+ const max = useMemo(() => {
+ const m = Math.max(0.01, ...points.map((p) => p.usd));
+ // A round top: the next 1, 2 or 5 step above the total.
+ const mag = 10 ** Math.floor(Math.log10(m));
+ const step = [1, 2, 2.5, 5, 10].map((k) => k * mag).find((s) => s >= m) ?? m;
+ return step;
+ }, [points]);
+ if (!points.length) return <p className="m-0 text-[12px] text-muted-2">No spend recorded yet.</p>;
+ const n = points.length;
+ const x = (i: number) => L + (n === 1 ? (W - L - R) / 2 : (i * (W - L - R)) / (n - 1));
+ const y = (v: number) => T + (1 - v / max) * (H - T - B);
+ let d = `M${x(0)},${y(points[0]!.usd)}`;
+ points.forEach((p, i) => {
+ if (i) d += ` H${x(i)} V${y(p.usd)}`;
+ });
+ const ticks = [0, max / 2, max];
+ // Thin the x labels so they never collide (about 34 px each).
+ const every = Math.max(1, Math.ceil(n / Math.floor((W - L - R) / 34)));
+ const litIndex = points.findIndex((p) => p.id === lit);
+ const last = points[n - 1]!;
+ const colW = n === 1 ? W - L - R : (W - L - R) / (n - 1);
+ const shown = hover ?? null;
+ const tip = shown !== null ? points[shown]! : null;
+
+ return (
+ <div className="relative" data-spend-chart="">
+ <svg
+ ref={ref}
+ viewBox={`0 0 ${W} ${H}`}
+ className="block h-[130px] w-full"
+ role="img"
+ aria-label={`Cumulative spend by step, ${money(points[0]!.usd)} at ${points[0]!.t} to ${money(last.usd)} at ${last.t}`}
+ onPointerLeave={() => setHover(null)}
+ >
+ {ticks.map((v) => (
+ <g key={v}>
+ <line x1={L} x2={W - R} y1={y(v)} y2={y(v)} stroke="var(--seam)" strokeWidth={1} />
+ <text x={L - 6} y={y(v) + 4} textAnchor="end" fill="var(--muted-2)" fontSize={10} fontFamily="var(--f-mono)">
+ {money(v)}
+ </text>
+ </g>
+ ))}
+ {points.map((p, i) =>
+ i % every === 0 || i === n - 1 ? (
+ <text key={`x-${p.id}`} x={x(i)} y={H - 6} textAnchor="middle" fill="var(--muted-2)" fontSize={10} fontFamily="var(--f-mono)">
+ {p.t}
+ </text>
+ ) : null,
+ )}
+ {tip && <line x1={x(shown!)} x2={x(shown!)} y1={T} y2={H - B} stroke="var(--seam-2)" strokeWidth={1} />}
+ <path d={d} fill="none" stroke="var(--meter)" strokeWidth={2} />
+ {points.map((p, i) => (
+ <circle
+ key={p.id}
+ cx={x(i)}
+ cy={y(p.usd)}
+ r={i === litIndex ? 5.5 : 4}
+ fill={i === litIndex ? "var(--signal)" : "var(--meter)"}
+ stroke="var(--ground)"
+ strokeWidth={2}
+ data-spend-point={p.id}
+ data-lit-point={i === litIndex ? "" : undefined}
+ />
+ ))}
+ <text x={x(n - 1) + 9} y={y(last.usd) + 4} fill="var(--text)" fontSize={11} fontFamily="var(--f-mono)" data-spend-end="">
+ {money(last.usd)}
+ </text>
+ {/* The hit layer: each step's whole column. */}
+ {points.map((p, i) => (
+ <rect
+ key={`hit-${p.id}`}
+ x={x(i) - colW / 2}
+ y={T}
+ width={Math.max(colW, 12)}
+ height={H - T - B}
+ fill="transparent"
+ className={onPick ? "cursor-pointer" : undefined}
+ onPointerEnter={() => setHover(i)}
+ onPointerMove={() => setHover(i)}
+ onClick={() => onPick?.(p.id)}
+ />
+ ))}
+ </svg>
+ {tip && (
+ <div
+ role="tooltip"
+ data-spend-tip=""
+ className="pointer-events-none absolute z-10 rounded-[3px] border border-seam-2 bg-panel px-2 py-1 text-[11.5px] shadow-[0_4px_14px_rgb(0_0_0/0.25)]"
+ style={{ left: `${Math.min(86, Math.max(2, (x(shown!) / W) * 100))}%`, top: 0, transform: "translate(-50%, -105%)" }}
+ >
+ <span className="mr-1.5 inline-block h-[2px] w-3 translate-y-[-3px] bg-meter align-middle" />
+ <b className="font-mono font-semibold text-text">{money(tip.usd)}</b>
+ <span className="ml-1.5 text-muted-2">
+ so far · {tip.t} {tip.label}
+ </span>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/components/shell/AppHeader.tsx b/umtool/components/shell/AppHeader.tsx
@@ -28,6 +28,7 @@ export default function AppHeader({
meta,
below,
variant = "page",
+ clamp = false,
className,
}: {
crumbs: Crumb[];
@@ -39,6 +40,8 @@ export default function AppHeader({
/** A full-width row at the foot of the head (a piece's stage stepper). */
below?: React.ReactNode;
variant?: "page" | "bench";
+ /** A long title (a run's question) wraps to two lines, its full text in `title`, instead of one truncated line. */
+ clamp?: boolean;
className?: string;
}) {
const trail = crumbs.slice(0, -1);
@@ -84,8 +87,10 @@ export default function AppHeader({
) : (
<h1
aria-current="page"
+ title={clamp ? here.label : undefined}
className={cn(
- "display m-0 truncate leading-none text-text",
+ "display m-0 text-text",
+ clamp ? "line-clamp-2 max-w-[1000px] leading-[1.15]" : "truncate leading-none",
here.label.length > 36 ? "text-[20px]" : "text-[26px]",
// A place (no trail) is a title in sentence case; a piece's id
// stays exactly as it is spelled.
diff --git a/umtool/e2e/board.spec.ts b/umtool/e2e/board.spec.ts
@@ -115,11 +115,12 @@ test("sections and order: a, alt+j/k across sections, the section menu; claim, n
// Light q1 and move it: down past q2, then on into the top of Approval.
await b.locator('[data-quote="q1"]').click({ position: { x: 8, y: 8 } });
await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q1");
+ // Two moves pressed at once: the second waits for the first's answer and is
+ // applied after it, never dropped -- q1 goes past q2, then past q3.
await page.keyboard.press("Alt+j");
- await expect.poll(() => caseJson("lighthouse-case").quotes.map((q: { id: string }) => q.id).join(" ")).toBe("q2 q1 q3");
- await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q1");
await page.keyboard.press("Alt+j");
await expect.poll(() => caseJson("lighthouse-case").quotes.map((q: { id: string }) => q.id).join(" ")).toBe("q2 q3 q1");
+ await expect(page.locator("[data-board-busy]")).toHaveCount(0);
await expect(litId(page)).toHaveAttribute("data-lit-id", "q:q1");
await page.keyboard.press("Alt+j");
await expect.poll(() => caseJson("lighthouse-case").quotes.find((q: { id: string }) => q.id === "q1").section).toBe("s1");
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -30,6 +30,7 @@ import { makeDeleteFixture } from "./delete-fixture.mjs";
import { makeDraftReviewFixture } from "./draft-review-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
+import { makeRunTraceFixture } from "./run-trace-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1935,6 +1936,9 @@ makeDeleteFixture({ dest, articles: ARTICLES, reports });
const { pub: RESEARCH_PUBLIC } = makeResearchFixture({ dest, channels: CHANNELS });
// R2: a research board with a drifted quote and an `en`-track one (REPORTS_ROOT is dest).
makeBoardFixture({ reportsRoot: dest, pub: RESEARCH_PUBLIC });
+// R3: transparent runs -- a traced sweep, an imported turns-only one with two
+// run starts, and one still running.
+makeRunTraceFixture({ articles: ARTICLES, source: `local:${RESEARCH_PUBLIC}` });
console.log(`fixture at ${dest}`);
console.log(` SITES_DIR=${SITES}`);
diff --git a/umtool/e2e/fixtures/run-trace-fixture.mjs b/umtool/e2e/fixtures/run-trace-fixture.mjs
@@ -0,0 +1,197 @@
+// The TRANSPARENT RUNS fixture (plans/umtool-redesign.md, R3): three sweep
+// iterations in the article store, for e2e/run-trace.spec.ts and
+// lib/research/runs.test.ts.
+//
+// runfix/iterations/1 a finished agent sweep with a trace.jsonl:
+// scope, an enumeration, a batch with the
+// extractor's lines, a quote refused then
+// repaired, a quote DROPPED (and why), two kept
+// findings, the end; coverage on the iteration;
+// its report.json cites the research fixture
+// runfix-turns/iterations/1 an imported run with only turns.jsonl, TWO run
+// starts (an import keeps every attempt): the
+// projection shows them as two runs
+// runfix-live/iterations/1 a sweep still RUNNING: its trace has a start, a
+// scope and one turn; the spec appends the rest
+//
+// Synthetic, like every fixture: the words are the research fixture's
+// invented lines.
+import { mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { ARCHIVE, DRIFTED_QUOTE, RESEARCH_PHRASE } from "./research-fixture.mjs";
+
+export const RUN_ARTICLE = "runfix";
+export const TURNS_ARTICLE = "runfix-turns";
+export const LIVE_ARTICLE = "runfix-live";
+/** The editor job the live run's iteration names (running.spec places a Running row by it). */
+export const LIVE_JOB = "e2e-run-live";
+export const RUN_QUESTION = "What did the harbor channels say about the lighthouse budget?";
+/** The quote the trace drops, and why. */
+export const DROPPED = {
+ quote: "the harbor master said the budget was always fine",
+ reason: 'not verbatim within 90 s of 1500 s: "the harbor master said the budget was always fine"',
+ claim: "The harbor master called the budget fine",
+};
+/** The quote refused in the first round, then repaired and kept. */
+export const REPAIRED = { was: `they voted the ${RESEARCH_PHRASE} down nine to one`, now: DRIFTED_QUOTE.now };
+export const KEPT_KEEPER = `the keeper never saw the ${RESEARCH_PHRASE}`;
+export const BATCH_LINE = `[34:04|2044] ${DRIFTED_QUOTE.now}`;
+
+const put = (file, value) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, typeof value === "string" ? value : `${JSON.stringify(value, null, 2)}\n`);
+};
+const jsonl = (rows) => rows.map((r) => JSON.stringify(r)).join("\n") + "\n";
+
+const AT = (s) => new Date(Date.parse("2026-10-14T09:00:00.000Z") + s * 1000).toISOString();
+const ev = (s, e) => ({ t: e.t, at: AT(s), run: e.run ?? 1, ...e });
+
+const iteration = (article, extra) => ({
+ format: "archilyzer-iteration",
+ version: 1,
+ article,
+ n: 1,
+ kind: "sweep",
+ parent: null,
+ copyOf: null,
+ status: "done",
+ usage: {},
+ steps: [],
+ createdAt: AT(0),
+ updatedAt: AT(80),
+ endedAt: AT(80),
+ ...extra,
+});
+
+/** The finished run's trace (an agent sweep): what common's sweep-agent writes. */
+export function finishedTrace(source = "local:/fixture/research-public") {
+ const cite = (video, start, extra = {}) => ({ channel: "harbor-radio", video, start, ...extra });
+ return [
+ ev(0, { t: "run", phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5", extractor: "claude-haiku-4-5" }),
+ ev(0, { t: "scope", source, channels: ["harbor-radio", "night-desk"], question: RUN_QUESTION, model: "claude-sonnet-5-5", extractor: "claude-haiku-4-5", origin: ARCHIVE, maxUsd: 2, batchSize: 10 }),
+ ev(4, { t: "cost", step: "turn 0", usd: 0.05, model: "claude-sonnet-5-5", total: 0.05, turn: 0, phase: "agent", calls: ["enumerate_matches"] }),
+ ev(5, { t: "enumerate", query: RESEARCH_PHRASE, n: 3, ids: ["hr-2022a", "nd-2023", "hr-2021a"], partial: false, unreached: [], total: 3, turn: 0, phase: "agent" }),
+ ev(9, { t: "cost", step: "turn 1", usd: 0.04, model: "claude-sonnet-5-5", total: 0.09, turn: 1, phase: "agent", calls: ["extract_batch"], text: "One batch of three." }),
+ ev(14, { t: "batch", k: 1, of: 1, ids: ["hr-2022a", "nd-2023", "hr-2021a"], lines: ["### Harbor Radio 80: the council vote", BATCH_LINE, "### Night Desk: the keeper", `[6:40|400] ${KEPT_KEEPER}`], model: "claude-haiku-4-5", usd: 0.01, turn: 1, phase: "agent" }),
+ ev(14, { t: "cost", step: "batch 1", usd: 0.01, model: "claude-haiku-4-5", total: 0.1, turn: 1, phase: "agent" }),
+ ev(20, { t: "cost", step: "turn 2", usd: 0.06, model: "claude-sonnet-5-5", total: 0.16, turn: 2, phase: "agent", calls: ["write_report"] }),
+ ev(21, { t: "note", text: "agent ended: end_turn", turn: 2, phase: "agent" }),
+ ev(22, { t: "check", quote: REPAIRED.was, cite: cite("hr-2022a", 2044, { citation: "c1" }), ok: false, reason: `not verbatim within 90 s of 2044 s: "${REPAIRED.was}"`, stage: "check", round: 1 }),
+ ev(22, { t: "check", quote: DROPPED.quote, cite: cite("hr-2021a", 1500, { citation: "c2" }), ok: false, reason: DROPPED.reason, stage: "check", round: 1 }),
+ ev(22, { t: "note", text: "2 quote problem(s) — one repair round", phase: "repair" }),
+ ev(30, { t: "cost", step: "repair turn 0", usd: 0.02, model: "claude-sonnet-5-5", total: 0.18, turn: 0, phase: "repair", calls: ["edit_report"] }),
+ ev(31, { t: "check", quote: DROPPED.quote, cite: cite("hr-2021a", 1500, { citation: "c2" }), ok: false, reason: DROPPED.reason, stage: "check", round: 2 }),
+ ev(31, { t: "check", quote: DROPPED.quote, cite: cite("hr-2021a", 1500, { citation: "c2" }), ok: false, reason: DROPPED.reason, stage: "drop", dropped: true, claim: DROPPED.claim }),
+ ev(32, { t: "finding", section: "The vote", claim: "The council voted the budget down", cites: [{ citation: "c1", kind: "video", channel: "harbor-radio", video: "hr-2022a", start: 2044, end: 2048, quote: REPAIRED.now }] }),
+ ev(32, { t: "finding", section: "The keeper", claim: "The keeper says he never saw it", cites: [{ citation: "c2", kind: "video", channel: "night-desk", video: "nd-2023", start: 400, end: 404, quote: KEPT_KEEPER }] }),
+ ev(32, { t: "check", quote: REPAIRED.now, cite: { citation: "c1", kind: "video", channel: "harbor-radio", video: "hr-2022a", start: 2044, end: 2048 }, ok: true, stage: "final", reason: "verbatim (strict)" }),
+ ev(32, { t: "check", quote: KEPT_KEEPER, cite: { citation: "c2", kind: "video", channel: "night-desk", video: "nd-2023", start: 400, end: 404 }, ok: true, stage: "final", reason: "verbatim (strict)" }),
+ ev(33, { t: "run", phase: "end", status: "done", summary: "“The lighthouse budget”: 2 section(s), 2 claim(s), 2 citation(s), 1 dropped — ~$0.18", usd: 0.18, minutes: 0.55, coverage: { matched: 3, read: 3, partial: false, unreached: [] } }),
+ ];
+}
+
+export const RUN_REPORT = {
+ format: "archilyzer-report",
+ version: 1,
+ id: RUN_ARTICLE,
+ kind: "sweep",
+ title: "The lighthouse budget",
+ citations: {
+ c1: { kind: "video", channel: "harbor-radio", id: "hr-2022a", start: 2044, end: 2048, quote: REPAIRED.now, label: "Harbor Radio 80: the council vote", date: "2022-02-11" },
+ c2: { kind: "video", channel: "night-desk", id: "nd-2023", start: 400, end: 404, quote: KEPT_KEEPER, label: "Night Desk: the keeper", date: "2023-09-01" },
+ },
+ sections: [
+ { id: "the-vote", title: "The vote", claims: [{ id: "k1", text: "The council voted the budget down", citations: ["c1"] }] },
+ { id: "the-keeper", title: "The keeper", claims: [{ id: "k2", text: "The keeper says he never saw it", citations: ["c2"] }] },
+ ],
+};
+
+/** An imported stopgap run's turns: two attempts (two "run started" notes), the turn's usd a running total. */
+export function twoStartTurns() {
+ const note = (s, text, stopgap) => ({ kind: "note", turn: 0, at: AT(s), text, ...(stopgap ? { stopgap } : {}) });
+ const resp = (s, turn, names, usd, text) => ({
+ kind: "response",
+ turn,
+ provider: "api",
+ at: AT(s),
+ stopReason: names.length ? "tool_use" : "end_turn",
+ content: [...(text ? [{ type: "text", text }] : []), ...names.map((name) => ({ type: "tool_use", name }))],
+ usage: {},
+ usd,
+ });
+ const tool = (turn, name, input, chars) => ({ kind: "tool", turn, name, input, result: "", chars, error: false, ms: 0 });
+ const sg = { question: RUN_QUESTION, channels: ["harbor-radio"] };
+ return [
+ note(0, `imported from the stopgap run ${TURNS_ARTICLE} (transcript.jsonl)`),
+ note(0, "stopgap run started: model claude-sonnet-5-5, extractor claude-haiku-4-5, cap $5", sg),
+ resp(2, 0, ["enumerate_matches"], 0.03),
+ tool(0, "enumerate_matches", { query: RESEARCH_PHRASE, channels: ["harbor-radio"] }, 1200),
+ resp(6, 1, ["extract_batch"], 0.07),
+ tool(1, "extract_batch", { video_ids: ["hr-2022a", "hr-2021a"], queries: [RESEARCH_PHRASE], directive: "what was said" }, 18),
+ resp(9, 2, [], 0.09, "Stopped: the extractor answered nothing."),
+ note(60, "stopgap run started: model claude-sonnet-5-5, extractor claude-haiku-4-5, cap $5", sg),
+ resp(62, 0, ["enumerate_matches"], 0.04),
+ tool(0, "enumerate_matches", { query: "council vote", channels: ["harbor-radio"] }, 900),
+ resp(66, 1, ["get_transcripts"], 0.1),
+ tool(1, "get_transcripts", { video_ids: ["hr-2022a"], queries: ["council vote"] }, 4100),
+ resp(70, 2, ["write_report"], 0.15),
+ tool(2, "write_report", {}, 92),
+ resp(72, 3, [], 0.16, "I wrote the report."),
+ ];
+}
+
+/** A run still going: started, scoped, one turn. The spec appends the rest. */
+export function liveTraceHead(source = "local:/fixture/research-public") {
+ return [
+ ev(0, { t: "run", phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5", extractor: "claude-haiku-4-5" }),
+ ev(0, { t: "scope", source, channels: ["harbor-radio"], question: "Is the ferry running?", model: "claude-sonnet-5-5", extractor: "claude-haiku-4-5", origin: ARCHIVE, maxUsd: 1 }),
+ ev(3, { t: "cost", step: "turn 0", usd: 0.03, model: "claude-sonnet-5-5", total: 0.03, turn: 0, phase: "agent", calls: ["enumerate_matches"] }),
+ ev(4, { t: "enumerate", query: "ferry", n: 2, ids: ["hr-2019a", "hr-2020a"], partial: false, unreached: [], turn: 0, phase: "agent" }),
+ ];
+}
+
+/** What the spec appends to the live run: its next turn. */
+export function liveTraceNext() {
+ return [ev(8, { t: "cost", step: "turn 1", usd: 0.05, model: "claude-sonnet-5-5", total: 0.08, turn: 1, phase: "agent", calls: ["get_transcripts"] })];
+}
+
+export const jsonLines = jsonl;
+
+export function makeRunTraceFixture({ articles, source }) {
+ const dir = (a) => path.join(articles, a, "iterations", "1");
+ put(
+ path.join(dir(RUN_ARTICLE), "iteration.json"),
+ iteration(RUN_ARTICLE, {
+ model: "claude-sonnet-5-5",
+ question: RUN_QUESTION,
+ scope: { channels: ["harbor-radio", "night-desk"] },
+ usage: { "claude-sonnet-5-5": { usd: 0.17, inputTokens: 30000, outputTokens: 2000, calls: 4 }, "claude-haiku-4-5": { usd: 0.01, inputTokens: 9000, outputTokens: 300, calls: 1 } },
+ minutes: 0.55,
+ checks: [{ name: "convert", ok: true }, { name: "quotes", ok: true, detail: "every quote verbatim (strict); 1 finding(s) dropped" }],
+ coverage: { matched: 3, read: 3, partial: false, unreached: [] },
+ }),
+ );
+ put(path.join(dir(RUN_ARTICLE), "trace.jsonl"), jsonl(finishedTrace(source)));
+ put(path.join(dir(RUN_ARTICLE), "report.json"), RUN_REPORT);
+
+ put(
+ path.join(dir(TURNS_ARTICLE), "iteration.json"),
+ iteration(TURNS_ARTICLE, {
+ model: "claude-sonnet-5-5",
+ question: RUN_QUESTION,
+ scope: { channels: ["harbor-radio"] },
+ usage: { "claude-sonnet-5-5": { usd: 0.16, inputTokens: 1000, outputTokens: 200, calls: 4 } },
+ minutes: 0.2,
+ checks: [{ name: "convert", ok: true }, { name: "verify-quotes", ok: true }],
+ imported: { from: "local-reports", run: TURNS_ARTICLE, at: AT(80), extractor: "claude-haiku-4-5" },
+ }),
+ );
+ put(path.join(dir(TURNS_ARTICLE), "turns.jsonl"), jsonl(twoStartTurns()));
+
+ put(
+ path.join(dir(LIVE_ARTICLE), "iteration.json"),
+ iteration(LIVE_ARTICLE, { model: "claude-sonnet-5-5", question: "Is the ferry running?", scope: { channels: ["harbor-radio"] }, status: "running", endedAt: undefined, jobId: LIVE_JOB }),
+ );
+ put(path.join(dir(LIVE_ARTICLE), "trace.jsonl"), jsonl(liveTraceHead(source)));
+ return { dir };
+}
diff --git a/umtool/e2e/run-trace.spec.ts b/umtool/e2e/run-trace.spec.ts
@@ -0,0 +1,195 @@
+import { test, expect, type Page } from "@playwright/test";
+import { appendFileSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { BOARD_CASE } from "./fixtures/research-fixture.mjs";
+import {
+ DROPPED,
+ KEPT_KEEPER,
+ LIVE_ARTICLE,
+ REPAIRED,
+ RUN_ARTICLE,
+ RUN_QUESTION,
+ TURNS_ARTICLE,
+ jsonLines,
+ liveTraceNext,
+} from "./fixtures/run-trace-fixture.mjs";
+import { researchCaseHref, researchHref } from "../lib/research/hrefs";
+import { runBoardId, runHref, runsHref } from "../lib/research/runs-hrefs";
+import { WARM_TIMEOUT, warm } from "./warm";
+
+// ---------------------------------------------------------------------------
+// Transparent runs (plans/umtool-redesign.md, R3) on the run fixture
+// (e2e/fixtures/run-trace-fixture.mjs): a traced sweep replayed step by step
+// with a dropped quote and its reason; an imported turns-only run whose two
+// starts are two runs; a run still going, followed live as its trace grows;
+// "Open as a board"; and a sweep planned from a case's scope.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const liveTrace = path.join(FIXTURE, "articles", LIVE_ARTICLE, "iterations", "1", "trace.jsonl");
+const runBoardDir = path.join(FIXTURE, ".umtool", "research", runBoardId(RUN_ARTICLE, 1));
+
+const steps = (page: Page) => page.getByRole("group", { name: "Steps" });
+const lit = (page: Page) => steps(page).locator("[data-lit-line][data-lit]");
+const step = (page: Page, id: string) => steps(page).locator(`[data-lit-line][data-lit-id="${id}"]`);
+const detail = (page: Page) => page.locator("[data-detail]");
+
+let liveHead = "";
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ liveHead = readFileSync(liveTrace, "utf8");
+ await warm(playwright, [runHref(RUN_ARTICLE, 1), runsHref(), `/api/research/runs/${RUN_ARTICLE}/1`, researchCaseHref(BOARD_CASE)]);
+});
+
+test.afterAll(() => {
+ // What the specs wrote, put back: the live trace, the run's board.
+ writeFileSync(liveTrace, liveHead);
+ rmSync(runBoardDir, { recursive: true, force: true });
+});
+
+test("a traced run: the head, its steps with their spend, the lit step's detail, a dropped quote and why", async ({ page }) => {
+ await page.goto(runHref(RUN_ARTICLE, 1));
+ await expect(page.locator("[data-run-mode]")).toHaveAttribute("data-run-mode", "replay");
+ // The question is the title (clamped to two lines, all of it in `title`); the run is in the trail.
+ const crumbs = page.getByRole("navigation", { name: "Breadcrumb" });
+ await expect(crumbs.locator("h1")).toHaveText(RUN_QUESTION);
+ await expect(crumbs.locator("h1")).toHaveAttribute("title", RUN_QUESTION);
+ await expect(crumbs.getByRole("link", { name: `${RUN_ARTICLE} · i1` })).toHaveAttribute("href", `/articles/${RUN_ARTICLE}?tab=iterations`);
+ const meta = page.locator("[data-run-meta]");
+ await expect(meta).toContainText("Sonnet 5.5 · Haiku 4.5 extractor");
+ await expect(meta).toContainText("harbor-radio, night-desk");
+ await expect(meta).toContainText("0.55 min");
+ await expect(page.locator("[data-run-usd]")).toHaveText("$0.18");
+ await expect(page.locator("[data-run-checks]")).toContainText("2 kept · 1 dropped");
+ // The rail lights Research; the trail reaches every run.
+ await expect(page.locator('a[aria-current][href="/research"]')).toBeVisible();
+ await expect(page.getByRole("navigation", { name: "Breadcrumb" }).getByRole("link", { name: "runs" })).toHaveAttribute("href", runsHref());
+
+ // The steps, in order, with the running spend.
+ await expect(steps(page).locator("[data-lit-line]")).toHaveCount(8);
+ expect(await steps(page).locator("[data-lit-line]").evaluateAll((els) => els.map((e) => e.getAttribute("data-lit-id")))).toEqual([
+ "scope",
+ "t0",
+ "t1",
+ "t2",
+ "r0",
+ "findings",
+ "checks",
+ "end",
+ ]);
+ await expect(step(page, "t1").locator("[data-step-usd]")).toHaveText("$0.10");
+ await expect(step(page, "checks")).toContainText("2 kept · 1 dropped");
+ await expect(page.locator("[data-lane-coverage]")).toContainText("3 matched · 3 read · complete");
+ await expect(page.locator("[data-spend-end]")).toHaveText("$0.18");
+
+ // The first step is lit: the scope.
+ await expect(lit(page)).toHaveAttribute("data-lit-id", "scope");
+ await expect(detail(page)).toContainText("lighthouse budget");
+ // j: the enumeration, its ids.
+ await steps(page).locator("[data-lit-line][data-lit]").focus();
+ await page.keyboard.press("j");
+ await expect(lit(page)).toHaveAttribute("data-lit-id", "t0");
+ await expect(detail(page).locator("[data-enumeration]")).toContainText("3 matched");
+ await expect(detail(page).locator("[data-ids] code")).toHaveCount(3);
+ // The batch: the extractor's own lines, on the reader surface.
+ await page.keyboard.press("j");
+ await expect(detail(page).locator("[data-batch-lines]")).toContainText(REPAIRED.now);
+ // The checks: the dropped quote, its reason; the refused one repaired and kept.
+ await step(page, "checks").click();
+ const dropped = detail(page).locator("[data-check-group=dropped] [data-check=dropped]");
+ await expect(dropped).toHaveCount(1);
+ await expect(dropped).toContainText(DROPPED.quote);
+ await expect(dropped.locator("[data-check-reason]")).toHaveText(`why: ${DROPPED.reason}`);
+ await expect(detail(page).locator("[data-check-group=kept] [data-check=kept]")).toHaveCount(2);
+ await expect(detail(page).locator("[data-check-group=refused]")).toContainText(REPAIRED.was);
+ // The spend chart lights the same step.
+ await step(page, "t2").click();
+ await expect(page.locator("[data-spend-point=t2]")).toHaveAttribute("data-lit-point", "");
+});
+
+test("replay: r lights every step in turn, from the first to the end", async ({ page }) => {
+ await page.goto(runHref(RUN_ARTICLE, 1));
+ await expect(steps(page)).toHaveAttribute("data-hydrated", "");
+ await page.locator("body").press("r");
+ await expect(page.locator("[data-replay]")).toHaveAttribute("data-replay", "on");
+ // Each step is lit for 650 ms: watch every frame, not the assertion's backed-off retries.
+ await page.waitForFunction(() => document.querySelector("[data-lit-line][data-lit]")?.getAttribute("data-lit-id") === "t2", null, { polling: "raf", timeout: 10_000 });
+ await expect(lit(page)).toHaveAttribute("data-lit-id", "end", { timeout: 10_000 });
+ await expect(page.locator("[data-replay]")).toHaveAttribute("data-replay", "off");
+});
+
+test("a run before the trace: turns.jsonl with two run starts is two runs, never summed; its checks are a gap", async ({ page }) => {
+ await page.goto(runHref(TURNS_ARTICLE, 1));
+ await expect(page.locator("[data-run-mode]")).toContainText("from turns.jsonl");
+ const picker = page.getByRole("navigation", { name: "Runs" });
+ await expect(picker.getByRole("link")).toHaveCount(2);
+ await expect(picker.getByRole("link", { name: "2" })).toHaveAttribute("aria-current", "page");
+ await expect(page.locator("[data-run-notes]")).toContainText("2 run starts");
+ expect(await steps(page).locator("[data-lit-line]").evaluateAll((els) => els.map((e) => e.getAttribute("data-lit-id")))).toEqual(["scope", "t0", "t1", "t2", "t3", "checks"]);
+ await expect(step(page, "checks")).toHaveAttribute("data-gap", "");
+ await expect(step(page, "checks")).toContainText("kept / dropped not recorded");
+ await expect(page.locator("[data-run-usd]")).toHaveText("$0.16");
+ await expect(page.locator("[data-lane-coverage]")).toContainText("not recorded");
+
+ await picker.getByRole("link", { name: "1" }).click();
+ await expect(page).toHaveURL(new RegExp(`/research/runs/${TURNS_ARTICLE}/1\\?run=1$`));
+ await expect(picker.getByRole("link", { name: "1" })).toHaveAttribute("aria-current", "page");
+ await expect(page.locator("[data-run-usd]")).toHaveText("$0.09");
+ expect(await steps(page).locator("[data-lit-line]").evaluateAll((els) => els.map((e) => e.getAttribute("data-lit-id")))).toEqual(["scope", "t0", "t1", "t2", "checks"]);
+ await step(page, "t1").click();
+ await expect(detail(page).locator("[data-lines-missing]")).toBeVisible();
+});
+
+test("live: a running sweep's page follows its trace as it grows", async ({ page }) => {
+ await page.goto(runHref(LIVE_ARTICLE, 1));
+ await expect(page.locator("[data-run-mode]")).toHaveAttribute("data-run-mode", "live");
+ await expect(steps(page).locator("[data-lit-line]")).toHaveCount(2);
+ await expect(lit(page)).toHaveAttribute("data-lit-id", "t0");
+ appendFileSync(liveTrace, jsonLines(liveTraceNext()));
+ await expect(step(page, "t1")).toBeVisible({ timeout: 10_000 });
+ await expect(lit(page)).toHaveAttribute("data-lit-id", "t1");
+ await expect(page.locator("[data-run-usd]")).toHaveText("$0.08");
+ await expect(page.getByRole("button", { name: /^Replay/ })).toBeDisabled();
+});
+
+test("open as a board: the run's kept findings become quotes by the agent; the board links back", async ({ page }) => {
+ await page.goto(runHref(RUN_ARTICLE, 1));
+ await page.getByRole("button", { name: /^Open as a board/ }).click();
+ const status = page.locator("[data-run-status-line]");
+ await expect(status).toContainText("Board made: 2 quotes added");
+ await status.getByRole("link", { name: "Open the board" }).click();
+ await expect(page).toHaveURL(new RegExp(`/research/${runBoardId(RUN_ARTICLE, 1)}$`));
+ const board = page.getByRole("group", { name: "Board" });
+ await expect(board.locator("[data-quote]")).toHaveCount(2);
+ await expect(board.locator("[data-by=agent]")).toHaveCount(2);
+ await expect(board.locator("[data-slip]").first()).toContainText(REPAIRED.now);
+ await expect(board).toContainText(KEPT_KEEPER);
+ await expect(page.locator("[data-case-run]").getByRole("link")).toHaveAttribute("href", runHref(RUN_ARTICLE, 1));
+ // Again: nothing added twice; the button says it updates.
+ await page.goto(runHref(RUN_ARTICLE, 1));
+ await page.getByRole("button", { name: /^Update the board/ }).click();
+ await expect(page.locator("[data-run-status-line]")).toContainText("Board updated: 0 quotes added, 2 already on it");
+});
+
+test("a case's scope: Run a sweep on this scope plans it (no seed, the model and cap shown); the runs index lists every sweep", async ({ page }) => {
+ await page.goto(researchCaseHref(BOARD_CASE));
+ await page.getByRole("button", { name: "Run a sweep on this scope" }).click();
+ const dlg = page.locator('dialog[data-handoff="sweep"]');
+ await expect(dlg).toContainText("Run a sweep on this scope");
+ await expect(dlg).toContainText("Corpus");
+ await expect(dlg).not.toContainText("the board as cited markdown");
+ await expect(dlg).toContainText(/Runs on\s*(claude-|qwen)/);
+ await expect(dlg.getByRole("button", { name: /^Start the sweep/ })).toBeVisible();
+ await page.keyboard.press("Escape");
+ await expect(dlg).toBeHidden();
+
+ await page.goto(researchHref());
+ await page.getByRole("link", { name: "Agent runs" }).click();
+ await expect(page).toHaveURL(/\/research\/runs$/);
+ for (const a of [RUN_ARTICLE, TURNS_ARTICLE, LIVE_ARTICLE]) await expect(page.locator(`[data-run-row="${a}/1"]`)).toBeVisible();
+ await page.locator(`[data-run-row="${RUN_ARTICLE}/1"]`).getByRole("link").click();
+ await expect(page).toHaveURL(new RegExp(`/research/runs/${RUN_ARTICLE}/1$`));
+});
diff --git a/umtool/e2e/running.spec.ts b/umtool/e2e/running.spec.ts
@@ -3,6 +3,8 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs";
+import { LIVE_ARTICLE, LIVE_JOB } from "./fixtures/run-trace-fixture.mjs";
+import { runHref } from "../lib/research/runs-hrefs";
// ---------------------------------------------------------------------------
// P2b: what is running, in the rail, and drafts as decisions in the Inbox.
@@ -84,14 +86,14 @@ test("the rail lists the editor's running and queued jobs, a draft's spend, and
// A running draft: its kind in words, its article (from the log's first
// line: no iteration names the job), its live spend in Meter, its turns,
- // a bar -- and a link to the article's iterations, not the editor.
+ // a bar -- and, a sweep, a link to its run page (R3), not the editor.
const draft = r.locator("[data-running=e2e-draft-run]");
await expect(draft).toHaveAttribute("data-running-state", "running");
await expect(draft.locator("[data-running-kind]")).toHaveText("Report draft");
await expect(draft.locator("[data-running-spend]")).toHaveText("$0.31");
await expect(draft.locator("[data-running-target]")).toHaveText("zeta i7 · 3/12 turns");
await expect(draft.locator("[data-job-progress]")).toHaveAttribute("data-job-progress", "25");
- await expect(draft.locator("a")).toHaveAttribute("href", "/articles/zeta?tab=iterations");
+ await expect(draft.locator("a")).toHaveAttribute("href", runHref("zeta", 7));
// A sync: its channel, its count; it has no piece, so it links the editor's /jobs.
const sync = r.locator("[data-running=e2e-sync]");
@@ -153,6 +155,25 @@ test("nothing running, the editor's token unset, and an editor that does not ans
await expect(r.locator("[data-today-spend]")).toHaveText("$0.42 today");
});
+test("a report-draft row links its run page when it is a sweep (R3), its article's iterations when not", async ({ page }) => {
+ await editorJobs(page.request, "ok", [
+ // Placed by its iteration's jobId (the run fixture's live sweep).
+ { id: LIVE_JOB, kind: "report-draft", status: "running", queuedAt: NOW - 20_000, startedAt: NOW - 20_000 },
+ // Placed by its log: a narration step, not a sweep.
+ { id: "e2e-draft-narrate", kind: "report-draft", status: "running", queuedAt: NOW - 10_000, startedAt: NOW - 10_000, log: ["narrate of zeta i1 on qwen3:8b (the local model)"] },
+ ]);
+ await page.goto("/tools");
+ const r = running(page);
+ const sweep = r.locator(`[data-running=${LIVE_JOB}]`);
+ await expect(sweep.locator("[data-running-target]")).toContainText(`${LIVE_ARTICLE} i1`);
+ await expect(sweep.locator("a")).toHaveAttribute("href", runHref(LIVE_ARTICLE, 1));
+ await expect(r.locator("[data-running=e2e-draft-narrate] a")).toHaveAttribute("href", "/articles/zeta?tab=iterations");
+ // The link lands on the live run.
+ await sweep.locator("a").click();
+ await expect(page).toHaveURL(new RegExp(`/research/runs/${LIVE_ARTICLE}/1$`));
+ await expect(page.locator("[data-run-mode]")).toHaveAttribute("data-run-mode", "live");
+});
+
// ─── Drafts as decisions ────────────────────────────────────────────────────
const DRAFTS = "reports/p2b-drafts";
diff --git a/umtool/lib/activity.ts b/umtool/lib/activity.ts
@@ -9,6 +9,7 @@ import { askEditor, EditorError, editorUrl, type EditorErrorReason } from "./art
import { ARTICLES_KEY } from "./articles/key.mjs";
import { sitesPaths } from "./articles/sites";
import { articleHref, mixHref, projectHref } from "./hrefs";
+import { hasRunPage, runHref } from "./research/runs-hrefs";
import { recentJobs as recentChainJobs, runningJob, type Job } from "./jobs";
import { recentJobs as recentRenders, type RenderJob } from "./mix";
import { labelFor } from "./paths";
@@ -114,6 +115,12 @@ export function entryStates(events: Record<string, unknown>[]): ActivityProgress
const storeArticleHref = (article: string) => articleHref({ site: ARTICLES_KEY, id: article }, { tab: "iterations" });
+// A report-draft SWEEP links its run page (R3, /research/runs/<article>/<n>:
+// the steps live, as it runs); any other placed job its article's iterations.
+function placeHref(j: { kind?: string }, place: JobPlace): string {
+ return j.kind === "report-draft" && !place.research && hasRunPage(place.task) ? runHref(place.article, place.n) : storeArticleHref(place.article);
+}
+
function fromChain(j: Job): ActivityItem {
const entries = entryStates(j.events);
const start = j.events.find((e) => e.ev === "start") as { entries?: number } | undefined;
@@ -311,7 +318,7 @@ function editorItem(j: EditorJob, place: JobPlace | null, rank: number, spend: n
error: null,
meter: queued ? { fraction: null, text: queueText(j.queue) } : { fraction: p?.fraction ?? null, text: p?.text ?? null },
...(rank === 0 ? { generation: true, spend } : {}),
- href: place ? storeArticleHref(place.article) : jobsHref,
+ href: place ? placeHref(j, place) : jobsHref,
...(place ? {} : { external: true }),
rank,
lane: isLane(j.kind),
diff --git a/umtool/lib/research/boards.test.ts b/umtool/lib/research/boards.test.ts
@@ -178,3 +178,30 @@ test("hand-off to a video: a plan, then a project whose timeline is the board's
assert.match(again.refusals.join(" "), /already exists/);
assert.equal((await boards.readCase("lighthouse-budget")).handoffs.length, 2);
});
+
+test("R3: a sweep on the case's scope — no seed, the policy's route (Claude Code's runs the API agent); confirmed, it answers the run's page", async () => {
+ const { boards, handoff } = lib;
+ // The stand-in policy routes sweeps to Claude Code: a session's, so the API agent runs it, and the plan says so.
+ const { plan } = await handoff.planScopeSweep("lighthouse-budget");
+ assert.equal(plan.seeded, false);
+ assert.equal(plan.seed.chars, 0);
+ assert.deepEqual(plan.refusals, []);
+ assert.match(plan.warnings.join(" "), /routes sweeps to Claude Code, which runs in a session; this sweep runs the API agent on claude-sonnet-5-5/);
+ assert.equal(plan.model, "claude-sonnet-5-5");
+ assert.equal(plan.capUsd, 4);
+ assert.deepEqual(plan.channels.sort(), ["harbor-radio", "harbor-radio-rumble", "night-desk"]);
+ // A local model named for it: no cap, no extractor.
+ const local = (await handoff.planScopeSweep("lighthouse-budget", { model: "qwen3:8b" })).plan;
+ assert.deepEqual([local.model, local.capUsd, local.extractor ?? null], ["qwen3:8b", null, null]);
+ const before = asked.length;
+ const out = await handoff.confirmScopeSweep("lighthouse-budget", {});
+ assert.deepEqual(out, { href: "/research/runs/lighthouse-budget/1", jobId: "job-1", iteration: 1 });
+ const sent = asked.slice(before).find((a) => a.url === "/api/ops/report-draft")!.body;
+ assert.equal(sent.task, "sweep");
+ assert.equal(sent.seed, undefined, "no seed: the scope alone");
+ assert.equal(sent.model, "claude-sonnet-5-5");
+ assert.equal(sent.question, "lighthouse budget");
+ assert.equal(sent.source, source);
+ const h = (await boards.readCase("lighthouse-budget")).handoffs.at(-1)!;
+ assert.match(h.what!, /^a sweep on the scope: lighthouse-budget i1, job job-1$/);
+});
diff --git a/umtool/lib/research/case-types.ts b/umtool/lib/research/case-types.ts
@@ -85,6 +85,8 @@ export type Quote = {
verify?: QuoteVerify;
/** Earlier words, kept when the operator took the current ones. */
history?: { text: string; at: string; why: string }[];
+ /** R3: a finding an agent's sweep kept ("Open as a board" on a run), not a person's pin. */
+ by?: "agent";
};
export type CaseSection = { id: string; title: string };
@@ -117,6 +119,8 @@ export type CaseDoc = {
quotes: Quote[];
notes: string;
handoffs: CaseHandoff[];
+ /** R3: the agent run this board was opened from (`/research/runs/<article>/<n>`). */
+ run?: { article: string; n: number; at: string };
counters: { quote: number; section: number };
createdAt: string;
updatedAt: string;
@@ -163,9 +167,13 @@ export type ArticlePlan = {
dateTo?: string;
source: string;
model: string | null;
+ /** The API agent's extractor (the policy's), when the sweep runs on Claude. */
+ extractor?: string | null;
route: string | null;
capUsd: number | null;
- /** The board as cited markdown: the sweep's report starts from it (seed.md). */
+ /** False: R3's "Run a sweep on this scope" -- no seed, the policy's sweep route. */
+ seeded?: boolean;
+ /** The board as cited markdown: the sweep's report starts from it (seed.md). Empty when not seeded. */
seed: { chars: number; quotes: number };
spends: true;
refusals: string[];
diff --git a/umtool/lib/research/cases.mjs b/umtool/lib/research/cases.mjs
@@ -188,6 +188,8 @@ function cleanQuote(q, sectionIds) {
speakerChecked: q.speakerChecked === true,
pinnedAt: str(q.pinnedAt, 40),
...(typeof q.query === "string" && q.query ? { query: q.query.slice(0, 500) } : {}),
+ // R3: a finding an agent's sweep kept (lib/research/runs-board.ts), not a person's pin.
+ ...(q.by === "agent" ? { by: "agent" } : {}),
...(verify ? { verify } : {}),
...(history.length ? { history } : {}),
};
@@ -245,6 +247,10 @@ export function normaliseCase(raw, id) {
quotes,
notes: str(raw.notes, NOTES_LIMIT),
handoffs,
+ // R3: the agent run a board was opened from (lib/research/runs-board.ts).
+ ...(raw.run && typeof raw.run === "object" && typeof raw.run.article === "string" && Number.isInteger(raw.run.n) && raw.run.n > 0
+ ? { run: { article: raw.run.article.slice(0, 64), n: raw.run.n, at: str(raw.run.at, 40) } }
+ : {}),
counters: {
quote: counter(raw.counters?.quote, maxOf(quotes, /^q(\d+)$/)),
section: counter(raw.counters?.section, maxOf(sections, /^s(\d+)$/)),
@@ -526,7 +532,7 @@ export const sameCite = (a, b) =>
* back where an undo took it from.
*
* @param {ReturnType<typeof normaliseCase>} doc
- * @param {{ text: string, cite: object, claim?: string, note?: string, section?: string | null, query?: string, at?: number }} snap
+ * @param {{ text: string, cite: object, claim?: string, note?: string, section?: string | null, query?: string, at?: number, by?: "agent" }} snap
* @param {{ search?: object, scope?: object, now?: Date }} [ctx]
*/
export function addQuote(doc, snap, ctx = {}) {
@@ -559,6 +565,7 @@ export function addQuote(doc, snap, ctx = {}) {
speakerChecked: false,
pinnedAt: now,
query: snap.query ?? search?.query ?? doc.scope.query,
+ ...(snap.by === "agent" ? { by: "agent" } : {}),
},
new Set(doc.sections.map((s) => s.id)),
);
diff --git a/umtool/lib/research/handoff.ts b/umtool/lib/research/handoff.ts
@@ -10,6 +10,8 @@ import { REPORTS_ROOT } from "../paths.mjs";
import { invalidateProjects } from "../projects";
import { scaffoldReportVideo, SLUG_RE } from "../projects/scaffold.mjs";
import { exportMarkdown, localOnlyQuotes } from "./board.mjs";
+import { isLocalOnly } from "./rules.mjs";
+import { runHref } from "./runs-hrefs";
import { CaseError, recordHandoff } from "./cases.mjs";
import { boardGroups, caseView, mutateBoard } from "./boards";
import type { ArticlePlan, CaseDoc, VideoPlan } from "./case-types";
@@ -35,6 +37,13 @@ import type { ArticlePlan, CaseDoc, VideoPlan } from "./case-types";
// pinned quote, in board order, its window the quote's cue span. It spends
// nothing; it writes a project.
//
+// "Run a sweep on this scope" (R3) is the same door without the seed: a
+// report-draft sweep over the case's scope (its query, channels, dates and
+// source), on the policy's sweep route -- the API agent and its extractor, or
+// the local pipeline; a route to Claude Code (a session's, not a job's) runs
+// the API agent, as a seeded sweep does -- planned and confirmed the same way, and answered with
+// the run's page (/research/runs/<article>/<n>), which follows it live.
+//
// RESEARCH RULES: a board holding a local-only quote (Candace's channels,
// rules.mjs) never hands off to an article -- the article store publishes.
// Its video project is local, and the plan says it must stay so.
@@ -51,45 +60,69 @@ function channelsOf(doc: CaseDoc): string[] {
// ── the article ──
-export async function planArticle(id: string, over: { article?: string; model?: string; question?: string } = {}): Promise<{ plan: ArticlePlan; seed: string }> {
+export async function planArticle(
+ id: string,
+ over: { article?: string; model?: string; question?: string } = {},
+ o: { seeded?: boolean } = {},
+): Promise<{ plan: ArticlePlan; seed: string }> {
+ const seeded = o.seeded !== false;
const view = await caseView(id);
const doc = view.case;
const refusals: string[] = [];
const warnings: string[] = [];
const article = (over.article ?? doc.id).trim();
if (!isReportId(article)) refusals.push(`"${article}" is not an article id (lowercase letters, digits and dashes)`);
- if (!doc.quotes.length) refusals.push("the board has no quotes: pin some first");
+ if (seeded && !doc.quotes.length) refusals.push("the board has no quotes: pin some first");
const local = localOnlyQuotes(doc).length;
- if (local) refusals.push(`${local} ${local === 1 ? "quote is" : "quotes are"} from a local-only channel: an article can be published, so this board never becomes one (export the markdown instead)`);
+ if (local && seeded) refusals.push(`${local} ${local === 1 ? "quote is" : "quotes are"} from a local-only channel: an article can be published, so this board never becomes one (export the markdown instead)`);
const channels = channelsOf(doc);
- if (!channels.length) refusals.push("the board names no channel to sweep");
+ if (!channels.length) refusals.push(seeded ? "the board names no channel to sweep" : "the case's scope names no channel: set the scope's channels (search and pin first)");
+ const localChannels = channels.filter((c) => isLocalOnly(c));
+ if (!seeded && localChannels.length) refusals.push(`${localChannels.join(", ")} ${localChannels.length === 1 ? "is" : "are"} local-only: a sweep makes an article, which can be published`);
const question = (over.question ?? doc.scope.query ?? doc.title).trim();
- const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length;
- if (drifted) warnings.push(`${drifted} ${drifted === 1 ? "quote" : "quotes"} drifted or missing at the last re-verify: the sweep checks every quote again`);
- const unverified = doc.quotes.filter((q) => !q.verify).length;
- if (unverified) warnings.push(`${unverified} ${unverified === 1 ? "quote was" : "quotes were"} never re-verified`);
- const unchecked = doc.quotes.filter((q) => !q.speakerChecked && q.cite.kind !== "post").length;
- if (unchecked) warnings.push(`${unchecked} with the speaker not checked: the seed says so on each`);
+ if (seeded) {
+ const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length;
+ if (drifted) warnings.push(`${drifted} ${drifted === 1 ? "quote" : "quotes"} drifted or missing at the last re-verify: the sweep checks every quote again`);
+ const unverified = doc.quotes.filter((q) => !q.verify).length;
+ if (unverified) warnings.push(`${unverified} ${unverified === 1 ? "quote was" : "quotes were"} never re-verified`);
+ const unchecked = doc.quotes.filter((q) => !q.speakerChecked && q.cite.kind !== "post").length;
+ if (unchecked) warnings.push(`${unchecked} with the speaker not checked: the seed says so on each`);
+ }
const articleExists = isReportId(article) ? await exists(articleDir(sitesPaths(), article)) : false;
if (articleExists) warnings.push(`the article "${article}" exists: the sweep adds an iteration to it`);
let model: string | null = null;
+ let extractor: string | null = null;
let route: string | null = null;
let capUsd: number | null = null;
let policyError: string | undefined;
try {
const p = await readPolicy();
route = p.generation.routes.sweep;
- model = over.model?.trim() || p.generation.models.api;
- capUsd = Math.min(p.generation.caps.sweep, p.generation.caps.max);
- if (route !== "api") warnings.push(`the policy routes sweeps to ${route === "code" ? "Claude Code" : "the local model"}; a seeded sweep runs the API agent on ${model}`);
+ if (seeded) {
+ model = over.model?.trim() || p.generation.models.api;
+ if (route !== "api") warnings.push(`the policy routes sweeps to ${route === "code" ? "Claude Code" : "the local model"}; a seeded sweep runs the API agent on ${model}`);
+ } else if (over.model?.trim()) {
+ model = over.model.trim();
+ } else if (route === "code") {
+ // Claude Code runs in a session, not as an editor job: the API agent
+ // runs it here, as a seeded sweep does, and the plan says so.
+ model = p.generation.models.api;
+ warnings.push(`the policy routes sweeps to Claude Code, which runs in a session; this sweep runs the API agent on ${model}`);
+ } else {
+ model = route === "api" ? p.generation.models.api : p.generation.models.local;
+ }
+ if (model?.startsWith("claude-")) {
+ capUsd = Math.min(p.generation.caps.sweep, p.generation.caps.max);
+ extractor = p.generation.models.extractor;
+ }
} catch (e) {
policyError = (e as Error).message;
model = over.model?.trim() || null;
}
- if (model && !model.startsWith("claude-")) refusals.push(`a seeded sweep runs on a Claude model, not ${model}: the local pipeline writes its report from scratch`);
+ if (seeded && model && !model.startsWith("claude-")) refusals.push(`a seeded sweep runs on a Claude model, not ${model}: the local pipeline writes its report from scratch`);
- const seed = exportMarkdown(doc, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) });
+ const seed = seeded ? exportMarkdown(doc, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) }) : "";
return {
plan: {
to: "article",
@@ -101,9 +134,11 @@ export async function planArticle(id: string, over: { article?: string; model?:
...(doc.scope.dateTo ? { dateTo: doc.scope.dateTo } : {}),
source: doc.scope.source,
model,
+ extractor,
route,
capUsd,
- seed: { chars: seed.length, quotes: doc.quotes.length },
+ seeded,
+ seed: { chars: seed.length, quotes: seeded ? doc.quotes.length : 0 },
spends: true,
refusals,
warnings,
@@ -136,6 +171,31 @@ export async function confirmArticle(id: string, over: { article?: string; model
return { href, jobId: answer.jobId, iteration: answer.iteration };
}
+// ── a sweep on the case's scope (R3) ──
+
+export const planScopeSweep = (id: string, over: { article?: string; model?: string; question?: string } = {}) => planArticle(id, over, { seeded: false });
+
+export async function confirmScopeSweep(id: string, over: { article?: string; model?: string; question?: string }): Promise<{ href: string; jobId: string; iteration: number }> {
+ const { plan } = await planScopeSweep(id, over);
+ if (plan.refusals.length) throw new CaseError(plan.refusals.join("; "), 409);
+ if (plan.policyError) throw new CaseError(`the editor cannot be asked: ${plan.policyError}`, 502);
+ const answer = await enqueueDraft({
+ task: "sweep",
+ article: plan.article,
+ question: plan.question,
+ channels: plan.channels,
+ from: plan.dateFrom,
+ to: plan.dateTo,
+ source: plan.source,
+ model: plan.model,
+ });
+ const href = runHref(plan.article, answer.iteration);
+ await mutateBoard(id, (doc) =>
+ recordHandoff(doc, { to: "article", href: articleHref({ site: ARTICLES_KEY, id: plan.article }), what: `a sweep on the scope: ${plan.article} i${answer.iteration}, job ${answer.jobId}` }),
+ );
+ return { href, jobId: answer.jobId, iteration: answer.iteration };
+}
+
// ── the video ──
/** The viewer origin every quote's link shares, else "" (the project's `check` asks for it). */
diff --git a/umtool/lib/research/runs-board.ts b/umtool/lib/research/runs-board.ts
@@ -0,0 +1,121 @@
+import { momentHref, postLinkHref } from "yt-dlp-transcript-common/lib/report/draft/tasks/links";
+import { clock } from "yt-dlp-transcript-common/lib/search/window";
+import { addQuote, CaseError } from "./cases.mjs";
+import { createCase, mutateBoard, readCase } from "./boards";
+import { citationText } from "./facets.mjs";
+import { isLocalOnly } from "./rules.mjs";
+import { listSources } from "./sources";
+import { readRunInputs, runOriginOf } from "./runs";
+import { researchCaseHref } from "./hrefs";
+import { runBoardId } from "./runs-hrefs";
+import type { CaseDoc, QuoteCite } from "./case-types";
+
+// ---------------------------------------------------------------------------
+// AN AGENT'S FINDINGS AS A BOARD (plans/umtool-redesign.md, R3): "Open as a
+// board" on a run makes -- or brings up to date -- the research case
+// `<article>-run<n>` (piece `c:<article>-run<n>`), whose quotes are the run's
+// KEPT findings: every quoted citation of the iteration's report, in its
+// sections, the finding's claim as the claim line. The same shape as a
+// person's pin (R2's addQuote: a snapshot of the words with their cite), each
+// marked `by: "agent"`, so human and agent research meet on one board.
+//
+// The words are the run's, as its strict check passed them; the board's
+// Re-verify reads them against the transcript now, as for any pin. A second
+// open adds what is new (a cite already on the board is not added twice) and
+// never touches the operator's claims, notes, sections or order.
+//
+// Umtool-side state, as every board: nothing here writes the article store.
+// ---------------------------------------------------------------------------
+
+type Citation = { kind?: string; channel?: string; id?: string; start?: number; end?: number; quote?: string; label?: string; date?: string };
+
+const ymd = (d?: string) => (d && /^\d{4}-\d{2}-\d{2}/.test(d) ? d.slice(0, 10).replace(/-/g, "") : d && /^\d{8}$/.test(d) ? d : undefined);
+
+/** The R1 source the board's quotes re-verify through: the run's own when offered, else one serving its links' origin, else the local corpus. */
+async function sourceFor(runSource: string | null, origin: string | null): Promise<string> {
+ const offered = await listSources().catch(() => []);
+ if (runSource && offered.some((o) => o.handle === runSource)) return runSource;
+ const byOrigin = origin ? offered.find((o) => o.handle === `remote:${origin.replace(/\/+$/, "")}`) : undefined;
+ if (byOrigin) return byOrigin.handle;
+ return offered[0]?.handle ?? runSource ?? "";
+}
+
+export function citeOfRun(c: Citation, o: { source: string; origin: string | null }): QuoteCite | null {
+ if (!c.channel || !c.id) return null;
+ const post = c.kind === "post";
+ if (!post && c.kind !== "video" && c.kind !== "audio") return null;
+ const t = typeof c.start === "number" ? c.start : 0;
+ const end = typeof c.end === "number" && c.end >= t ? c.end : t;
+ const url = o.origin ? (post ? postLinkHref(o.origin, c.channel, c.id) : momentHref(o.origin, c.channel, c.id, t)) : null;
+ const title = post ? `Post in ${c.channel}` : (c.label ?? c.id);
+ const date = ymd(c.date);
+ const iso = date ? `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}` : "";
+ return {
+ kind: post ? "post" : "video",
+ source: o.source,
+ channel: c.channel,
+ video: c.id,
+ title,
+ ...(date ? { date } : {}),
+ t,
+ end,
+ ...(post ? { track: "post" } : { clock: clock(t) }),
+ url,
+ citation: citationText(post ? { quote: c.quote, title: "", post: { author: c.channel, date: iso }, url } : { quote: c.quote, title, clock: clock(t), url }),
+ ...(isLocalOnly(c.channel) ? { localOnly: true } : {}),
+ };
+}
+
+export type RunBoardResult = { id: string; href: string; created: boolean; added: number; already: number; skipped: number };
+
+/** Open the run's kept findings as a board (create it, or add what is new). */
+export async function openRunBoard(article: string, n: number): Promise<RunBoardResult> {
+ const { it, trace, sweep, report } = await readRunInputs(article, n);
+ if (!report?.sections?.length) throw new CaseError(`${article} i${n} kept no findings yet (no report.json)${it.status !== "done" ? `: it is ${it.status}` : ""}`, 409);
+ const id = runBoardId(article, n);
+ const ran = runOriginOf(trace, sweep);
+ const source = await sourceFor(ran.source, ran.origin);
+ const citations = (report.citations ?? {}) as Record<string, Citation>;
+ const question = it.question ?? report.title ?? article;
+ let created = false;
+ try {
+ await readCase(id);
+ } catch (e) {
+ if ((e as { status?: number }).status !== 404) throw e;
+ await createCase({
+ id,
+ title: report.title ?? question,
+ scope: { source, channels: it.scope?.channels ?? [], dateFrom: it.scope?.from, dateTo: it.scope?.to },
+ query: question,
+ });
+ created = true;
+ }
+ const r = await mutateBoard(id, (doc: CaseDoc) => {
+ doc.run = { article, n, at: new Date().toISOString() };
+ let added = 0;
+ let already = 0;
+ let skipped = 0;
+ for (const s of report.sections ?? []) {
+ let section = doc.sections.find((x) => x.title === s.title);
+ if (!section && (s.claims ?? []).length) {
+ section = { id: `s${++doc.counters.section}`, title: s.title };
+ doc.sections.push(section);
+ }
+ for (const claim of s.claims ?? []) {
+ for (const cid of claim.citations ?? []) {
+ const c = citations[cid];
+ const cite = c?.quote ? citeOfRun(c, { source, origin: ran.origin }) : null;
+ if (!c?.quote || !cite) {
+ skipped++;
+ continue;
+ }
+ const out = addQuote(doc, { text: c.quote, cite, claim: claim.text, section: section?.id ?? null, query: question, by: "agent" }) as { duplicate: boolean };
+ if (out.duplicate) already++;
+ else added++;
+ }
+ }
+ }
+ return { added, already, skipped };
+ });
+ return { id, href: researchCaseHref(id), created, ...r.result };
+}
diff --git a/umtool/lib/research/runs-hrefs.ts b/umtool/lib/research/runs-hrefs.ts
@@ -0,0 +1,35 @@
+// A transparent run's addresses (plans/umtool-redesign.md, R3), one builder per
+// URL shape (lib/hrefs.ts's rule). Pure: a client component links with them,
+// and so may the Iterations tab and the Running list (their owners wire them):
+//
+// runHref(article, n) /research/runs/<article>/<n>
+// runHref(article, n, { run: 2 }) the iteration's second run (a trace or a
+// turns file can hold several)
+import { withQuery } from "../hrefs";
+
+const enc = encodeURIComponent;
+
+/** Every sweep run, newest first. */
+export const runsHref = () => "/research/runs";
+
+/** One iteration's run page (its last run unless `run` names another). */
+export function runHref(article: string, n: number, q: { run?: number } = {}): string {
+ return withQuery(`/research/runs/${enc(article)}/${n}`, { run: q.run });
+}
+
+/** GET: the run's view (lib/research/runs-types.ts RunView). */
+export function runApi(article: string, n: number, q: { run?: number } = {}): string {
+ return withQuery(`/api/research/runs/${enc(article)}/${n}`, { run: q.run });
+}
+
+/** POST: open (or update) the run's findings as a research board. */
+export const runBoardApi = (article: string, n: number) => `/api/research/runs/${enc(article)}/${n}/board`;
+
+/** The board a run's findings open as: case `<article>-run<n>` (its piece `c:<article>-run<n>`), cut to a piece segment. */
+export function runBoardId(article: string, n: number): string {
+ const tail = `-run${n}`;
+ return `${article.slice(0, 64 - tail.length).replace(/-+$/, "")}${tail}`;
+}
+
+/** Which tasks have a run page: the sweeps (an agent's or the pipeline's). */
+export const hasRunPage = (kind: string) => kind === "sweep";
diff --git a/umtool/lib/research/runs-types.ts b/umtool/lib/research/runs-types.ts
@@ -0,0 +1,143 @@
+// A TRANSPARENT RUN's shapes (plans/umtool-redesign.md, R3): what
+// /research/runs/<article>/<n> and GET /api/research/runs/<article>/<n> show of
+// one sweep run -- read from its trace.jsonl, or projected from turns.jsonl for
+// a run made before the trace (lib/research/runs-view.ts). Types only: safe
+// for a client component.
+
+export type RunCite = {
+ citation?: string;
+ kind?: string;
+ channel?: string;
+ video?: string;
+ start?: number;
+ end?: number;
+ url?: string;
+ label?: string;
+ quote?: string;
+};
+
+/** One quote check: kept, refused (a later round may fix it), or dropped, with why. */
+export type RunCheck = {
+ quote: string;
+ cite: RunCite;
+ ok: boolean;
+ reason: string | null;
+ /** extract (the pipeline's window check) · check (a strict round) · strict · drop · final (kept). */
+ stage: string;
+ dropped: boolean;
+ claim: string | null;
+ round: number | null;
+};
+
+export type RunFinding = { section: string; claim: string; cites: RunCite[] };
+
+/** A tool call a turn made (the turns projection: its input in a line). */
+export type RunCall = { name: string; summary: string; chars: number | null; error: boolean };
+
+export type RunEnumeration = {
+ query: string;
+ n: number;
+ ids: string[];
+ partial: boolean;
+ unreached: string[];
+ total: number | null;
+ posts: number;
+};
+
+export type RunBatch = {
+ k: number;
+ of: number | null;
+ ids: string[];
+ /** The extractor's own lines; null when the run kept none (before the trace). */
+ lines: string[] | null;
+ model: string | null;
+ usd: number | null;
+ cut: boolean;
+};
+
+export type RunStepKind = "scope" | "terms" | "turn" | "enumerate" | "batch" | "group" | "findings" | "checks" | "end";
+
+export type RunStep = {
+ /** Stable within the run: `scope`, `t3`, `r0` (a repair turn), `e2`, `b1`, `checks` … */
+ id: string;
+ kind: RunStepKind;
+ /** The left column: `t3`, `b1`, or `—`. */
+ t: string;
+ label: string;
+ sub: string | null;
+ /** The run's spend once this step was done (cumulative), when known. */
+ usd: number | null;
+ /** This step's own spend, when known. */
+ stepUsd: number | null;
+ /** Not recorded: the trace did not exist yet (an old run's quote checks). */
+ gap: boolean;
+ detail: {
+ /** Key / value rows (the scope, the end). */
+ facts: [string, string][];
+ /** The model's own words this turn. */
+ text: string | null;
+ calls: RunCall[];
+ enumerations: RunEnumeration[];
+ batches: RunBatch[];
+ reads: { tool: string; ids: string[] }[];
+ checks: RunCheck[];
+ findings: RunFinding[];
+ notes: string[];
+ };
+};
+
+/** One run of the iteration (a trace's or a turns file's run start). */
+export type RunSummary = { index: number; startedAt: string | null; steps: number; usd: number | null; status: string | null };
+
+export type RunCoverage = { matched: number; read: number; partial: boolean; unreached: string[] };
+
+export type RunView = {
+ article: string;
+ n: number;
+ /** `i3`. */
+ label: string;
+ kind: string;
+ /** The iteration's status (queued, running, done, failed, cancelled). */
+ status: string;
+ /** The shown run is the iteration's last and it is still going: the page polls. */
+ live: boolean;
+ /** trace: trace.jsonl; turns: projected from turns.jsonl (a run before R3); none: nothing recorded yet. */
+ from: "trace" | "turns" | "none";
+ runs: RunSummary[];
+ /** The run shown, 1-based. */
+ run: number;
+ header: {
+ question: string | null;
+ title: string | null;
+ task: string | null;
+ model: string | null;
+ extractor: string | null;
+ channels: string[];
+ dateFrom: string | null;
+ dateTo: string | null;
+ sourceLabel: string | null;
+ startedAt: string | null;
+ endedAt: string | null;
+ minutes: number | null;
+ /** This run's spend. */
+ usd: number | null;
+ /** The iteration's recorded spend (every run, as the usage says). */
+ iterationUsd: number;
+ checks: { name: string; ok: boolean; detail: string | null }[];
+ coverage: RunCoverage | null;
+ kept: number | null;
+ dropped: number | null;
+ /** Refused by a strict round (and then repaired or dropped). */
+ refused: number | null;
+ seed: { chars: number } | null;
+ error: string | null;
+ summary: string | null;
+ };
+ steps: RunStep[];
+ /** What the page must say about how this was read (several run starts, an untraced run). */
+ notes: string[];
+ /** The kept findings "Open as a board" makes quotes of (the iteration's report). */
+ findings: number;
+ /** The run's board (`<article>-run<n>`), when one was opened. */
+ board: { id: string; quotes: number } | null;
+};
diff --git a/umtool/lib/research/runs-view.ts b/umtool/lib/research/runs-view.ts
@@ -0,0 +1,837 @@
+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<string, unknown>;
+
+/** 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<string, { usd?: number }>;
+ 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<string, Json>;
+};
+
+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<string, string> = { 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<string, number>();
+ 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<number, Json[]> {
+ const out = new Map<number, Json[]>();
+ 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<string, RunStep>();
+ const batchSteps = new Map<number, RunStep>();
+ 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 "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<string>();
+ 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;
+}
diff --git a/umtool/lib/research/runs.test.ts b/umtool/lib/research/runs.test.ts
@@ -0,0 +1,192 @@
+// Transparent runs (R3): a trace projected into steps (scope, turns with
+// their enumerations and batches, the findings, the quote checks kept,
+// refused and dropped with why, the end), a turns-only run projected the same
+// way with what it never recorded as a gap, several run starts as separate
+// runs never summed, and a run's findings opened as a board.
+//
+// Run with: pnpm --filter umtool exec tsx --test lib/research/runs.test.ts
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import {
+ DROPPED,
+ KEPT_KEEPER,
+ REPAIRED,
+ RUN_ARTICLE,
+ RUN_REPORT,
+ TURNS_ARTICLE,
+ finishedTrace,
+ jsonLines,
+ liveTraceHead,
+ liveTraceNext,
+ twoStartTurns,
+} from "../../e2e/fixtures/run-trace-fixture.mjs";
+import { prettyModel, runView, sourceLabelOf, summarizeCalls, turnRuns, type RunIteration } from "./runs-view";
+import { runBoardId, runHref } from "./runs-hrefs";
+
+const IT: RunIteration = {
+ kind: "sweep",
+ status: "done",
+ model: "claude-sonnet-5-5",
+ question: "q",
+ scope: { channels: ["harbor-radio"] },
+ usage: { "claude-sonnet-5-5": { usd: 0.17 }, "claude-haiku-4-5": { usd: 0.01 } },
+ checks: [{ name: "convert", ok: true }],
+};
+
+test("a trace: scope, the turns with their enumeration and batch, findings, checks, the end; spend cumulative", () => {
+ const v = runView({ article: RUN_ARTICLE, n: 1, iteration: IT, trace: jsonLines(finishedTrace()), turns: null, report: RUN_REPORT, board: null });
+ assert.equal(v.from, "trace");
+ assert.equal(v.live, false);
+ assert.deepEqual(v.runs.map((r) => r.index), [1]);
+ assert.deepEqual(
+ v.steps.map((s) => [s.id, s.label]),
+ [
+ ["scope", "scope"],
+ ["t0", "enumerate"],
+ ["t1", "extract"],
+ ["t2", "write_report"],
+ ["r0", "edit_report"],
+ ["findings", "findings"],
+ ["checks", "quote checks"],
+ ["end", "ended · done"],
+ ],
+ );
+ const t0 = v.steps[1]!;
+ assert.equal(t0.detail.enumerations[0]!.n, 3);
+ assert.match(t0.sub!, /3 matched/);
+ const t1 = v.steps[2]!;
+ assert.deepEqual(t1.detail.batches[0]!.ids, ["hr-2022a", "nd-2023", "hr-2021a"]);
+ assert.ok(t1.detail.batches[0]!.lines!.some((l) => l.includes(REPAIRED.now)), "the extractor's own lines");
+ assert.equal(t1.usd, 0.1, "the turn's total takes in its batch");
+ assert.equal(Math.round(t1.stepUsd! * 100) / 100, 0.05, "the turn and its extractor");
+ assert.deepEqual(v.steps.map((s) => s.usd), [null, 0.05, 0.1, 0.16, 0.18, null, null, 0.18]);
+ const checks = v.steps.find((s) => s.kind === "checks")!;
+ assert.equal(checks.sub, "2 kept · 1 dropped · 3 refused");
+ const drop = checks.detail.checks.find((c) => c.dropped)!;
+ assert.deepEqual([drop.quote, drop.reason, drop.claim], [DROPPED.quote, DROPPED.reason, DROPPED.claim]);
+ assert.equal(v.steps.find((s) => s.kind === "findings")!.detail.findings[1]!.cites[0]!.quote, KEPT_KEEPER);
+ assert.deepEqual([v.header.kept, v.header.dropped, v.header.usd, v.header.iterationUsd], [2, 1, 0.18, 0.18]);
+ assert.deepEqual(v.header.coverage, { matched: 3, read: 3, partial: false, unreached: [] });
+ assert.equal(v.header.extractor, "claude-haiku-4-5");
+ assert.equal(v.findings, 2, "two quotes to open as a board");
+});
+
+test("a live trace: no end, live; the next turn lands as a step", () => {
+ const head = jsonLines(liveTraceHead());
+ const live = runView({ article: "l", n: 1, iteration: { ...IT, status: "running" }, trace: head, turns: null, report: null, board: null });
+ assert.equal(live.live, true);
+ assert.deepEqual(live.steps.map((s) => s.id), ["scope", "t0"]);
+ const more = runView({ article: "l", n: 1, iteration: { ...IT, status: "running" }, trace: head + jsonLines(liveTraceNext()) + '{"t":"cost","to', turns: null, report: null, board: null });
+ assert.deepEqual(more.steps.map((s) => s.id), ["scope", "t0", "t1"], "a torn last line (still being written) is skipped");
+ assert.equal(more.steps.at(-1)!.usd, 0.08);
+});
+
+test("a trace with two runs: the last by default, either on asking, never summed", () => {
+ const two = jsonLines(finishedTrace()) + jsonLines(liveTraceHead().map((e) => ({ ...e, run: 2 })));
+ const v = runView({ article: "x", n: 1, iteration: IT, trace: two, turns: null, report: RUN_REPORT, board: null });
+ assert.equal(v.run, 2);
+ assert.deepEqual(v.runs.map((r) => [r.index, r.usd]), [[1, 0.18], [2, 0.03]]);
+ assert.equal(v.header.usd, 0.03);
+ assert.equal(v.findings, 2, "the report is the last run's");
+ const first = runView({ article: "x", n: 1, iteration: IT, trace: two, turns: null, report: RUN_REPORT, board: null, want: 1 });
+ assert.equal(first.header.usd, 0.18);
+ assert.equal(first.findings, 0, "an earlier run does not open the report as its board");
+});
+
+test("turns only, two run starts: two runs, the stopgap's running totals as each step's spend, the checks a gap", () => {
+ const turns = jsonLines(twoStartTurns());
+ const v = runView({ article: TURNS_ARTICLE, n: 1, iteration: { ...IT, imported: { extractor: "claude-haiku-4-5" } }, trace: null, turns, report: null, board: null });
+ assert.equal(v.from, "turns");
+ assert.deepEqual(v.runs.map((r) => r.index), [1, 2]);
+ assert.equal(v.run, 2);
+ assert.deepEqual(v.steps.map((s) => s.id), ["scope", "t0", "t1", "t2", "t3", "checks"]);
+ assert.deepEqual(v.steps.map((s) => s.usd), [null, 0.04, 0.1, 0.15, 0.16, null]);
+ const gap = v.steps.at(-1)!;
+ assert.equal(gap.gap, true);
+ assert.equal(gap.sub, "kept / dropped not recorded");
+ assert.ok(v.notes.some((n) => /2 run starts/.test(n)));
+ const first = runView({ article: TURNS_ARTICLE, n: 1, iteration: IT, trace: null, turns, report: null, board: null, want: 1 });
+ assert.deepEqual(first.steps.map((s) => s.id), ["scope", "t0", "t1", "t2", "checks"]);
+ assert.equal(first.header.usd, 0.09, "the first run's own total, not the file's");
+ const t1 = first.steps[2]!;
+ assert.deepEqual(t1.detail.batches[0]!.ids, ["hr-2022a", "hr-2021a"]);
+ assert.equal(t1.detail.batches[0]!.lines, null, "the extractor's lines were never kept");
+ assert.equal(first.steps[0]!.detail.facts.find(([k]) => k === "extractor")![1], "claude-haiku-4-5");
+});
+
+test("turnRuns: a file with no start notes splits where turn 0 comes back, but not at its repair round", () => {
+ const r = (turn: number) => ({ kind: "response", turn, usd: 0.01 });
+ const runs = turnRuns([r(0), r(1), { kind: "note", text: "repair round" }, r(0), r(1), r(0), r(1)]);
+ assert.deepEqual(runs.map((x) => x.length), [5, 2]);
+ assert.deepEqual(turnRuns([]).length, 1);
+});
+
+test("the small words: models, sources, calls, the board's id and the run's href", () => {
+ assert.equal(prettyModel("claude-sonnet-5-5"), "Sonnet 5.5");
+ assert.equal(prettyModel("claude-haiku-4-5-20251001"), "Haiku 4.5");
+ assert.equal(prettyModel("qwen3:8b"), "qwen3:8b");
+ assert.equal(sourceLabelOf("local:/x/export/.export-builds/jasolyzer-private/out"), "jasolyzer-private build");
+ assert.equal(sourceLabelOf("local:/repo/export/public"), "local corpus");
+ assert.equal(sourceLabelOf("remote:https://anilyzer.pages.dev"), "anilyzer.pages.dev");
+ assert.equal(summarizeCalls(["enumerate_matches", "enumerate_matches", "get_post"]), "enumerate ×2 · get_post");
+ assert.equal(runBoardId("piratesoftware-ai-friends", 1), "piratesoftware-ai-friends-run1");
+ assert.equal(runBoardId("a".repeat(64), 12).length, 64);
+ assert.equal(runHref("a-b", 3), "/research/runs/a-b/3");
+ assert.equal(runHref("a-b", 3, { run: 2 }), "/research/runs/a-b/3?run=2");
+});
+
+// ── a run's findings as a board (the store in a temp REPORTS_ROOT) ──
+
+let tmp: string;
+let lib: { board: typeof import("./runs-board"); boards: typeof import("./boards") };
+
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-runs-"));
+ const fixture = await import("../../e2e/fixtures/run-trace-fixture.mjs");
+ const research = await import("../../e2e/fixtures/research-fixture.mjs");
+ const pub = research.makeResearchFixture({ dest: tmp, channels: path.join(tmp, "channels") }).pub;
+ fixture.makeRunTraceFixture({ articles: path.join(tmp, "articles"), source: `local:${pub}` });
+ process.env.TRANSCRIPT_LOCAL_DIR = pub;
+ process.env.TRANSCRIPT_HUB_URL = "";
+ process.env.CHANNELS_DIR = path.join(tmp, "channels");
+ process.env.SITES_DIR = path.join(tmp, "sites");
+ process.env.ARTICLES_DIR = path.join(tmp, "articles");
+ process.env.REPORTS_DIR = path.join(tmp, "reports");
+ process.env.UMTOOL_CACHE_DIR = path.join(tmp, "cache");
+ process.env.SETTINGS_FILE = path.join(tmp, "settings.json");
+ lib = { board: await import("./runs-board"), boards: await import("./boards") };
+});
+
+after(async () => {
+ await rm(tmp, { recursive: true, force: true });
+});
+
+test("open as a board: the kept findings become quotes by the agent, in their sections; a second open adds nothing twice", async () => {
+ const out = await lib.board.openRunBoard(RUN_ARTICLE, 1);
+ assert.deepEqual([out.id, out.created, out.added, out.already, out.href], ["runfix-run1", true, 2, 0, "/research/runfix-run1"]);
+ const doc = await lib.boards.readCase(out.id);
+ assert.equal(doc.title, "The lighthouse budget");
+ assert.deepEqual(doc.run && [doc.run.article, doc.run.n], [RUN_ARTICLE, 1]);
+ assert.deepEqual(doc.sections.map((s) => s.title), ["The vote", "The keeper"]);
+ assert.deepEqual(doc.quotes.map((q) => [q.text, q.by, q.claim, q.section]), [
+ [REPAIRED.now, "agent", "The council voted the budget down", "s1"],
+ [KEPT_KEEPER, "agent", "The keeper says he never saw it", "s2"],
+ ]);
+ const c = doc.quotes[0]!.cite;
+ assert.deepEqual([c.kind, c.channel, c.video, c.t, c.end, c.date, c.clock], ["video", "harbor-radio", "hr-2022a", 2044, 2048, "20220211", "34:04"]);
+ assert.equal(c.url, "https://archive.example/?v=harbor-radio%2Fhr-2022a&t=2044");
+ assert.match(c.source, /^local:/);
+ // The operator's edit survives a second open, which adds nothing twice.
+ await lib.boards.patchQuote(out.id, "q1", { claim: "Ours now" });
+ const again = await lib.board.openRunBoard(RUN_ARTICLE, 1);
+ assert.deepEqual([again.created, again.added, again.already], [false, 0, 2]);
+ assert.equal((await lib.boards.readCase(out.id)).quotes[0]!.claim, "Ours now");
+ // A run with no report keeps nothing to open.
+ await assert.rejects(lib.board.openRunBoard(TURNS_ARTICLE, 1), /kept no findings yet/);
+ // The board's quotes re-verify against the corpus like any pin.
+ const verified = await lib.boards.verifyCase(out.id);
+ assert.deepEqual(verified.results.map((r) => r.verify.status), ["ok", "ok"]);
+});
diff --git a/umtool/lib/research/runs.ts b/umtool/lib/research/runs.ts
@@ -0,0 +1,131 @@
+import { readdir } from "node:fs/promises";
+import path from "node:path";
+import { iterationUsd, readIteration, readIterationFile, readIterations, type Iteration } from "yt-dlp-transcript-common/lib/report/iterations";
+import { isReportId } from "yt-dlp-transcript-common/lib/report/schema";
+import { sitesPaths } from "@/lib/articles/sites";
+import { readCase } from "./boards";
+import { runBoardId } from "./runs-hrefs";
+import { parseLines, runView, type RunIteration, type RunReport } from "./runs-view";
+import type { RunView } from "./runs-types";
+
+// ---------------------------------------------------------------------------
+// TRANSPARENT RUNS, read (plans/umtool-redesign.md, R3): an iteration of the
+// article store -- its iteration.json, trace.jsonl (else turns.jsonl) and
+// report.json -- through common's readers, READ ONLY (the editor writes them;
+// umtool never does). The projection is lib/research/runs-view.ts.
+// ---------------------------------------------------------------------------
+
+export class RunError extends Error {
+ constructor(
+ message: string,
+ readonly status = 400,
+ ) {
+ super(message);
+ }
+}
+
+function checkAddress(article: string, n: number) {
+ if (!isReportId(article)) throw new RunError(`not an article id: ${JSON.stringify(article)}`);
+ if (!Number.isInteger(n) || n < 1) throw new RunError(`not an iteration number: ${JSON.stringify(n)} (1, 2, …)`);
+}
+
+/** The iteration, its files, and its board, as the view takes them. */
+export async function readRunInputs(article: string, n: number) {
+ checkAddress(article, n);
+ const paths = sitesPaths();
+ let it: Iteration | null;
+ try {
+ it = await readIteration(article, n, paths);
+ } catch (e) {
+ throw new RunError(`${article} i${n} cannot be read: ${(e as Error).message}`, 409);
+ }
+ if (!it) throw new RunError(`"${article}" has no iteration i${n}`, 404);
+ const file = (name: "trace.jsonl" | "turns.jsonl" | "report.json" | "sweep.md") => readIterationFile(article, n, name, paths).catch(() => null);
+ const [trace, turns, reportText, sweep] = await Promise.all([file("trace.jsonl"), file("turns.jsonl"), file("report.json"), file("sweep.md")]);
+ let report: RunReport | null = null;
+ try {
+ report = reportText ? (JSON.parse(reportText) as RunReport) : null;
+ } catch {
+ report = null;
+ }
+ const boardId = runBoardId(article, n);
+ const board = await readCase(boardId).then(
+ (c) => ({ id: c.id, quotes: c.quotes.length }),
+ () => null,
+ );
+ return { it, trace, turns, report, sweep, board };
+}
+
+/** One run of an iteration, as the page shows it. `want` is the run (1-based); the last by default. */
+export async function readRunView(article: string, n: number, want?: number | null): Promise<RunView> {
+ const { it, trace, turns, report, board } = await readRunInputs(article, n);
+ return runView({ article, n, iteration: it as unknown as RunIteration, trace, turns, report, board, want: want ?? null });
+}
+
+// ── every run, for the index ──
+
+export type RunRow = {
+ article: string;
+ n: number;
+ status: string;
+ model: string;
+ question: string | null;
+ createdAt: string;
+ endedAt: string | null;
+ usd: number;
+ /** trace: a trace.jsonl; turns: only turns.jsonl; none: nothing recorded. */
+ from: "trace" | "turns" | "none";
+ coverage: Iteration["coverage"] | null;
+};
+
+/** Every sweep iteration in the article store, newest first (at most `limit`). */
+export async function listRuns(limit = 200): Promise<RunRow[]> {
+ const paths = sitesPaths();
+ const names = await readdir(/* turbopackIgnore: true */ paths.articlesDir, { withFileTypes: true }).catch(() => []);
+ const rows: RunRow[] = [];
+ await Promise.all(
+ names
+ .filter((d) => d.isDirectory() && isReportId(d.name))
+ .map(async (d) => {
+ const read = await readIterations(d.name, paths).catch(() => null);
+ for (const it of read?.iterations ?? []) {
+ if (it.kind !== "sweep") continue;
+ const has = async (name: "trace.jsonl" | "turns.jsonl") =>
+ readdir(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ paths.articlesDir, d.name, "iterations", String(it.n))).then(
+ (xs) => xs.includes(name),
+ () => false,
+ );
+ const from = (await has("trace.jsonl")) ? "trace" : (await has("turns.jsonl")) ? "turns" : "none";
+ rows.push({
+ article: d.name,
+ n: it.n,
+ status: it.status,
+ model: it.model,
+ question: it.question ?? null,
+ createdAt: it.createdAt,
+ endedAt: it.endedAt ?? null,
+ usd: Math.round(iterationUsd(it) * 100) / 100,
+ from,
+ coverage: it.coverage ?? null,
+ });
+ }
+ }),
+ );
+ return rows.sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.article.localeCompare(b.article) || b.n - a.n).slice(0, limit);
+}
+
+/** The source handle and link origin a run read through: its trace's scope, else its sweep.md's links. */
+export function runOriginOf(trace: string | null, sweep: string | null): { source: string | null; origin: string | null } {
+ let source: string | null = null;
+ let origin: string | null = null;
+ for (const e of parseLines(trace)) {
+ if (e.t !== "scope") continue;
+ if (typeof e.source === "string") source = e.source;
+ if (typeof e.origin === "string") origin = e.origin;
+ }
+ if (!origin && sweep) {
+ const m = /\]\((https?:\/\/[^/\s)]+)\/\?v=/.exec(sweep);
+ if (m) origin = m[1]!;
+ }
+ return { source, origin };
+}