// A RESEARCH CASE'S STAGES, RUN (plans/release-38/research-cases-and-assist.md, lane A): each one reads what the // stage before it wrote in the case's directory, does its work, writes its own file and records its run in // stages.json (lib/research/caseStore-server.ts runStage). The same functions run from umtool's case page (its // routes, in the background) and from `archilyzer case …` (a shell, a Claude Code session), so either sees the // other's run. // // 1 coverage controller/caseCorpus.ts caseCoverage → coverage.json (the corpus, read-only) // 2 candidates caseCandidates → candidates.jsonl + candidates.counts.json (the corpus, read-only) // 3 batches candidates → batches/index.json + batches/.txt, wrapped (pending: lane B reads them) // 5 merge findings.jsonl → sections (a preview: nothing written) // 5 export the merge + summary.json → REPORT.md + REPORT.html (behind the privacy gate) // 9 date-checks the subject's uploads + findings → date-checks.json // // Stage 4 (the read) is lane B's: it writes findings.jsonl through appendFindings, as a person's rows do. import { readFile } from "node:fs/promises"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { CASE_FILES } from "../lib/research/caseTypes"; import { evidenceRows } from "../lib/research/caseEvidence"; import type { CaseBatch, CaseDefinition, CaseStageRun, CoverageRow, DateCheck, FindingRow } from "../lib/research/caseTypes"; import { CasePipelineError, dateChecks, groupFor, mergeFindings, reportHtml, reportMarkdown, rowGateText, type MergeResult, type ScanOptions, } from "../lib/research/casePipeline"; import { readBatches, readCandidateCounts, readCandidates, readDefinition, readFindings, readSummary, rebuildBatches, runStage, withholdWindow, writeCandidates, writeCoverage, writeDateChecks, writeReport, } from "../lib/research/caseStore-server"; import { assertNoPrivateNames } from "../lib/research/casePrivacy-server"; import { caseCandidates, caseChannels, caseCoverage, subjectUploads } from "./caseCorpus"; type By = CaseStageRun["by"]; const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; async function definitionOf(dir: string, caseId: string): Promise { const def = await readDefinition(dir, caseId); if (!def) throw new CasePipelineError(`case ${caseId} has no pipeline yet: define its subjects, eras and groups first`, 409); return def; } export async function runCoverage(dir: string, caseId: string, paths: Paths, by: By): Promise<{ rows: CoverageRow[]; skipped: { slug: string; reason: string }[] }> { const def = await definitionOf(dir, caseId); return runStage(dir, "coverage", by, async (log) => { const r = await caseCoverage(paths, def); for (const p of r.problems) log(p); for (const s of r.skipped) log(`skipped ${s.slug}: ${s.reason}`); await writeCoverage(dir, r.rows); const channels = new Set(r.rows.map((x) => x.channel)).size; log(`${channels} ${channels === 1 ? "channel" : "channels"}, ${r.rows.length} channel-years`); return { result: { rows: r.rows, skipped: r.skipped }, counts: { channels, listed: r.rows.reduce((n, x) => n + x.listed, 0), held: r.rows.reduce((n, x) => n + x.held, 0), transcribed: r.rows.reduce((n, x) => n + x.transcribed, 0), untranscribedAudio: r.rows.reduce((n, x) => n + x.untranscribedAudio, 0), skipped: r.skipped.length, }, }; }); } export async function runCandidates(dir: string, caseId: string, paths: Paths, by: By, o: ScanOptions = {}) { const def = await definitionOf(dir, caseId); return runStage(dir, "candidates", by, async (log) => { const r = await caseCandidates(paths, def, { ...o, onNote: log }); for (const p of r.problems) log(p); // The case's private names never sit in its files: withheld from the windows' words before they are written. let withheld = 0; r.windows = r.windows.map((w) => { const x = withholdWindow(w, def.privateNames.sha256); withheld += x.replaced; return x.window; }); if (withheld) log(`${withheld} private ${withheld === 1 ? "name" : "names"} withheld in the windows' words`); await writeCandidates(dir, r.windows, r.counts); log(`${r.counts.windows} ${r.counts.windows === 1 ? "window" : "windows"} in ${r.counts.videos} ${r.counts.videos === 1 ? "recording" : "recordings"}`); return { result: r, counts: { windows: r.counts.windows, recordings: r.counts.videos, titleHits: r.counts.titleHits, noise: Object.values(r.counts.noise).reduce((a, b) => a + b, 0), noText: r.counts.scanned.noText }, }; }); } export async function runBatches(dir: string, caseId: string, by: By, o: { budget?: number } = {}) { const def = await definitionOf(dir, caseId); return runStage(dir, "batches", by, async (log) => { const windows = await readCandidates(dir); if (!windows.length) throw new CasePipelineError("no candidate windows: build the candidates first", 409); const r = await rebuildBatches(dir, def, windows, o); log(`round ${r.round}: ${r.made.length} new ${r.made.length === 1 ? "batch" : "batches"}; ${r.kept.length} kept (a reader's work)`); return { result: r, counts: { batches: r.batches.length, made: r.made.length, kept: r.kept.length, round: r.round } }; }); } /** Which group a row belongs to: its batch's, else the group its channel and date would be read by. */ export function rowGroup(def: CaseDefinition, batches: CaseBatch[]): (r: FindingRow) => string { const byBatch = new Map(batches.map((b) => [b.id, b.group])); return (r) => byBatch.get(r.batch) ?? groupFor(def, r.slug, def.eras.find((e) => e.from.replace(/-/g, "") <= r.date && r.date <= e.to.replace(/-/g, ""))?.id ?? "")?.id ?? "unsorted"; } export type MergeView = MergeResult & { invalid: { line: number; errors: string[] }[] }; /** The merge as a preview: what the report would hold, nothing written. */ export async function mergeView(dir: string, caseId: string, o: { minRelevance?: number } = {}): Promise { const def = await definitionOf(dir, caseId); const [{ rows, invalid }, batches] = await Promise.all([readFindings(dir), readBatches(dir)]); return { ...mergeFindings(def, rows, rowGroup(def, batches), o), invalid }; } /** The report's coverage paragraph: the scope, the candidates, the batches, the rows. */ async function coverageLine(dir: string, def: CaseDefinition, paths: Paths | null): Promise { const counts = await readCandidateCounts(dir).catch(() => null); const batches = await readBatches(dir); const channels = paths ? (await caseChannels(paths, def)).slugs : def.scope.channels; const read = batches.filter((b) => b.state === "read").length; const eras = def.eras.map((e) => `${e.id} (${e.from} to ${e.to})`).join(", "); return [ `Scope: ${channels.length} ${channels.length === 1 ? "channel" : "channels"}${channels.length && channels.length <= 12 ? ` (${channels.join(", ")})` : ""}${eras ? `; eras ${eras}` : ""}.`, counts ? `Candidates: ${counts.windows} windows in ${counts.videos} recordings, ${counts.scanned.withText} recordings with words read for them and ${counts.scanned.noText} in an era with no transcript yet; the noise filters dropped ${plural(counts.noise.noSubject + counts.noise.noGroup + counts.noise.capped, "window")} and ${plural(counts.noise.notStrict, "hit")}.` : "No candidate scan is recorded.", `Batches: ${batches.length}, ${read} read.`, ].join(" "); } /** evidence.json's rows (lane C's evidence stage); none when there is no file, and a file that does not parse is said. */ async function readEvidenceRows(dir: string, log: (line: string) => void) { let text: string; try { text = await readFile(/* turbopackIgnore: true */ path.join(dir, CASE_FILES.evidence), "utf8"); } catch { return []; } try { return evidenceRows(JSON.parse(text)); } catch (e) { log(`${CASE_FILES.evidence} is not JSON (${(e as Error).message}): the Evidence section is left out`); return []; } } /** REPORT.md and REPORT.html from the merge and the summary, behind the privacy gate. */ export async function runExport(dir: string, caseId: string, title: string, by: By, o: { minRelevance?: number; paths?: Paths } = {}) { const def = await definitionOf(dir, caseId); return runStage(dir, "export", by, async (log) => { const merged = await mergeView(dir, caseId, o); if (merged.invalid.length) log(`${merged.invalid.length} findings ${merged.invalid.length === 1 ? "line does" : "lines do"} not check (lines ${merged.invalid.map((x) => x.line).join(", ")}): left out`); const summary = await readSummary(dir); // The gate names the rows first (counts and row ids); the whole markdown is checked again as it is written. assertNoPrivateNames( "the export", [ ...[...merged.sections.flatMap((x) => x.rows), ...merged.quarantined].map((r) => ({ id: r.row, text: rowGateText(r) })), { id: "summary", text: summary?.text ?? "" }, { id: "title", text: title }, ], def.privateNames.sha256, ); // Lane C: the captures and forum attachments the case took (evidence.json), in an Evidence section. const evidence = await readEvidenceRows(dir, log); const markdown = reportMarkdown({ title, summary, merged, coverage: await coverageLine(dir, def, o.paths ?? null), evidence }); await writeReport(dir, markdown, reportHtml(markdown), def.privateNames.sha256); const shown = merged.sections.reduce((n, s) => n + s.rows.length, 0); log(`REPORT.md and REPORT.html: ${shown} findings in ${merged.sections.length} sections, ${merged.quarantined.length} quarantined`); return { result: { markdown, merged }, counts: { findings: shown, sections: merged.sections.length, quarantined: merged.quarantined.length, duplicates: merged.duplicates.length, belowFloor: merged.belowFloor.length } }; }); } export async function runDateChecks(dir: string, caseId: string, paths: Paths, by: By, o: { aroundDays?: number; latest?: number } = {}): Promise { const def = await definitionOf(dir, caseId); return runStage(dir, "date-checks", by, async (log) => { const { uploads, skipped } = await subjectUploads(paths, def); for (const s of skipped) log(`skipped ${s.slug}: ${s.reason}`); const { rows } = await readFindings(dir); const checks = dateChecks(def, uploads, rows, o); await writeDateChecks(dir, checks); log(`${checks.length} key ${checks.length === 1 ? "date" : "dates"} over ${uploads.length} uploads`); return { result: checks, counts: { dates: checks.length, uploads: uploads.length, responses: checks.filter((c) => c.sentence.startsWith("response found")).length } }; }); }