// A case's pipeline files (lib/research/caseStore-server.ts) and the privacy gate (casePrivacy-server.ts): the // definition gated, findings appended with ids never reused, a planted private name blocking findings, summary and // export with counts and row ids only (never the term), batches rebuilt around a reader's work, a stage's record. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/research/caseStore.test.ts import test from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { privateNameHash } from "./privateNames-server"; import { PrivacyBlocked, privacyGate, withholdPrivateNames } from "./casePrivacy-server"; import { appendFindings, readBatchText, readBatches, readDefinition, readFindings, readStages, readCandidates, rebuildBatches, runStage, withholdStored, writeCandidates, saveDefinition, setBatchState, writeReport, writeSummary, } from "./caseStore-server"; import { emptyCounts, longestLine, normalizeDefinition } from "./casePipeline"; import { BATCH_LINE_MAX, type CandidateWindow } from "./caseTypes"; const PLANTED = "Ottoline Brackenridge"; // invented: the private name the gate must catch const HASHES = [privateNameHash(PLANTED)]; const dirs: string[] = []; async function caseDir() { const d = await mkdtemp(path.join(os.tmpdir(), "case-store-")); dirs.push(d); return d; } test.after(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); const row = (over: Record = {}) => ({ batch: "own-1-001", slug: "wren-own", id: "o2", date: "20210101", title: "Vlog", t: 50, url: "", category: "shop", relevance: 2, quote: "the lantern shop is closing", summary: "She says the shop is closing", speaker: "Wren Halloway", confidence: "high", round: 1, by: "hand", ...over, }); test("the gate: counts and item ids, never the term, in its result or its message", () => { const r = privacyGate( [ { id: "f1", text: "nothing private here" }, { id: "f2", text: `she met ${PLANTED} at the shop, ${PLANTED.toUpperCase()} again` }, ], HASHES, ); assert.equal(r.blocked, true); assert.deepEqual(r.rows.map((x) => x.id), ["f2"]); assert.ok(r.hits >= 1); const e = new PrivacyBlocked("these findings", r); assert.doesNotMatch(e.message, /Ottoline|Brackenridge/i); assert.match(e.message, /private-name hits? in 1 item \(f2\)/); assert.equal(privacyGate([{ id: "x", text: PLANTED }], []).blocked, false); }); test("saveDefinition: checked, and a reader prompt naming a private person is blocked", async () => { const dir = await caseDir(); const def = await saveDefinition(dir, "wren", { subjects: [{ name: "Wren", aliases: [] }], privateNames: { sha256: HASHES, note: "a relative" } }); assert.equal(def.case, "wren"); assert.equal((await readDefinition(dir, "wren"))?.privateNames.sha256[0], HASHES[0]); await assert.rejects( saveDefinition(dir, "wren", { ...def, readerPrompts: { common: `Never mention ${PLANTED}.` } }), (e: Error) => e instanceof PrivacyBlocked && /readerPrompts\.common/.test(e.message) && !/Ottoline/.test(e.message), ); const onDisk = await readFile(path.join(dir, "pipeline.json"), "utf8"); assert.doesNotMatch(onDisk, /Ottoline/); }); test("appendFindings: rows checked, ids f1, f2 … never reused, the whole write blocked by a planted name", async () => { const dir = await caseDir(); const a = await appendFindings(dir, [row(), row({ t: 120 })], HASHES); assert.deepEqual(a.map((r) => r.row), ["f1", "f2"]); assert.equal(a[0].quoteCheck, "unchecked"); await assert.rejects(appendFindings(dir, [row({ relevance: 5 })], HASHES), /#1: relevance is 1, 2 or 3/); await assert.rejects( appendFindings(dir, [row({ t: 200 }), row({ t: 300, summary: `with ${PLANTED}` })], HASHES), (e: Error) => e instanceof PrivacyBlocked && /\(f4\)/.test(e.message) && !/Ottoline/.test(e.message), ); // Nothing of the blocked write landed; the next id is still one past the highest written. const b = await appendFindings(dir, [row({ t: 400 })], HASHES); assert.equal(b[0].row, "f3"); const read = await readFindings(dir); assert.deepEqual(read.rows.map((r) => r.row), ["f1", "f2", "f3"]); // A line a person broke by hand is named, never dropped silently. await writeFile(path.join(dir, "findings.jsonl"), `${await readFile(path.join(dir, "findings.jsonl"), "utf8")}{"row":"f9","oops":1}\nnot json\n`); const again = await readFindings(dir); assert.equal(again.rows.length, 3); assert.deepEqual(again.invalid.map((x) => x.line), [4, 5]); const c = await appendFindings(dir, [row({ t: 500 })], HASHES); assert.equal(c[0].row, "f10", "a row id is never reused, even one on a broken line"); }); test("summary and export: gated; a model's summary is a draft, a person's is not", async () => { const dir = await caseDir(); const s = await writeSummary(dir, { text: "What she said.", draft: false, by: "local", model: "qwen3:8b" }, HASHES); assert.equal(s.draft, true); assert.equal((await writeSummary(dir, { text: "Mine.", draft: true, by: "hand" }, HASHES)).draft, false); await assert.rejects(writeSummary(dir, { text: `About ${PLANTED}.`, draft: false, by: "hand" }, HASHES), PrivacyBlocked); await assert.rejects(writeReport(dir, `# R\n\n- "${PLANTED} said" — x`, "

", HASHES), (e: Error) => e instanceof PrivacyBlocked && /the export/.test(e.message)); assert.ok(!(await readdir(dir)).includes("REPORT.md"), "a blocked export writes nothing"); await writeReport(dir, "# R\n", "

R

", HASHES); assert.ok((await readdir(dir)).includes("REPORT.html")); }); const win = (key: string, group: string, n = 300): CandidateWindow => ({ key, slug: key.split("/")[0], id: "v", date: "20150101", title: "T", from: Number(key.split("@")[1]), to: Number(key.split("@")[1]) + 60, era: "early", group, track: "en", hits: [], text: "a word ".repeat(n), }); test("rebuildBatches: pending ones replaced, a read one kept with its file and never batched again, the next round", async () => { const dir = await caseDir(); const def = normalizeDefinition({ groups: [{ id: "own", label: "Own", channels: "subject" }] }, "wren"); const ws = [win("a/v@0", "own"), win("a/v@100", "own"), win("a/v@200", "own")]; const first = await rebuildBatches(dir, def, ws, { budget: 5000 }); assert.equal(first.round, 1); assert.deepEqual(first.batches.map((b) => b.id), ["own-1-001", "own-1-002"]); for (const b of first.batches) assert.ok(longestLine(await readBatchText(dir, b.id)) <= BATCH_LINE_MAX); await setBatchState(dir, "own-1-001", "read"); const second = await rebuildBatches(dir, def, [...ws, win("a/v@300", "own")], { budget: 5000 }); assert.equal(second.round, 2); assert.deepEqual(second.kept.map((b) => b.id), ["own-1-001"]); const covered = new Set(second.kept.flatMap((b) => b.windows)); assert.ok(second.made.every((b) => b.windows.every((k) => !covered.has(k)))); assert.deepEqual((await readdir(path.join(dir, "batches"))).sort(), ["index.json", ...second.batches.map((b) => `${b.id}.txt`)].sort()); assert.equal((await readBatches(dir)).length, second.batches.length); await assert.rejects(readBatchText(dir, "../pipeline"), /not a batch id/); }); test("runStage keeps the stage's record: running, then done with counts or failed with the error", async () => { const dir = await caseDir(); const n = await runStage(dir, "coverage", "cli", async (log) => { log("two channels"); return { result: 7, counts: { rows: 7 } }; }); assert.equal(n, 7); await assert.rejects(runStage(dir, "merge", "cli", async () => { throw new Error("no findings yet"); }), /no findings yet/); const s = await readStages(dir); assert.equal(s.coverage?.state, "done"); assert.deepEqual(s.coverage?.log, ["two channels"]); assert.equal(s.coverage?.counts?.rows, 7); assert.equal(s.merge?.state, "failed"); assert.equal(s.merge?.error, "no findings yet"); // A run left "running" by a process that is gone reads as interrupted. await writeFile(path.join(dir, "stages.json"), JSON.stringify({ batches: { state: "running", startedAt: "x", by: "umtool", pid: 2 ** 22 + 12345, log: [] } })); assert.equal((await readStages(dir)).batches?.state, "failed"); }); test("the gate looks past a possessive; withholdPrivateNames takes the name out and keeps everything else", () => { assert.equal(privacyGate([{ id: "x", text: "that was Ottoline Brackenridge’s idea" }], HASHES).blocked, true); const one = [privateNameHash("Ottoline")]; const r = withholdPrivateNames("Then OTTOLINE said, and Ottoline's dog barked; Ottolines stayed.", one); assert.equal(r.text, "Then [name withheld] said, and [name withheld]'s dog barked; Ottolines stayed."); assert.equal(r.replaced, 2); assert.equal(withholdPrivateNames(`with ${PLANTED} there`, HASHES).text, "with [name withheld] there"); assert.equal(withholdPrivateNames("nothing here", HASHES).replaced, 0); }); test("withholdStored: a name added after the candidates and batches were written is taken out of them, findings untouched", async () => { const dir = await caseDir(); const def = normalizeDefinition({ groups: [{ id: "own", label: "Own", channels: "subject" }] }, "wren"); const w = { ...win("a/v@0", "own", 20), title: `With ${PLANTED}`, text: `${"a word ".repeat(26)}then ${PLANTED} spoke` }; await writeCandidates(dir, [w], emptyCounts()); await rebuildBatches(dir, def, [w]); await appendFindings(dir, [row({ summary: `about ${PLANTED}` })], []); const n = await withholdStored(dir, HASHES); assert.equal(n, 4, "the window's words and title, and the batch's title and words"); const [after] = await readCandidates(dir); assert.match(after.text, /then \[name withheld\] spoke$/); assert.equal(after.title, "With [name withheld]"); const batch = await readBatchText(dir, "own-1-001"); assert.doesNotMatch(batch, /Ottoline/); assert.ok(longestLine(batch) <= BATCH_LINE_MAX); assert.match(await readFile(path.join(dir, "findings.jsonl"), "utf8"), /Ottoline/, "a finding is never rewritten: the gate names its row"); });