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, withholdStored, 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//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 }).__umtoolCaseStages ??= new Set()); function gapsOf(rows: Awaited>): PipelineGap[] { const by = new Map(); 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 { 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 { const c = await ensureCase(id); const raw = (body && typeof body === "object" ? body : {}) as Record; const pn = raw.privateNames as Record | 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; withheld: 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), ); // A name added after the candidates and batches were written is withheld from them now. const withheld = add.length ? await withholdStored(c.dir, def.privateNames.sha256) : 0; return { count: def.privateNames.sha256.length, changed, withheld }; } // ── 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 => { 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 { 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 { 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 { 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; 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 = { 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 }; }