// A CASE'S PIPELINE FILES, read and written (plans/release-38/research-cases-and-assist.md, lane A): the files // caseTypes.ts's CASE_FILES names, in a case's directory BESIDE umtool's board (`case.json`, which this never // touches -- the board has its own store and writer, umtool/lib/research/cases.mjs). // // Every write is a whole file to a temp name and a rename. findings.jsonl is appended to under a lock FILE (the // page and the CLI are two processes); a row that does not check is refused with the row named, and the privacy // gate (casePrivacy-server.ts) reads every write of findings, summary, export and hand-off before it lands. // // The directory is the caller's to name (umtool's REPORTS_ROOT/.umtool/research//, or the CLI's): this // module never resolves a root, so a test points it at a temp dir and nothing else. import { mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { CASE_FILES, type CandidateCounts, type CandidateWindow, type CaseBatch, type CaseDefinition, type CaseStage, type CaseStageRun, type CaseStageRuns, type CaseSummaryText, type CoverageRow, type DateCheck, type FindingRow, } from "./caseTypes"; import { CasePipelineError, checkFindingRow, normalizeDefinition, planBatches, rowGateText, wrapText } from "./casePipeline"; import { assertNoPrivateNames, withholdPrivateNames } from "./casePrivacy-server"; import { tmpPathFor } from "../atomicFile.mjs"; const file = (dir: string, name: string) => path.join(/* turbopackIgnore: true */ dir, name); async function readText(p: string): Promise { try { return await readFile(/* turbopackIgnore: true */ p, "utf8"); } catch (e) { if ((e as NodeJS.ErrnoException).code === "ENOENT") return null; throw e; } } async function readJsonFile(p: string): Promise { const t = await readText(p); if (t === null) return null; try { return JSON.parse(t) as T; } catch (e) { throw new CasePipelineError(`${path.basename(p)} is not JSON (${(e as Error).message}): fix or remove it`, 409); } } /** A whole file, to a temp name and a rename. */ export async function writeAtomic(p: string, body: string): Promise { await mkdir(/* turbopackIgnore: true */ path.dirname(p), { recursive: true }); const tmp = tmpPathFor(p); try { await writeFile(/* turbopackIgnore: true */ tmp, body); await rename(/* turbopackIgnore: true */ tmp, p); } catch (e) { await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {}); throw e; } } const json = (v: unknown) => `${JSON.stringify(v, null, 2)}\n`; /** One writer per lock file across processes: O_EXCL, retried; a lock older than 30 s is a dead writer's. */ export async function withFileLock(lockPath: string, fn: () => Promise): Promise { await mkdir(/* turbopackIgnore: true */ path.dirname(lockPath), { recursive: true }); for (let i = 0; ; i++) { try { const fh = await open(/* turbopackIgnore: true */ lockPath, "wx"); await fh.writeFile(String(process.pid)); await fh.close(); break; } catch (e) { if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e; const st = await stat(/* turbopackIgnore: true */ lockPath).catch(() => null); if (st && Date.now() - st.mtimeMs > 30_000) { await rm(/* turbopackIgnore: true */ lockPath, { force: true }); continue; } if (i > 100) throw new CasePipelineError(`${path.basename(lockPath)} is held by another writer: try again`, 409); await new Promise((r) => setTimeout(r, 50)); } } try { return await fn(); } finally { await rm(/* turbopackIgnore: true */ lockPath, { force: true }).catch(() => {}); } } // ── the definition ── /** The case's pipeline.json, or null when none was written yet. */ export async function readDefinition(dir: string, caseId: string): Promise { const raw = await readJsonFile(file(dir, CASE_FILES.definition)); return raw === null ? null : normalizeDefinition(raw, caseId); } /** * Write the definition, checked. The texts a person writes into it -- the reader prompts and the private names' * note -- go through the gate: a prompt naming a private person would hand the name to every reader. */ export async function saveDefinition(dir: string, caseId: string, raw: unknown, now = new Date()): Promise { return withFileLock(file(dir, `${CASE_FILES.definition}.lock`), async () => { const prev = await readDefinition(dir, caseId); const def = normalizeDefinition({ ...(raw as object), case: caseId }, caseId, now); def.createdAt = prev?.createdAt ?? def.createdAt; def.updatedAt = now.toISOString(); assertNoPrivateNames( "the case definition", [ { id: "privateNames.note", text: def.privateNames.note }, ...Object.entries(def.readerPrompts).map(([k, v]) => ({ id: `readerPrompts.${k}`, text: v })), ], def.privateNames.sha256, ); await writeAtomic(file(dir, CASE_FILES.definition), json(def)); return def; }); } /** Change the definition inside its lock: `fn` gets the current one (an empty one when none exists). */ export async function mutateDefinition( dir: string, caseId: string, fn: (def: CaseDefinition) => void, empty: () => CaseDefinition, now = new Date(), ): Promise { const cur = (await readDefinition(dir, caseId)) ?? empty(); fn(cur); return saveDefinition(dir, caseId, cur, now); } // ── stage 1: coverage; stage 9: date checks ── export const readCoverage = async (dir: string) => (await readJsonFile(file(dir, CASE_FILES.coverage))) ?? []; export const writeCoverage = (dir: string, rows: CoverageRow[]) => writeAtomic(file(dir, CASE_FILES.coverage), json(rows)); export const readDateChecks = async (dir: string) => (await readJsonFile(file(dir, CASE_FILES.dateChecks))) ?? []; export const writeDateChecks = (dir: string, rows: DateCheck[]) => writeAtomic(file(dir, CASE_FILES.dateChecks), json(rows)); // ── stage 2: candidates ── /** candidates.jsonl, one window per line, and the counts beside it. */ export async function writeCandidates(dir: string, windows: CandidateWindow[], counts: CandidateCounts): Promise { await writeAtomic(file(dir, CASE_FILES.candidates), windows.map((w) => JSON.stringify(w)).join("\n") + (windows.length ? "\n" : "")); await writeAtomic(file(dir, CASE_FILES.candidateCounts), json(counts)); } export async function readCandidates(dir: string): Promise { const t = await readText(file(dir, CASE_FILES.candidates)); if (!t) return []; const out: CandidateWindow[] = []; t.split("\n").forEach((l, i) => { if (!l.trim()) return; try { out.push(JSON.parse(l) as CandidateWindow); } catch { throw new CasePipelineError(`candidates.jsonl line ${i + 1} is not JSON: build the candidates again`, 409); } }); return out; } export const readCandidateCounts = (dir: string) => readJsonFile(file(dir, CASE_FILES.candidateCounts)); /** A window with the case's private names withheld from everything it stores of the corpus's words. */ export function withholdWindow(w: CandidateWindow, hashes: readonly string[]): { window: CandidateWindow; replaced: number } { if (!hashes.length) return { window: w, replaced: 0 }; const t = withholdPrivateNames(w.text, hashes); const title = withholdPrivateNames(w.title, hashes); let replaced = t.replaced + title.replaced; const hits = w.hits.map((h) => { const m = withholdPrivateNames(h.match, hashes); replaced += m.replaced; return m.replaced ? { ...h, match: m.text } : h; }); return { window: replaced ? { ...w, text: t.text, title: title.text, hits } : w, replaced }; } /** * Withhold the case's private names from what it stores of the corpus -- candidates.jsonl and every batch's text * (re-wrapped: no line over the limit) -- when a name is added after they were written. Findings are a person's or * a reader's writing and are never changed here: the gate names their rows. Answers how many places changed. */ export async function withholdStored(dir: string, hashes: readonly string[]): Promise { if (!hashes.length) return 0; let replaced = 0; const windows = await readCandidates(dir); if (windows.length) { const next = windows.map((w) => { const r = withholdWindow(w, hashes); replaced += r.replaced; return r.window; }); const counts = await readCandidateCounts(dir); if (replaced && counts) await writeCandidates(dir, next, counts); } await withFileLock(file(dir, `${CASE_FILES.batchIndex}.lock`), async () => { const batches = await readBatches(dir); let changed = false; for (const b of batches) { const t = await readText(file(dir, b.file)); if (t === null) continue; const r = withholdPrivateNames(t, hashes); if (!r.replaced) continue; replaced += r.replaced; const body = wrapText(r.text); b.chars = body.length; changed = true; await writeAtomic(file(dir, b.file), body); } if (changed) await writeAtomic(file(dir, CASE_FILES.batchIndex), json(batches)); }); return replaced; } // ── stage 3: batches ── export const readBatches = async (dir: string) => (await readJsonFile(file(dir, CASE_FILES.batchIndex))) ?? []; /** One batch's wrapped text (lane B's reader reads it; lane D's case_batch pages it). */ export async function readBatchText(dir: string, batchId: string): Promise { if (!/^[a-z0-9][a-z0-9-]{0,100}$/.test(batchId)) throw new CasePipelineError(`not a batch id: ${JSON.stringify(batchId)}`); const t = await readText(file(dir, path.join(CASE_FILES.batchDir, `${batchId}.txt`))); if (t === null) throw new CasePipelineError(`no batch ${batchId}`, 404); return t; } /** * Batch the candidates again. A batch already reading, read or failed is KEPT, with its file -- a reader's work is * never discarded -- and its windows are not batched again; the pending batches are replaced. The new batches' * round is one past the highest kept batch's (1 when none is kept). */ export async function rebuildBatches( dir: string, def: CaseDefinition, windows: CandidateWindow[], o: { budget?: number } = {}, ): Promise<{ batches: CaseBatch[]; made: CaseBatch[]; kept: CaseBatch[]; round: number }> { return withFileLock(file(dir, `${CASE_FILES.batchIndex}.lock`), async () => { const prev = await readBatches(dir); const kept = prev.filter((b) => b.state !== "pending"); const round = kept.length ? Math.max(...kept.map((b) => b.round)) + 1 : 1; const exclude = new Set(kept.flatMap((b) => b.windows)); const { batches: made, texts } = planBatches(def, windows, { budget: o.budget, round, exclude }); const batchDir = file(dir, CASE_FILES.batchDir); await mkdir(/* turbopackIgnore: true */ batchDir, { recursive: true }); const keepFiles = new Set([...kept, ...made].map((b) => path.basename(b.file))); for (const name of await readdir(/* turbopackIgnore: true */ batchDir).catch(() => [] as string[])) { if (name.endsWith(".txt") && !keepFiles.has(name)) await rm(/* turbopackIgnore: true */ path.join(batchDir, name), { force: true }); } for (const b of made) { // The windows are withheld when the candidates are written; a name added since is withheld here too. const body = wrapText(withholdPrivateNames(texts.get(b.id)!, def.privateNames.sha256).text); b.chars = body.length; await writeAtomic(file(dir, b.file), body); } const batches = [...kept, ...made]; await writeAtomic(file(dir, CASE_FILES.batchIndex), json(batches)); return { batches, made, kept, round }; }); } /** A batch's state, as a reader moves it (lane B: pending → reading → read | failed). */ export async function setBatchState(dir: string, batchId: string, state: CaseBatch["state"]): Promise { return withFileLock(file(dir, `${CASE_FILES.batchIndex}.lock`), async () => { const batches = await readBatches(dir); const b = batches.find((x) => x.id === batchId); if (!b) throw new CasePipelineError(`no batch ${batchId}`, 404); b.state = state; await writeAtomic(file(dir, CASE_FILES.batchIndex), json(batches)); return b; }); } // ── stage 4's output, stage 5's input: findings ── export type FindingsRead = { rows: FindingRow[]; invalid: { line: number; errors: string[] }[] }; /** findings.jsonl: every row that checks, and every line that does not, named (never dropped silently). */ export async function readFindings(dir: string): Promise { const t = await readText(file(dir, CASE_FILES.findings)); const rows: FindingRow[] = []; const invalid: FindingsRead["invalid"] = []; if (!t) return { rows, invalid }; const seen = new Set(); t.split("\n").forEach((l, i) => { if (!l.trim()) return; let raw: unknown; try { raw = JSON.parse(l); } catch { invalid.push({ line: i + 1, errors: ["not JSON"] }); return; } const c = checkFindingRow(raw); if (!c.ok) invalid.push({ line: i + 1, errors: c.errors }); else if (!c.row.row) invalid.push({ line: i + 1, errors: ["no row id"] }); else if (seen.has(c.row.row)) invalid.push({ line: i + 1, errors: [`row ${c.row.row} appears twice`] }); else { seen.add(c.row.row); rows.push(c.row as FindingRow); } }); return { rows, invalid }; } const rowNumber = (r: string) => Number(/^f(\d+)$/.exec(r)?.[1] ?? 0); /** * Append rows: each checked (a row that does not check refuses the whole write, every bad row named by its index), * each given the next `f`, the lot gated. Answers the rows as written. */ export async function appendFindings(dir: string, raws: unknown[], hashes: readonly string[]): Promise { if (!Array.isArray(raws) || !raws.length) throw new CasePipelineError("findings: a list of rows"); const checked = raws.map((r, i) => ({ i, c: checkFindingRow(r) })); const bad = checked.filter((x) => !x.c.ok); if (bad.length) { throw new CasePipelineError( `${bad.length} ${bad.length === 1 ? "row does" : "rows do"} not check: ` + bad.slice(0, 10).map((x) => `#${x.i + 1}: ${(x.c as { errors: string[] }).errors.join("; ")}`).join(" · "), ); } return withFileLock(file(dir, `${CASE_FILES.findings}.lock`), async () => { const { rows: existing } = await readFindings(dir); let next = Math.max(0, ...existing.map((r) => rowNumber(r.row))); const t = (await readText(file(dir, CASE_FILES.findings))) ?? ""; // A row id is never reused: one past the highest ever written, even when that line no longer checks. for (const m of t.matchAll(/"row"\s*:\s*"f(\d+)"/g)) next = Math.max(next, Number(m[1])); const rows = checked.map((x) => ({ ...(x.c as { row: FindingRow }).row, row: `f${++next}` }) as FindingRow); assertNoPrivateNames("these findings", rows.map((r) => ({ id: r.row, text: rowGateText(r) })), hashes); const body = rows.map((r) => JSON.stringify(r)).join("\n") + "\n"; await writeAtomic(file(dir, CASE_FILES.findings), (t && !t.endsWith("\n") ? `${t}\n` : t) + body); return rows; }); } /** Rewrite findings.jsonl whole (verify and merge rewrite it, lane C), gated. */ export async function writeFindings(dir: string, rows: FindingRow[], hashes: readonly string[]): Promise { assertNoPrivateNames("the findings", rows.map((r) => ({ id: r.row, text: rowGateText(r) })), hashes); await withFileLock(file(dir, `${CASE_FILES.findings}.lock`), () => writeAtomic(file(dir, CASE_FILES.findings), rows.map((r) => JSON.stringify(r)).join("\n") + (rows.length ? "\n" : "")), ); } // ── stage 5: the summary and the export ── export const readSummary = (dir: string) => readJsonFile(file(dir, CASE_FILES.summary)); /** The summary, gated. A hand-written one is never a draft; a model's is until a person saves it. */ export async function writeSummary(dir: string, s: Omit, hashes: readonly string[], now = new Date()): Promise { if (typeof s.text !== "string") throw new CasePipelineError("summary: text"); assertNoPrivateNames("the summary", [{ id: "summary", text: s.text }], hashes); const doc: CaseSummaryText = { text: s.text.slice(0, 20_000), draft: s.by !== "hand", by: s.by, ...(s.model ? { model: s.model.slice(0, 100) } : {}), at: now.toISOString(), }; await writeAtomic(file(dir, CASE_FILES.summary), json(doc)); return doc; } /** REPORT.md and REPORT.html, gated as one export. */ export async function writeReport(dir: string, markdown: string, html: string, hashes: readonly string[]): Promise { assertNoPrivateNames("the export", [{ id: "REPORT.md", text: markdown }], hashes); await writeAtomic(file(dir, CASE_FILES.report), markdown); await writeAtomic(file(dir, CASE_FILES.reportHtml), html); } export const readReport = (dir: string) => readText(file(dir, CASE_FILES.report)); export const readReportHtml = (dir: string) => readText(file(dir, CASE_FILES.reportHtml)); // ── each stage's last run ── export async function readStages(dir: string): Promise { const s = (await readJsonFile(file(dir, CASE_FILES.stages))) ?? {}; // A "running" whose process is gone was interrupted: say so rather than spin for ever. for (const [k, run] of Object.entries(s) as [CaseStage, CaseStageRun][]) { if (run?.state !== "running") continue; let alive = true; try { process.kill(run.pid, 0); } catch (e) { alive = (e as NodeJS.ErrnoException).code === "EPERM"; } if (!alive) s[k] = { ...run, state: "failed", error: "interrupted: the process that ran it is gone" }; } return s; } /** Record a stage's run (merged into stages.json under its lock). */ export async function recordStage(dir: string, stage: CaseStage, run: CaseStageRun): Promise { await withFileLock(file(dir, `${CASE_FILES.stages}.lock`), async () => { const cur = (await readJsonFile(file(dir, CASE_FILES.stages))) ?? {}; cur[stage] = { ...run, log: run.log.slice(-200) }; await writeAtomic(file(dir, CASE_FILES.stages), json(cur)); }); } /** * Run a stage with its record kept: "running" first, then "done" with its counts or "failed" with the error's * message (a PrivacyBlocked's message is counts and row ids only). `log` lines are kept as written. */ export async function runStage( dir: string, stage: CaseStage, by: CaseStageRun["by"], fn: (log: (line: string) => void) => Promise<{ result: T; counts?: Record }>, ): Promise { const lines: string[] = []; const startedAt = new Date().toISOString(); const base = { startedAt, by, pid: process.pid } as const; await recordStage(dir, stage, { ...base, state: "running", log: lines }); try { const { result, counts } = await fn((l) => lines.push(l)); await recordStage(dir, stage, { ...base, state: "done", endedAt: new Date().toISOString(), log: lines, ...(counts ? { counts } : {}) }); return result; } catch (e) { await recordStage(dir, stage, { ...base, state: "failed", endedAt: new Date().toISOString(), log: lines, error: (e as Error).message }).catch(() => {}); throw e; } }