commit df7873ac2bf686342be2b1302c372a24a5d5fd13
parent 638ab3f927bd709ebb1804fecaa5a8c2d3550262
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 04:27:12 -0500
research cases: the case's private names withheld from what it stores of the corpus, and the gate looks past a possessive
The candidate windows and the batches are corpus text, which names whom it names. Now a
window's words, title and hits are written with every phrase that hashes to one of the
case's private names replaced by [name withheld] (casePrivacy-server.ts
withholdPrivateNames; "[name withheld]'s" for a possessive), and a name added after the
candidates and batches were written is withheld from them at once (caseStore-server.ts
withholdStored, run by the page's Private names box and `archilyzer case private-names
add`), the batches re-wrapped so no line passes 200. So no file of a case holds a private
name -- a reader never sees one, and a quote written with [name withheld] still matches its
window (lane B's quote check). Findings are never rewritten: the gate names their rows.
Contract: privateNameCandidates also hashes each phrase with a possessive ending on its
last word dropped -- "Ottoline's" was not caught.
Also: plurals in the CLI and on the page; the page's status line stays in view while the
stages scroll; the report's coverage line says windows and hits apart; the e2e follows a
background stage for up to 30 s (a dev server compiles the route on the first poll), and
asserts that no file of the case names the planted name once it is withheld.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 212 insertions(+), 29 deletions(-)
diff --git a/common/bin/case.ts b/common/bin/case.ts
@@ -32,6 +32,7 @@ import {
readStages,
readSummary,
saveDefinition,
+ withholdStored,
writeSummary,
} from "../lib/research/caseStore-server";
import { mergeView, runBatches, runCandidates, runCoverage, runDateChecks, runExport } from "../controller/casePipelineRun";
@@ -71,6 +72,8 @@ async function readStdin(): Promise<string> {
return Buffer.concat(chunks).toString("utf8");
}
+const n = (k: number, w: string) => `${k} ${w}${k === 1 ? "" : "s"}`;
+
const out = (json: boolean, value: unknown, text: () => string) => {
console.log(json ? JSON.stringify(value, null, 2) : text());
return 0;
@@ -119,7 +122,7 @@ export async function main(verb: CaseVerb, positionals: string[], flags: Record<
return out(json, view, () =>
[
`${c.title} (${c.id}) — ${c.dir}`,
- def ? `defined: ${view.subjects.length} subjects, eras ${view.eras.join(", ") || "none"}, groups ${view.groups.join(", ") || "none"}, ${view.privateNames} private ${view.privateNames === 1 ? "name" : "names"} (hashed); status ${view.status}` : "not defined yet (archilyzer case define <case> --file pipeline.json)",
+ def ? `defined: ${n(view.subjects.length, "subject")}, eras ${view.eras.join(", ") || "none"}, groups ${view.groups.join(", ") || "none"}, ${n(view.privateNames, "private name")} (hashed); status ${view.status}` : "not defined yet (archilyzer case define <case> --file pipeline.json)",
`coverage: ${view.coverage} channel-years · candidates: ${view.candidates ?? "not built"} · batches: ${view.batches.total} (${view.batches.pending} pending, ${view.batches.read} read) · findings: ${view.findings.rows}${view.findings.invalid ? ` (${view.findings.invalid} lines do not check)` : ""} · summary: ${summary ? (summary.draft ? "a draft" : "written") : "none"}`,
...Object.entries(stages).map(([k, s]) => ` ${k}: ${s?.state} ${s?.endedAt ?? s?.startedAt} (${s?.by})${s?.error ? ` — ${s.error}` : ""}`),
].join("\n"),
@@ -133,14 +136,14 @@ export async function main(verb: CaseVerb, positionals: string[], flags: Record<
if (pn && "terms" in pn) throw new CasePipelineError("privateNames.terms is never stored: add the names with `archilyzer case private-names <case> add` (stdin), which keeps only their hashes");
const prev = await readDefinition(c.dir, c.id);
const def = await saveDefinition(c.dir, c.id, { ...raw, privateNames: { sha256: prev?.privateNames.sha256 ?? [], note: typeof pn?.note === "string" ? pn.note : (prev?.privateNames.note ?? "") } });
- return out(json, def, () => `${c.id}: ${def.subjects.length} subjects, ${def.eras.length} eras, ${def.groups.length} groups saved (${CASE_FILES.definition}); ${def.privateNames.sha256.length} private names kept`);
+ return out(json, def, () => `${c.id}: ${n(def.subjects.length, "subject")}, ${n(def.eras.length, "era")}, ${n(def.groups.length, "group")} saved (${CASE_FILES.definition}); ${n(def.privateNames.sha256.length, "private name")} kept`);
}
case "private-names": {
const op = positionals[1];
if (op !== "add" && op !== "remove" && op !== "clear" && op !== "count") throw new CasePipelineError("private-names takes add, remove, clear or count (terms on stdin)");
if (op === "count") {
const def = await readDefinition(c.dir, c.id);
- return out(json, { count: def?.privateNames.sha256.length ?? 0 }, () => `${def?.privateNames.sha256.length ?? 0} private names (hashed)`);
+ return out(json, { count: def?.privateNames.sha256.length ?? 0 }, () => `${n(def?.privateNames.sha256.length ?? 0, "private name")} (hashed)`);
}
const terms = op === "clear" ? [] : (await readStdin()).split("\n").map((t) => t.trim()).filter(Boolean);
for (const [i, t] of terms.entries()) {
@@ -161,7 +164,11 @@ export async function main(verb: CaseVerb, positionals: string[], flags: Record<
},
() => emptyDefinition(c.id),
);
- return out(json, { changed, count: def.privateNames.sha256.length }, () => `${op === "add" ? "added" : "removed"} ${changed}; ${def.privateNames.sha256.length} private names (hashed)`);
+ // A name added after the candidates and batches were written is withheld from them now.
+ const withheld = op === "add" ? await withholdStored(c.dir, def.privateNames.sha256) : 0;
+ return out(json, { changed, count: def.privateNames.sha256.length, withheld }, () =>
+ `${op === "add" ? "added" : "removed"} ${changed}; ${n(def.privateNames.sha256.length, "private name")} (hashed)${withheld ? `; withheld in ${n(withheld, "place")} of the candidates and batches` : ""}`,
+ );
}
case "prompt": {
const def = await readDefinition(c.dir, c.id);
@@ -187,7 +194,7 @@ export async function main(verb: CaseVerb, positionals: string[], flags: Record<
const k = r.counts;
return out(json, k, () =>
[
- `${k.windows} windows in ${k.videos} recordings (${k.titleHits} title hits) → ${CASE_FILES.candidates}`,
+ `${n(k.windows, "window")} in ${n(k.videos, "recording")} (${n(k.titleHits, "title hit")}) → ${CASE_FILES.candidates}`,
`by family: ${Object.entries(k.byFamily).map(([f, n]) => `${f} ${n}`).join(", ") || "none"}`,
`by year: ${Object.entries(k.byYear).map(([y, n]) => `${y} ${n}`).join(", ") || "none"}`,
`by channel: ${Object.entries(k.byChannel).map(([s, n]) => `${s} ${n}`).join(", ") || "none"}`,
@@ -200,7 +207,7 @@ export async function main(verb: CaseVerb, positionals: string[], flags: Record<
}
case "batches": {
const r = await runBatches(c.dir, c.id, "cli", { budget: int(flags.budget, "budget") });
- return out(json, r.batches, () => [`round ${r.round}: ${r.made.length} made, ${r.kept.length} kept`, ...r.batches.map((b) => `${b.id}\t${b.state}\t${b.windows.length} windows\t${b.chars} chars\t${b.file}`)].join("\n"));
+ return out(json, r.batches, () => [`round ${r.round}: ${r.made.length} made, ${r.kept.length} kept`, ...r.batches.map((b) => `${b.id}\t${b.state}\t${n(b.windows.length, "window")}\t${b.chars} chars\t${b.file}`)].join("\n"));
}
case "batch": {
const t = await readBatchText(c.dir, positionals[1] ?? "");
@@ -247,7 +254,7 @@ export async function main(verb: CaseVerb, positionals: string[], flags: Record<
}
case "date-checks": {
const r = await runDateChecks(c.dir, c.id, corpus(), "cli", { aroundDays: int(flags.around, "around"), latest: int(flags.latest, "latest") });
- return out(json, r, () => r.map((d) => `${d.date} ${d.label}: ${d.uploads.length} uploads — ${d.sentence}`).join("\n"));
+ return out(json, r, () => r.map((d) => `${d.date} ${d.label}: ${n(d.uploads.length, "upload")} — ${d.sentence}`).join("\n"));
}
}
} catch (e) {
diff --git a/common/controller/casePipelineRun.ts b/common/controller/casePipelineRun.ts
@@ -34,6 +34,7 @@ import {
readSummary,
rebuildBatches,
runStage,
+ withholdWindow,
writeCandidates,
writeCoverage,
writeDateChecks,
@@ -77,6 +78,14 @@ export async function runCandidates(dir: string, caseId: string, paths: Paths, b
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 {
@@ -122,7 +131,7 @@ async function coverageLine(dir: string, def: CaseDefinition, paths: Paths | nul
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; ${Object.values(counts.noise).reduce((a, b) => a + b, 0)} windows dropped by the noise filters.`
+ ? `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 ${counts.noise.noSubject + counts.noise.noGroup + counts.noise.capped} windows and ${counts.noise.notStrict} hits.`
: "No candidate scan is recorded.",
`Batches: ${batches.length}, ${read} read.`,
].join(" ");
diff --git a/common/lib/research/casePrivacy-server.ts b/common/lib/research/casePrivacy-server.ts
@@ -6,7 +6,8 @@
// matched, never in a log -- the case's private names are in no file, and the gate's refusal must not put them in
// one. A caller logs the error's message as it stands; it holds nothing else.
-import { privateNameHits } from "./privateNames-server";
+import { NAME_WITHHELD, normalizeTerm, stripPossessive } from "./caseTypes";
+import { privateNameHash, privateNameHits } from "./privateNames-server";
export type GateItem = { id: string; text: string };
export type GateResult = { blocked: boolean; hits: number; rows: { id: string; hits: number }[] };
@@ -47,3 +48,43 @@ export function assertNoPrivateNames(what: string, items: readonly GateItem[], h
const r = privacyGate(items, hashes);
if (r.blocked) throw new PrivacyBlocked(what, r);
}
+
+/**
+ * The case's private names taken OUT of a text the case stores (lane A): every word or 2- or 3-word phrase that
+ * hashes to one of them becomes NAME_WITHHELD (a possessive keeps its ending: "[name withheld]'s"). The windows
+ * and batches a reader reads are corpus text, which names whom it names; withheld here, the case's files never
+ * hold a private name, a reader never sees one, and a quote written with [name withheld] still matches its
+ * window's words (lane B's quote check).
+ */
+export function withholdPrivateNames(text: string, hashes: readonly string[]): { text: string; replaced: number } {
+ if (!hashes.length || !text) return { text, replaced: 0 };
+ const set = new Set(hashes);
+ const tokens = [...text.matchAll(/[\p{L}\p{N}'’\-]+/gu)].map((m) => ({ start: m.index ?? 0, end: (m.index ?? 0) + m[0].length, norm: normalizeTerm(m[0]) }));
+ let out = "";
+ let at = 0;
+ let replaced = 0;
+ for (let i = 0; i < tokens.length; ) {
+ let n = 0;
+ let keep = "";
+ for (let k = Math.min(3, tokens.length - i); k >= 1 && !n; k--) {
+ const words = tokens.slice(i, i + k).map((t) => t.norm);
+ if (set.has(privateNameHash(words.join(" ")))) n = k;
+ else {
+ const last = stripPossessive(words[k - 1]);
+ if (last !== words[k - 1] && set.has(privateNameHash([...words.slice(0, -1), last].join(" ")))) {
+ n = k;
+ keep = text.slice(tokens[i + k - 1].end - 2, tokens[i + k - 1].end);
+ }
+ }
+ }
+ if (!n) {
+ i++;
+ continue;
+ }
+ out += text.slice(at, tokens[i].start) + NAME_WITHHELD + keep;
+ at = tokens[i + n - 1].end;
+ replaced++;
+ i += n;
+ }
+ return { text: out + text.slice(at), replaced };
+}
diff --git a/common/lib/research/caseStore-server.ts b/common/lib/research/caseStore-server.ts
@@ -25,8 +25,8 @@ import {
type DateCheck,
type FindingRow,
} from "./caseTypes";
-import { CasePipelineError, checkFindingRow, normalizeDefinition, planBatches, rowGateText } from "./casePipeline";
-import { assertNoPrivateNames } from "./casePrivacy-server";
+import { CasePipelineError, checkFindingRow, normalizeDefinition, planBatches, rowGateText, wrapText } from "./casePipeline";
+import { assertNoPrivateNames, withholdPrivateNames } from "./casePrivacy-server";
const file = (dir: string, name: string) => path.join(/* turbopackIgnore: true */ dir, name);
@@ -167,6 +167,57 @@ export async function readCandidates(dir: string): Promise<CandidateWindow[]> {
export const readCandidateCounts = (dir: string) => readJsonFile<CandidateCounts>(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<number> {
+ 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<CaseBatch[]>(file(dir, CASE_FILES.batchIndex))) ?? [];
@@ -202,7 +253,12 @@ export async function rebuildBatches(
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) await writeAtomic(file(dir, b.file), texts.get(b.id)!);
+ 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 };
diff --git a/common/lib/research/caseStore.test.ts b/common/lib/research/caseStore.test.ts
@@ -10,7 +10,7 @@ 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 } from "./casePrivacy-server";
+import { PrivacyBlocked, privacyGate, withholdPrivateNames } from "./casePrivacy-server";
import {
appendFindings,
readBatchText,
@@ -18,14 +18,17 @@ import {
readDefinition,
readFindings,
readStages,
+ readCandidates,
rebuildBatches,
runStage,
+ withholdStored,
+ writeCandidates,
saveDefinition,
setBatchState,
writeReport,
writeSummary,
} from "./caseStore-server";
-import { longestLine, normalizeDefinition } from "./casePipeline";
+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
@@ -178,3 +181,31 @@ test("runStage keeps the stage's record: running, then done with counts or faile
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");
+});
diff --git a/common/lib/research/caseTypes.ts b/common/lib/research/caseTypes.ts
@@ -340,14 +340,25 @@ export const isRelevance = (value: unknown): value is Relevance => value === 1 |
/** A term's words NFKC-normalised, lowercased and single-spaced: what privateNameHash hashes. */
export const normalizeTerm = (s: string) => s.normalize("NFKC").toLowerCase().trim().split(/\s+/u).join(" ");
-/** What the gate hashes: every word of `text` and every 2- and 3-word phrase, each normalizeTerm'd. */
+/** A word's possessive ending, which the gate looks past (lane A): "Ottoline's" is Ottoline. */
+export const stripPossessive = (word: string) => word.replace(/['’]s$/u, "");
+
+/**
+ * What the gate hashes: every word of `text` and every 2- and 3-word phrase, each normalizeTerm'd -- and each
+ * phrase again with a possessive ending on its last word dropped (lane A: a name in the possessive is the name).
+ */
export function privateNameCandidates(text: string): string[] {
const words = normalizeTerm(text.replace(/[^\p{L}\p{N}'’\-\s]/gu, " "))
.split(" ")
.filter(Boolean);
const out = new Set<string>();
for (let i = 0; i < words.length; i++) {
- for (let n = 1; n <= 3 && i + n <= words.length; n++) out.add(words.slice(i, i + n).join(" "));
+ for (let n = 1; n <= 3 && i + n <= words.length; n++) {
+ const phrase = words.slice(i, i + n);
+ out.add(phrase.join(" "));
+ const last = stripPossessive(phrase[n - 1]);
+ if (last && last !== phrase[n - 1]) out.add([...phrase.slice(0, -1), last].join(" "));
+ }
}
return [...out];
}
diff --git a/umtool/components/research/CasePipeline.tsx b/umtool/components/research/CasePipeline.tsx
@@ -212,10 +212,13 @@ export default function CasePipeline({ initial }: { initial: PipelineView }) {
if (problem) throw new Error(problem);
body = { [op]: [await privateNameHashWeb(term)] };
}
- const r = await call<{ count: number; changed: number }>(api("private-names"), "POST", body);
+ const r = await call<{ count: number; changed: number; withheld: 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";
+ return op === "add"
+ ? r.changed
+ ? `added: ${plural(r.count, "private name")} (hashed)${r.withheld ? `; withheld in ${plural(r.withheld, "place")} of the candidates and batches` : ""}`
+ : `already there: ${plural(r.count, "private name")}` : op === "remove" ? (r.changed ? `removed: ${r.count} left` : "that name was not there") : "every private name removed";
});
const addRows = () =>
@@ -317,7 +320,7 @@ export default function CasePipeline({ initial }: { initial: PipelineView }) {
<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")}>
+ <div role={status.tone === "error" ? "alert" : "status"} data-pipeline-status="" className={cn("sticky top-0 z-10 rounded-[3px] border bg-panel px-3 py-2 text-[12.5px] shadow-sm", status.tone === "error" ? "border-reject-text text-reject-text" : "border-seam-2 text-text-2")}>
{status.text}
</div>
)}
@@ -640,7 +643,7 @@ export default function CasePipeline({ initial }: { initial: PipelineView }) {
</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>}>
+ <Panel id="stage-privacy" title="6 · Privacy gate" aside={<span className="font-mono text-[11px] text-muted">{plural(view.privateNames, "private name")} (hashed)</span>}>
<Manual>every write of findings, the summary, the export and a hand-off is checked against the case'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 ? (
diff --git a/umtool/e2e/case-pipeline.spec.ts b/umtool/e2e/case-pipeline.spec.ts
@@ -1,5 +1,5 @@
import { test, expect, type Page } from "@playwright/test";
-import { readFileSync, writeFileSync } from "node:fs";
+import { readdirSync, readFileSync, statSync, 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";
@@ -19,9 +19,27 @@ import { WARM_TIMEOUT, warm } from "./warm";
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 }[];
+// The stub writes its log on its first request; before that there is none.
+const stubLog = (): { route?: string; slug?: string }[] => {
+ try {
+ return JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8"));
+ } catch {
+ return [];
+ }
+};
+// A background stage ends in well under a second; the first poll of a route can wait on its compile.
+const STAGE = { timeout: 30_000 };
const SHOTS = process.env.E2E_SHOTS_DIR;
+/** The case's files whose text names the planted private name, relative to the case dir. */
+function filesNaming(term: string, dir = CASE_DIR, base = CASE_DIR): string[] {
+ return readdirSync(dir).flatMap((name) => {
+ const p = path.join(dir, name);
+ if (statSync(p).isDirectory()) return filesNaming(term, p, base);
+ return readFileSync(p, "utf8").toLowerCase().includes(term.toLowerCase()) ? [path.relative(base, p)] : [];
+ });
+}
+
async function shot(page: Page, name: string, stage?: string) {
if (!SHOTS) return;
if (stage) await page.locator(`#stage-${stage}`).scrollIntoViewIfNeeded();
@@ -60,7 +78,7 @@ test("a case through its pipeline: define, coverage, candidates, batches, findin
// 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");
+ await expect(stageState(page, "coverage")).toHaveAttribute("data-stage-state", "done", STAGE);
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", "");
@@ -82,7 +100,7 @@ test("a case through its pipeline: define, coverage, candidates, batches, findin
// 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");
+ await expect(stageState(page, "candidates")).toHaveAttribute("data-stage-state", "done", STAGE);
const counts = page.locator("[data-candidate-counts]");
await expect(counts).toContainText("3 windows in 3 recordings");
await expect(counts).toContainText("noSubject 1");
@@ -129,6 +147,9 @@ test("a case through its pipeline: define, coverage, candidates, batches, findin
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 candidates and batches written before it are withheld now; only the row a person wrote still names it.
+ await expect(status(page)).toContainText("added: 1 private name (hashed); withheld in");
+ expect(filesNaming(PLANTED)).toEqual(["findings.jsonl"]);
// 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]");
@@ -144,7 +165,7 @@ test("a case through its pipeline: define, coverage, candidates, batches, findin
// 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(stageState(page, "export")).toHaveAttribute("data-stage-state", "failed", STAGE);
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");
@@ -160,12 +181,13 @@ test("a case through its pipeline: define, coverage, candidates, batches, findin
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");
+ await expect(stageState(page, "export")).toHaveAttribute("data-stage-state", "done", STAGE);
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);
+ expect(filesNaming(PLANTED)).toEqual([]);
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");
@@ -181,7 +203,7 @@ test("a case through its pipeline: define, coverage, candidates, batches, findin
// 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(stageState(page, "date-checks")).toHaveAttribute("data-stage-state", "done", STAGE);
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");
});
diff --git a/umtool/lib/research/pipeline.ts b/umtool/lib/research/pipeline.ts
@@ -27,6 +27,7 @@ import {
readStages,
readSummary,
saveDefinition,
+ withholdStored,
writeSummary,
} from "yt-dlp-transcript-common/lib/research/caseStore-server";
import { caseChannels } from "yt-dlp-transcript-common/controller/caseCorpus";
@@ -160,7 +161,7 @@ export async function saveCaseDefinition(id: string, body: unknown): Promise<Cas
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 }> {
+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 [];
@@ -182,7 +183,9 @@ export async function changePrivateNames(id: string, body: { add?: unknown; remo
},
() => emptyDefinition(c.id),
);
- return { count: def.privateNames.sha256.length, changed };
+ // 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 ──