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 { 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 { 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 }; }