commit 9a494d7c03968a29c6dd19e1f284b0df67fa0d67
parent e02f68d5a074704bb64ab9125c02706a8d94d459
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 07:24:37 -0400
umtool: transparent runs — /research/runs/<article>/<n> (steps, the lit step's detail, the cumulative spend chart; live while running, replay when done; a turns.jsonl projection with each run start its own run), /research/runs, open a run's kept findings as a board (by agent), and run a sweep on a case's scope
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
22 files changed, 2712 insertions(+), 35 deletions(-)
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/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;
@@ -472,6 +473,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 +494,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 +530,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,623 @@
+"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" },
+ { label: `${view.article} ${view.label}` },
+ ]}
+ 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">
+ <p className="display m-0 max-w-[1000px] text-[19px] leading-[1.2] text-text" data-run-question="">
+ {h.question ?? h.title ?? "No question recorded"}
+ </p>
+ <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/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,195 @@
+// 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";
+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 }),
+ );
+ put(path.join(dir(LIVE_ARTICLE), "trace.jsonl"), jsonl(liveTraceHead(source)));
+ return { dir };
+}
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,12 @@ 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 -- 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 +59,66 @@ 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") {
+ refusals.push("the policy routes sweeps to Claude Code, which runs in a session, not here: route sweeps to the API or the local model in Settings");
+ } 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 +130,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 +167,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, then repaired or dropped` : ""].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, then repaired or dropped");
+ 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 };
+}