Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 638ab3f927bd709ebb1804fecaa5a8c2d3550262
parent 128acda557035d27812cf75d523d23a6b8390095
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 04:13:43 -0500

umtool: the case pipeline page beside the board -- /research/<case>/pipeline, its routes, the gate on the board's exits

/research/<case>/pipeline (components/research/CasePipeline.tsx): one panel per stage,
each with its manual path and its buttons -- the definition (JSON, checked whole), the
private names (typed into a password field, hashed in the browser with Web Crypto, only
the hash posted; the page shows a count), coverage per channel x year with the key
years marked and each gap's button (download-missing, transcribe-bucket, persist-videos
over the key period, channel-priority focus: the editor's own ops, plan first, persist's
plan its dryRun), candidates and their counts, batches and their wrapped text, the read's
manual path (the reader prompts with the naming rule; finding rows pasted as JSON lines --
the deck and case-read are lane B's), the merge preview and the summary, what the privacy
gate blocks (counts and row ids), export (REPORT.md / .html) and the hand-off to the
board, the date checks. A long stage runs in the background and the page follows
stages.json, so a run from `archilyzer case` shows the same way.

lib/research/pipeline.ts binds common's stages to REPORTS_ROOT's case dir and umtool's
CHANNELS_DIR (read-only; a fixture's channels date from their own index, never the
checkout's). The hand-off pins the merged findings to the board, one section per reader
group (the quarantined left out), and the board's own hand-offs take them from there.
The board's export and its article and video hand-offs now refuse a board whose quotes,
claims or notes name one of the case's private names (lib/research/case-private.ts).

The routes: GET/PUT .../pipeline, POST .../pipeline/<coverage|candidates|batches|export|
date-checks|private-names|findings|summary|handoff|gap>, GET .../pipeline/<batch|report>
-- the door lane D's MCP case tools use through UMTOOL_URL.

e2e: case-pipeline.spec.ts on a new fixture (case-fixture.mjs: two invented channels with
words on disk, an empty board); the editor stub answers the four gap ops.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/lib/research/casePipeline.ts | 5+++--
Mcommon/lib/research/caseTypes.ts | 6+++---
Aumtool/app/api/research/cases/[id]/pipeline/[op]/route.ts | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/pipeline/route.ts | 32++++++++++++++++++++++++++++++++
Aumtool/app/research/[case]/pipeline/page.tsx | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/research/BoardView.tsx | 10++++++++++
Aumtool/components/research/CasePipeline.tsx | 772+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/case-pipeline.spec.ts | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/case-fixture.mjs | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 22++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Mumtool/lib/research/boards.ts | 4++++
Aumtool/lib/research/case-private.ts | 30++++++++++++++++++++++++++++++
Mumtool/lib/research/handoff.ts | 6++++++
Mumtool/lib/research/hrefs.ts | 8++++++++
Aumtool/lib/research/pipeline-types.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/pipeline.ts | 392+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
17 files changed, 1754 insertions(+), 5 deletions(-)

diff --git a/common/lib/research/casePipeline.ts b/common/lib/research/casePipeline.ts @@ -458,7 +458,8 @@ const bump = (o: Record<string, number>, k: string, n = 1) => (o[k] = (o[k] ?? 0 * words did not hit -- a garbled caption under a telling title is still a candidate; * - noSubject: a window a coverage group would read that names no subject in its words or the title (for * coverage, a mention of a subject at all is the bar); - * - notStrict: on a subject's own channel in an era with strictFamilies, a hit of another family makes no window; + * - notStrict: on a subject's own channel in an era with strictFamilies, a hit of another family makes no window + * (counted as hits, not windows); * - noGroup: no reader group takes the window. */ export function recordingWindows(def: CaseDefinition, rec: RecordingText, counts: CandidateCounts, opts: ScanOptions = {}): CandidateWindow[] { @@ -476,7 +477,7 @@ export function recordingWindows(def: CaseDefinition, rec: RecordingText, counts if (own && era.strictFamilies?.length) { const strict = new Set(era.strictFamilies); const kept = hits.filter((h) => strict.has(h.family)); - if (kept.length < hits.length && !kept.length) counts.noise.notStrict += 1; + counts.noise.notStrict += hits.length - kept.length; hits = kept; } const spans = mergeHitWindows(hits, W, maxSpan, rec.duration ?? Infinity); diff --git a/common/lib/research/caseTypes.ts b/common/lib/research/caseTypes.ts @@ -179,9 +179,9 @@ export type CandidateCounts = { byEra: Record<string, number>; /** Recordings whose title a family matched. */ titleHits: number; - /** Dropped by a noise filter, by filter: noSubject (a coverage window naming no subject), notStrict (a subject's - * own window in a strict era with no strict family), noGroup (no reader group takes it), capped (past the - * per-recording cap). */ + /** Dropped by a noise filter, by filter: noSubject (a coverage window naming no subject), notStrict (HITS of a + * non-strict family on a subject's own channel in a strict era), noGroup (no reader group takes it), capped (past + * the per-recording cap). */ noise: Record<string, number>; /** Recordings: in scope, dated inside an era, with text to read, and without (still to download or transcribe). */ scanned: { channels: number; videos: number; inEra: number; withText: number; noText: number; undated: number }; diff --git a/umtool/app/api/research/cases/[id]/pipeline/[op]/route.ts b/umtool/app/api/research/cases/[id]/pipeline/[op]/route.ts @@ -0,0 +1,77 @@ +import { addFindings, batchFile, changePrivateNames, gapAction, handoffToBoard, pipelineView, reportFile, saveSummary, startStage } from "@/lib/research/pipeline"; +import { CasePipelineError } from "yt-dlp-transcript-common/lib/research/casePipeline"; +import { fail, ok } from "../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// A CASE'S PIPELINE, its actions (lib/research/pipeline.ts). The door an agent uses too (the MCP's case tools, +// lane D, through UMTOOL_URL); `archilyzer case …` runs the same stages from a shell. +// +// POST coverage | candidates {window?, maxSpan?} | date-checks {aroundDays?, latest?} +// -> { started: true, view }: runs in the background; follow GET ../ +// POST batches {budget?} | export {minRelevance?} +// -> { view } when done +// POST private-names {add?: [hex], remove?: [hex], clear?: true} +// -> { count, changed }: sha256 hex digests ONLY (the page hashes a name +// in the browser); a term is refused +// POST findings {rows: [FindingRow…]} -> { rows } appended: each checked, the whole write behind the gate +// POST summary {text, by?, model?} -> { summary }: a person's (by hand), or a model's draft +// POST handoff {confirm?, minRelevance?} +// -> { plan } / { plan, pinned, duplicates }: the merged findings onto +// the board, one section per reader group, behind the gate +// POST gap {action: download-missing | transcribe | persist | focus, slug, confirm?} +// -> { plan } / { done, route, answer }: the editor's own ops +// GET batch?batch=<id> -> the batch's wrapped text (text/plain) +// GET report?format=md|html[&download=1] +// -> REPORT.md / REPORT.html as exported +// A PrivacyBlocked is a 409 whose words are counts and row ids. +const STAGES = new Set(["coverage", "candidates", "batches", "export", "date-checks"]); + +type Ctx = { params: Promise<{ id: string; op: string }> }; + +export async function POST(request: Request, ctx: Ctx) { + try { + const { id: raw, op } = await ctx.params; + const id = decodeURIComponent(raw); + const body = ((await request.json().catch(() => ({}))) ?? {}) as Record<string, unknown>; + if (typeof body !== "object" || Array.isArray(body)) throw new CasePipelineError("expected a JSON object"); + if (STAGES.has(op)) { + const r = await startStage(id, op, body); + return ok({ ...r, view: await pipelineView(id) }); + } + if (op === "private-names") return ok(await changePrivateNames(id, body)); + if (op === "findings") return ok({ rows: await addFindings(id, body.rows) }); + if (op === "summary") return ok({ summary: await saveSummary(id, body) }); + if (op === "handoff") return ok(await handoffToBoard(id, { confirm: body.confirm === true, minRelevance: body.minRelevance as number | undefined })); + if (op === "gap") return ok(await gapAction(id, body)); + throw new CasePipelineError(`no pipeline action "${op}"`, 404); + } catch (e) { + return fail(e); + } +} + +export async function GET(request: Request, ctx: Ctx) { + try { + const { id: raw, op } = await ctx.params; + const id = decodeURIComponent(raw); + const q = new URL(request.url).searchParams; + if (op === "batch") { + return new Response(await batchFile(id, q.get("batch") ?? ""), { headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } }); + } + if (op === "report") { + const format = q.get("format") === "html" ? "html" : "md"; + const r = await reportFile(id, format); + if (!r) throw new CasePipelineError("nothing exported yet: Export the report first", 404); + return new Response(r.body, { + headers: { + "content-type": format === "html" ? "text/html; charset=utf-8" : "text/markdown; charset=utf-8", + "cache-control": "no-store", + ...(q.get("download") === "1" ? { "content-disposition": `attachment; filename="${r.name}"` } : {}), + }, + }); + } + throw new CasePipelineError(`no pipeline read "${op}"`, 404); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/pipeline/route.ts b/umtool/app/api/research/cases/[id]/pipeline/route.ts @@ -0,0 +1,32 @@ +import { pipelineView, saveCaseDefinition } from "@/lib/research/pipeline"; +import { CasePipelineError } from "yt-dlp-transcript-common/lib/research/casePipeline"; +import { fail, ok } from "../../../_respond"; + +export const dynamic = "force-dynamic"; + +// A CASE'S PIPELINE (lib/research/pipeline.ts; plans/release-38/research-cases-and-assist.md, lane A), beside its +// board. The stages and the rest are ./[op]/route.ts. +// GET -> PipelineView (lib/research/pipeline-types.ts): the definition (private names as a count only), each +// stage's file and last run, what the privacy gate says now +// PUT the definition (pipeline.json): { subjects, scope, eras, groups, readerPrompts, keyDates, status, +// privateNames: { note } } -> PipelineView. Private names are never part of it (POST ./private-names). +export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + return ok(await pipelineView(decodeURIComponent(id))); + } catch (e) { + return fail(e); + } +} + +export async function PUT(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const body = (await request.json().catch(() => null)) as unknown; + if (!body || typeof body !== "object" || Array.isArray(body)) throw new CasePipelineError("expected the definition as a JSON object"); + await saveCaseDefinition(decodeURIComponent(id), body); + return ok(await pipelineView(decodeURIComponent(id))); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/research/[case]/pipeline/page.tsx b/umtool/app/research/[case]/pipeline/page.tsx @@ -0,0 +1,46 @@ +import Link from "next/link"; +import AppHeader from "@/components/shell/AppHeader"; +import AppRail from "@/components/shell/AppRail"; +import CasePipeline from "@/components/research/CasePipeline"; +import { EmptyState } from "@/components/ui/empty-state"; +import { pipelineView } from "@/lib/research/pipeline"; +import { researchCaseHref, researchHref } from "@/lib/research/hrefs"; +import type { PipelineView } from "@/lib/research/pipeline-types"; + +export const dynamic = "force-dynamic"; + +// A CASE'S PIPELINE (plans/release-38/research-cases-and-assist.md, lane A), beside its board at +// /research/<case>: the stages -- define, coverage, candidates, batches, the read, merge, the privacy gate, +// export and hand-off, date checks -- each with its manual path and its buttons. The page is the client's +// (components/research/CasePipeline.tsx); this reads the first frame. +export default async function CasePipelinePage({ params }: { params: Promise<{ case: string }> }) { + const { case: raw } = await params; + const id = decodeURIComponent(raw); + let view: PipelineView | null = null; + let error: { status: number; message: string } | null = null; + try { + view = await pipelineView(id); + } 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 ? ( + <CasePipeline initial={view} /> + ) : ( + <> + <AppHeader crumbs={[{ href: researchHref(), label: "Research" }, { href: researchCaseHref(id), label: id }, { label: "Pipeline" }]} /> + <div className="px-7 pt-6"> + <EmptyState title={error?.status === 404 ? `No case “${id}”` : "This case's pipeline cannot be read"}> + <span role="alert">{error?.message}</span>{" "} + <Link href={researchHref()} className="ink-link"> + Research + </Link> + </EmptyState> + </div> + </> + )} + </div> + ); +} diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx @@ -17,6 +17,7 @@ import { researchCaseApi, researchCaseExportApi, researchCaseQuoteApi, + researchCasePipelineHref, researchCaseVerifyApi, researchFromCaseHref, researchHref, @@ -627,6 +628,15 @@ export default function BoardView({ initial }: { initial: CaseView }) { </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> + <div> + <span className="micro">Pipeline</span> + <p className="mb-0 mt-1.5 text-[12px] text-muted"> + Coverage, candidate windows, batches, findings, the merge and its privacy gate, date checks.{" "} + <Link prefetch={false} href={researchCasePipelineHref(doc.id)} className="ink-link" data-case-pipeline=""> + Open the case pipeline + </Link> + </p> + </div> <dl data-case-facts="" className="m-0 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3.5 gap-y-1.5 text-[12.5px]"> <dt className="text-muted">Scope</dt> <dd className="m-0 text-text-2">{scopeLine}</dd> diff --git a/umtool/components/research/CasePipeline.tsx b/umtool/components/research/CasePipeline.tsx @@ -0,0 +1,772 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import AppHeader from "@/components/shell/AppHeader"; +import { badgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { Field, Input, Select, Textarea } from "@/components/ui/field"; +import { Panel } from "@/components/ui/panel"; +import { Table, TD, TH } from "@/components/ui/table"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { privateNameHashWeb, privateTermProblem } from "yt-dlp-transcript-common/lib/research/casePipeline"; +import type { CaseStage, CaseStageRun } from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { researchCaseHref, researchCasePipelineApi, researchHref } from "@/lib/research/hrefs"; +import type { PipelineView } from "@/lib/research/pipeline-types"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// THE CASE PIPELINE (plans/release-38/research-cases-and-assist.md, lane A): one panel per stage, in order, each +// with its manual path (what a person does by hand) and its buttons. Every change is the API's +// (app/api/research/cases/[id]/pipeline/**) and the page redraws from what it answers; a long stage runs in the +// background and the page follows its record (stages.json) until it ends -- a run from `archilyzer case …` shows +// here the same way. +// +// PRIVATE NAMES never leave this page as text: a typed name is hashed here (Web Crypto) and only the hash is +// posted; the field is a password field, so a screenshot shows dots. What the page shows of them is a count, and +// what the gate blocked as counts and row ids. +// +// Stage 4 (the read: the candidate deck, the case-read task, the quote check) is lane B's: until it lands, its +// panel is the manual path -- the reader prompts to copy and a box for finding rows. +// --------------------------------------------------------------------------- + +const nf = new Intl.NumberFormat("en-US"); +const plural = (n: number, w: string) => `${nf.format(n)} ${w}${n === 1 ? "" : "s"}`; +const STAGE_NAV: { id: string; label: string }[] = [ + { id: "define", label: "Define" }, + { id: "coverage", label: "1 Coverage" }, + { id: "candidates", label: "2 Candidates" }, + { id: "batches", label: "3 Batches" }, + { id: "read", label: "4 Read" }, + { id: "merge", label: "5 Merge" }, + { id: "privacy", label: "6 Privacy" }, + { id: "export", label: "Export" }, + { id: "date-checks", label: "9 Date checks" }, +]; + +async function call<T>(url: string, method: string, body?: unknown): Promise<T> { + const r = await fetch(url, { method, headers: { "content-type": "application/json" }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), cache: "no-store" }); + const j = (await r.json().catch(() => null)) as (T & { error?: string }) | null; + if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`); + return j as T; +} + +function RunState({ run }: { run?: CaseStageRun }) { + if (!run) return <span className={badgeVariants({ variant: "info", size: "sm" })}>not run</span>; + const when = (run.endedAt ?? run.startedAt).replace("T", " ").slice(0, 16); + return ( + <span className="flex items-center gap-2" data-stage-state={run.state}> + <span className={badgeVariants({ variant: run.state === "failed" ? "blocking" : run.state === "running" ? "state" : "neutral", size: "sm" })}>{run.state}</span> + <span className="font-mono text-[11px] text-muted"> + {when} · {run.by} + </span> + </span> + ); +} + +function StageLog({ run }: { run?: CaseStageRun }) { + if (!run || (!run.log.length && !run.error)) return null; + return ( + <div className="mt-2 rounded-[3px] bg-panel-2 px-2.5 py-1.5 font-mono text-[11px] leading-relaxed text-text-2" data-stage-log=""> + {run.log.slice(-8).map((l, i) => ( + <div key={i}>{l}</div> + ))} + {run.error && ( + <div role="alert" className="text-reject-text"> + {run.error} + </div> + )} + </div> + ); +} + +function Manual({ children }: { children: React.ReactNode }) { + return <p className="mb-2 mt-0 text-[12px] text-muted">By hand: {children}</p>; +} + +function Counts({ title, of }: { title: string; of: Record<string, number> }) { + const e = Object.entries(of); + return ( + <div> + <div className="micro mb-1">{title}</div> + {e.length ? ( + <ul className="m-0 list-none p-0 font-mono text-[11.5px] text-text-2"> + {e.map(([k, n]) => ( + <li key={k}> + {k} <span className="text-meter">{nf.format(n)}</span> + </li> + ))} + </ul> + ) : ( + <span className="text-[12px] text-muted-2">none</span> + )} + </div> + ); +} + +type Plan = { title: string; what: string; detail?: unknown; confirm: () => Promise<void> }; + +/** The editable part of a definition, as the editor's JSON shows it (never the private-name hashes). */ +function editable(def: PipelineView["definition"]) { + return { + subjects: def.subjects, + scope: def.scope, + eras: def.eras, + groups: def.groups, + readerPrompts: def.readerPrompts, + keyDates: def.keyDates ?? [], + status: def.status, + privateNames: { note: def.privateNames.note }, + }; +} + +export default function CasePipeline({ initial }: { initial: PipelineView }) { + const hydrated = useHydrated(); + const [view, setView] = useState(initial); + const [busy, setBusy] = useState<string | null>(null); + const [status, setStatus] = useState<{ text: string; tone?: "error" } | null>(null); + const [plan, setPlan] = useState<Plan | null>(null); + const [batchShown, setBatchShown] = useState<{ id: string; text: string } | null>(null); + const [defText, setDefText] = useState(() => JSON.stringify(editable(initial.definition), null, 2)); + const [defError, setDefError] = useState<string | null>(null); + const [term, setTerm] = useState(""); + const [rowsText, setRowsText] = useState(""); + const [summaryText, setSummaryText] = useState(initial.summary?.text ?? ""); + const [W, setW] = useState("30"); + const [budget, setBudget] = useState("60000"); + const [minRel, setMinRel] = useState("2"); + const id = view.case.id; + const api = useCallback((op?: string) => researchCasePipelineApi(id, op), [id]); + + const refresh = useCallback(async () => { + const v = await call<PipelineView>(api(), "GET"); + setView(v); + return v; + }, [api]); + + const anyRunning = Object.values(view.stages).some((s) => s?.state === "running"); + useEffect(() => { + if (!anyRunning) return; + const t = setInterval(() => void refresh().catch(() => {}), 1200); + return () => clearInterval(t); + }, [anyRunning, refresh]); + + const act = useCallback( + async (label: string, fn: () => Promise<string | void>) => { + setBusy(label); + setStatus(null); + try { + const text = await fn(); + if (text) setStatus({ text }); + } catch (e) { + setStatus({ text: (e as Error).message, tone: "error" }); + } finally { + setBusy(null); + } + }, + [], + ); + + const runStage = (stage: CaseStage, body: Record<string, unknown> = {}) => + act(stage, async () => { + let r: { started: boolean; view: PipelineView }; + try { + r = await call<{ started: boolean; view: PipelineView }>(api(stage), "POST", body); + } catch (e) { + // A refused stage still left its record (a failed run): draw it. + await refresh().catch(() => {}); + throw e; + } + setView(r.view); + const run = r.view.stages[stage]; + if (run?.state === "failed") throw new Error(run.error ?? `${stage} failed`); + return r.started ? `${stage}: started` : `${stage}: done`; + }); + + const saveDefinition = () => + act("define", async () => { + let body: unknown; + try { + body = JSON.parse(defText); + } catch (e) { + setDefError(`not JSON: ${(e as Error).message}`); + return; + } + try { + const v = await call<PipelineView>(api(), "PUT", body); + setView(v); + setDefText(JSON.stringify(editable(v.definition), null, 2)); + setDefError(null); + return "definition saved"; + } catch (e) { + setDefError((e as Error).message); + } + }); + + const privateNames = (op: "add" | "remove" | "clear") => + act("private", async () => { + let body: Record<string, unknown> = { clear: true }; + if (op !== "clear") { + const problem = privateTermProblem(term); + if (problem) throw new Error(problem); + body = { [op]: [await privateNameHashWeb(term)] }; + } + const r = await call<{ count: number; changed: number }>(api("private-names"), "POST", body); + setTerm(""); + await refresh(); + return op === "add" ? (r.changed ? `added: ${r.count} private ${r.count === 1 ? "name" : "names"} (hashed)` : `already there: ${r.count} private names`) : op === "remove" ? (r.changed ? `removed: ${r.count} left` : "that name was not there") : "every private name removed"; + }); + + const addRows = () => + act("findings", async () => { + const rows = rowsText + .split("\n") + .filter((l) => l.trim()) + .map((l, i) => { + try { + return JSON.parse(l) as unknown; + } catch { + throw new Error(`line ${i + 1} is not JSON`); + } + }); + const r = await call<{ rows: { row: string }[] }>(api("findings"), "POST", { rows }); + setRowsText(""); + await refresh(); + return `${r.rows.length} ${r.rows.length === 1 ? "row" : "rows"} added: ${r.rows.map((x) => x.row).join(", ")}`; + }); + + const saveSummary = () => + act("summary", async () => { + await call(api("summary"), "POST", { text: summaryText }); + await refresh(); + return "summary saved as yours"; + }); + + const showBatch = (b: string) => + act("batch", async () => { + const r = await fetch(`${api("batch")}?batch=${encodeURIComponent(b)}`, { cache: "no-store" }); + if (!r.ok) throw new Error((await r.json().catch(() => null))?.error ?? `HTTP ${r.status}`); + setBatchShown({ id: b, text: await r.text() }); + }); + + const askGap = (action: "download-missing" | "transcribe" | "persist" | "focus", slug = "") => + act("gap", async () => { + const r = await call<{ plan: { route: string; request: unknown; what: string; dryRun?: unknown; dryRunError?: string } }>(api("gap"), "POST", { action, slug }); + setPlan({ + title: action === "focus" ? "Focus the case" : `${action} · ${slug}`, + what: r.plan.what, + detail: { route: r.plan.route, request: r.plan.request, ...(r.plan.dryRun ? { dryRun: r.plan.dryRun } : {}), ...(r.plan.dryRunError ? { dryRunError: r.plan.dryRunError } : {}) }, + confirm: async () => { + await call(api("gap"), "POST", { action, slug, confirm: true }); + setStatus({ text: `asked the editor: ${r.plan.route.replace("/api/ops/", "")}${slug ? ` ${slug}` : ""}` }); + }, + }); + }); + + const askHandoff = () => + act("handoff", async () => { + const r = await call<{ plan: { findings: number; sections: { label: string; rows: number }[]; quarantinedLeftOut: number; blocked: { hits: number; rows: string[] } | null } }>(api("handoff"), "POST", { minRelevance: Number(minRel) }); + if (r.plan.blocked) throw new Error(`the privacy gate blocks the hand-off: ${r.plan.blocked.hits} private-name hits in ${r.plan.blocked.rows.length} rows (${r.plan.blocked.rows.join(", ")})`); + setPlan({ + title: "Hand off to the board", + what: `Pin ${r.plan.findings} ${r.plan.findings === 1 ? "finding" : "findings"} to the board, one section per reader group${r.plan.quarantinedLeftOut ? `; ${r.plan.quarantinedLeftOut} quarantined left out` : ""}. The board's own hand-offs then draft the article or start the video.`, + detail: r.plan.sections, + confirm: async () => { + const c = await call<{ pinned: number; duplicates: number }>(api("handoff"), "POST", { confirm: true, minRelevance: Number(minRel) }); + setStatus({ text: `pinned ${c.pinned} to the board${c.duplicates ? ` (${c.duplicates} already there)` : ""}` }); + }, + }); + }); + + const s = view.stages; + const def = view.definition; + const counts = view.candidates.counts; + const keyYears = useMemo(() => new Set(view.keyYears), [view.keyYears]); + const gateFindings = view.gate.findings; + const shownFindings = view.merge?.sections.reduce((n, x) => n + x.rows.length, 0) ?? 0; + const dis = !hydrated || busy !== null; + + return ( + <> + <AppHeader + crumbs={[{ href: researchHref(), label: "Research" }, { href: researchCaseHref(id), label: view.case.title }, { label: "Pipeline" }]} + meta={ + <> + <span className="micro mr-2">Research · case pipeline</span> + <span data-pipeline-meta=""> + {view.defined ? `${plural(def.subjects.length, "subject")} · ${plural(def.eras.length, "era")} · ${plural(def.groups.length, "reader group")} · ${plural(view.channels.slugs.length, "channel")} · status ${def.status}` : "not defined yet"} + </span> + </> + } + actions={ + <Link prefetch={false} href={researchCaseHref(id)} className={buttonVariants({ variant: "outline", size: "sm" })}> + The board + </Link> + } + below={ + <nav aria-label="Stages" className="flex flex-wrap gap-x-3 gap-y-1 text-[12px]"> + {STAGE_NAV.map((n) => ( + <a key={n.id} href={`#stage-${n.id}`} className="ink-link"> + {n.label} + </a> + ))} + </nav> + } + /> + <div className="min-h-0 flex-1 overflow-auto px-7 pb-10 pt-3 max-md:px-4" data-pipeline=""> + <div className="mx-auto grid max-w-[1100px] gap-4"> + {status && ( + <div role={status.tone === "error" ? "alert" : "status"} data-pipeline-status="" className={cn("rounded-[3px] border px-3 py-2 text-[12.5px]", status.tone === "error" ? "border-reject-text text-reject-text" : "border-seam-2 text-text-2")}> + {status.text} + </div> + )} + + {/* ── Define ── */} + <Panel id="stage-define" title="Define the case" aside={<span className="font-mono text-[11px] text-muted">{view.stored}pipeline.json</span>}> + <Manual> + the subjects (and their own channels), the scope (channels, <code>site:group</code> groups, sites), the eras with their term families (regex; a strict + family for a subject&apos;s own late material), the reader groups (a list of channels, &quot;subject&quot; or &quot;coverage&quot;), the reader prompts and the key dates. Or + <code> archilyzer case define {id} --file pipeline.json</code>. + </Manual> + <Field label="Definition (JSON)" error={defError ?? undefined}> + <Textarea aria-label="Definition" rows={14} spellCheck={false} className="font-mono text-[12px]" value={defText} onChange={(e) => setDefText(e.target.value)} /> + </Field> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <button type="button" disabled={dis} className={buttonVariants({ variant: "go", size: "sm" })} onClick={saveDefinition}> + Save the definition + </button> + <span className="text-[12px] text-muted">{view.channels.slugs.length ? `reads ${view.channels.slugs.join(", ")}` : "no channel in scope yet"}</span> + {view.channels.problems.map((p) => ( + <span key={p} className="text-[12px] text-doubt-text"> + {p} + </span> + ))} + </div> + <div className="mt-4 border-t border-seam pt-3" data-private-names=""> + <div className="micro mb-1">Private names</div> + <p className="mb-2 mt-0 text-[12px] text-muted"> + A name typed here is hashed in this browser and only its hash is stored: no file holds it, and nothing shows it again. The gate blocks findings, the + summary, the export and a hand-off that name one. + </p> + <div className="flex flex-wrap items-end gap-2"> + <Field label="A private name (at most three words)"> + <Input type="password" autoComplete="off" aria-label="A private name" value={term} onChange={(e) => setTerm(e.target.value)} className="w-[260px]" /> + </Field> + <button type="button" disabled={dis || !term.trim()} className={buttonVariants({ size: "sm" })} onClick={() => void privateNames("add")}> + Add + </button> + <button type="button" disabled={dis || !term.trim()} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => void privateNames("remove")}> + Remove + </button> + <button type="button" disabled={dis || !view.privateNames} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => void privateNames("clear")}> + Remove all + </button> + <span className="font-mono text-[12px] text-meter" data-private-count=""> + {view.privateNames} hashed + </span> + </div> + </div> + </Panel> + + {/* ── 1 Coverage ── */} + <Panel id="stage-coverage" title="1 · Coverage" aside={<RunState run={s.coverage} />}> + <Manual>per channel and year, what is listed, held, transcribed and held as audio with no transcript; the key years (an era touches them) are marked. A gap&apos;s button asks the editor&apos;s own action, plan first.</Manual> + <div className="flex flex-wrap items-center gap-2"> + <button type="button" disabled={dis || !view.defined || s.coverage?.state === "running"} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void runStage("coverage")}> + Count coverage + </button> + <button type="button" disabled={dis || !view.defined || !view.editor} className={buttonVariants({ size: "sm" })} onClick={() => void askGap("focus")} title={view.editor ? undefined : "umtool has no WORKER_TOKEN: the editor cannot be asked"}> + Focus the case{def.scope.sites.length ? `'s site (${def.scope.sites[0]})` : "'s channels"} + </button> + </div> + <StageLog run={s.coverage} /> + {view.coverage.rows.length > 0 && ( + <div className="mt-3 grid gap-3"> + <Table aria-label="Coverage"> + <thead> + <tr> + <TH>Channel</TH> + <TH>Year</TH> + <TH className="text-right">Listed</TH> + <TH className="text-right">Held</TH> + <TH className="text-right">Transcribed</TH> + <TH className="text-right">Audio, no transcript</TH> + </tr> + </thead> + <tbody> + {view.coverage.rows.map((r) => ( + <tr key={`${r.channel}:${r.year}`} data-key-year={r.key ? "" : undefined} className={r.key ? "bg-panel-2" : undefined}> + <TD>{r.channel}</TD> + <TD> + <span className="font-mono">{r.year || "undated"}</span> + {r.key && <span className={cn(badgeVariants({ variant: "meter", size: "sm" }), "ml-2")}>key</span>} + </TD> + <TD numeric>{nf.format(r.listed)}</TD> + <TD numeric>{nf.format(r.held)}</TD> + <TD numeric>{nf.format(r.transcribed)}</TD> + <TD numeric className={r.untranscribedAudio ? "text-doubt-text" : undefined}> + {nf.format(r.untranscribedAudio)} + </TD> + </tr> + ))} + </tbody> + </Table> + <div className="grid gap-1.5" aria-label="Gaps"> + {view.coverage.gaps.map((g) => ( + <div key={g.slug} className="flex flex-wrap items-center gap-2 text-[12.5px]" data-gap={g.slug}> + <span className="min-w-[160px] font-medium text-text-2">{g.slug}</span> + <button type="button" disabled={dis || !g.missing || !view.editor} className={buttonVariants({ size: "sm" })} onClick={() => void askGap("download-missing", g.slug)}> + Download missing ({nf.format(g.missing)}) + </button> + <button type="button" disabled={dis || !g.untranscribedAudio || !view.editor} className={buttonVariants({ size: "sm" })} onClick={() => void askGap("transcribe", g.slug)}> + Transcribe ({nf.format(g.untranscribedAudio)}) + </button> + <button type="button" disabled={dis || !g.keyHeld || !view.editor} className={buttonVariants({ size: "sm" })} onClick={() => void askGap("persist", g.slug)}> + Persist the key period ({nf.format(g.keyHeld)} held) + </button> + </div> + ))} + </div> + </div> + )} + </Panel> + + {/* ── 2 Candidates ── */} + <Panel id="stage-candidates" title="2 · Candidates" aside={<RunState run={s.candidates} />}> + <Manual>the scope&apos;s transcripts searched for each era&apos;s families (en-orig before en; rolling captions folded; title hits), ±W s windows merged, the noise filters applied — counted before anything is read. Deterministic: the same corpus gives the same windows.</Manual> + <div className="flex flex-wrap items-end gap-2"> + <Field label="W (seconds either side)"> + <Input aria-label="Window seconds" className="w-[90px]" value={W} onChange={(e) => setW(e.target.value)} inputMode="numeric" /> + </Field> + <button type="button" disabled={dis || !view.defined || !def.eras.length || s.candidates?.state === "running"} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void runStage("candidates", { window: Number(W) })}> + Find candidates + </button> + </div> + <StageLog run={s.candidates} /> + {counts && ( + <div className="mt-3 grid gap-3" data-candidate-counts=""> + <p className="m-0 text-[13px]"> + <span className="font-mono text-meter">{nf.format(counts.windows)}</span> windows in <span className="font-mono text-meter">{nf.format(counts.videos)}</span> recordings ·{" "} + {nf.format(counts.titleHits)} title hits · scanned {nf.format(counts.scanned.videos)} recordings in {counts.scanned.channels} channels, {nf.format(counts.scanned.inEra)} in an era, {nf.format(counts.scanned.withText)} with words,{" "} + <span className={counts.scanned.noText ? "text-doubt-text" : undefined}>{nf.format(counts.scanned.noText)} with none yet</span> + </p> + <div className="grid grid-cols-[repeat(auto-fill,minmax(160px,1fr))] gap-3"> + <Counts title="By family" of={counts.byFamily} /> + <Counts title="By year" of={counts.byYear} /> + <Counts title="By channel" of={counts.byChannel} /> + <Counts title="By group" of={counts.byGroup} /> + <Counts title="Noise (dropped)" of={counts.noise} /> + </div> + {counts.skipped.map((x) => ( + <span key={x.slug} className="text-[12px] text-doubt-text"> + skipped {x.slug}: {x.reason} + </span> + ))} + {view.candidates.sample.length > 0 && ( + <details> + <summary className="cursor-pointer text-[12.5px] text-text-2"> + The first {view.candidates.sample.length} of {nf.format(view.candidates.total)} windows + </summary> + <ol className="m-0 mt-2 grid list-none gap-2 p-0"> + {view.candidates.sample.map((w) => ( + <li key={w.key} className="border-l-2 border-seam-2 pl-2.5 text-[12px]" data-window={w.key}> + <div className="font-mono text-[11px] text-muted"> + {w.key} · {w.date} · {w.group} · {w.track} + {w.titleHit ? " · title hit" : ""} + </div> + <div className="text-text-2">{w.title}</div> + <div className="text-muted">{w.text}</div> + </li> + ))} + </ol> + </details> + )} + </div> + )} + </Panel> + + {/* ── 3 Batches ── */} + <Panel id="stage-batches" title="3 · Batches" aside={<RunState run={s.batches} />}> + <Manual> + the windows grouped per reader group under a character budget, written as wrapped text — no line over 200 characters, so a reader&apos;s file tool never drops the densest windows. A batch a reader has begun is kept; new windows make the next round. Or <code>archilyzer case batch {id} &lt;batch&gt;</code>. + </Manual> + <div className="flex flex-wrap items-end gap-2"> + <Field label="Budget (characters a batch)"> + <Input aria-label="Batch budget" className="w-[110px]" value={budget} onChange={(e) => setBudget(e.target.value)} inputMode="numeric" /> + </Field> + <button type="button" disabled={dis || !view.candidates.total} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void runStage("batches", { budget: Number(budget) })}> + Make batches + </button> + </div> + <StageLog run={s.batches} /> + {view.batches.length > 0 && ( + <Table aria-label="Batches" className="mt-3"> + <thead> + <tr> + <TH>Batch</TH> + <TH>Group</TH> + <TH className="text-right">Round</TH> + <TH className="text-right">Windows</TH> + <TH className="text-right">Characters</TH> + <TH>State</TH> + <TH /> + </tr> + </thead> + <tbody> + {view.batches.map((b) => ( + <tr key={b.id} data-batch={b.id}> + <TD className="font-mono">{b.id}</TD> + <TD>{b.group}</TD> + <TD numeric>{b.round}</TD> + <TD numeric>{b.windows.length}</TD> + <TD numeric>{nf.format(b.chars)}</TD> + <TD> + <span className={badgeVariants({ variant: b.state === "read" ? "neutral" : b.state === "failed" ? "blocking" : "state", size: "sm" })}>{b.state}</span> + </TD> + <TD> + <button type="button" disabled={dis} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => void showBatch(b.id)}> + Read the text + </button> + </TD> + </tr> + ))} + </tbody> + </Table> + )} + </Panel> + + {/* ── 4 Read (lane B) ── */} + <Panel id="stage-read" title="4 · Read" aside={<span className="font-mono text-[11px] text-muted">{view.findings.rows.length} rows</span>}> + <Manual> + read a batch with its group&apos;s prompt (the naming rule is always in it) and write one finding row per quote — verbatim, at most 45 words, the window&apos;s key and second. Paste the rows below (one JSON object a line), or + <code> archilyzer case findings {id} --file rows.jsonl</code>. The candidate deck and the case-read readers are the next lane&apos;s. + </Manual> + {Object.keys(view.prompts).length > 0 && ( + <details className="mb-2"> + <summary className="cursor-pointer text-[12.5px] text-text-2">Reader prompts</summary> + <div className="mt-2 grid gap-2"> + {Object.entries(view.prompts).map(([g, p]) => ( + <div key={g}> + <div className="micro">{g}</div> + <pre className="m-0 whitespace-pre-wrap rounded-[3px] bg-panel-2 px-2.5 py-1.5 text-[11.5px] text-text-2" data-prompt={g}> + {p} + </pre> + </div> + ))} + </div> + </details> + )} + <Field label="Finding rows (JSON lines)"> + <Textarea aria-label="Finding rows" rows={4} spellCheck={false} className="font-mono text-[11.5px]" value={rowsText} onChange={(e) => setRowsText(e.target.value)} placeholder='{"batch":"own-1-001","slug":"…","id":"…","date":"20150310","title":"…","t":31,"url":"…","category":"…","relevance":3,"quote":"…","summary":"…","speaker":"…","confidence":"high","round":1,"by":"hand"}' /> + </Field> + <button type="button" disabled={dis || !rowsText.trim()} className={cn(buttonVariants({ size: "sm" }), "mt-2")} onClick={addRows}> + Add rows + </button> + {view.findings.invalid.length > 0 && ( + <p role="alert" className="mt-2 text-[12px] text-reject-text"> + {view.findings.invalid.length} lines of findings.jsonl do not check: {view.findings.invalid.map((x) => `line ${x.line} (${x.errors.join("; ")})`).join(" · ")} + </p> + )} + {view.findings.rows.length > 0 && ( + <Table aria-label="Findings" className="mt-3"> + <thead> + <tr> + <TH>Row</TH> + <TH>Recording</TH> + <TH className="text-right">Rel.</TH> + <TH>Quote</TH> + <TH>By</TH> + <TH>Check</TH> + </tr> + </thead> + <tbody> + {view.findings.rows.map((r) => ( + <tr key={r.row} data-finding={r.row} className={gateFindings.rows.some((x) => x.id === r.row) ? "bg-[color-mix(in_srgb,var(--reject-text)_8%,transparent)]" : undefined}> + <TD className="font-mono">{r.row}</TD> + <TD> + <span className="font-mono text-[11px]"> + {r.slug}/{r.id} @ {Math.floor(r.t)}s + </span> + <div className="text-muted">{r.date}</div> + </TD> + <TD numeric>{r.relevance}</TD> + <TD>{r.quote}</TD> + <TD>{r.by}</TD> + <TD>{r.quoteCheck}{r.verify ? ` · ${r.verify.status}` : ""}</TD> + </tr> + ))} + </tbody> + </Table> + )} + </Panel> + + {/* ── 5 Merge ── */} + <Panel id="stage-merge" title="5 · Merge" aside={<span className="font-mono text-[11px] text-muted">{shownFindings} in the report</span>}> + <Manual>the same recording within 20 s is one finding (the higher relevance, then the later round); sections by reader group; relevance 2 and up by default; the quarantined in their own section. A preview: nothing is written until Export.</Manual> + <Field label="Relevance floor" className="w-[150px]"> + <Select aria-label="Relevance floor" value={minRel} onChange={(e) => setMinRel(e.target.value)}> + <option value="1">1 and up</option> + <option value="2">2 and up</option> + <option value="3">3 only</option> + </Select> + </Field> + {view.merge && ( + <div className="mt-2 grid gap-2 text-[12.5px]" data-merge=""> + {view.merge.sections.map((sec) => ( + <div key={sec.group}> + <span className="font-medium">{sec.label}</span> <span className="font-mono text-meter">{sec.rows.length}</span> — <span className="font-mono text-[11px] text-muted">{sec.rows.map((r) => r.row).join(", ")}</span> + </div> + ))} + {view.merge.quarantined.length > 0 && ( + <div> + <span className="font-medium">Quarantined</span> <span className="font-mono text-meter">{view.merge.quarantined.length}</span> + </div> + )} + <div className="text-muted"> + {view.merge.duplicates.length} folded as duplicates ({view.merge.duplicates.map((d) => `${d.row} → ${d.of}`).join(", ") || "none"}) · {view.merge.belowFloor.length} below the floor · {view.merge.total} rows + </div> + </div> + )} + <div className="mt-3 border-t border-seam pt-3"> + <Field label="Summary (on top of the report)" hint={view.summary?.draft ? `A draft by ${view.summary.model ?? view.summary.by}: saving it here makes it yours.` : "Written by hand. A model's draft is marked as a draft until a person saves it."}> + <Textarea aria-label="Summary" rows={4} value={summaryText} onChange={(e) => setSummaryText(e.target.value)} /> + </Field> + <button type="button" disabled={dis || !summaryText.trim()} className={cn(buttonVariants({ size: "sm" }), "mt-2")} onClick={saveSummary}> + Save the summary + </button> + {view.summary?.draft && <span className={cn(badgeVariants({ variant: "open", size: "sm" }), "ml-2")}>draft</span>} + </div> + </Panel> + + {/* ── 6 Privacy gate ── */} + <Panel id="stage-privacy" title="6 · Privacy gate" aside={<span className="font-mono text-[11px] text-muted">{view.privateNames} private names (hashed)</span>}> + <Manual>every write of findings, the summary, the export and a hand-off is checked against the case&apos;s private names (every word and 2- and 3-word phrase, hashed). A hit blocks it and names the rows — never the name. Write [name withheld] in its place.</Manual> + <div data-gate={gateFindings.blocked || view.gate.summary.blocked ? "blocked" : "clear"} className="text-[12.5px]"> + {gateFindings.blocked ? ( + <p role="alert" className="m-0 text-reject-text"> + Blocked: {gateFindings.hits} private-name {gateFindings.hits === 1 ? "hit" : "hits"} in {gateFindings.rows.length} {gateFindings.rows.length === 1 ? "row" : "rows"} ({gateFindings.rows.map((r) => `${r.id} ×${r.hits}`).join(", ")}). + </p> + ) : ( + <p className="m-0 text-text-2">{view.privateNames ? `Clear: no finding names a private name (${view.findings.rows.length} rows read).` : "No private names in this case yet."}</p> + )} + {view.gate.summary.blocked && ( + <p role="alert" className="m-0 mt-1 text-reject-text"> + The summary names a private name ({view.gate.summary.hits} {view.gate.summary.hits === 1 ? "hit" : "hits"}). + </p> + )} + </div> + </Panel> + + {/* ── Export and hand-off ── */} + <Panel id="stage-export" title="Export and hand-off" aside={<RunState run={s.export} />}> + <Manual> + the merge and the summary as REPORT.md (cited markdown in the house format: it converts as a /sweep report) and REPORT.html; or pin the merged findings to the board, whose own hand-offs then draft the article or start the video. Or <code>archilyzer case export {id}</code>. + </Manual> + <div className="flex flex-wrap items-center gap-2"> + <button type="button" disabled={dis || !view.defined} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void runStage("export", { minRelevance: Number(minRel) })}> + Export the report + </button> + <button type="button" disabled={dis || !shownFindings} className={buttonVariants({ size: "sm" })} onClick={askHandoff}> + Hand off to the board + </button> + {view.report.exists && ( + <> + <a className="ink-link text-[12.5px]" href={`${api("report")}?format=md`} target="_blank" rel="noreferrer"> + REPORT.md + </a> + <a className="ink-link text-[12.5px]" href={`${api("report")}?format=html`} target="_blank" rel="noreferrer"> + REPORT.html + </a> + </> + )} + </div> + <StageLog run={s.export} /> + </Panel> + + {/* ── 9 Date checks ── */} + <Panel id="stage-date-checks" title="9 · Absence and date checks" aside={<RunState run={s["date-checks"]} />}> + <Manual>the subject&apos;s own uploads around each key date and the latest after it, captioned or not, and whether any finding is a response.</Manual> + <button type="button" disabled={dis || !view.defined || s["date-checks"]?.state === "running"} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void runStage("date-checks")}> + Check the dates + </button> + <StageLog run={s["date-checks"]} /> + <div className="mt-3 grid gap-4"> + {view.dateChecks.map((d) => ( + <div key={`${d.date}:${d.label}`} data-date-check={d.date}> + <div className="text-[13px]"> + <span className="font-mono">{d.date}</span> <span className="font-medium">{d.label}</span> + </div> + <p className="m-0 text-[12.5px] text-text-2" data-date-sentence=""> + {d.sentence} + </p> + {d.uploads.length > 0 && ( + <Table aria-label={`Uploads around ${d.date}`} className="mt-1"> + <thead> + <tr> + <TH>Date</TH> + <TH>Recording</TH> + <TH>Title</TH> + <TH>Captioned</TH> + </tr> + </thead> + <tbody> + {d.uploads.map((u) => ( + <tr key={`${u.slug}/${u.id}`}> + <TD className="font-mono"> + {u.date} + {u.date >= d.date.replace(/-/g, "") ? " ·after" : " ·before"} + </TD> + <TD className="font-mono text-[11px]"> + {u.slug}/{u.id} + </TD> + <TD>{u.title}</TD> + <TD>{u.captioned ? "yes" : "no"}</TD> + </tr> + ))} + </tbody> + </Table> + )} + </div> + ))} + </div> + </Panel> + </div> + </div> + + <Dialog open={!!plan} onClose={() => setPlan(null)} title={plan?.title ?? ""}> + {plan && ( + <div className="grid gap-3 px-4 py-3 text-[13px]"> + <p className="m-0">{plan.what}</p> + {plan.detail !== undefined && <pre className="m-0 max-h-[260px] overflow-auto rounded-[3px] bg-panel-2 px-2.5 py-1.5 text-[11px]">{JSON.stringify(plan.detail, null, 2)}</pre>} + <div className="flex gap-2"> + <button + type="button" + className={buttonVariants({ variant: "go", size: "sm" })} + onClick={() => + void act("confirm", async () => { + await plan.confirm(); + setPlan(null); + await refresh(); + }) + } + > + Confirm + </button> + <button type="button" className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => setPlan(null)}> + Cancel + </button> + </div> + </div> + )} + </Dialog> + <Dialog open={!!batchShown} onClose={() => setBatchShown(null)} title={batchShown ? `Batch ${batchShown.id}` : ""} className="w-[min(900px,calc(100vw-32px))]"> + {batchShown && ( + <pre className="m-0 max-h-[70vh] overflow-auto px-4 py-3 font-mono text-[11.5px] leading-relaxed" data-batch-text=""> + {batchShown.text} + </pre> + )} + </Dialog> + </> + ); +} diff --git a/umtool/e2e/case-pipeline.spec.ts b/umtool/e2e/case-pipeline.spec.ts @@ -0,0 +1,205 @@ +import { test, expect, type Page } from "@playwright/test"; +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { PIPELINE_CASE, PIPELINE_DEFINITION, PLANTED, SUBJECT_CHANNEL, TALK_CHANNEL } from "./fixtures/case-fixture.mjs"; +import { researchCaseHref, researchCasePipelineApi, researchCasePipelineHref } from "../lib/research/hrefs"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// THE CASE PIPELINE (plans/release-38/research-cases-and-assist.md, lane A) on its fixture +// (e2e/fixtures/case-fixture.mjs): from the board to the pipeline; the definition saved; a private name typed, +// stored only as a hash; coverage per channel × year with the key years and a gap's button asking the editor +// (stubbed) after its plan; candidates and their counts; batches whose every line is at most 200 characters; +// finding rows by hand, one refused by the gate; the gate blocking the export of a row written before the name was +// added, by row id and never the name; the export once the row is withheld; the hand-off to the board; the date +// checks' sentence. E2E_SHOTS_DIR, when set, collects a screenshot of each stage. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const CASE_DIR = path.join(FIXTURE, ".umtool", "research", PIPELINE_CASE); +const stubLog = () => JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")) as { route?: string; slug?: string }[]; +const SHOTS = process.env.E2E_SHOTS_DIR; + +async function shot(page: Page, name: string, stage?: string) { + if (!SHOTS) return; + if (stage) await page.locator(`#stage-${stage}`).scrollIntoViewIfNeeded(); + await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false }); +} + +const status = (page: Page) => page.locator("[data-pipeline-status]"); +const stageState = (page: Page, stage: string) => page.locator(`#stage-${stage} [data-stage-state]`); + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, [researchCasePipelineHref(PIPELINE_CASE), researchCasePipelineApi(PIPELINE_CASE), researchCaseHref(PIPELINE_CASE)]); +}); + +test("a case through its pipeline: define, coverage, candidates, batches, findings, the privacy gate, export, hand-off, date checks", async ({ page }) => { + test.setTimeout(180_000); + await page.setViewportSize({ width: 1366, height: 900 }); + + // From the board. + await page.goto(researchCaseHref(PIPELINE_CASE)); + await page.locator("[data-case-pipeline]").click(); + await expect(page).toHaveURL(new RegExp(`/research/${PIPELINE_CASE}/pipeline`)); + await expect(page.locator("[data-pipeline-meta]")).toHaveText("not defined yet"); + + // Define: a private name in the definition is refused; the definition itself saves. + const defBox = page.getByRole("textbox", { name: "Definition" }); + await defBox.fill(JSON.stringify({ ...PIPELINE_DEFINITION, privateNames: { note: "x", sha256: ["a".repeat(64)] } })); + await page.getByRole("button", { name: "Save the definition" }).click(); + await expect(page.locator("#stage-define [role=alert]")).toContainText("never saved with the definition"); + await defBox.fill(JSON.stringify(PIPELINE_DEFINITION, null, 2)); + await page.getByRole("button", { name: "Save the definition" }).click(); + await expect(page.locator("[data-pipeline-meta]")).toContainText("1 subject · 2 eras · 2 reader groups · 2 channels"); + await shot(page, "01-define", "define"); + + // Coverage: per channel × year; the key years marked; a gap's button plans, then asks the editor. + await page.getByRole("button", { name: "Count coverage" }).click(); + await expect(stageState(page, "coverage")).toHaveAttribute("data-stage-state", "done"); + const cov = page.getByRole("table", { name: "Coverage" }); + const own2015 = cov.locator("tr", { hasText: SUBJECT_CHANNEL }).filter({ hasText: "2015" }); + await expect(own2015).toHaveAttribute("data-key-year", ""); + await expect(own2015.locator("td")).toHaveText([SUBJECT_CHANNEL, /2015\s*key/, "2", "2", "1", "1"]); + await expect(cov.locator("tr", { hasText: "undated" })).toHaveCount(1); + await shot(page, "02-coverage", "coverage"); + const gap = page.locator(`[data-gap="${SUBJECT_CHANNEL}"]`); + await gap.getByRole("button", { name: /Download missing \(2\)/ }).click(); + const dialog = page.getByRole("dialog"); + await expect(dialog).toContainText(`download every listed video ${SUBJECT_CHANNEL} does not hold`); + await expect(dialog).toContainText('"/api/ops/download-missing"'); + expect(stubLog().some((r) => r.route === "download-missing")).toBe(false); + await dialog.getByRole("button", { name: "Confirm" }).click(); + await expect(status(page)).toHaveText(`asked the editor: download-missing ${SUBJECT_CHANNEL}`); + await expect.poll(() => stubLog().filter((r) => r.route === "download-missing").map((r) => r.slug)).toEqual([SUBJECT_CHANNEL]); + await gap.getByRole("button", { name: /Persist the key period/ }).click(); + await expect(dialog).toContainText('"toFetch"'); + await dialog.getByRole("button", { name: "Cancel" }).click(); + + // Candidates: counted before any read; the talk show's line that names no subject is noise. + await page.getByRole("button", { name: "Find candidates" }).click(); + await expect(stageState(page, "candidates")).toHaveAttribute("data-stage-state", "done"); + const counts = page.locator("[data-candidate-counts]"); + await expect(counts).toContainText("3 windows in 3 recordings"); + await expect(counts).toContainText("noSubject 1"); + await expect(counts).toContainText("notStrict 1"); + await shot(page, "03-candidates", "candidates"); + + // Batches: per group, wrapped -- no line over 200 characters, on the page and on disk. + await page.getByRole("button", { name: "Make batches" }).click(); + await expect(page.locator("[data-batch]")).toHaveCount(2); + await expect(page.locator('[data-batch="own-1-001"]')).toContainText("pending"); + await page.locator('[data-batch="talk-1-001"]').getByRole("button", { name: "Read the text" }).click(); + const text = (await page.locator("[data-batch-text]").textContent()) ?? ""; + expect(text).toContain("Naming rule"); + expect(text).toContain("Wren Halloway stopped by the lantern shop"); + expect(Math.max(...text.split("\n").map((l) => l.length))).toBeLessThanOrEqual(200); + for (const b of ["own-1-001", "talk-1-001"]) { + const onDisk = readFileSync(path.join(CASE_DIR, "batches", `${b}.txt`), "utf8"); + expect(Math.max(...onDisk.split("\n").map((l) => l.length))).toBeLessThanOrEqual(200); + } + await shot(page, "04-batches"); + await page.keyboard.press("Escape"); + + // Findings by hand, before any private name: the talk-show row names a private person. + const row = (o: Record<string, unknown>) => + JSON.stringify({ batch: "own-1-001", slug: SUBJECT_CHANNEL, id: "lw-2015a", date: "20150310", title: "Opening the lantern shop", t: 120, url: "https://www.youtube.com/watch?v=lw-2015a", category: "shop", relevance: 3, quote: "welcome to the lantern shop", summary: "She opens the shop", speaker: "Wren Halloway", confidence: "high", round: 1, by: "hand", ...o }); + const rows = [ + row({}), + row({ t: 126, relevance: 2, quote: "I built every lantern here myself", summary: "She built the lanterns" }), + row({ batch: "talk-1-001", slug: TALK_CHANNEL, id: "ht-2015a", date: "20150320", title: "Harbor Talk 12", t: 186, url: "https://www.youtube.com/watch?v=ht-2015a", quote: `she was with ${PLANTED} that day`, summary: "The host says who she was with", speaker: "host" }), + row({ id: "lw-2021a", date: "20210305", title: "Closing the shop", t: 240, quote: "the lantern shop is closing for good", summary: "She closes the shop" }), + ]; + await page.getByRole("textbox", { name: "Finding rows" }).fill(rows.join("\n")); + await page.getByRole("button", { name: "Add rows" }).click(); + await expect(status(page)).toHaveText("4 rows added: f1, f2, f3, f4"); + + // The private name, typed: hashed in the browser, posted as a hash, shown as a count. + const posted: string[] = []; + page.on("request", (r) => { + if (r.url().includes("/pipeline/private-names")) posted.push(r.postData() ?? ""); + }); + await page.getByLabel("A private name", { exact: true }).fill(PLANTED); + await page.getByRole("button", { name: "Add", exact: true }).click(); + await expect(page.locator("[data-private-count]")).toHaveText("1 hashed"); + expect(posted.join("")).not.toMatch(/Ottoline|Brackenridge/i); + expect(posted.join("")).toMatch(/"add":\["[0-9a-f]{64}"\]/); + expect(readFileSync(path.join(CASE_DIR, "pipeline.json"), "utf8")).not.toMatch(/Ottoline|Brackenridge/i); + + // The gate: row f3 is blocked, by id; a new row naming the name is refused at the write. + const gate = page.locator("[data-gate]"); + await expect(gate).toHaveAttribute("data-gate", "blocked"); + await expect(gate).toContainText("in 1 row (f3 ×"); + await page.getByRole("textbox", { name: "Finding rows" }).fill(row({ t: 300, summary: `Again with ${PLANTED}` })); + await page.getByRole("button", { name: "Add rows" }).click(); + await expect(status(page)).toContainText("the privacy gate blocked these findings"); + await expect(status(page)).toContainText("(f5)"); + await expect(status(page)).not.toContainText("Ottoline"); + await shot(page, "05-privacy-gate", "privacy"); + + // The export is blocked, naming REPORT.md's count, never the name; nothing is written. + await page.getByRole("button", { name: "Export the report" }).click(); + await expect(status(page)).toContainText("the privacy gate blocked the export"); + await expect(stageState(page, "export")).toHaveAttribute("data-stage-state", "failed"); + await expect(page.locator("#stage-export [data-stage-log]")).not.toContainText("Ottoline"); + expect(readFileSync(path.join(CASE_DIR, "stages.json"), "utf8")).not.toMatch(/Ottoline|Brackenridge/i); + await shot(page, "06-export-blocked", "export"); + + // A person withholds the name in the row (lane C's correction; here, the file), and the export goes through. + const f = path.join(CASE_DIR, "findings.jsonl"); + writeFileSync(f, readFileSync(f, "utf8").replace(PLANTED, "[name withheld]")); + await page.getByRole("textbox", { name: "Summary" }).fill("What Wren said about the shop, from opening to closing."); + await page.getByRole("button", { name: "Save the summary" }).click(); + await expect(status(page)).toHaveText("summary saved as yours"); + await expect(gate).toHaveAttribute("data-gate", "clear"); + await expect(page.locator("[data-merge]")).toContainText("Her own words 2"); + await expect(page.locator("[data-merge]")).toContainText("What others said 1"); + await expect(page.locator("[data-merge]")).toContainText("f2 → f1"); + await page.getByRole("button", { name: "Export the report" }).click(); + await expect(stageState(page, "export")).toHaveAttribute("data-stage-state", "done"); + const md = readFileSync(path.join(CASE_DIR, "REPORT.md"), "utf8"); + expect(md).toMatch(/^# Wren and the lantern shop\n\nWhat Wren said about the shop/); + expect(md).toContain('## Her own words\n\n- She opens the shop: "welcome to the lantern shop" — [Opening the lantern shop @ 2:00](https://www.youtube.com/watch?v=lw-2015a&t=120s)'); + expect(md).toContain('"she was with [name withheld] that day"'); + expect(md).not.toMatch(/Ottoline|Brackenridge/i); + const html = await (await page.request.get(`${researchCasePipelineApi(PIPELINE_CASE, "report")}?format=html`)).text(); + expect(html).toContain("<h2>Her own words</h2>"); + await shot(page, "07-export", "export"); + + // Hand off to the board: plan, confirm, the board holds the findings in sections. + await page.getByRole("button", { name: "Hand off to the board" }).click(); + await expect(dialog).toContainText("Pin 3 findings to the board"); + await dialog.getByRole("button", { name: "Confirm" }).click(); + await expect(status(page)).toHaveText("pinned 3 to the board"); + const board = JSON.parse(readFileSync(path.join(CASE_DIR, "case.json"), "utf8")) as { sections: { title: string }[]; quotes: { text: string; claim: string }[] }; + expect(board.sections.map((s) => s.title)).toEqual(["Her own words", "What others said"]); + expect(board.quotes.map((q) => q.claim)).toContain("She closes the shop"); + + // Date checks: the subject's uploads around the key date, and the sentence. + await page.getByRole("button", { name: "Check the dates" }).click(); + await expect(stageState(page, "date-checks")).toHaveAttribute("data-stage-state", "done"); + await expect(page.locator('[data-date-check="2021-03-01"] [data-date-sentence]')).toHaveText("response found: 1 finding in uploads from 2021-03-05 to 2021-03-05 (rows f4)"); + await shot(page, "08-date-checks", "date-checks"); +}); + +test("the API refuses a private name sent as text, and the board's own exits are gated by the case's names", async ({ request }) => { + const r = await request.post(researchCasePipelineApi(PIPELINE_CASE, "private-names"), { data: { add: [PLANTED] } }); + expect(r.status()).toBe(400); + expect((await r.json()).error).toContain("sha256 hex digests only"); + // The board exports what was pinned: clear now (the row was withheld before the hand-off). + const ok = await request.get(`/api/research/cases/${PIPELINE_CASE}/export.md`); + expect(ok.status()).toBe(200); + // A pinned note naming the private person blocks the board's export, by quote id. + const doc = JSON.parse(readFileSync(path.join(CASE_DIR, "case.json"), "utf8")); + doc.quotes[0].note = `ask ${PLANTED}`; + writeFileSync(path.join(CASE_DIR, "case.json"), JSON.stringify(doc, null, 2)); + const blocked = await request.get(`/api/research/cases/${PIPELINE_CASE}/export.md`); + expect(blocked.status()).toBe(409); + const err = (await blocked.json()).error as string; + expect(err).toContain(`(${doc.quotes[0].id})`); + expect(err).not.toMatch(/Ottoline|Brackenridge/i); +}); diff --git a/umtool/e2e/fixtures/case-fixture.mjs b/umtool/e2e/fixtures/case-fixture.mjs @@ -0,0 +1,85 @@ +// THE CASE PIPELINE fixture (plans/release-38/research-cases-and-assist.md, lane A): two channels in the +// fixture's CHANNELS_DIR with words on disk -- a subject's own and a talk show that covers her -- and an empty +// board, `lantern-case`, that the pipeline sits beside. case-pipeline.spec.ts defines it, counts its coverage, +// finds its candidates, batches them, writes finding rows by hand, watches the privacy gate block a planted +// private name, and exports. +// +// INVENTED, every word: no channel, recording, person or line here is real. PLANTED is the private name the gate +// must catch; it is in one talk-show line and never in a definition. +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const PIPELINE_CASE = "lantern-case"; +export const PLANTED = "Ottoline Brackenridge"; +export const SUBJECT_CHANNEL = "lantern-wren"; +export const TALK_CHANNEL = "harbor-talk"; + +const ts = (s) => { + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}.000`; +}; +const vtt = (cues) => "WEBVTT\n\n" + cues.map(([a, t]) => `${ts(a)} --> ${ts(a + 3)}\n${t}\n`).join("\n"); +const write = (p, body) => { + mkdirSync(path.dirname(p), { recursive: true }); + writeFileSync(p, body); +}; +// Filler around each said line, every 6 s, so a window has words either side. +function lines(say, duration = 600) { + const fill = ["okay where were we", "the tide is out", "we got letters about the ferry", "let me read the next one", "the fog came in early", "thanks for calling in"]; + const at = new Map(say); + const out = []; + for (let t = 0, i = 0; t < duration; t += 6) out.push([t, at.get(t) ?? fill[i++ % fill.length]]); + return out; +} + +export function makeCaseFixture({ channels, reportsRoot }) { + const video = (slug, id, date, title, files) => { + const dir = path.join(channels, slug, "data", id); + write(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title, upload_date: date, duration: 600, webpage_url: `https://www.youtube.com/watch?v=${id}` })); + for (const [n, b] of Object.entries(files)) write(path.join(dir, n), b); + }; + const channel = (slug, name, playlist) => { + write(path.join(channels, slug, "config.json"), JSON.stringify({ handling: "youtube", name })); + write(path.join(channels, slug, "playlist"), playlist.map((id) => `https://www.youtube.com/watch?v=${id}`).join("\n") + "\n"); + }; + // The subject's own: two transcribed (en-orig beside a served en that rewrites a line), one held as audio only, + // one listed and never fetched. + channel(SUBJECT_CHANNEL, "Lantern Wren", ["lw-2015a", "lw-2015b", "lw-2015c", "lw-2016x", "lw-2021a"]); + video(SUBJECT_CHANNEL, "lw-2015a", "20150310", "Opening the lantern shop", { + "transcript.en-orig.vtt": vtt(lines([[120, "welcome to the lantern shop"], [126, "I built every lantern here myself"]])), + "transcript.en.vtt": vtt([[120, "welcome to the candle store"]]), + }); + video(SUBJECT_CHANNEL, "lw-2015b", "20150601", "A quiet week", { "audio.opus": "fixture audio" }); + video(SUBJECT_CHANNEL, "lw-2021a", "20210305", "Closing the shop", { "transcript.en-orig.vtt": vtt(lines([[240, "the lantern shop is closing for good"], [300, "wren here with an update"]])) }); + // The talk show: one recording names her and the shop; one mentions the shop only (coverage noise). + channel(TALK_CHANNEL, "Harbor Talk", ["ht-2015a", "ht-2015b"]); + video(TALK_CHANNEL, "ht-2015a", "20150320", "Harbor Talk 12", { + "transcript.en.vtt": vtt(lines([[180, "Wren Halloway stopped by the lantern shop"], [186, `she was with ${PLANTED} that day`]])), + }); + video(TALK_CHANNEL, "ht-2015b", "20150402", "Harbor Talk 13", { "transcript.en.vtt": vtt(lines([[60, "the lantern shop downtown had a sale"]])) }); + // The board, empty: the pipeline is defined on the page. + const at = "2026-11-01T12:00:00.000Z"; + write( + path.join(reportsRoot, ".umtool", "research", PIPELINE_CASE, "case.json"), + `${JSON.stringify({ format: "umtool-research-case", version: 1, id: PIPELINE_CASE, title: "Wren and the lantern shop", scope: { source: "" }, search: null, sessions: [], sections: [], quotes: [], notes: "", handoffs: [], counters: { quote: 0, section: 0 }, createdAt: at, updatedAt: at }, null, 2)}\n`, + ); +} + +/** The definition the spec types (no private name in it). */ +export const PIPELINE_DEFINITION = { + subjects: [{ name: "Wren Halloway", aliases: ["Wren"], channels: [SUBJECT_CHANNEL] }], + scope: { channels: [TALK_CHANNEL], groups: [], sites: [] }, + eras: [ + { id: "shop", from: "2015-01-01", to: "2016-12-31", families: { shop: "lantern shop", name: "\\bwren\\b" } }, + { id: "closing", from: "2021-01-01", to: "2021-12-31", families: { shop: "lantern shop", name: "\\bwren\\b" }, strictFamilies: ["shop"] }, + ], + groups: [ + { id: "own", label: "Her own words", channels: "subject" }, + { id: "talk", label: "What others said", channels: "coverage" }, + ], + readerPrompts: { common: "Quote verbatim, at most 45 words.", own: "She is the speaker unless said otherwise." }, + keyDates: [{ date: "2021-03-01", label: "the shop closes" }], + status: "gathering", + privateNames: { note: "a private person named on the talk show" }, +}; diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -1291,6 +1291,28 @@ const server = http.createServer((req, res) => { // narration crossed the wire and landed under the card, not how it sounds. // An engine other than kokoro / espeak-ng / orpheus is refused, as the // editor refuses one it does not have. + // THE CASE PIPELINE'S GAP BUTTONS (release 38 lane A, case-pipeline.spec.ts): the editor's own actions, + // recorded and answered as queued -- download-missing, transcribe-bucket, persist-videos (its dryRun answers + // the buckets) and channel-priority's focus. + if (req.method === "POST" && ["/api/ops/download-missing", "/api/ops/transcribe-bucket", "/api/ops/persist-videos", "/api/ops/channel-priority"].includes(url.pathname)) { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + let body = {}; + try { + body = raw ? JSON.parse(raw) : {}; + } catch { + return json(res, 400, { ok: false, error: "malformed JSON body" }); + } + requests.push({ route: url.pathname.slice("/api/ops/".length), ...body, authorization: auth }); + record(); + if (url.pathname === "/api/ops/persist-videos" && body.dryRun) { + return json(res, 200, { ok: true, dryRun: true, buckets: { saved: [], wrongHeight: [], toFetch: (body.items ?? []).map((i) => i.id), noUrl: [], unknown: [] } }); + } + json(res, 200, { ok: true, jobId: `stub-${url.pathname.slice("/api/ops/".length)}-${nextJob++}` }); + }); + return; + } if (req.method === "POST" && url.pathname === "/api/ops/tts") { let raw = ""; req.on("data", (c) => (raw += c)); diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -38,6 +38,7 @@ import { makeTakeWalkFixture } from "./take-walk-fixture.mjs"; import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; +import { makeCaseFixture } from "./case-fixture.mjs"; import { makeDigestContextFixture } from "./digest-context-fixture.mjs"; import { makeRunTraceFixture } from "./run-trace-fixture.mjs"; import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs"; @@ -2260,6 +2261,8 @@ const { pub: RESEARCH_PUBLIC } = makeResearchFixture({ dest, channels: CHANNELS makeDigestContextFixture({ 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 }); +// Release 38 lane A: a case pipeline over two channels with words on disk, beside an empty board. +makeCaseFixture({ channels: CHANNELS, reportsRoot: dest }); // 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}` }); diff --git a/umtool/lib/research/boards.ts b/umtool/lib/research/boards.ts @@ -20,6 +20,7 @@ import { removeQuote, storedPath, } from "./cases.mjs"; +import { boardGate } from "./case-private"; import { windowOf } from "./corpus"; import { citationText, isoDate, trackOf } from "./facets.mjs"; import { readLog } from "./log.mjs"; @@ -319,6 +320,9 @@ export async function caseView(id: string): Promise<CaseView> { /** The board as cited markdown (house format; it converts as a /sweep report). */ export async function exportCase(id: string): Promise<{ doc: CaseDoc; markdown: string }> { const view = await caseView(id); + // The case pipeline's privacy gate (lib/research/case-private.ts): a 409 naming quote ids, never the name. + const blocked = await boardGate(view.case, "this export"); + if (blocked) throw blocked; return { doc: view.case, markdown: exportMarkdown(view.case, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) }), diff --git a/umtool/lib/research/case-private.ts b/umtool/lib/research/case-private.ts @@ -0,0 +1,30 @@ +import { readDefinition } from "yt-dlp-transcript-common/lib/research/caseStore-server"; +import { PrivacyBlocked, privacyGate } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; +import { REPORTS_ROOT } from "../paths.mjs"; +import { caseDir } from "./cases.mjs"; +import type { CaseDoc } from "./case-types"; + +// The board's own exits behind the case pipeline's privacy gate (plans/release-38/research-cases-and-assist.md, +// stage 6): a board whose case has private names (pipeline.json `privateNames.sha256`) neither exports nor hands +// off a quote, claim or note that names one. The refusal is counts and quote ids, never the name. In a module of +// its own so boards.ts and handoff.ts can ask without importing the pipeline. + +/** The case's private-name hashes; none when it has no pipeline (or it cannot be read: the pipeline says why). */ +export async function casePrivateHashes(id: string): Promise<string[]> { + try { + return (await readDefinition(caseDir(REPORTS_ROOT, id), id))?.privateNames.sha256 ?? []; + } catch { + return []; + } +} + +/** The gate over a board's quotes (their words, claims and notes): null when clear, else the refusal. */ +export async function boardGate(doc: Pick<CaseDoc, "id" | "quotes" | "notes" | "title">, what: string): Promise<PrivacyBlocked | null> { + const hashes = await casePrivateHashes(doc.id); + if (!hashes.length) return null; + const r = privacyGate( + [{ id: "the case's notes", text: `${doc.title}\n${doc.notes}` }, ...doc.quotes.map((q) => ({ id: q.id, text: [q.text, q.claim, q.note].join("\n") }))], + hashes, + ); + return r.blocked ? new PrivacyBlocked(what, r) : null; +} diff --git a/umtool/lib/research/handoff.ts b/umtool/lib/research/handoff.ts @@ -14,6 +14,7 @@ import { isLocalOnly } from "./rules.mjs"; import { runHref } from "./runs-hrefs"; import { CaseError, recordHandoff } from "./cases.mjs"; import { boardGroups, caseView, mutateBoard } from "./boards"; +import { boardGate } from "./case-private"; import type { ArticlePlan, CaseDoc, VideoPlan } from "./case-types"; // --------------------------------------------------------------------------- @@ -123,6 +124,9 @@ export async function planArticle( 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 = seeded ? exportMarkdown(doc, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) }) : ""; + // The case pipeline's privacy gate: quote ids and counts, never the name. + const blocked = seeded ? await boardGate(doc, "this hand-off") : null; + if (blocked) refusals.push(blocked.message); return { plan: { to: "article", @@ -264,6 +268,8 @@ export async function planVideo(id: string, over: { slug?: string; title?: strin if (local) warnings.push(`${local} local-only ${local === 1 ? "quote" : "quotes"}: this project must never be published`); const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length; if (drifted) warnings.push(`${drifted} drifted or missing at the last re-verify: their windows are the pinned seconds`); + const blocked = await boardGate(doc, "this hand-off"); + if (blocked) refusals.push(blocked.message); const siteOrigin = originOf(doc); if (!siteOrigin) warnings.push("no one viewer origin in the quotes' links: set provenance.siteOrigin before the build"); return { diff --git a/umtool/lib/research/hrefs.ts b/umtool/lib/research/hrefs.ts @@ -35,6 +35,14 @@ export function researchCaseHref(id: string): string { return `/research/${enc(id)}`; } +/** A case's pipeline (release 38): its stages beside the board. */ +export function researchCasePipelineHref(id: string, stage?: string): string { + return `/research/${enc(id)}/pipeline${stage ? `#stage-${stage}` : ""}`; +} + +/** The pipeline's API (app/api/research/cases/[id]/pipeline/[op]/route.ts documents it). */ +export const researchCasePipelineApi = (id: string, op?: string) => `/api/research/cases/${enc(id)}/pipeline${op ? `/${enc(op)}` : ""}`; + /** Research with a case's scope and query, pins going to the case. */ export function researchFromCaseHref(c: { id: string; scope: Partial<Scope> & { query?: string } }): string { const { query, ...scope } = c.scope; diff --git a/umtool/lib/research/pipeline-types.ts b/umtool/lib/research/pipeline-types.ts @@ -0,0 +1,56 @@ +import type { + CandidateCounts, + CandidateWindow, + CaseBatch, + CaseDefinition, + CaseStageRuns, + CaseSummaryText, + CoverageRow, + DateCheck, + FindingRow, +} from "yt-dlp-transcript-common/lib/research/caseTypes"; +import type { MergeView } from "yt-dlp-transcript-common/controller/casePipelineRun"; +import type { GateResult } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; + +// What the case pipeline page reads (lib/research/pipeline.ts pipelineView). Types only: the page imports them. + +/** A channel's coverage summed over its years, with what its gap buttons would ask for. */ +export type PipelineGap = { + slug: string; + listed: number; + held: number; + transcribed: number; + untranscribedAudio: number; + /** Listed and not held: what download-missing fetches. */ + missing: number; + /** Held in a key year: what "persist the key period" looks at. */ + keyHeld: number; +}; + +export type PipelineView = { + case: { id: string; title: string }; + stored: string; + defined: boolean; + /** The definition with its private-name hashes left out (never sent to a page). */ + definition: CaseDefinition; + /** How many private names the case holds (hashed). */ + privateNames: number; + channels: { slugs: string[]; problems: string[] }; + keyYears: number[]; + eraSpan: { from: string; to: string } | null; + coverage: { rows: CoverageRow[]; gaps: PipelineGap[] }; + candidates: { counts: CandidateCounts | null; total: number; sample: CandidateWindow[] }; + batches: CaseBatch[]; + findings: { rows: FindingRow[]; invalid: { line: number; errors: string[] }[] }; + merge: MergeView | null; + /** What the privacy gate says of the findings and the summary now: counts and row ids. */ + gate: { findings: GateResult; summary: GateResult }; + summary: CaseSummaryText | null; + report: { exists: boolean }; + dateChecks: DateCheck[]; + stages: CaseStageRuns; + /** Each reader group's prompt as a reader gets it (the naming rule always last). */ + prompts: Record<string, string>; + /** umtool can ask the editor (a WORKER_TOKEN is set). */ + editor: boolean; +}; diff --git a/umtool/lib/research/pipeline.ts b/umtool/lib/research/pipeline.ts @@ -0,0 +1,392 @@ +import path from "node:path"; +import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; +import { CASE_FILES, CASE_STAGES, type CaseDefinition, type CaseStage, type FindingRow } from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { + CasePipelineError, + emptyDefinition, + eraSpan, + findingLink, + keyYears, + readerPrompt, + rowGateText, +} from "yt-dlp-transcript-common/lib/research/casePipeline"; +import { PrivacyBlocked, privacyGate } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; +import { + appendFindings, + mutateDefinition, + readBatchText, + readBatches, + readCandidateCounts, + readCandidates, + readCoverage, + readDateChecks, + readDefinition, + readFindings, + readReport, + readReportHtml, + readStages, + readSummary, + saveDefinition, + writeSummary, +} from "yt-dlp-transcript-common/lib/research/caseStore-server"; +import { caseChannels } from "yt-dlp-transcript-common/controller/caseCorpus"; +import { mergeView, runBatches, runCandidates, runCoverage, runDateChecks, runExport } from "yt-dlp-transcript-common/controller/casePipelineRun"; +import { readDateAndTitle } from "yt-dlp-transcript-common/controller/channelCoverage"; +import { heldVideoIds } from "yt-dlp-transcript-common/controller/videoCues"; +import { CHANNELS_DIR, REPORTS_ROOT, SITES_DIR } from "../paths.mjs"; +import { askEditor } from "../articles/generation"; +import { addQuote, caseDir, storedPath } from "./cases.mjs"; +import { mutateBoard, readCase } from "./boards"; +import type { PipelineGap, PipelineView } from "./pipeline-types"; + +// --------------------------------------------------------------------------- +// A CASE'S PIPELINE, umtool's side (plans/release-38/research-cases-and-assist.md, lane A): the stages of +// common/controller/casePipelineRun.ts bound to the case's directory under REPORTS_ROOT (beside the board's +// case.json, which only cases.mjs writes) and to the corpus umtool reads (CHANNELS_DIR, read-only). The page is +// /research/<case>/pipeline; the routes are app/api/research/cases/[id]/pipeline/**; `archilyzer case …` runs +// the same stages from a shell, and stages.json shows either's run to the other. +// +// A long stage (coverage, candidates, date checks) runs in the background of this process and the page follows +// stages.json; one run per case and stage at a time. The quick ones answer when done. +// +// The private names: only their HASHES reach the server (the page hashes a typed term in the browser, +// casePipeline.ts privateNameHashWeb), and the view never sends them back -- a count, and what the gate blocked, +// as counts and row ids. +// --------------------------------------------------------------------------- + +/** The corpus as the stages read it: umtool's CHANNELS_DIR and SITES_DIR, and the index beside the channels. */ +export function corpusPaths(): Paths { + const base = getPaths(); + const channelsUnderCorpus = path.resolve(CHANNELS_DIR) === path.resolve(base.channelsDir); + return { + ...base, + channelsDir: CHANNELS_DIR, + sitesDir: SITES_DIR, + // A fixture's channels (or a TRANSCRIPTS_DIR's) date from their own index, never the checkout's. + lmdbPath: channelsUnderCorpus ? base.lmdbPath : path.join(/* turbopackIgnore: true */ path.dirname(CHANNELS_DIR), "index.mdb"), + }; +} + +const dirOf = (id: string) => caseDir(REPORTS_ROOT, id); + +async function ensureCase(id: string): Promise<{ id: string; title: string; dir: string }> { + const doc = await readCase(id); + return { id: doc.id, title: doc.title, dir: dirOf(doc.id) }; +} + +async function definitionOrEmpty(c: { id: string; dir: string }): Promise<{ def: CaseDefinition; defined: boolean }> { + const def = await readDefinition(c.dir, c.id); + return def ? { def, defined: true } : { def: emptyDefinition(c.id), defined: false }; +} + +// ── the view ── + +const running = ((globalThis as { __umtoolCaseStages?: Set<string> }).__umtoolCaseStages ??= new Set<string>()); + +function gapsOf(rows: Awaited<ReturnType<typeof readCoverage>>): PipelineGap[] { + const by = new Map<string, PipelineGap>(); + for (const r of rows) { + const g = by.get(r.channel) ?? { slug: r.channel, listed: 0, held: 0, transcribed: 0, untranscribedAudio: 0, missing: 0, keyHeld: 0 }; + g.listed += r.listed; + g.held += r.held; + g.transcribed += r.transcribed; + g.untranscribedAudio += r.untranscribedAudio; + if (r.key) g.keyHeld += r.held; + by.set(r.channel, g); + } + for (const g of by.values()) g.missing = Math.max(0, g.listed - g.held); + return [...by.values()].sort((a, b) => a.slug.localeCompare(b.slug)); +} + +export async function pipelineView(id: string): Promise<PipelineView> { + const c = await ensureCase(id); + const { def, defined } = await definitionOrEmpty(c); + const [coverage, counts, windows, batches, findings, summary, dateChecks, stages, report] = await Promise.all([ + readCoverage(c.dir), + readCandidateCounts(c.dir), + readCandidates(c.dir), + readBatches(c.dir), + readFindings(c.dir), + readSummary(c.dir), + readDateChecks(c.dir), + readStages(c.dir), + readReport(c.dir), + ]); + const hashes = def.privateNames.sha256; + const merge = defined ? await mergeView(c.dir, c.id).catch(() => null) : null; + const channels = defined ? await caseChannels(corpusPaths(), def).catch((e: Error) => ({ slugs: [], problems: [e.message] })) : { slugs: [], problems: [] }; + for (const s of CASE_STAGES) if (running.has(`${c.id}:${s}`) && stages[s]?.state !== "running") running.delete(`${c.id}:${s}`); + return { + case: { id: c.id, title: c.title }, + stored: storedPath(c.id), + defined, + definition: { ...def, privateNames: { sha256: [], note: def.privateNames.note } }, + privateNames: hashes.length, + channels, + keyYears: [...keyYears(def)].sort(), + eraSpan: eraSpan(def), + coverage: { rows: coverage, gaps: gapsOf(coverage) }, + candidates: { counts, total: windows.length, sample: windows.slice(0, 40).map((w) => ({ ...w, text: w.text.length > 600 ? `${w.text.slice(0, 600)}…` : w.text })) }, + batches, + findings: { rows: findings.rows, invalid: findings.invalid }, + merge, + gate: { + findings: privacyGate(findings.rows.map((r) => ({ id: r.row, text: rowGateText(r) })), hashes), + summary: privacyGate(summary ? [{ id: "summary", text: summary.text }] : [], hashes), + }, + summary, + report: { exists: report !== null }, + dateChecks, + stages, + prompts: Object.fromEntries([["common", readerPrompt(def, "common")], ...def.groups.map((g) => [g.id, readerPrompt(def, g.id)])]), + editor: !!process.env.WORKER_TOKEN?.trim(), + }; +} + +// ── the definition and its private names ── + +/** Save the definition from the page's editor. The private-name hashes are never part of it: they are kept. */ +export async function saveCaseDefinition(id: string, body: unknown): Promise<CaseDefinition> { + const c = await ensureCase(id); + const raw = (body && typeof body === "object" ? body : {}) as Record<string, unknown>; + const pn = raw.privateNames as Record<string, unknown> | undefined; + if (pn && ("terms" in pn || (Array.isArray(pn.sha256) && pn.sha256.length))) { + throw new CasePipelineError("private names are never saved with the definition: add them in the Private names box, which keeps only their hashes"); + } + const prev = await readDefinition(c.dir, c.id); + return saveDefinition(c.dir, c.id, { ...raw, privateNames: { sha256: prev?.privateNames.sha256 ?? [], note: typeof pn?.note === "string" ? pn.note : (prev?.privateNames.note ?? "") } }); +} + +const HEX = /^[0-9a-f]{64}$/; + +/** Add, remove or clear private-name hashes (hex digests; a term never reaches this). Answers the count. */ +export async function changePrivateNames(id: string, body: { add?: unknown; remove?: unknown; clear?: unknown }): Promise<{ count: number; changed: number }> { + const c = await ensureCase(id); + const hexes = (v: unknown) => { + if (v === undefined) return []; + if (!Array.isArray(v) || v.some((h) => typeof h !== "string" || !HEX.test(h))) throw new CasePipelineError("private names arrive as sha256 hex digests only: the page hashes a name before it sends it"); + return v as string[]; + }; + const add = hexes(body.add); + const remove = hexes(body.remove); + let changed = 0; + const def = await mutateDefinition( + c.dir, + c.id, + (d) => { + const before = new Set(d.privateNames.sha256); + let next = body.clear === true ? [] : [...before]; + next = [...new Set([...next, ...add])].filter((h) => !remove.includes(h)); + changed = [...new Set([...before, ...next])].filter((h) => before.has(h) !== next.includes(h)).length; + d.privateNames.sha256 = next; + }, + () => emptyDefinition(c.id), + ); + return { count: def.privateNames.sha256.length, changed }; +} + +// ── the stages ── + +export type StageBody = { window?: number; maxSpan?: number; budget?: number; minRelevance?: number; aroundDays?: number; latest?: number }; + +const num = (v: unknown, name: string, min: number, max: number): number | undefined => { + if (v === undefined || v === null || v === "") return undefined; + const n = Number(v); + if (!Number.isFinite(n) || n < min || n > max) throw new CasePipelineError(`${name} is a number from ${min} to ${max}`); + return n; +}; + +/** + * Run a stage. coverage, candidates and date-checks start in the background (`{ started: true }`; the page follows + * stages.json); batches and export answer when done. A stage already running for this case is a 409. + */ +export async function startStage(id: string, stage: string, body: StageBody = {}): Promise<{ started: boolean }> { + const c = await ensureCase(id); + if (!(CASE_STAGES as readonly string[]).includes(stage) || stage === "handoff") throw new CasePipelineError(`not a stage: ${stage} (coverage, candidates, batches, export, date-checks)`, 404); + const key = `${c.id}:${stage}`; + if (running.has(key) || (await readStages(c.dir))[stage as CaseStage]?.state === "running") throw new CasePipelineError(`${stage} is already running for this case`, 409); + const paths = corpusPaths(); + const run = (): Promise<unknown> => { + switch (stage as CaseStage) { + case "coverage": + return runCoverage(c.dir, c.id, paths, "umtool"); + case "candidates": + return runCandidates(c.dir, c.id, paths, "umtool", { W: num(body.window, "window", 5, 600), maxSpan: num(body.maxSpan, "maxSpan", 30, 3600) }); + case "batches": + return runBatches(c.dir, c.id, "umtool", { budget: num(body.budget, "budget", 2000, 400_000) }); + case "export": + return runExport(c.dir, c.id, c.title, "umtool", { minRelevance: num(body.minRelevance, "minRelevance", 1, 3), paths }); + case "date-checks": + return runDateChecks(c.dir, c.id, paths, "umtool", { aroundDays: num(body.aroundDays, "aroundDays", 1, 365), latest: num(body.latest, "latest", 1, 100) }); + default: + throw new CasePipelineError(`not a stage: ${stage}`, 404); + } + }; + // The definition must exist before anything runs (each runner checks it; asked here so a background stage refuses at once). + if (!(await readDefinition(c.dir, c.id))) throw new CasePipelineError("define the case first: its subjects, eras and reader groups", 409); + if (stage === "batches" || stage === "export") { + await run(); + return { started: false }; + } + running.add(key); + void run() + .catch(() => {}) + .finally(() => running.delete(key)); + // Let the stage write "running" before the page asks again. + await new Promise((r) => setTimeout(r, 50)); + return { started: true }; +} + +// ── findings, the summary, the report ── + +/** Append finding rows by hand (or an agent's, lane D), checked and gated. */ +export async function addFindings(id: string, rows: unknown): Promise<FindingRow[]> { + const c = await ensureCase(id); + if (!Array.isArray(rows)) throw new CasePipelineError("rows is a list of finding rows"); + const def = await readDefinition(c.dir, c.id); + return appendFindings(c.dir, rows, def?.privateNames.sha256 ?? []); +} + +/** The summary written on the page: a person's, so never a draft. A model's draft arrives with `by` set. */ +export async function saveSummary(id: string, body: { text?: unknown; by?: unknown; model?: unknown }) { + const c = await ensureCase(id); + if (typeof body.text !== "string") throw new CasePipelineError("summary: { text }"); + const by = body.by === undefined ? "hand" : body.by; + if (by !== "hand" && by !== "api" && by !== "local" && by !== "code") throw new CasePipelineError("by is hand, api, local or code"); + const def = await readDefinition(c.dir, c.id); + return writeSummary(c.dir, { text: body.text, draft: by !== "hand", by, ...(typeof body.model === "string" && body.model ? { model: body.model } : {}) }, def?.privateNames.sha256 ?? []); +} + +export async function batchFile(id: string, batch: string): Promise<string> { + const c = await ensureCase(id); + return readBatchText(c.dir, batch); +} + +/** REPORT.md or REPORT.html as exported, or null. */ +export async function reportFile(id: string, format: "md" | "html"): Promise<{ body: string; name: string } | null> { + const c = await ensureCase(id); + const body = format === "html" ? await readReportHtml(c.dir) : await readReport(c.dir); + return body === null ? null : { body, name: `${c.id}-${format === "html" ? CASE_FILES.reportHtml : CASE_FILES.report}` }; +} + +// ── the hand-off: the merged findings onto the board ── + +/** + * The merge's findings pinned to the case's board, one board section per reader group -- the board's own hand-offs + * (an article, a video) then take them, as they take any pin. Plan first (`confirm` false: what would be pinned, + * and what the gate says); behind the privacy gate; the quarantined are never pinned (not evidence). A finding + * already on the board (the same recording and second) is not pinned twice. + */ +export async function handoffToBoard(id: string, o: { confirm?: boolean; minRelevance?: number } = {}) { + const c = await ensureCase(id); + const def = await readDefinition(c.dir, c.id); + if (!def) throw new CasePipelineError("define the case first", 409); + const merged = await mergeView(c.dir, c.id, { minRelevance: num(o.minRelevance, "minRelevance", 1, 3) }); + const rows = merged.sections.flatMap((s) => s.rows.map((r) => ({ r, label: s.label }))); + const gate = privacyGate(rows.map(({ r }) => ({ id: r.row, text: rowGateText(r) })), def.privateNames.sha256); + const plan = { + sections: merged.sections.map((s) => ({ label: s.label, rows: s.rows.length })), + findings: rows.length, + quarantinedLeftOut: merged.quarantined.length, + blocked: gate.blocked ? { hits: gate.hits, rows: gate.rows.map((x) => x.id) } : null, + }; + if (!o.confirm) return { plan, pinned: 0, duplicates: 0 }; + if (!rows.length) throw new CasePipelineError("no finding to hand off: the merge has none at this relevance", 409); + if (gate.blocked) throw new PrivacyBlocked("the hand-off", gate); + const windows = await readCandidates(c.dir); + const r = await mutateBoard(c.id, (doc) => { + let pinned = 0; + let duplicates = 0; + for (const { r: f, label } of rows) { + let sec = doc.sections.find((s) => s.title === label); + if (!sec) { + sec = { id: `s${++doc.counters.section}`, title: label }; + doc.sections.push(sec); + } + const w = windows.find((x) => x.slug === f.slug && x.id === f.id && x.from <= f.t && f.t <= x.to); + const link = /\]\((.+)\)$/.exec(findingLink(f))?.[1] ?? null; + const res = addQuote(doc, { + text: f.quote, + cite: { kind: "video", source: "", channel: f.slug, video: f.id, title: f.title, date: f.date, t: f.t, end: Math.min(w?.to ?? f.t + 15, f.t + 30), url: link, track: w?.track ?? "" }, + claim: f.summary, + note: `${f.category} · relevance ${f.relevance} · ${f.speaker ? `speaker ${f.speaker} · ` : ""}row ${f.row}${f.quoteCheck === "not-found" ? " · quote not found in the captions" : ""}`, + section: sec.id, + ...(f.by === "hand" ? {} : { by: "agent" as const }), + }); + if (res.duplicate) duplicates++; + else pinned++; + } + return { pinned, duplicates }; + }); + return { plan, ...r.result }; +} + +// ── the gaps: existing editor ops, plan then confirm ── + +/** Held recordings of `slug` dated inside an era: what "persist the key period" saves. */ +async function keyPeriodIds(def: CaseDefinition, slug: string): Promise<string[]> { + const span = eraSpan(def); + if (!span) return []; + const dataDir = path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug, "data"); + const ids = [...(await heldVideoIds(dataDir))].sort(); + const out: string[] = []; + for (const vid of ids) { + const d = (await readDateAndTitle(path.join(/* turbopackIgnore: true */ dataDir, vid))).uploadDate ?? ""; + if (d && def.eras.some((e) => e.from.replace(/-/g, "") <= d && d <= e.to.replace(/-/g, ""))) out.push(vid); + } + return out; +} + +export type GapAction = "download-missing" | "transcribe" | "persist" | "focus"; + +/** + * A coverage gap's button: the editor's own action, asked over its ops API (WORKER_TOKEN) -- download-missing, + * transcribe-bucket, persist-videos (the key period's held recordings; the plan is its dryRun), and + * channel-priority's focus (the case's site, else its channels). Without `confirm` it answers the request it + * would send and asks nothing (persist's plan asks the editor's dryRun). + */ +export async function gapAction(id: string, body: { action?: unknown; slug?: unknown; confirm?: unknown }) { + const c = await ensureCase(id); + const def = await readDefinition(c.dir, c.id); + if (!def) throw new CasePipelineError("define the case first", 409); + const action = body.action as GapAction; + const slug = typeof body.slug === "string" ? body.slug : ""; + const scoped = (await caseChannels(corpusPaths(), def)).slugs; + if (action !== "focus" && !scoped.includes(slug)) throw new CasePipelineError(`"${slug}" is not a channel of this case`); + let route: string; + let request: Record<string, unknown>; + let what: string; + if (action === "download-missing") { + route = "/api/ops/download-missing"; + request = { slug }; + what = `download every listed video ${slug} does not hold (paced, on its platform's queue)`; + } else if (action === "transcribe") { + route = "/api/ops/transcribe-bucket"; + request = { slug }; + what = `transcribe ${slug}'s "downloaded, not transcribed" bucket on the transcription queue`; + } else if (action === "persist") { + const ids = await keyPeriodIds(def, slug); + if (!ids.length) throw new CasePipelineError(`${slug} holds nothing dated inside the case's eras`, 409); + route = "/api/ops/persist-videos"; + request = { items: ids.map((v) => ({ slug, id: v })) }; + what = `save ${ids.length} of ${slug}'s recordings from the case's eras to the saved-video store (one job per channel; saved ones are skipped)`; + } else if (action === "focus") { + route = "/api/ops/channel-priority"; + request = def.scope.sites.length ? { focus: { kind: "site", siteId: def.scope.sites[0] } } : { focus: { kind: "channels", slugs: scoped } }; + what = def.scope.sites.length ? `put the site ${def.scope.sites[0]}'s channels ahead in every lane` : `put the case's ${scoped.length} channels ahead in every lane`; + } else throw new CasePipelineError("action is download-missing, transcribe, persist or focus"); + if (body.confirm !== true) { + const plan: Record<string, unknown> = { route, request, what }; + if (action === "persist") { + try { + plan.dryRun = await askEditor(route, { method: "POST", body: { ...request, dryRun: true } }); + } catch (e) { + plan.dryRunError = (e as Error).message; + } + } + return { plan }; + } + const answer = await askEditor(route, { method: "POST", body: request }); + return { done: true, route, answer }; +} +