Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 128acda557035d27812cf75d523d23a6b8390095
parent 1df2a71eca6d3d883347c2a61cf158e02de04fcd
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 04:03:09 -0500

common: research cases as a pipeline -- stages 1-3, 5, 6 and 9 over the live corpus, and `archilyzer case`

The pure half (lib/research/casePipeline.ts): the case definition checked whole (every bad
field named), the reader prompt with the naming rule always appended ([name withheld]),
rolling captions folded, term-family hits into +/-W s windows merged under a span cap,
title hits, the noise filters (a coverage window must name a subject; a strict era's
own-channel windows need a strict family) and their counts, batches as WRAPPED text (no
line over BATCH_LINE_MAX), a finding row checked, the merge (same recording within 20 s:
higher relevance, then later round), the report as cited markdown in the board's house
format and as HTML, the date checks' sentence, and a Web Crypto private-name hash equal
to the server's.

The stores (caseStore-server.ts), beside umtool's board and never inside case.json:
pipeline.json, coverage.json, candidates.jsonl + counts, batches (a batch a reader has
started is kept and its windows never batched again; the next round), findings.jsonl
appended under a lock file with row ids never reused, summary.json (a model's is a draft),
REPORT.md/.html, date-checks.json, stages.json (each stage's last run, CLI or page).

The privacy gate (casePrivacy-server.ts): every write of findings, summary, export and
the definition's prompts is scanned against privateNames.sha256; a hit blocks and says
counts and row ids, never the term.

The corpus readers (controller/caseCorpus.ts), read-only, through the readers that exist:
heldVideoIds, the LMDB byChannel key scan for dates, readDateAndTitle, readCuesInVideoDir
(en-orig before en), readVideoFiles; the scope through site pools and <site>:<group>.

`archilyzer case show|define|private-names|prompt|coverage|candidates|batches|batch|
findings|summary|merge|export|date-checks` (bin/case.ts): private names from stdin only,
stored as hashes. COMMANDS.md regenerated.

Contract (caseTypes.ts) extended where a stage needs it: CaseSubject.channels (the
"subject" group, the date checks), CaseEra.strictFamilies (the strict noise filter),
CaseDefinition.keyDates (stage 9), CandidateWindow.titleFamilies and url, CandidateCounts,
CaseSummaryText, CaseStage/CaseStageRun, CASE_FILES summary/report/reportHtml/stages/
candidateCounts; coverage's year 0 is the undated row.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 13+++++++++++++
Mcommon/bin/archilyzer.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/case.test.ts | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/case.ts | 257+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/caseCorpus.test.ts | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/caseCorpus.ts | 308+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/casePipelineRun.ts | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/research/casePipeline.test.ts | 304+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/research/casePipeline.ts | 979+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/research/casePrivacy-server.ts | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/research/caseStore-server.ts | 372+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/research/caseStore.test.ts | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/research/caseTypes.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
13 files changed, 3041 insertions(+), 2 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -77,6 +77,19 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi | `archilyzer migrate channel-priority` | `[--dry-run]` | the one-shot channel-priority migration (plans/channel-priority.md, S5) *(passthrough)* | | `archilyzer storage report` | `[<slug>…] [--json]` | each channel's media (tierable), text and clip bytes and where its media is — off the reports, no drive touched; totals per place (the corpus disk's is what a move would free) | | `archilyzer corpus grep` | `--regex <re> [--channels a,b] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--window 30] [--limit N] [--case-sensitive] [--json]` | search the LIVE corpus's transcripts off disk, no index and no editor: each held video's cues (transcript.cues.json, else its best caption track, en-orig before en, rolling repeats collapsed), dated by metadata.info.json upload\_date; prints date, channel, id, start second, title and the window's text (case-insensitive unless --case-sensitive), then the videos in range with no transcript yet; a channel whose text is unreadable is skipped and named; default every channel that is not social; TRANSCRIPTS\_DIR picks the corpus; writes nothing | +| `archilyzer case show` | `<case> [--root <dir>] [--json]` | a research case's pipeline (release 38): what is defined (subjects, eras, reader groups, how many private names — hashed, never shown), each stage's file and its last run, from the page or here | +| `archilyzer case define` | `<case> --file <pipeline.json> [--root <dir>] [--json]` | write the case's definition beside its umtool board (`<root>/.umtool/research/<case>/pipeline.json`): subjects (with their own channels), scope (channels, `<site>:<group>` groups, sites), eras with term families (regex, flags iu) and strict families, reader groups (a list of slugs, "subject" or "coverage"; an era), reader prompts, key dates; checked whole, every bad field named; a reader prompt naming a private person is blocked by the privacy gate; the private names already stored are kept, and a file carrying `privateNames.terms` is refused | +| `archilyzer case private-names` | `<case> add\|remove\|clear\|count [--root <dir>] [--json]` | the case's private names, read from STDIN one per line (never an argument: the shell's history), each stored as the sha256 of its normalized words and nothing else; at most three words a name (the gate checks words and 2- and 3-word phrases); prints counts only | +| `archilyzer case prompt` | `<case> [<group>\|common] [--root <dir>]` | print the reader prompt a group gets: the case's common prompt, the group's own, the subjects, and the naming rule (`[name withheld]`), which is always there | +| `archilyzer case coverage` | `<case> [--root <dir>] [--json]` | stage 1: per channel × year in the case's scope, listed, held, transcribed and untranscribed audio, off the live corpus (read only; TRANSCRIPTS\_DIR picks it), the key years (an era touches them) starred, a channel that cannot be read skipped with its reason; writes coverage.json | +| `archilyzer case candidates` | `<case> [--window <s>] [--max-span <s>] [--per-recording <n>] [--root <dir>] [--json]` | stage 2, deterministic: every held recording in scope dated inside an era, its words read through the caption-track rule (en-orig before en, a transcript above captions, rolling repeats folded), each era's term families matched, ±--window (30) s windows merged up to --max-span (240), title hits, and the noise filters (a coverage window must name a subject; a strict era's own-channel windows need a strict family); writes candidates.jsonl and the counts per family, year, channel and group before any read | +| `archilyzer case batches` | `<case> [--budget <chars>] [--root <dir>] [--json]` | stage 3: the candidate windows into batches per reader group under --budget (60000) characters, written as WRAPPED text (no line over 200 characters) in batches/&lt;id&gt;.txt, each pending for a reader; a batch already reading or read is kept and its windows are never batched again, and the new batches are the next round | +| `archilyzer case batch` | `<case> <batch> [--root <dir>]` | print one batch's wrapped text, for a reader (a Claude Code session) to read | +| `archilyzer case findings` | `<case> --file <rows.jsonl> [--root <dir>] [--json]` | append finding rows (one JSON object per line: batch, slug, id, date, title, t, url, category, relevance 1–3, quote — verbatim, at most 45 words —, summary, speaker, confidence, round, by), each checked, each given the next row id; the whole write is refused when a row does not check or the privacy gate finds a private name (it names the rows, never the name) | +| `archilyzer case summary` | `<case> --file <summary.md> [--by hand\|api\|local\|code] [--model <m>] [--root <dir>] [--json]` | the report's summary, through the privacy gate; written by a model (--by other than hand) it is a draft, and the report says so until a person saves it | +| `archilyzer case merge` | `<case> [--min-relevance <n>] [--root <dir>] [--json]` | stage 5's preview: the findings deduped (the same recording within 20 s is one finding: the higher relevance, then the later round), sections by reader group at relevance --min-relevance (2) and up, the quarantined in their own; writes nothing | +| `archilyzer case export` | `<case> [--min-relevance <n>] [--root <dir>] [--json]` | stage 5: REPORT.md (cited markdown in the house format: it converts as a /sweep report) and REPORT.html from the merge and the summary, behind the privacy gate (a hit writes nothing and names the rows) | +| `archilyzer case date-checks` | `<case> [--around <days>] [--latest <n>] [--root <dir>] [--json]` | stage 9: the subject's own uploads within --around (14) days of each key date and the --latest (10) after it, captioned or not, and the sentence ("no response found in captioned uploads through &lt;date&gt;", or the findings that are one); writes date-checks.json | | `archilyzer storage migrate-tier` | `<slug>…\|--all [--order smallest] [--include-large] [--dry-run] [--reclaim]` | bring a channel off the retired whole-directory layout onto the media tier, its text home to the corpus disk (editor stopped; --all stops before the three big-text channels) *(passthrough)* | | `archilyzer brand media` | `[--out <dir>] [--video-kit]` | render the Archilyzer Media channel's assets *(passthrough)* | | `archilyzer mcp` | `[--local <dir>\|--remote <url>\|--hub <url>]` | start the MCP server on stdio (as `pnpm --filter yt-dlp-transcript-mcp exec tsx src/index.ts`) *(passthrough)* | diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts @@ -918,6 +918,97 @@ export const COMMANDS: Command[] = [ }, run: async ({ flags }) => (await import("./corpus-grep")).main(flags), }, + { + path: ["case", "show"], + usage: "<case> [--root <dir>] [--json] a research case's pipeline (release 38): what is defined (subjects, eras, reader groups, how many private names — hashed, never shown), each stage's file and its last run, from the page or here", + flags: { root: "string", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./case")).main("show", positionals, flags), + }, + { + path: ["case", "define"], + usage: "<case> --file <pipeline.json> [--root <dir>] [--json] write the case's definition beside its umtool board (`<root>/.umtool/research/<case>/pipeline.json`): subjects (with their own channels), scope (channels, `<site>:<group>` groups, sites), eras with term families (regex, flags iu) and strict families, reader groups (a list of slugs, \"subject\" or \"coverage\"; an era), reader prompts, key dates; checked whole, every bad field named; a reader prompt naming a private person is blocked by the privacy gate; the private names already stored are kept, and a file carrying `privateNames.terms` is refused", + flags: { root: "string", file: "string", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./case")).main("define", positionals, flags), + }, + { + path: ["case", "private-names"], + usage: "<case> add|remove|clear|count [--root <dir>] [--json] the case's private names, read from STDIN one per line (never an argument: the shell's history), each stored as the sha256 of its normalized words and nothing else; at most three words a name (the gate checks words and 2- and 3-word phrases); prints counts only", + flags: { root: "string", json: "boolean" }, + maxPositionals: 2, + run: async ({ positionals, flags }) => (await import("./case")).main("private-names", positionals, flags), + }, + { + path: ["case", "prompt"], + usage: "<case> [<group>|common] [--root <dir>] print the reader prompt a group gets: the case's common prompt, the group's own, the subjects, and the naming rule (`[name withheld]`), which is always there", + flags: { root: "string" }, + maxPositionals: 2, + run: async ({ positionals, flags }) => (await import("./case")).main("prompt", positionals, flags), + }, + { + path: ["case", "coverage"], + usage: "<case> [--root <dir>] [--json] stage 1: per channel × year in the case's scope, listed, held, transcribed and untranscribed audio, off the live corpus (read only; TRANSCRIPTS_DIR picks it), the key years (an era touches them) starred, a channel that cannot be read skipped with its reason; writes coverage.json", + flags: { root: "string", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./case")).main("coverage", positionals, flags), + }, + { + path: ["case", "candidates"], + usage: "<case> [--window <s>] [--max-span <s>] [--per-recording <n>] [--root <dir>] [--json] stage 2, deterministic: every held recording in scope dated inside an era, its words read through the caption-track rule (en-orig before en, a transcript above captions, rolling repeats folded), each era's term families matched, ±--window (30) s windows merged up to --max-span (240), title hits, and the noise filters (a coverage window must name a subject; a strict era's own-channel windows need a strict family); writes candidates.jsonl and the counts per family, year, channel and group before any read", + flags: { root: "string", window: "string", "max-span": "string", "per-recording": "string", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./case")).main("candidates", positionals, flags), + }, + { + path: ["case", "batches"], + usage: "<case> [--budget <chars>] [--root <dir>] [--json] stage 3: the candidate windows into batches per reader group under --budget (60000) characters, written as WRAPPED text (no line over 200 characters) in batches/<id>.txt, each pending for a reader; a batch already reading or read is kept and its windows are never batched again, and the new batches are the next round", + flags: { root: "string", budget: "string", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./case")).main("batches", positionals, flags), + }, + { + path: ["case", "batch"], + usage: "<case> <batch> [--root <dir>] print one batch's wrapped text, for a reader (a Claude Code session) to read", + flags: { root: "string" }, + maxPositionals: 2, + run: async ({ positionals, flags }) => (await import("./case")).main("batch", positionals, flags), + }, + { + path: ["case", "findings"], + usage: "<case> --file <rows.jsonl> [--root <dir>] [--json] append finding rows (one JSON object per line: batch, slug, id, date, title, t, url, category, relevance 1–3, quote — verbatim, at most 45 words —, summary, speaker, confidence, round, by), each checked, each given the next row id; the whole write is refused when a row does not check or the privacy gate finds a private name (it names the rows, never the name)", + flags: { root: "string", file: "string", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./case")).main("findings", positionals, flags), + }, + { + path: ["case", "summary"], + usage: "<case> --file <summary.md> [--by hand|api|local|code] [--model <m>] [--root <dir>] [--json] the report's summary, through the privacy gate; written by a model (--by other than hand) it is a draft, and the report says so until a person saves it", + flags: { root: "string", file: "string", by: "string", model: "string", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./case")).main("summary", positionals, flags), + }, + { + path: ["case", "merge"], + usage: "<case> [--min-relevance <n>] [--root <dir>] [--json] stage 5's preview: the findings deduped (the same recording within 20 s is one finding: the higher relevance, then the later round), sections by reader group at relevance --min-relevance (2) and up, the quarantined in their own; writes nothing", + flags: { root: "string", "min-relevance": "string", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./case")).main("merge", positionals, flags), + }, + { + path: ["case", "export"], + usage: "<case> [--min-relevance <n>] [--root <dir>] [--json] stage 5: REPORT.md (cited markdown in the house format: it converts as a /sweep report) and REPORT.html from the merge and the summary, behind the privacy gate (a hit writes nothing and names the rows)", + flags: { root: "string", "min-relevance": "string", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./case")).main("export", positionals, flags), + }, + { + path: ["case", "date-checks"], + usage: "<case> [--around <days>] [--latest <n>] [--root <dir>] [--json] stage 9: the subject's own uploads within --around (14) days of each key date and the --latest (10) after it, captioned or not, and the sentence (\"no response found in captioned uploads through <date>\", or the findings that are one); writes date-checks.json", + flags: { root: "string", around: "string", latest: "string", json: "boolean" }, + maxPositionals: 1, + run: async ({ positionals, flags }) => (await import("./case")).main("date-checks", positionals, flags), + }, script(["storage", "migrate-tier"], "migrate-media-tier.ts", "<slug>…|--all [--order smallest] [--include-large] [--dry-run] [--reclaim] bring a channel off the retired whole-directory layout onto the media tier, its text home to the corpus disk (editor stopped; --all stops before the three big-text channels)"), { diff --git a/common/bin/case.test.ts b/common/bin/case.test.ts @@ -0,0 +1,114 @@ +// `archilyzer case …` (bin/case.ts) end to end over a temp reports root and a temp corpus: define, coverage, +// candidates, batches (no line over 200), hand-written findings, the gate blocking a planted private name at the +// export (counts and row ids, never the name), and the export once the row is fixed. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test bin/case.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { privateNameHash } from "../lib/research/privateNames-server"; +import { mutateDefinition } from "../lib/research/caseStore-server"; +import { emptyDefinition, longestLine } from "../lib/research/casePipeline"; +import { main } from "./case"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "case-cli-")); +test.after(() => rm(ROOT, { recursive: true, force: true })); +const reports = path.join(ROOT, "reports"); +const caseDir = path.join(reports, ".umtool", "research", "wren"); +const paths = { transcriptsDir: ROOT, channelsDir: path.join(ROOT, "channels"), sitesDir: path.join(ROOT, "sites"), lmdbPath: path.join(ROOT, "none.mdb") } as Paths; +const PLANTED = "Ottoline Brackenridge"; + +const vtt = (cues: [number, string][]) => + "WEBVTT\n\n" + cues.map(([a, t]) => `00:${String(Math.floor(a / 60)).padStart(2, "0")}:${String(a % 60).padStart(2, "0")}.000 --> 00:${String(Math.floor((a + 3) / 60)).padStart(2, "0")}:${String((a + 3) % 60).padStart(2, "0")}.000\n${t}\n`).join("\n"); + +await mkdir(caseDir, { recursive: true }); +await writeFile(path.join(caseDir, "case.json"), JSON.stringify({ format: "umtool-research-case", version: 1, id: "wren", title: "Wren and the shop" })); +for (const [slug, id, date, line] of [ + ["wren-own", "o1", "20150310", "welcome to the lantern shop"], + ["talk-show", "t1", "20150320", "Wren Halloway at the lantern shop"], +] as const) { + const dir = path.join(paths.channelsDir, slug, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(paths.channelsDir, slug, "config.json"), JSON.stringify({ handling: "youtube", name: slug })); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: `${slug} ${id}`, upload_date: date, duration: 600, webpage_url: `https://www.youtube.com/watch?v=${id}` })); + await writeFile(path.join(dir, "transcript.en-orig.vtt"), vtt([[30, line]])); +} + +const flags = { root: reports }; +const quiet = async <T>(fn: () => Promise<T>): Promise<{ value: T; out: string; err: string }> => { + const log = console.log; + const error = console.error; + let out = ""; + let err = ""; + console.log = (...a: unknown[]) => void (out += `${a.join(" ")}\n`); + console.error = (...a: unknown[]) => void (err += `${a.join(" ")}\n`); + try { + return { value: await fn(), out, err }; + } finally { + console.log = log; + console.error = error; + } +}; + +test("a case through the CLI: define → coverage → candidates → batches → findings → the gate → export", async () => { + const defFile = path.join(ROOT, "pipeline.json"); + await writeFile( + defFile, + JSON.stringify({ + subjects: [{ name: "Wren Halloway", aliases: ["Wren"], channels: ["wren-own"] }], + scope: { channels: ["talk-show"], groups: [], sites: [] }, + eras: [{ id: "early", from: "2015-01-01", to: "2016-12-31", families: { shop: "lantern shop" } }], + groups: [{ id: "own", label: "Her own", channels: "subject" }, { id: "others", label: "Coverage", channels: "coverage" }], + }), + ); + assert.equal((await quiet(() => main("define", ["wren"], { ...flags, file: defFile }))).value, 0); + await writeFile(path.join(ROOT, "bad.json"), JSON.stringify({ privateNames: { terms: ["x"] } })); + const refused = await quiet(() => main("define", ["wren"], { ...flags, file: path.join(ROOT, "bad.json") })); + assert.equal(refused.value, 2); + assert.match(refused.err, /privateNames\.terms is never stored/); + assert.equal((await quiet(() => main("show", ["nosuch"], flags))).value, 1); + + const cov = await quiet(() => main("coverage", ["wren"], { ...flags, json: true }, { paths })); + assert.equal(cov.value, 0); + assert.equal(JSON.parse(cov.out).rows.length, 2); + const cand = await quiet(() => main("candidates", ["wren"], { ...flags, json: true }, { paths })); + assert.equal(JSON.parse(cand.out).windows, 2); + const bat = await quiet(() => main("batches", ["wren"], { ...flags, json: true })); + const batches = JSON.parse(bat.out) as { id: string; file: string; state: string }[]; + assert.deepEqual(batches.map((b) => [b.id, b.state]), [["own-1-001", "pending"], ["others-1-001", "pending"]]); + for (const b of batches) assert.ok(longestLine(await readFile(path.join(caseDir, b.file), "utf8")) <= 200); + + // The private name lands in the case's definition AFTER a row naming that person was written by hand. + const rows = path.join(ROOT, "rows.jsonl"); + const r = (o: Record<string, unknown>) => JSON.stringify({ batch: "own-1-001", slug: "wren-own", id: "o1", date: "20150310", title: "wren-own o1", t: 30, url: "https://www.youtube.com/watch?v=o1", category: "shop", relevance: 3, quote: "welcome to the lantern shop", summary: "She opens the shop", speaker: "Wren Halloway", confidence: "high", round: 1, by: "hand", ...o }); + await writeFile(rows, `${r({})}\n${r({ batch: "others-1-001", slug: "talk-show", id: "t1", date: "20150320", title: "talk-show t1", summary: `Her friend ${PLANTED} was there`, quote: "Wren Halloway at the lantern shop", speaker: "host" })}\n`); + assert.equal((await quiet(() => main("findings", ["wren"], { ...flags, file: rows }))).value, 0); + await mutateDefinition(caseDir, "wren", (d) => void (d.privateNames.sha256 = [privateNameHash(PLANTED)]), () => emptyDefinition("wren")); + + const blocked = await quiet(() => main("export", ["wren"], flags, { paths })); + assert.equal(blocked.value, 1); + assert.match(blocked.err, /the privacy gate blocked the export: \d+ private-name hits? in 1 item \(REPORT\.md\)/); + assert.doesNotMatch(blocked.err + blocked.out, /Ottoline|Brackenridge/i); + assert.ok(!(await readdir(caseDir)).includes("REPORT.md")); + const stages = JSON.parse(await readFile(path.join(caseDir, "stages.json"), "utf8")); + assert.equal(stages.export.state, "failed"); + assert.doesNotMatch(JSON.stringify(stages), /Ottoline|Brackenridge/i); + + // A new row withheld; and adding the same row again is refused by the gate at the write, naming the row. + const again = await quiet(() => main("findings", ["wren"], { ...flags, file: rows })); + assert.equal(again.value, 1); + assert.match(again.err, /blocked these findings: .*\(f4\)/); + const fixed = (await readFile(path.join(caseDir, "findings.jsonl"), "utf8")).replace(PLANTED, "[name withheld]"); + await writeFile(path.join(caseDir, "findings.jsonl"), fixed); + const ok = await quiet(() => main("export", ["wren"], flags, { paths })); + assert.equal(ok.value, 0, ok.err); + const md = await readFile(path.join(caseDir, "REPORT.md"), "utf8"); + assert.match(md, /^# Wren and the shop/); + assert.match(md, /## Her own\n\n- She opens the shop: "welcome to the lantern shop"/); + assert.match(md, /## Coverage\n\nScope: 2 channels \(talk-show, wren-own\)/); + assert.match(await readFile(path.join(caseDir, "REPORT.html"), "utf8"), /<h2>Coverage<\/h2>/); +}); diff --git a/common/bin/case.ts b/common/bin/case.ts @@ -0,0 +1,257 @@ +// `archilyzer case <verb> <case> …` -- a research case's pipeline from a shell or a Claude Code session +// (plans/release-38/research-cases-and-assist.md, lane A). The stages are controller/casePipelineRun.ts, the same +// functions umtool's case page runs; each records its run in the case's stages.json, so the page shows a run made +// here and the other way round. +// +// The case is umtool's board, `<reports root>/.umtool/research/<case>/case.json` (created on umtool's /research); +// the pipeline's files sit beside it. The reports root is --root, else REPORTS_DIR, else the parent of +// SONG_REPORTS_DIR, else ~/reports -- umtool's own rule (umtool/lib/paths.mjs). The corpus is read, never written: +// TRANSCRIPTS_DIR picks it, as for `archilyzer corpus grep`. +// +// PRIVATE NAMES ARE NEVER ARGUMENTS. `case private-names <case> add` reads the terms from stdin, one per line, +// hashes each and stores only the hash; nothing it prints names one. An argument would sit in the shell's history +// and the process list. + +import { readFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { getPaths, type Paths } from "../lib/paths"; +import type { FlagValue } from "./_parseFlags"; +import { CASE_FILES, isFindingBy, type FindingBy } from "../lib/research/caseTypes"; +import { privateNameHash } from "../lib/research/privateNames-server"; +import { CasePipelineError, emptyDefinition, longestLine, privateTermProblem, readerPrompt } from "../lib/research/casePipeline"; +import { + appendFindings, + mutateDefinition, + readBatchText, + readBatches, + readCandidateCounts, + readCoverage, + readDefinition, + readFindings, + readStages, + readSummary, + saveDefinition, + writeSummary, +} from "../lib/research/caseStore-server"; +import { mergeView, runBatches, runCandidates, runCoverage, runDateChecks, runExport } from "../controller/casePipelineRun"; + +const str = (v: FlagValue | undefined) => (typeof v === "string" ? v : undefined); +const int = (v: FlagValue | undefined, name: string): number | undefined => { + if (v === undefined) return undefined; + const n = Number(v); + if (!Number.isFinite(n) || n < 0) throw new CasePipelineError(`--${name} is a number`); + return n; +}; + +export function reportsRoot(flags: Record<string, FlagValue>, env: NodeJS.ProcessEnv = process.env): string { + const r = str(flags.root) ?? env.REPORTS_DIR ?? (env.SONG_REPORTS_DIR ? path.dirname(path.resolve(env.SONG_REPORTS_DIR)) : path.join(os.homedir(), "reports")); + return path.resolve(r); +} + +/** The case's directory, refused unless umtool made the case (its case.json is there). */ +export async function caseDirOf(root: string, id: string | undefined): Promise<{ dir: string; id: string; title: string }> { + if (!id || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(id)) throw new CasePipelineError(`a case id (lowercase letters, digits and dashes), not ${JSON.stringify(id ?? "")}`); + const dir = path.join(root, ".umtool", "research", id); + let title = id; + try { + const c = JSON.parse(await readFile(path.join(dir, "case.json"), "utf8")) as { title?: unknown }; + if (typeof c.title === "string" && c.title) title = c.title; + } catch (e) { + if ((e as NodeJS.ErrnoException).code === "ENOENT") throw new CasePipelineError(`no case "${id}" under ${root} (make it on umtool's /research first: the pipeline sits beside its board)`, 404); + throw new CasePipelineError(`${id}/case.json cannot be read: ${(e as Error).message}`, 409); + } + return { dir, id, title }; +} + +async function readStdin(): Promise<string> { + if (process.stdin.isTTY) process.stderr.write("one per line, then Ctrl-D:\n"); + const chunks: Buffer[] = []; + for await (const c of process.stdin) chunks.push(c as Buffer); + return Buffer.concat(chunks).toString("utf8"); +} + +const out = (json: boolean, value: unknown, text: () => string) => { + console.log(json ? JSON.stringify(value, null, 2) : text()); + return 0; +}; + +export type CaseVerb = + | "show" + | "define" + | "private-names" + | "prompt" + | "coverage" + | "candidates" + | "batches" + | "batch" + | "findings" + | "summary" + | "merge" + | "export" + | "date-checks"; + +export async function main(verb: CaseVerb, positionals: string[], flags: Record<string, FlagValue>, deps: { paths?: Paths } = {}): Promise<number> { + try { + const c = await caseDirOf(reportsRoot(flags), positionals[0]); + const json = flags.json === true; + const corpus = () => deps.paths ?? getPaths(); + switch (verb) { + case "show": { + const def = await readDefinition(c.dir, c.id); + const [stages, counts, batches, findings, summary, coverage] = await Promise.all([readStages(c.dir), readCandidateCounts(c.dir), readBatches(c.dir), readFindings(c.dir), readSummary(c.dir), readCoverage(c.dir)]); + const view = { + case: c.id, + dir: c.dir, + defined: !!def, + status: def?.status ?? null, + subjects: def?.subjects.map((s) => s.name) ?? [], + eras: def?.eras.map((e) => e.id) ?? [], + groups: def?.groups.map((g) => g.id) ?? [], + privateNames: def?.privateNames.sha256.length ?? 0, + coverage: coverage.length, + candidates: counts?.windows ?? null, + batches: { total: batches.length, pending: batches.filter((b) => b.state === "pending").length, read: batches.filter((b) => b.state === "read").length }, + findings: { rows: findings.rows.length, invalid: findings.invalid.length }, + summary: summary ? { draft: summary.draft, by: summary.by } : null, + stages, + }; + 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)", + `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"), + ); + } + case "define": { + const file = str(flags.file); + if (!file) throw new CasePipelineError("--file <pipeline.json> is required"); + const raw = JSON.parse(await readFile(file, "utf8")) as Record<string, unknown>; + const pn = raw.privateNames as Record<string, unknown> | undefined; + 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`); + } + 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)`); + } + const terms = op === "clear" ? [] : (await readStdin()).split("\n").map((t) => t.trim()).filter(Boolean); + for (const [i, t] of terms.entries()) { + const p = privateTermProblem(t); + if (p) throw new CasePipelineError(`line ${i + 1}: ${p}`); + } + const hashes = terms.map(privateNameHash); + let changed = 0; + const def = await mutateDefinition( + c.dir, + c.id, + (d) => { + const before = d.privateNames.sha256.length; + if (op === "clear") d.privateNames.sha256 = []; + else if (op === "add") d.privateNames.sha256 = [...new Set([...d.privateNames.sha256, ...hashes])]; + else d.privateNames.sha256 = d.privateNames.sha256.filter((h) => !hashes.includes(h)); + changed = Math.abs(d.privateNames.sha256.length - before); + }, + () => emptyDefinition(c.id), + ); + return out(json, { changed, count: def.privateNames.sha256.length }, () => `${op === "add" ? "added" : "removed"} ${changed}; ${def.privateNames.sha256.length} private names (hashed)`); + } + case "prompt": { + const def = await readDefinition(c.dir, c.id); + if (!def) throw new CasePipelineError(`case ${c.id} has no pipeline yet`, 409); + const group = positionals[1] ?? "common"; + if (group !== "common" && !def.groups.some((g) => g.id === group)) throw new CasePipelineError(`no group "${group}" (${def.groups.map((g) => g.id).join(", ")})`); + console.log(readerPrompt(def, group)); + return 0; + } + case "coverage": { + const r = await runCoverage(c.dir, c.id, corpus(), "cli"); + return out(json, r, () => + [ + "channel\tyear\tlisted\theld\ttranscribed\tuntranscribed audio", + ...r.rows.map((x) => `${x.channel}\t${x.year || "undated"}${x.key ? "*" : ""}\t${x.listed}\t${x.held}\t${x.transcribed}\t${x.untranscribedAudio}`), + ...r.skipped.map((s) => `skipped ${s.slug}: ${s.reason}`), + "(* a key year: an era touches it)", + ].join("\n"), + ); + } + case "candidates": { + const r = await runCandidates(c.dir, c.id, corpus(), "cli", { W: int(flags.window, "window"), maxSpan: int(flags["max-span"], "max-span"), maxPerRecording: int(flags["per-recording"], "per-recording") }); + const k = r.counts; + return out(json, k, () => + [ + `${k.windows} windows in ${k.videos} recordings (${k.titleHits} title hits) → ${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"}`, + `by group: ${Object.entries(k.byGroup).map(([g, n]) => `${g} ${n}`).join(", ") || "none"}`, + `noise: ${Object.entries(k.noise).map(([f, n]) => `${f} ${n}`).join(", ")}`, + `scanned: ${k.scanned.channels} channels, ${k.scanned.videos} recordings, ${k.scanned.inEra} in an era, ${k.scanned.withText} with words, ${k.scanned.noText} with none yet, ${k.scanned.undated} undated`, + ...k.skipped.map((s) => `skipped ${s.slug}: ${s.reason}`), + ].join("\n"), + ); + } + 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")); + } + case "batch": { + const t = await readBatchText(c.dir, positionals[1] ?? ""); + process.stdout.write(t); + if (longestLine(t) > 200) process.stderr.write("warning: this batch has a line over 200 characters (it was written by something else)\n"); + return 0; + } + case "findings": { + const file = str(flags.file); + if (!file) throw new CasePipelineError("--file <rows.jsonl> is required (one finding row per line)"); + const def = await readDefinition(c.dir, c.id); + const rows = (await readFile(file, "utf8")).split("\n").filter((l) => l.trim()).map((l, i) => { + try { + return JSON.parse(l) as unknown; + } catch { + throw new CasePipelineError(`line ${i + 1} of ${file} is not JSON`); + } + }); + const written = await appendFindings(c.dir, rows, def?.privateNames.sha256 ?? []); + return out(json, written, () => `${written.length} ${written.length === 1 ? "row" : "rows"} appended: ${written.map((r) => r.row).join(", ")}`); + } + case "summary": { + const file = str(flags.file); + if (!file) throw new CasePipelineError("--file <summary.md> is required"); + const by = str(flags.by) ?? "hand"; + if (!isFindingBy(by)) throw new CasePipelineError("--by is hand, api, local or code"); + const def = await readDefinition(c.dir, c.id); + const s = await writeSummary(c.dir, { text: await readFile(file, "utf8"), draft: by !== "hand", by: by as FindingBy, ...(str(flags.model) ? { model: str(flags.model) } : {}) }, def?.privateNames.sha256 ?? []); + return out(json, s, () => `summary saved${s.draft ? " (a draft: it says so in the report until a person saves it)" : ""}`); + } + case "merge": { + const m = await mergeView(c.dir, c.id, { minRelevance: int(flags["min-relevance"], "min-relevance") }); + return out(json, m, () => + [ + ...m.sections.map((s) => `${s.label} (${s.group}): ${s.rows.length} — ${s.rows.map((r) => r.row).join(", ")}`), + `quarantined: ${m.quarantined.length}; below relevance ${m.minRelevance}: ${m.belowFloor.length}; duplicates folded: ${m.duplicates.length}; rows: ${m.total}`, + ...m.invalid.map((x) => `line ${x.line} does not check: ${x.errors.join("; ")}`), + ].join("\n"), + ); + } + case "export": { + const r = await runExport(c.dir, c.id, c.title, "cli", { minRelevance: int(flags["min-relevance"], "min-relevance"), paths: corpus() }); + return out(json, { report: path.join(c.dir, CASE_FILES.report) }, () => `${path.join(c.dir, CASE_FILES.report)} and ${CASE_FILES.reportHtml}: ${r.merged.sections.reduce((n, s) => n + s.rows.length, 0)} findings`); + } + 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")); + } + } + } catch (e) { + console.error(`case ${verb}: ${(e as Error).message}`); + return e instanceof CasePipelineError && e.status === 400 ? 2 : 1; + } +} diff --git a/common/controller/caseCorpus.test.ts b/common/controller/caseCorpus.test.ts @@ -0,0 +1,132 @@ +// A research case over a corpus on disk (controller/caseCorpus.ts): the scope resolved through a site's pool and +// a site group, coverage per channel × year (listed, held, transcribed, untranscribed audio; the undated row; key +// years), candidates over the en-orig track with the noise filters and counts, and the subject's uploads. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/caseCorpus.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { normalizeDefinition } from "../lib/research/casePipeline"; +import { caseCandidates, caseChannels, caseCoverage, subjectUploads } from "./caseCorpus"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "case-corpus-")); +const paths = { + transcriptsDir: ROOT, + channelsDir: path.join(ROOT, "channels"), + sitesDir: path.join(ROOT, "sites"), + lmdbPath: path.join(ROOT, "index.mdb"), +} as Paths; +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const ts = (s: number) => `00:${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}.000`; +const vtt = (cues: [number, string][]) => "WEBVTT\n\n" + cues.map(([a, t]) => `${ts(a)} --> ${ts(a + 3)}\n${t}\n`).join("\n"); + +async function channel(slug: string, playlist: string[] = [], config: Record<string, unknown> = {}) { + const dir = path.join(paths.channelsDir, slug); + await mkdir(path.join(dir, "data"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "youtube", name: slug, ...config })); + if (playlist.length) await writeFile(path.join(dir, "playlist"), playlist.map((id) => `https://www.youtube.com/watch?v=${id}`).join("\n") + "\n"); +} +async function video(slug: string, id: string, date: string, title: string, files: Record<string, string> = {}) { + const dir = path.join(paths.channelsDir, slug, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title, upload_date: date, duration: 900, webpage_url: `https://www.youtube.com/watch?v=${id}` })); + for (const [n, b] of Object.entries(files)) await writeFile(path.join(dir, n), b); +} + +// Wren's own channel: two transcribed (en-orig beside a rewriting en), one with audio only, one listed and scanned, +// one listed and never fetched. +await channel("wren-own", ["o1", "o2", "o3", "o4", "o5"]); +await video("wren-own", "o1", "20150310", "Opening day", { + "transcript.en-orig.vtt": vtt([[10, "welcome to the lantern shop"], [40, "it is my shop"], [400, "goodbye"]]), + "transcript.en.vtt": vtt([[10, "welcome to the candle store"]]), +}); +await video("wren-own", "o2", "20210305", "Closing the shop", { "transcript.en-orig.vtt": vtt([[20, "the lantern shop is closing"], [90, "wren here"]]) }); +await video("wren-own", "o3", "20150601", "Audio only", { "audio.opus": "x".repeat(10) }); +await writeFile(path.join(paths.channelsDir, "wren-own", "metadata-scan.json"), JSON.stringify({ version: 1, updatedAt: "", lastRun: null, entries: { o4: { title: "Scanned", description: "", uploadDate: "20160101", scannedAt: "x" } }, errors: {} })); +// A talk show (coverage) on a site, in a site group; a posts channel; a channel that is not there. +await channel("talk-show"); +await video("talk-show", "t1", "20150320", "Talk", { "transcript.en.vtt": vtt([[100, "the lantern shop opened"], [300, "Wren Halloway came by the lantern shop"]]) }); +await channel("x-posts", [], { sourceKind: "social", platform: "twitter" }); +await mkdir(path.join(paths.sitesDir, "wrensite"), { recursive: true }); +await writeFile( + path.join(paths.sitesDir, "wrensite", "site.json"), + JSON.stringify({ groups: [{ id: "default" }, { id: "talk" }], defaultGroupId: "default", channels: [{ slug: "talk-show", groupId: "talk" }, { slug: "x-posts" }] }), +); + +const def = normalizeDefinition( + { + subjects: [{ name: "Wren Halloway", aliases: ["Wren"], channels: ["wren-own"] }], + scope: { channels: ["missing-one"], groups: ["wrensite:talk"], sites: ["wrensite"] }, + eras: [ + { id: "early", from: "2015-01-01", to: "2016-12-31", families: { shop: "lantern shop" } }, + { id: "late", from: "2021-01-01", to: "2021-12-31", families: { shop: "lantern shop", name: "\\bwren\\b" }, strictFamilies: ["shop"] }, + ], + groups: [ + { id: "own", label: "Her own", channels: "subject" }, + { id: "others", label: "Coverage", channels: "coverage" }, + ], + keyDates: [{ date: "2021-03-01", label: "the shop closes" }], + }, + "wren", +); + +test("caseChannels: the scope's channels, a site's pool, a site group's members, the subject's own", async () => { + const r = await caseChannels(paths, def); + assert.deepEqual(r.slugs, ["missing-one", "talk-show", "wren-own", "x-posts"]); + assert.deepEqual(r.problems, []); + const bad = await caseChannels(paths, normalizeDefinition({ scope: { sites: ["nosuch"], groups: ["wrensite:nogroup"] } }, "wren")); + assert.deepEqual(bad.problems, ["site nosuch: no site.json", "group wrensite:nogroup: no channel of wrensite is in it"]); +}); + +test("caseCoverage: per channel × year, listed ⊇ held ⊇ transcribed; audio without a transcript; undated; key years", async () => { + const r = await caseCoverage(paths, def); + const own = r.rows.filter((x) => x.channel === "wren-own"); + const y = (n: number) => own.find((x) => x.year === n); + assert.deepEqual(y(2015), { channel: "wren-own", year: 2015, listed: 2, held: 2, transcribed: 1, untranscribedAudio: 1, key: true }); + assert.deepEqual(y(2016), { channel: "wren-own", year: 2016, listed: 1, held: 0, transcribed: 0, untranscribedAudio: 0, key: true }); + assert.deepEqual(y(2021), { channel: "wren-own", year: 2021, listed: 1, held: 1, transcribed: 1, untranscribedAudio: 0, key: true }); + assert.deepEqual(y(0), { channel: "wren-own", year: 0, listed: 1, held: 0, transcribed: 0, untranscribedAudio: 0 }); + assert.deepEqual(r.skipped, [ + { slug: "missing-one", reason: "not in the corpus" }, + { slug: "x-posts", reason: "a social channel: posts, not recordings" }, + ]); +}); + +test("caseCandidates: en-orig read, families per era, the noise filters, deterministic keys, counts before any read", async () => { + const notes: string[] = []; + const a = await caseCandidates(paths, def, { onNote: (l) => notes.push(l) }); + assert.deepEqual(a.windows.map((w) => [w.key, w.group, w.track, w.era]), [ + ["wren-own/o1@0", "own", "en-orig", "early"], + ["wren-own/o2@0", "own", "en-orig", "late"], + ["talk-show/t1@270", "others", "en", "early"], + ]); + // The rewriting `en` track is not what was read. + assert.match(a.windows[0].text, /lantern shop/); + assert.doesNotMatch(a.windows[0].text, /candle/); + assert.equal(a.windows[0].url, "https://www.youtube.com/watch?v=o1"); + // talk-show at 100 s names no subject: noise. o2's "wren" in the strict late era makes no window of its own. + assert.equal(a.counts.noise.noSubject, 1); + assert.equal(a.counts.windows, 3); + assert.deepEqual(a.counts.byGroup, { own: 2, others: 1 }); + assert.equal(a.counts.byFamily.shop, 3); + assert.deepEqual(a.counts.scanned, { channels: 2, videos: 4, inEra: 4, withText: 3, noText: 1, undated: 0 }); + assert.deepEqual(a.counts.skipped.map((s) => s.slug), ["missing-one", "x-posts"]); + assert.ok(notes.some((n) => /^wren-own: 3 held, 2 windows$/.test(n))); + const b = await caseCandidates(paths, def); + assert.deepEqual(b.windows, a.windows, "the same corpus and definition give the same windows"); +}); + +test("subjectUploads: held and listed-only uploads, captioned or not", async () => { + const r = await subjectUploads(paths, def); + assert.deepEqual(r.uploads.map((u) => [u.id, u.date, u.captioned]), [ + ["o1", "20150310", true], + ["o3", "20150601", false], + ["o4", "20160101", false], + ["o2", "20210305", true], + ]); +}); diff --git a/common/controller/caseCorpus.ts b/common/controller/caseCorpus.ts @@ -0,0 +1,308 @@ +// A RESEARCH CASE OVER THE LIVE CORPUS (plans/release-38/research-cases-and-assist.md, lane A, stages 1, 2 and 9): +// what the case's scope holds per channel × year, the candidate windows its term families find, and the subject's +// uploads for the date checks. READ-ONLY on the corpus; the caller writes the case's own files +// (lib/research/caseStore-server.ts). +// +// Why the live corpus and not a published build: a case reads private channels and channels no site carries (the +// Oneylyzer case did), and recordings downloaded since the last publish. So it reads `channels/<slug>/` through the +// readers that already exist, never a walk of its own: +// - which recordings are held: heldVideoIds (videoCues.ts); +// - their dates: the LMDB index's `byChannel` key scan (recencyIndex.ts openUploadDateIndex: the transcribed +// videos, for one cheap scan), then a head/tail read of metadata.info.json for the rest (channelCoverage.ts +// readDateAndTitle) -- and for a listed video never fetched, the channel's metadata scan; +// - their words: readCuesInVideoDir (videoCues.ts) -- a fresh transcript.cues.json, else what normalize would +// write: the caption-track rule (en-orig before en, a local transcription above captions), rolling captions +// folded by parseVtt; +// - transcribed or not, audio or not: readVideoFiles (videoStatus.ts). +// A channel whose text cannot be read (a drive not answering, a move in flight) is SKIPPED WITH ITS REASON, never +// read as "nothing held" (assertChannelTextReadable); a social channel holds posts, not recordings. + +import path from "node:path"; +import { readFile } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import { isSocialChannel } from "../lib/channelConfig"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import { mapConcurrent } from "../lib/concurrency"; +import { extractVideoId } from "../lib/videoId"; +import { isVideoTranscribed, readVideoFiles } from "../lib/videoStatus"; +import type { CandidateCounts, CandidateWindow, CaseDefinition, CoverageRow } from "../lib/research/caseTypes"; +import { + day8, + emptyCounts, + erasOn, + keyYears, + recordingWindows, + sortWindows, + subjectChannels, + trackOfFile, + type DatedUpload, + type ScanOptions, +} from "../lib/research/casePipeline"; +import { readChannelConfig } from "./channels"; +import { readDateAndTitle } from "./channelCoverage"; +import { loadMetadataScan } from "./metadataScanStore"; +import { openUploadDateIndex } from "./recencyIndex"; +import { heldVideoIds, readCuesInVideoDir } from "./videoCues"; + +export type CaseChannels = { slugs: string[]; problems: string[] }; + +type SiteJson = { channels?: { slug?: unknown; groupId?: unknown }[]; defaultGroupId?: unknown; groups?: { id?: unknown }[] }; + +async function readSite(paths: Paths, id: string): Promise<SiteJson | null> { + if (!/^[a-z0-9][a-z0-9_-]*$/i.test(id)) return null; + try { + return JSON.parse(await readFile(path.join(paths.sitesDir, id, "site.json"), "utf8")) as SiteJson; + } catch { + return null; + } +} + +/** + * The channels a case reads: its scope's channels, every channel of its scope's sites (a site.json's pool), every + * channel of its `<site>:<group>` groups, its reader groups' named channels, and the subjects' own. A site or a + * group that cannot be read is a problem, said; never an empty scope. + */ +export async function caseChannels(paths: Paths, def: CaseDefinition): Promise<CaseChannels> { + const out = new Set<string>(def.scope.channels); + const problems: string[] = []; + for (const s of def.subjects) for (const c of s.channels ?? []) out.add(c); + for (const g of def.groups) if (Array.isArray(g.channels)) for (const c of g.channels) out.add(c); + for (const id of def.scope.sites) { + const site = await readSite(paths, id); + if (!site) { + problems.push(`site ${id}: no site.json`); + continue; + } + for (const c of site.channels ?? []) if (typeof c.slug === "string" && c.slug) out.add(c.slug); + } + for (const sg of def.scope.groups) { + const [siteId, groupId] = sg.split(":"); + const site = await readSite(paths, siteId); + if (!site) { + problems.push(`group ${sg}: no site.json for ${siteId}`); + continue; + } + const fallback = typeof site.defaultGroupId === "string" ? site.defaultGroupId : site.groups?.[0]?.id; + const members = (site.channels ?? []).filter((c) => typeof c.slug === "string" && (typeof c.groupId === "string" ? c.groupId : fallback) === groupId); + if (!members.length) problems.push(`group ${sg}: no channel of ${siteId} is in it`); + for (const c of members) out.add(c.slug as string); + } + return { slugs: [...out].sort(), problems }; +} + +type Opened = { ok: true; slug: string; configName?: string; dataDir: string } | { ok: false; slug: string; reason: string }; + +async function openChannel(paths: Paths, slug: string): Promise<Opened> { + const config = await readChannelConfig(paths, slug); + if (!config) return { ok: false, slug, reason: "not in the corpus" }; + if (isSocialChannel(config)) return { ok: false, slug, reason: "a social channel: posts, not recordings" }; + try { + await assertChannelTextReadable(paths, slug, config); + } catch (e) { + return { ok: false, slug, reason: (e as Error).message }; + } + return { ok: true, slug, configName: config.name, dataDir: path.join(paths.channelsDir, slug, "data") }; +} + +/** Held recordings with their dates: the index's first (one key scan), a metadata read for the rest. */ +async function datedHeld(dataDir: string, indexDates: Map<string, string> | undefined): Promise<{ id: string; date: string; title?: string }[]> { + const ids = [...(await heldVideoIds(dataDir))].sort(); + return mapConcurrent(ids, 16, async (id) => { + const fromIndex = indexDates?.get(id); + if (fromIndex && /^\d{8}$/.test(fromIndex)) return { id, date: fromIndex }; + const r = await readDateAndTitle(path.join(dataDir, id)); + return { id, date: r.uploadDate ?? "", ...(r.title ? { title: r.title } : {}) }; + }); +} + +/** A channel's listed ids: its playlist's lines, each the canonical id of its URL (or the line, when it is one). */ +async function listedIds(paths: Paths, slug: string): Promise<Set<string>> { + let raw = ""; + try { + raw = await readFile(path.join(paths.channelsDir, slug, "playlist"), "utf8"); + } catch { + return new Set(); + } + const out = new Set<string>(); + for (const line of raw.split("\n")) { + const l = line.trim(); + if (!l) continue; + const id = /^https?:\/\//.test(l) ? extractVideoId(l) : l; + if (id) out.add(id); + } + return out; +} + +// --------------------------------------------------------------------------------------------------------------- +// Stage 1: coverage + +/** + * One channel per year: LISTED (its playlist and everything it holds), HELD (a data/<id>/), TRANSCRIBED (held with + * a transcript or English captions) and UNTRANSCRIBED AUDIO (held with audio and no transcript). A held video is + * dated by the index or its metadata; a listed one never fetched by the channel's metadata scan; what nothing + * dates is the row of year 0. `key` marks a year one of the case's eras touches. + */ +export async function channelYearCoverage( + paths: Paths, + slug: string, + def: Pick<CaseDefinition, "eras">, + indexDates?: Map<string, string>, +): Promise<{ rows: CoverageRow[]; problem?: string }> { + const ch = await openChannel(paths, slug); + if (!ch.ok) return { rows: [], problem: ch.reason }; + const years = keyYears(def); + const by = new Map<number, CoverageRow>(); + const row = (year: number) => { + let r = by.get(year); + if (!r) by.set(year, (r = { channel: slug, year, listed: 0, held: 0, transcribed: 0, untranscribedAudio: 0, ...(years.has(year) ? { key: true } : {}) })); + return r; + }; + const held = await datedHeld(ch.dataDir, indexDates); + const heldIds = new Set(held.map((h) => h.id)); + await mapConcurrent(held, 16, async (h) => { + const files = await readVideoFiles(path.join(ch.dataDir, h.id)); + const r = row(h.date ? Number(h.date.slice(0, 4)) : 0); + r.listed++; + r.held++; + if (isVideoTranscribed(files)) r.transcribed++; + else if (files.audioFiles.length > 0) r.untranscribedAudio++; + }); + const listed = await listedIds(paths, slug); + const scan = await loadMetadataScan(paths, slug).catch(() => null); + for (const id of listed) { + if (heldIds.has(id)) continue; + const d = day8(scan?.entries[id]?.uploadDate); + row(d ? Number(d.slice(0, 4)) : 0).listed++; + } + return { rows: [...by.values()].sort((a, b) => a.year - b.year) }; +} + +/** Every channel of the case, per year; the channels it could not read, with why. */ +export async function caseCoverage(paths: Paths, def: CaseDefinition): Promise<{ rows: CoverageRow[]; skipped: { slug: string; reason: string }[]; problems: string[] }> { + const { slugs, problems } = await caseChannels(paths, def); + const index = openUploadDateIndex(paths, slugs); + try { + const rows: CoverageRow[] = []; + const skipped: { slug: string; reason: string }[] = []; + for (const slug of slugs) { + const r = await channelYearCoverage(paths, slug, def, index.datesBySlug.get(slug)); + if (r.problem) skipped.push({ slug, reason: r.problem }); + rows.push(...r.rows); + } + return { rows, skipped, problems }; + } finally { + await index.close().catch(() => {}); + } +} + +// --------------------------------------------------------------------------------------------------------------- +// Stage 2: candidates + +export type CaseCandidatesOptions = ScanOptions & { onNote?: (line: string) => void }; + +/** + * The candidate windows of every recording in scope dated inside an era (casePipeline.ts recordingWindows: the + * families, ±W s windows merged, title hits, the noise filters), in reading order, and the counts -- per family, + * year, channel and group -- before anything is read. Deterministic: the same corpus and definition give the same + * windows with the same keys. + */ +export async function caseCandidates(paths: Paths, def: CaseDefinition, o: CaseCandidatesOptions = {}): Promise<{ windows: CandidateWindow[]; counts: CandidateCounts; problems: string[] }> { + const counts = emptyCounts(); + const { slugs, problems } = await caseChannels(paths, def); + if (!def.eras.length) throw new Error("the case has no era: define an era and its term families first"); + const index = openUploadDateIndex(paths, slugs); + const windows: CandidateWindow[] = []; + try { + for (const slug of slugs) { + const ch = await openChannel(paths, slug); + if (!ch.ok) { + counts.skipped.push({ slug, reason: ch.reason }); + o.onNote?.(`skipped ${slug}: ${ch.reason}`); + continue; + } + counts.scanned.channels++; + const held = await datedHeld(ch.dataDir, index.datesBySlug.get(slug)); + let found = 0; + await mapConcurrent(held, 8, async (h) => { + counts.scanned.videos++; + if (!h.date) { + counts.scanned.undated++; + return; + } + if (!erasOn(def, h.date).length) return; + counts.scanned.inEra++; + const read = await readCuesInVideoDir({ slug, id: h.id, videoDir: path.join(ch.dataDir, h.id), configName: ch.configName }).catch(() => null); + if (!read || !read.cues.length) { + counts.scanned.noText++; + return; + } + counts.scanned.withText++; + const ws = recordingWindows( + def, + { + slug, + id: h.id, + date: h.date, + title: read.title ?? h.title ?? h.id, + ...(read.webpageUrl ? { url: read.webpageUrl } : {}), + ...(typeof read.duration === "number" ? { duration: read.duration } : {}), + track: trackOfFile(read.file), + cues: read.cues, + }, + counts, + o, + ); + found += ws.length; + windows.push(...ws); + }); + o.onNote?.(`${slug}: ${held.length} held, ${found} ${found === 1 ? "window" : "windows"}`); + } + } finally { + await index.close().catch(() => {}); + } + return { windows: sortWindows(def, windows), counts, problems }; +} + +// --------------------------------------------------------------------------------------------------------------- +// Stage 9: the subject's uploads + +/** + * Every upload of the subjects' own channels, held or only listed: its date, title and whether it has words to + * check (a transcript or captions). A listed upload never fetched is dated by the metadata scan, and is not + * captioned -- it cannot be checked, and the table says so. + */ +export async function subjectUploads(paths: Paths, def: CaseDefinition): Promise<{ uploads: DatedUpload[]; skipped: { slug: string; reason: string }[] }> { + const slugs = [...subjectChannels(def)].sort(); + const index = openUploadDateIndex(paths, slugs); + const uploads: DatedUpload[] = []; + const skipped: { slug: string; reason: string }[] = []; + try { + for (const slug of slugs) { + const ch = await openChannel(paths, slug); + if (!ch.ok) { + skipped.push({ slug, reason: ch.reason }); + continue; + } + const held = await datedHeld(ch.dataDir, index.datesBySlug.get(slug)); + await mapConcurrent(held, 16, async (h) => { + if (!h.date) return; + const dir = path.join(ch.dataDir, h.id); + const files = await readVideoFiles(dir); + const title = h.title ?? (await readDateAndTitle(dir)).title ?? h.id; + uploads.push({ slug, id: h.id, date: h.date, title, captioned: isVideoTranscribed(files) }); + }); + const heldIds = new Set(held.map((h) => h.id)); + const scan = await loadMetadataScan(paths, slug).catch(() => null); + for (const id of await listedIds(paths, slug)) { + if (heldIds.has(id)) continue; + const e = scan?.entries[id]; + const d = day8(e?.uploadDate); + if (d) uploads.push({ slug, id, date: d, title: e?.title || id, captioned: false }); + } + } + } finally { + await index.close().catch(() => {}); + } + uploads.sort((a, b) => a.date.localeCompare(b.date) || a.slug.localeCompare(b.slug) || a.id.localeCompare(b.id)); + return { uploads, skipped }; +} diff --git a/common/controller/casePipelineRun.ts b/common/controller/casePipelineRun.ts @@ -0,0 +1,157 @@ +// 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/<id>.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 type { Paths } from "../lib/paths"; +import type { CaseBatch, CaseDefinition, CaseStageRun, CoverageRow, DateCheck, FindingRow } from "../lib/research/caseTypes"; +import { + CasePipelineError, + dateChecks, + groupFor, + mergeFindings, + reportHtml, + reportMarkdown, + type MergeResult, + type ScanOptions, +} from "../lib/research/casePipeline"; +import { + readBatches, + readCandidateCounts, + readCandidates, + readDefinition, + readFindings, + readSummary, + rebuildBatches, + runStage, + writeCandidates, + writeCoverage, + writeDateChecks, + writeReport, +} from "../lib/research/caseStore-server"; +import { caseCandidates, caseChannels, caseCoverage, subjectUploads } from "./caseCorpus"; + +type By = CaseStageRun["by"]; + +async function definitionOf(dir: string, caseId: string): Promise<CaseDefinition> { + 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); + 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<MergeView> { + 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<string> { + 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; ${Object.values(counts.noise).reduce((a, b) => a + b, 0)} windows dropped by the noise filters.` + : "No candidate scan is recorded.", + `Batches: ${batches.length}, ${read} read.`, + ].join(" "); +} + +/** 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); + const markdown = reportMarkdown({ title, summary, merged, coverage: await coverageLine(dir, def, o.paths ?? null) }); + 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<DateCheck[]> { + 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 } }; + }); +} diff --git a/common/lib/research/casePipeline.test.ts b/common/lib/research/casePipeline.test.ts @@ -0,0 +1,304 @@ +// The case pipeline's pure half (lib/research/casePipeline.ts): the definition checked, the naming rule in every +// reader prompt, rolling captions folded, hits into windows, the noise filters, the batch rule (no line over 200), +// a finding checked, the merge, the report, the date checks' sentence, and the browser hash agreeing with the +// server's. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/research/casePipeline.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { BATCH_LINE_MAX, NAME_WITHHELD, type CaseDefinition, type FindingRow } from "./caseTypes"; +import { + CasePipelineError, + NAMING_RULE, + batchText, + checkFindingRow, + dateChecks, + emptyCounts, + emptyDefinition, + familyHits, + foldCues, + groupFor, + longestLine, + mergeFindings, + mergeHitWindows, + normalizeDefinition, + planBatches, + privateNameHashWeb, + privateTermProblem, + readerPrompt, + recordingWindows, + reportHtml, + reportMarkdown, + trackOfFile, + wrapLine, +} from "./casePipeline"; +import { privateNameHash } from "./privateNames-server"; + +const def = (over: Partial<CaseDefinition> = {}): CaseDefinition => + normalizeDefinition( + { + subjects: [{ name: "Wren Halloway", aliases: ["Wren"], channels: ["wren-own"] }], + scope: { channels: ["wren-own", "talk-show"], groups: [], sites: [] }, + eras: [ + { id: "early", from: "2014-01-01", to: "2016-12-31", families: { name: "\\bwren\\b", shop: "lantern shop" } }, + { id: "late", from: "2020-01-01", to: "2022-12-31", families: { name: "\\bwren\\b", shop: "lantern shop" }, strictFamilies: ["shop"] }, + ], + groups: [ + { id: "own", label: "Her own words", channels: "subject" }, + { id: "others", label: "Coverage", channels: "coverage" }, + ], + readerPrompts: { common: "Quote verbatim.", own: "She is the speaker unless said otherwise." }, + ...over, + }, + "wren", + ); + +test("normalizeDefinition: a whole case passes, every bad field is refused by name", () => { + const d = def(); + assert.equal(d.case, "wren"); + assert.equal(d.eras[1].strictFamilies?.[0], "shop"); + const bad = (raw: Record<string, unknown>, re: RegExp) => assert.throws(() => normalizeDefinition(raw, "wren"), (e: Error) => e instanceof CasePipelineError && re.test(e.message)); + bad({ eras: [{ id: "x", from: "2014-01-01", to: "2014-02-01", families: { a: "(" } }] }, /era x, family a: not a regex/); + bad({ eras: [{ id: "x", from: "2015-01-01", to: "2014-02-01", families: {} }] }, /after/); + bad({ eras: [{ id: "x", from: "2015-02-30", to: "2016-02-01", families: {} }] }, /dates/); + bad({ privateNames: { sha256: ["Jane Doe"] } }, /never a name/); + bad({ readerPrompts: { common: "", ghost: "x" } }, /no group "ghost"/); + bad({ groups: [{ id: "g", channels: [] }] }, /channels is "subject"/); + bad({ scope: { groups: ["nosite"] } }, /<site>:<group>/); + bad({ case: "other" }, /filed under "wren"/); + assert.equal(emptyDefinition("wren").status, "defining"); +}); + +test("readerPrompt always carries the naming rule, even when the case's prompts are empty", () => { + assert.ok(readerPrompt(def(), "own").includes(NAMING_RULE)); + assert.ok(readerPrompt(def(), "own").includes("She is the speaker")); + assert.ok(readerPrompt(def(), "own").includes("Wren Halloway / Wren")); + const empty = def({ readerPrompts: { common: "" } }); + assert.ok(readerPrompt(empty, "others").endsWith(NAMING_RULE)); + assert.ok(NAMING_RULE.includes(NAME_WITHHELD)); +}); + +test("privateTermProblem: at most three words, and something to hash", () => { + assert.equal(privateTermProblem("Jane Q Private"), null); + assert.match(privateTermProblem("one two three four") ?? "", /three words/); + assert.match(privateTermProblem(" .. ") ?? "", /letters/); +}); + +test("privateNameHashWeb is the server's hash (a term typed on the page never leaves it)", async () => { + for (const t of ["Jane Q Private", " JANE q private ", "Zoë Ł"]) assert.equal(await privateNameHashWeb(t), privateNameHash(t)); +}); + +test("foldCues drops a rolling caption's repeated head, and a cue that only repeats", () => { + const f = foldCues([ + { start: 0, end: 2, text: "so the lantern" }, + { start: 2, end: 4, text: "so the lantern shop opened" }, + { start: 4, end: 6, text: "lantern shop opened" }, + { start: 6, end: 8, text: "in the spring" }, + ]); + assert.equal(f.text, "so the lantern shop opened in the spring"); + assert.deepEqual(f.offsets.map((o) => o.t), [0, 2, 6]); +}); + +test("familyHits puts each match at its cue's second; mergeHitWindows merges ±W and caps a span", () => { + const cues = [ + { start: 10, end: 12, text: "talking about Wren" }, + { start: 30, end: 32, text: "and the lantern shop" }, + { start: 400, end: 402, text: "wren again" }, + ]; + const hits = familyHits(cues, [ + { id: "name", re: /\bwren\b/iu }, + { id: "shop", re: /lantern shop/iu }, + ]); + assert.deepEqual(hits.map((h) => [h.t, h.family]), [[10, "name"], [30, "shop"], [400, "name"]]); + const w = mergeHitWindows(hits, 30, 240); + assert.deepEqual(w.map((x) => [x.from, x.to, x.hits.length]), [[0, 60, 2], [370, 430, 1]]); + const capped = mergeHitWindows(Array.from({ length: 10 }, (_, i) => ({ t: i * 50, family: "f", match: "x" })), 30, 120); + assert.ok(capped.every((x) => x.to - x.from <= 150)); + assert.ok(capped.length > 1); +}); + +test("trackOfFile: en-orig, en, a transcript, cues", () => { + assert.equal(trackOfFile("transcript.en-orig.vtt"), "en-orig"); + assert.equal(trackOfFile("transcript.en.vtt"), "en"); + assert.equal(trackOfFile("transcript.en-US.vtt"), "en"); + assert.equal(trackOfFile("transcript.json"), "transcript"); + assert.equal(trackOfFile(undefined), "cues"); +}); + +test("groupFor: a named channel, else the subject's group, else coverage", () => { + const d = def({ groups: [{ id: "own", label: "Own", channels: "subject" }, { id: "talk", label: "Talk", channels: ["talk-show"] }, { id: "others", label: "Coverage", channels: "coverage" }] }); + assert.equal(groupFor(d, "talk-show", "early")?.id, "talk"); + assert.equal(groupFor(d, "wren-own", "early")?.id, "own"); + assert.equal(groupFor(d, "elsewhere", "early")?.id, "others"); + assert.equal(groupFor(def({ groups: [{ id: "own", label: "Own", channels: "subject", era: "early" }] }), "wren-own", "late"), null); +}); + +const cuesSaying = (lines: [number, string][]) => lines.map(([t, text]) => ({ start: t, end: t + 3, text })); + +test("recordingWindows: coverage needs a subject named, a strict era wants its strict family, a title hit stands alone", () => { + const d = def(); + const counts = emptyCounts(); + // Coverage: the family matches ("lantern shop") but no subject is named -> noise. + const none = recordingWindows(d, { slug: "talk-show", id: "t1", date: "20150301", title: "A show", track: "en", cues: cuesSaying([[100, "the lantern shop downtown"]]) }, counts); + assert.equal(none.length, 0); + assert.equal(counts.noise.noSubject, 1); + // Coverage naming her: a window, in the coverage group. + const named = recordingWindows(d, { slug: "talk-show", id: "t2", date: "20150301", title: "A show", track: "en", cues: cuesSaying([[100, "Wren and the lantern shop"]]) }, counts); + assert.equal(named.length, 1); + assert.equal(named[0].group, "others"); + assert.equal(named[0].key, "talk-show/t2@70"); + // Her own channel, the late (strict) era: "wren" alone makes nothing; "lantern shop" does. + const loose = recordingWindows(d, { slug: "wren-own", id: "o1", date: "20210101", title: "Vlog", track: "en-orig", cues: cuesSaying([[50, "hi I'm wren"]]) }, counts); + assert.equal(loose.length, 0); + assert.equal(counts.noise.notStrict, 1); + const strict = recordingWindows(d, { slug: "wren-own", id: "o2", date: "20210101", title: "Vlog", track: "en-orig", cues: cuesSaying([[50, "the lantern shop is closing"]]) }, counts); + assert.equal(strict.length, 1); + assert.equal(strict[0].group, "own"); + assert.equal(strict[0].era, "late"); + // A title hit with no word hit is a window of its own at the start. + const titled = recordingWindows(d, { slug: "wren-own", id: "o3", date: "20150101", title: "Wren answers", track: "en-orig", cues: cuesSaying([[5, "garbled"], [20, "words"]]) }, counts); + assert.equal(titled.length, 1); + assert.equal(titled[0].from, 0); + assert.equal(titled[0].titleHit, true); + assert.deepEqual(titled[0].titleFamilies, ["name"]); + // Out of every era: nothing. + assert.equal(recordingWindows(d, { slug: "wren-own", id: "o4", date: "20180101", title: "Wren", track: "en", cues: cuesSaying([[5, "wren"]]) }, counts).length, 0); + assert.equal(counts.windows, 3); + assert.equal(counts.byGroup.own, 2); + assert.equal(counts.byFamily.shop, 2); + assert.equal(counts.byYear["2015"], 2); + assert.equal(counts.titleHits, 1); +}); + +test("wrapLine: no line over the limit, a long word cut, the words kept", () => { + const long = `${"word ".repeat(120)}${"x".repeat(450)} tail`; + const lines = wrapLine(long); + assert.ok(lines.every((l) => [...l].length <= BATCH_LINE_MAX), `longest ${Math.max(...lines.map((l) => l.length))}`); + assert.equal(lines.join(" ").replace(/\s+/g, " ").replace(/x /g, "x").length > 0, true); + assert.equal(lines.join("").replace(/\s/g, ""), long.replace(/\s/g, "")); + assert.deepEqual(wrapLine(""), [""]); +}); + +test("THE BATCH RULE: no line of a batch file is over BATCH_LINE_MAX, whatever the window holds", () => { + const d = def(); + const huge = { + key: "talk-show/t9@0", + slug: "talk-show", + id: "t9", + date: "20150301", + title: `A very long title ${"that goes on ".repeat(40)}`, + from: 0, + to: 3600, + era: "early", + group: "others", + track: "en" as const, + hits: Array.from({ length: 30 }, (_, i) => ({ t: i * 10, family: "name", match: "Wren" })), + url: `https://www.youtube.com/watch?v=t9&${"pad=1&".repeat(60)}`, + text: `${"Wren said a thing about the lantern shop and then ".repeat(400)}${"y".repeat(900)}`, + }; + const { batches, texts } = planBatches(d, [huge, { ...huge, key: "talk-show/t9@4000", from: 4000 }], { round: 1, budget: 30_000 }); + assert.equal(batches.length, 2, "a window over the budget is a batch of its own"); + assert.deepEqual(batches.map((b) => b.id), ["others-1-001", "others-1-002"]); + for (const b of batches) { + const t = texts.get(b.id)!; + assert.ok(longestLine(t) <= BATCH_LINE_MAX, `${b.id}: a line of ${longestLine(t)}`); + assert.ok(t.includes("Naming rule")); + assert.equal(b.chars, t.length); + assert.equal(b.state, "pending"); + } + assert.ok(longestLine(batchText({ id: "x", group: "others", round: 1 }, "Coverage", [huge])) <= BATCH_LINE_MAX); +}); + +test("planBatches: per group, under the budget, and never a window a read batch covers", () => { + const d = def(); + const mk = (slug: string, from: number, group: string) => ({ key: `${slug}/v@${from}`, slug, id: "v", date: "20150101", title: "T", from, to: from + 60, era: "early", group, track: "en" as const, hits: [], text: "w ".repeat(400) }); + const ws = [mk("a", 0, "own"), mk("a", 100, "own"), mk("a", 200, "own"), mk("b", 0, "others")]; + const { batches } = planBatches(d, ws, { round: 2, budget: 1200, exclude: new Set(["a/v@100"]) }); + assert.deepEqual(batches.map((b) => [b.id, b.windows]), [["own-2-001", ["a/v@0"]], ["own-2-002", ["a/v@200"]], ["others-2-001", ["b/v@0"]]]); +}); + +const row = (over: Partial<FindingRow>): FindingRow => ({ + row: "f1", + batch: "own-1-001", + slug: "wren-own", + id: "o2", + date: "20210101", + title: "Vlog", + t: 50, + url: "https://www.youtube.com/watch?v=o2", + 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", + quoteCheck: "found", + ...over, +}); + +test("checkFindingRow: a quote over 45 words, a relevance of 4, a missing batch -- refused by name", () => { + const ok = checkFindingRow({ ...row({}), row: undefined, quoteCheck: undefined }); + assert.equal(ok.ok, true); + if (ok.ok) assert.equal(ok.row.quoteCheck, "unchecked"); + const bad = checkFindingRow({ ...row({}), relevance: 4, quote: "w ".repeat(46), batch: "" }); + assert.equal(bad.ok, false); + if (!bad.ok) { + assert.ok(bad.errors.some((e) => /relevance/.test(e))); + assert.ok(bad.errors.some((e) => /45 words/.test(e))); + assert.ok(bad.errors.some((e) => /batch/.test(e))); + } + const dashed = checkFindingRow({ ...row({}), date: "2021-01-01" }); + assert.ok(dashed.ok && dashed.row.date === "20210101"); +}); + +test("mergeFindings: within 20 s on one recording is one finding (higher relevance, then later round); sections; quarantine; the floor", () => { + const d = def(); + const rows = [ + row({ row: "f1", t: 50, relevance: 2, round: 1 }), + row({ row: "f2", t: 60, relevance: 3, round: 1 }), + row({ row: "f3", t: 65, relevance: 3, round: 2 }), + row({ row: "f4", t: 200, relevance: 1 }), + row({ row: "f5", slug: "talk-show", id: "t2", batch: "others-1-001", t: 10, relevance: 3 }), + row({ row: "f6", slug: "forum", id: "p1", batch: "others-1-001", t: 0, relevance: 3, verify: { status: "quarantined", at: "x" } }), + ]; + const groupOf = (r: FindingRow) => r.batch.replace(/-\d+-\d+$/, ""); + const m = mergeFindings(d, rows, groupOf); + assert.deepEqual(m.duplicates, [{ row: "f1", of: "f3" }, { row: "f2", of: "f3" }]); + assert.deepEqual(m.sections.map((s) => [s.group, s.rows.map((r) => r.row)]), [["own", ["f3"]], ["others", ["f5"]]]); + assert.deepEqual(m.quarantined.map((r) => r.row), ["f6"]); + assert.deepEqual(m.belowFloor.map((r) => r.row), ["f4"]); + assert.deepEqual(mergeFindings(d, rows, groupOf, { minRelevance: 1 }).sections[0].rows.map((r) => r.row), ["f3", "f4"]); + + const md = reportMarkdown({ title: "Wren", summary: { text: "What she said.", draft: true, by: "local", model: "qwen3:8b", at: "x" }, merged: m, coverage: "Scope: two channels." }); + assert.match(md, /^# Wren\n/); + assert.match(md, /Draft summary, by qwen3:8b: not yet reviewed\./); + assert.match(md, /## Her own words\n\n- She says the shop is closing: "the lantern shop is closing" — \[Vlog @ 1:05\]\(https:\/\/www\.youtube\.com\/watch\?v=o2&t=65s\)/); + assert.match(md, /## Quarantined/); + assert.match(md, /row f6/); + assert.match(md, /## Coverage\n\nScope: two channels\./); + const html = reportHtml(md.replace("Wren", "Wren <b>&")); + assert.match(html, /<h1>Wren &lt;b&gt;&amp;<\/h1>/); + assert.match(html, /<a href="https:\/\/www\.youtube\.com\/watch\?v=o2&amp;t=65s">/); + assert.doesNotMatch(html, /<script/); +}); + +test("dateChecks: uploads around and after each key date, and the sentence", () => { + const d = def({ keyDates: [{ date: "2021-03-01", label: "the shop closes" }] }); + const uploads = [ + { slug: "wren-own", id: "a", date: "20210220", title: "Before", captioned: true }, + { slug: "wren-own", id: "b", date: "20210305", title: "After", captioned: true }, + { slug: "wren-own", id: "c", date: "20210601", title: "Later", captioned: false }, + ]; + const [none] = dateChecks(d, uploads, []); + assert.equal(none.date, "2021-03-01"); + assert.deepEqual(none.uploads.map((u) => u.id), ["a", "b", "c"]); + assert.equal(none.sentence, "no response found in captioned uploads through 2021-03-05"); + const [found] = dateChecks(d, uploads, [{ row: "f9", slug: "wren-own", date: "20210305", relevance: 3 }]); + assert.match(found.sentence, /^response found: 1 finding in uploads from 2021-03-05 to 2021-03-05 \(rows f9\)$/); + const [early] = dateChecks(def(), [], []); + assert.equal(early.label, "early begins"); + assert.match(early.sentence, /no captioned upload on or after 2014-01-01/); +}); diff --git a/common/lib/research/casePipeline.ts b/common/lib/research/casePipeline.ts @@ -0,0 +1,979 @@ +// RESEARCH CASES AS A PIPELINE, the pure half (plans/release-38/research-cases-and-assist.md, lane A): the case +// definition checked, the reader prompt and its naming rule, the candidate windows built from a recording's cues, +// the noise filters and the counts, the batches as wrapped text, a finding row checked, the merge, the report as +// cited markdown and HTML, and the date checks' sentence. No I/O and no node built-ins: the case page, the CLI, +// umtool's routes and the MCP (lane D) all compute the same answer. The stores are caseStore-server.ts; the +// corpus readers are controller/caseCandidates.ts, caseCoverage.ts and caseDateChecks.ts. +// +// The reference is the Oneylyzer case's own scripts (candidates.py, merge.py; not committed, they read a private +// case). What each step learned is in its comment. + +import type { Cue } from "../vtt"; +import { platformMomentUrl } from "../momentUrl"; +import { + BATCH_LINE_MAX, + CASE_PIPELINE_FORMAT, + CASE_PIPELINE_VERSION, + CASE_STATUSES, + FINDING_BY, + MERGE_DEDUPE_SECONDS, + MERGE_MIN_RELEVANCE, + NAME_WITHHELD, + QUOTE_WORDS_MAX, + VERIFY_STATUSES, + WINDOW_TRACKS, + isCaseStatus, + isFindingBy, + isRelevance, + isVerifyStatus, + normalizeTerm, + type CandidateCounts, + type CandidateHit, + type CandidateWindow, + type CaseBatch, + type CaseDefinition, + type CaseEra, + type CaseSummaryText, + type DateCheck, + type FindingRow, + type ReaderGroup, + type WindowTrack, +} from "./caseTypes"; + +/** A refusal a caller can fix, with the HTTP status a route answers it with. */ +export class CasePipelineError extends Error { + constructor( + message: string, + readonly status = 400, + ) { + super(message); + this.name = "CasePipelineError"; + } +} + +// --------------------------------------------------------------------------------------------------------------- +// The naming rule, in every reader prompt + +/** + * What every reader is told, whatever the case's prompts say: the case's private names are hashes, so a reader + * cannot be given them -- it is told whom it may name, and to withhold everyone else. + */ +export const NAMING_RULE = + `Naming rule: name only the case's subjects and public figures (a channel's host, a person known by their public ` + + `work). Every other person -- a relative, a partner, a classmate, a private individual, a forum user's real name ` + + `-- is written ${NAME_WITHHELD}, in the quote as well as the summary and the speaker. Change nothing else in a ` + + `quote: it stays verbatim.`; + +/** The prompt a reader of `group` gets: the case's common prompt, the group's own, and the naming rule, always. */ +export function readerPrompt(def: Pick<CaseDefinition, "readerPrompts" | "subjects">, group: string): string { + const parts = [def.readerPrompts.common?.trim() ?? "", group !== "common" ? (def.readerPrompts[group]?.trim() ?? "") : ""].filter(Boolean); + const subjects = def.subjects.map((s) => [s.name, ...s.aliases].filter(Boolean).join(" / ")).filter(Boolean); + if (subjects.length) parts.push(`The case's subjects: ${subjects.join("; ")}.`); + parts.push(NAMING_RULE); + return parts.join("\n\n"); +} + +// --------------------------------------------------------------------------------------------------------------- +// The definition, checked + +const SLUG = /^[a-z0-9][a-z0-9-]{0,63}$/; +const CHANNEL = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; +const DAY = /^\d{4}-\d{2}-\d{2}$/; +const HEX64 = /^[0-9a-f]{64}$/; + +const text = (v: unknown, max: number) => (typeof v === "string" ? v.replace(/\s+/g, " ").trim().slice(0, max) : ""); +const list = (v: unknown, max: number, each = 200): string[] => + (Array.isArray(v) ? v : []) + .filter((x): x is string => typeof x === "string" && !!x.trim()) + .map((x) => x.trim().slice(0, each)) + .slice(0, max); +const realDay = (d: string) => { + if (!DAY.test(d)) return false; + const t = new Date(`${d}T00:00:00Z`); + return !Number.isNaN(t.getTime()) && t.toISOString().slice(0, 10) === d; +}; + +/** A new case's definition: nothing defined yet. */ +export function emptyDefinition(caseId: string, now = new Date()): CaseDefinition { + const at = now.toISOString(); + return { + format: CASE_PIPELINE_FORMAT, + version: CASE_PIPELINE_VERSION, + case: caseId, + subjects: [], + scope: { channels: [], groups: [], sites: [] }, + eras: [], + groups: [], + privateNames: { sha256: [], note: "" }, + readerPrompts: { common: "" }, + keyDates: [], + status: "defining", + createdAt: at, + updatedAt: at, + }; +} + +/** A family's regex, compiled as the scan compiles it (flags "iu"); a bad one is named. */ +export function compileFamily(era: string, family: string, source: string): RegExp { + try { + return new RegExp(source, "iu"); + } catch (e) { + throw new CasePipelineError(`era ${era}, family ${family}: not a regex (${(e as Error).message})`); + } +} + +/** + * A definition from what was read or sent, every field checked: an unknown shape is refused with the field named, + * never silently dropped (a case's eras and families are the operator's work). `caseId` is the umtool case it sits + * beside. The private-name hashes are kept as they are; a TERM never arrives here (privateNames.ts hashes it first). + */ +export function normalizeDefinition(raw: unknown, caseId: string, now = new Date()): CaseDefinition { + const r = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>; + if (r.format !== undefined && r.format !== CASE_PIPELINE_FORMAT) throw new CasePipelineError(`not a ${CASE_PIPELINE_FORMAT} file`, 409); + if (r.case !== undefined && r.case !== caseId) throw new CasePipelineError(`pipeline.json names case "${String(r.case)}" but is filed under "${caseId}"`, 409); + const base = emptyDefinition(caseId, now); + + const subjects = (Array.isArray(r.subjects) ? r.subjects : []).map((s, i) => { + const o = (s && typeof s === "object" ? s : {}) as Record<string, unknown>; + const name = text(o.name, 120); + if (!name) throw new CasePipelineError(`subject ${i + 1} has no name`); + const channels = list(o.channels, 50, 128); + const bad = channels.find((c) => !CHANNEL.test(c)); + if (bad) throw new CasePipelineError(`subject ${name}: "${bad}" is not a channel slug`); + return { name, aliases: list(o.aliases, 30, 120), ...(channels.length ? { channels } : {}) }; + }); + if (subjects.length > 20) throw new CasePipelineError("a case has at most 20 subjects"); + + const sc = (r.scope && typeof r.scope === "object" ? r.scope : {}) as Record<string, unknown>; + const scope = { channels: list(sc.channels, 500, 128), groups: list(sc.groups, 100, 200), sites: list(sc.sites, 50, 64) }; + const badCh = scope.channels.find((c) => !CHANNEL.test(c)); + if (badCh) throw new CasePipelineError(`scope: "${badCh}" is not a channel slug`); + const badGroup = scope.groups.find((g) => !/^[a-z0-9][a-z0-9-]*:[a-z0-9][a-z0-9-]*$/.test(g)); + if (badGroup) throw new CasePipelineError(`scope: a group is "<site>:<group>", not "${badGroup}"`); + + const eraIds = new Set<string>(); + const eras: CaseEra[] = (Array.isArray(r.eras) ? r.eras : []).map((e, i) => { + const o = (e && typeof e === "object" ? e : {}) as Record<string, unknown>; + const id = text(o.id, 64); + if (!SLUG.test(id)) throw new CasePipelineError(`era ${i + 1}: an id is a lowercase slug, not "${id}"`); + if (eraIds.has(id)) throw new CasePipelineError(`era ${id} is defined twice`); + eraIds.add(id); + const from = text(o.from, 10); + const to = text(o.to, 10); + if (!realDay(from) || !realDay(to)) throw new CasePipelineError(`era ${id}: from and to are dates (YYYY-MM-DD)`); + if (from > to) throw new CasePipelineError(`era ${id}: from ${from} is after to ${to}`); + const fam = (o.families && typeof o.families === "object" ? o.families : {}) as Record<string, unknown>; + const families: Record<string, string> = {}; + for (const [k, v] of Object.entries(fam)) { + if (!SLUG.test(k)) throw new CasePipelineError(`era ${id}: a family id is a lowercase slug, not "${k}"`); + if (typeof v !== "string" || !v.trim()) throw new CasePipelineError(`era ${id}, family ${k}: a regex, as text`); + compileFamily(id, k, v); + families[k] = v.slice(0, 2000); + } + if (Object.keys(families).length > 40) throw new CasePipelineError(`era ${id}: at most 40 families`); + const strict = list(o.strictFamilies, 40, 64); + const unknownStrict = strict.find((f) => !(f in families)); + if (unknownStrict) throw new CasePipelineError(`era ${id}: strict family "${unknownStrict}" is not one of its families`); + return { id, from, to, families, ...(strict.length ? { strictFamilies: strict } : {}) }; + }); + + const groupIds = new Set<string>(); + const groups: ReaderGroup[] = (Array.isArray(r.groups) ? r.groups : []).map((g, i) => { + const o = (g && typeof g === "object" ? g : {}) as Record<string, unknown>; + const id = text(o.id, 64); + if (!SLUG.test(id) || id === "common") throw new CasePipelineError(`group ${i + 1}: an id is a lowercase slug (not "common"), not "${id}"`); + if (groupIds.has(id)) throw new CasePipelineError(`group ${id} is defined twice`); + groupIds.add(id); + const label = text(o.label, 120) || id; + let channels: ReaderGroup["channels"]; + if (o.channels === "subject" || o.channels === "coverage") channels = o.channels; + else { + channels = list(o.channels, 500, 128); + const bad = channels.find((c) => !CHANNEL.test(c)); + if (bad) throw new CasePipelineError(`group ${id}: "${bad}" is not a channel slug`); + if (!channels.length) throw new CasePipelineError(`group ${id}: channels is "subject", "coverage" or a list of slugs`); + } + const era = text(o.era, 64); + if (era && !eraIds.has(era)) throw new CasePipelineError(`group ${id}: no era "${era}"`); + return { id, label, channels, ...(era ? { era } : {}) }; + }); + + const pn = (r.privateNames && typeof r.privateNames === "object" ? r.privateNames : {}) as Record<string, unknown>; + const sha256 = [...new Set(list(pn.sha256, 2000, 64).map((h) => h.toLowerCase()))]; + const badHash = sha256.find((h) => !HEX64.test(h)); + if (badHash !== undefined) throw new CasePipelineError("privateNames.sha256 holds sha256 hex digests only (64 lowercase hex characters), never a name"); + + const rp = (r.readerPrompts && typeof r.readerPrompts === "object" ? r.readerPrompts : {}) as Record<string, unknown>; + const readerPrompts: CaseDefinition["readerPrompts"] = { common: typeof rp.common === "string" ? rp.common.slice(0, 8000) : "" }; + for (const [k, v] of Object.entries(rp)) { + if (k === "common") continue; + if (!groupIds.has(k)) throw new CasePipelineError(`readerPrompts: no group "${k}"`); + if (typeof v === "string") readerPrompts[k] = v.slice(0, 8000); + } + + const keyDates = (Array.isArray(r.keyDates) ? r.keyDates : []).map((k, i) => { + const o = (k && typeof k === "object" ? k : {}) as Record<string, unknown>; + const date = text(o.date, 10); + if (!realDay(date)) throw new CasePipelineError(`key date ${i + 1}: a date (YYYY-MM-DD)`); + return { date, label: text(o.label, 200) || date }; + }); + + const status = r.status === undefined ? base.status : r.status; + if (!isCaseStatus(status)) throw new CasePipelineError(`status is one of ${CASE_STATUSES.join(", ")}`); + return { + ...base, + subjects, + scope, + eras, + groups, + privateNames: { sha256, note: typeof pn.note === "string" ? pn.note.slice(0, 1000) : "" }, + readerPrompts, + keyDates: keyDates.slice(0, 200), + status, + createdAt: typeof r.createdAt === "string" && r.createdAt ? r.createdAt.slice(0, 40) : base.createdAt, + updatedAt: typeof r.updatedAt === "string" && r.updatedAt ? r.updatedAt.slice(0, 40) : base.updatedAt, + }; +} + +/** The gate refuses a term of more than three words: it hashes words and 2–3-word phrases, so it could never match. */ +export function privateTermProblem(term: string): string | null { + const n = normalizeTerm(term.replace(/[^\p{L}\p{N}'’\-\s]/gu, " ")); + if (!n) return "a private name has letters in it"; + if (n.split(" ").length > 3) return "a private name is at most three words (the gate checks words and 2- and 3-word phrases)"; + return null; +} + +/** + * privateNameHash in a browser, so a term typed on the case page never leaves it (Web Crypto; the same digest as + * privateNames-server.ts's, which its test holds it to). The page posts only the hex. + */ +export async function privateNameHashWeb(term: string): Promise<string> { + const bytes = new TextEncoder().encode(normalizeTerm(term)); + const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes); + return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join(""); +} + +// --------------------------------------------------------------------------------------------------------------- +// Eras, groups and dates + +/** YYYYMMDD from YYYYMMDD or YYYY-MM-DD; "" otherwise. */ +export const day8 = (d: string | undefined | null): string => { + const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(String(d ?? "")); + return m ? `${m[1]}${m[2]}${m[3]}` : ""; +}; +/** YYYY-MM-DD from YYYYMMDD or YYYY-MM-DD; "" otherwise. */ +export const dayDashed = (d: string | undefined | null): string => { + const e = day8(d); + return e ? `${e.slice(0, 4)}-${e.slice(4, 6)}-${e.slice(6)}` : ""; +}; + +/** The eras a recording dated `date` falls in, in definition order. */ +export function erasOn(def: Pick<CaseDefinition, "eras">, date: string): CaseEra[] { + const d = day8(date); + if (!d) return []; + return def.eras.filter((e) => day8(e.from) <= d && d <= day8(e.to)); +} + +/** The span every era covers together, YYYYMMDD, or null when there is no era. */ +export function eraSpan(def: Pick<CaseDefinition, "eras">): { from: string; to: string } | null { + if (!def.eras.length) return null; + return { from: def.eras.map((e) => day8(e.from)).sort()[0], to: def.eras.map((e) => day8(e.to)).sort().at(-1)! }; +} + +/** The years any era touches: coverage highlights them. */ +export function keyYears(def: Pick<CaseDefinition, "eras">): Set<number> { + const out = new Set<number>(); + for (const e of def.eras) for (let y = Number(e.from.slice(0, 4)); y <= Number(e.to.slice(0, 4)); y++) out.add(y); + return out; +} + +/** Every subject's own channels. */ +export const subjectChannels = (def: Pick<CaseDefinition, "subjects">): Set<string> => new Set(def.subjects.flatMap((s) => s.channels ?? [])); + +/** + * Which reader group reads a window from `slug` in `era`: a group naming the channel; else, for a subject's own + * channel, the "subject" group; else the "coverage" group. A group with an era takes only that era's windows, and + * is preferred over one without. null: no group takes it (the noise count says so). + */ +export function groupFor(def: Pick<CaseDefinition, "groups" | "subjects">, slug: string, era: string): ReaderGroup | null { + const fits = (g: ReaderGroup) => !g.era || g.era === era; + const pick = (gs: ReaderGroup[]) => gs.filter(fits).sort((a, b) => Number(!!b.era) - Number(!!a.era))[0] ?? null; + const named = pick(def.groups.filter((g) => Array.isArray(g.channels) && g.channels.includes(slug))); + if (named) return named; + if (subjectChannels(def).has(slug)) return pick(def.groups.filter((g) => g.channels === "subject")); + return pick(def.groups.filter((g) => g.channels === "coverage")); +} + +/** The subjects' names and aliases as one word-bounded regex, or null when the case names none. */ +export function subjectMatcher(def: Pick<CaseDefinition, "subjects">): RegExp | null { + const names = def.subjects.flatMap((s) => [s.name, ...s.aliases]).map((n) => n.trim()).filter((n) => n.length >= 2); + if (!names.length) return null; + const esc = names.sort((a, b) => b.length - a.length).map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\s+/g, "\\s+")); + return new RegExp(`(?<![\\p{L}\\p{N}])(?:${esc.join("|")})(?![\\p{L}\\p{N}])`, "iu"); +} + +// --------------------------------------------------------------------------------------------------------------- +// A recording's text, rolling captions folded + +/** + * The cues as one text with each cue's offset in it. YouTube's rolling auto-captions repeat the tail of a line at + * the head of the next; parseVtt folds the word-timed kind, but a served track or an old cues.json can still carry + * the overlap, and a window that reads each sentence twice wastes a reader's budget and splits a quote across the + * seam. So each cue's longest head that repeats the text's tail (up to 24 words, compared without case and + * punctuation) is dropped, and a cue that only repeats is dropped whole. + */ +export function foldCues(cues: readonly Cue[]): { text: string; offsets: { at: number; t: number }[] } { + const norm = (w: string) => w.toLowerCase().replace(/[^\p{L}\p{N}']/gu, ""); + const tail: string[] = []; + const parts: string[] = []; + const offsets: { at: number; t: number }[] = []; + let at = 0; + for (const c of cues) { + const words = String(c.text ?? "").replace(/\s+/g, " ").trim().split(" ").filter(Boolean); + if (!words.length) continue; + const keys = words.map(norm); + let k = Math.min(24, words.length, tail.length); + for (; k > 0; k--) { + let same = true; + for (let i = 0; i < k; i++) if (tail[tail.length - k + i] !== keys[i]) { same = false; break; } + if (same) break; + } + const fresh = words.slice(k); + if (!fresh.length) continue; + const piece = fresh.join(" "); + if (parts.length) at += 1; + offsets.push({ at, t: c.start }); + parts.push(piece); + at += piece.length; + tail.push(...keys.slice(k)); + if (tail.length > 48) tail.splice(0, tail.length - 48); + } + return { text: parts.join(" "), offsets }; +} + +/** The second the character at `index` was said: the start of the cue it is in. */ +function secondAt(offsets: { at: number; t: number }[], index: number): number { + let lo = 0; + let hi = offsets.length - 1; + while (lo < hi) { + const mid = (lo + hi + 1) >> 1; + if (offsets[mid].at <= index) lo = mid; + else hi = mid - 1; + } + return offsets[lo]?.t ?? 0; +} + +/** The text said from `from` to `to`, rolling captions folded (foldCues). */ +export function textBetween(cues: readonly Cue[], from: number, to: number): string { + return foldCues(cues.filter((c) => c.start >= from && c.start <= to)).text; +} + +/** Every match of every family in the folded text, each at the second its cue starts. */ +export function familyHits(cues: readonly Cue[], families: { id: string; re: RegExp }[]): CandidateHit[] { + const { text: all, offsets } = foldCues(cues); + if (!all) return []; + const out: CandidateHit[] = []; + for (const f of families) { + const g = new RegExp(f.re.source, f.re.flags.includes("g") ? f.re.flags : `${f.re.flags}g`); + for (const m of all.matchAll(g)) { + if (!m[0]) continue; + out.push({ t: secondAt(offsets, m.index ?? 0), family: f.id, match: m[0].slice(0, 120) }); + if (out.length > 5000) break; + } + } + return out.sort((a, b) => a.t - b.t || a.family.localeCompare(b.family)); +} + +/** + * Hits into windows: each hit ±W seconds, overlapping spans merged, a merged span never longer than `maxSpan` + * (a recording that says the name every minute is many windows, not one hour-long one). + */ +export function mergeHitWindows(hits: readonly CandidateHit[], W: number, maxSpan: number, duration = Infinity): { from: number; to: number; hits: CandidateHit[] }[] { + const out: { from: number; to: number; hits: CandidateHit[] }[] = []; + for (const h of [...hits].sort((a, b) => a.t - b.t)) { + const from = Math.max(0, Math.floor(h.t - W)); + const to = Math.min(duration, Math.ceil(h.t + W)); + const last = out.at(-1); + if (last && from <= last.to && to - last.from <= maxSpan) { + last.to = Math.max(last.to, to); + last.hits.push(h); + } else out.push({ from, to: Math.max(from, to), hits: [h] }); + } + return out; +} + +/** A window's track, from the file its cues came from (videoCues.ts `file`): en-orig before en, then a transcript. */ +export function trackOfFile(file: string | undefined): WindowTrack { + if (!file) return "cues"; + if (file === "transcript.json") return "transcript"; + if (/\.en-orig\.vtt$/.test(file) || /\.en-[^.]+-orig\.vtt$/.test(file)) return "en-orig"; + if (/\.en(?:-[A-Za-z0-9]+)?\.vtt$/.test(file)) return "en"; + return "cues"; +} + +export type ScanOptions = { + /** Seconds either side of a hit (default 30). */ + W?: number; + /** The longest merged window, seconds (default 240). */ + maxSpan?: number; + /** Windows kept per recording, the rest counted as noise "capped" (default 40). */ + maxPerRecording?: number; +}; + +export type RecordingText = { + slug: string; + id: string; + /** YYYYMMDD. */ + date: string; + title: string; + url?: string; + duration?: number; + track: WindowTrack; + cues: readonly Cue[]; +}; + +/** A fresh counts record. */ +export function emptyCounts(): CandidateCounts { + return { + windows: 0, + videos: 0, + byFamily: {}, + byYear: {}, + byChannel: {}, + byGroup: {}, + byEra: {}, + titleHits: 0, + noise: { noSubject: 0, notStrict: 0, noGroup: 0, capped: 0 }, + scanned: { channels: 0, videos: 0, inEra: 0, withText: 0, noText: 0, undated: 0 }, + skipped: [], + }; +} + +const bump = (o: Record<string, number>, k: string, n = 1) => (o[k] = (o[k] ?? 0) + n); + +/** + * One recording's candidate windows, the noise filters applied and counted into `counts`: + * - a family's hits in the words, per era the recording is dated in, ±W s, merged; + * - a title hit marks every window of the recording, or is a window of its own (the first 2W seconds) when the + * words did not hit -- a garbled caption under a telling title is still a candidate; + * - noSubject: a window a coverage group would read that names no subject in its words or the title (for + * coverage, a mention of a subject at all is the bar); + * - notStrict: on a subject's own channel in an era with strictFamilies, a hit of another family makes no window; + * - noGroup: no reader group takes the window. + */ +export function recordingWindows(def: CaseDefinition, rec: RecordingText, counts: CandidateCounts, opts: ScanOptions = {}): CandidateWindow[] { + const W = opts.W ?? 30; + const maxSpan = opts.maxSpan ?? 240; + const cap = opts.maxPerRecording ?? 40; + const subject = subjectMatcher(def); + const own = subjectChannels(def).has(rec.slug); + const out: CandidateWindow[] = []; + let titled = false; + for (const era of erasOn(def, rec.date)) { + const families = Object.entries(era.families).map(([id, src]) => ({ id, re: compileFamily(era.id, id, src) })); + const titleFamilies = families.filter((f) => f.re.test(rec.title)).map((f) => f.id); + let hits = familyHits(rec.cues, families); + if (own && era.strictFamilies?.length) { + const strict = new Set(era.strictFamilies); + const kept = hits.filter((h) => strict.has(h.family)); + if (kept.length < hits.length && !kept.length) counts.noise.notStrict += 1; + hits = kept; + } + const spans = mergeHitWindows(hits, W, maxSpan, rec.duration ?? Infinity); + if (!spans.length && titleFamilies.length) spans.push({ from: 0, to: Math.min(rec.duration ?? 2 * W, 2 * W), hits: [] }); + if (titleFamilies.length && !titled) { + titled = true; + counts.titleHits += 1; + } + for (const s of spans) { + const group = groupFor(def, rec.slug, era.id); + if (!group) { + counts.noise.noGroup += 1; + continue; + } + const words = textBetween(rec.cues, s.from, s.to); + if (group.channels === "coverage" && subject && !subject.test(words) && !subject.test(rec.title)) { + counts.noise.noSubject += 1; + continue; + } + if (out.length >= cap) { + counts.noise.capped += 1; + continue; + } + out.push({ + key: `${rec.slug}/${rec.id}@${s.from}`, + slug: rec.slug, + id: rec.id, + date: day8(rec.date), + title: rec.title, + from: s.from, + to: s.to, + era: era.id, + group: group.id, + track: rec.track, + hits: s.hits, + ...(titleFamilies.length ? { titleHit: true, titleFamilies } : {}), + ...(rec.url ? { url: rec.url } : {}), + text: words, + }); + } + } + // One window per key: overlapping eras on the same second keep the first era's. + const seen = new Set<string>(); + const unique = out.filter((w) => (seen.has(w.key) ? false : (seen.add(w.key), true))); + if (unique.length) counts.videos += 1; + for (const w of unique) { + counts.windows += 1; + bump(counts.byYear, w.date.slice(0, 4)); + bump(counts.byChannel, w.slug); + bump(counts.byGroup, w.group); + bump(counts.byEra, w.era); + for (const f of new Set([...w.hits.map((h) => h.family), ...(w.titleFamilies ?? [])])) bump(counts.byFamily, f); + } + return unique; +} + +/** Windows in reading order: group (definition order), then date, channel, recording, second. */ +export function sortWindows(def: Pick<CaseDefinition, "groups">, windows: CandidateWindow[]): CandidateWindow[] { + const rank = new Map(def.groups.map((g, i) => [g.id, i])); + return [...windows].sort( + (a, b) => + (rank.get(a.group) ?? 999) - (rank.get(b.group) ?? 999) || + a.date.localeCompare(b.date) || + a.slug.localeCompare(b.slug) || + a.id.localeCompare(b.id) || + a.from - b.from, + ); +} + +// --------------------------------------------------------------------------------------------------------------- +// Batches, as wrapped text + +/** + * One line cut into lines of at most `max` characters, at spaces where it can and mid-word where a word alone is + * longer. The round-1 lesson: a reader's file tool truncates long lines, and the densest windows went missing + * without a word said. Every line a batch writes goes through here. + */ +export function wrapLine(line: string, max = BATCH_LINE_MAX, indent = ""): string[] { + if (max < 20) throw new Error("wrapLine: max is at least 20"); + const out: string[] = []; + let rest = line.replace(/\s+$/, ""); + let first = true; + while ([...rest].length > (first ? max : max - indent.length)) { + const room = first ? max : max - indent.length; + const chars = [...rest]; + let cut = chars.slice(0, room + 1).lastIndexOf(" "); + if (cut <= 0) cut = room; + out.push((first ? "" : indent) + chars.slice(0, cut).join("").replace(/\s+$/, "")); + rest = chars.slice(cut).join("").replace(/^\s+/, ""); + first = false; + } + if (rest || first) out.push((first ? "" : indent) + rest); + return out; +} + +/** Every line of `text` wrapped (wrapLine). */ +export const wrapText = (text: string, max = BATCH_LINE_MAX): string => + text + .split("\n") + .flatMap((l) => wrapLine(l, max)) + .join("\n"); + +/** The longest line of a text, in characters (the test of the batch rule). */ +export const longestLine = (text: string): number => Math.max(0, ...text.split("\n").map((l) => [...l].length)); + +const clockOf = (s: number) => { + const t = Math.max(0, Math.floor(s)); + const h = Math.floor(t / 3600); + const m = Math.floor((t % 3600) / 60); + const ss = String(t % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; +}; + +/** One window as a reader reads it: a head line, the title, the hits, the link, then the words. */ +export function windowBlock(w: CandidateWindow, n: number): string[] { + const lines = [ + `=== w${n} ${w.key}`, + `${dayDashed(w.date)} · ${w.slug}/${w.id} · ${clockOf(w.from)}–${clockOf(w.to)} · ${w.track} · era ${w.era}${w.titleHit ? " · title hit" : ""}`, + `title: ${w.title}`, + ]; + if (w.hits.length) lines.push(`hits: ${w.hits.map((h) => `${h.family} "${h.match}" @ ${clockOf(h.t)}`).join("; ")}`); + if (w.titleFamilies?.length) lines.push(`title families: ${w.titleFamilies.join(", ")}`); + const at = w.url ? platformMomentUrl(w.url, null, w.from) : null; + if (at) lines.push(`url: ${at}`); + lines.push("", w.text || "(no words in this window)", ""); + return lines; +} + +/** A batch's file: its head (id, group, round, the naming rule) and its windows, every line wrapped. */ +export function batchText(batch: Pick<CaseBatch, "id" | "group" | "round">, groupLabel: string, windows: CandidateWindow[]): string { + const head = [ + `# batch ${batch.id} · ${groupLabel} (${batch.group}) · round ${batch.round} · ${windows.length} ${windows.length === 1 ? "window" : "windows"}`, + `# ${NAMING_RULE}`, + `# Each window: a head line (=== w<n> <key>), the date, recording, span, track and era, the title, the hits,`, + `# the link, then the words. A finding names its window's key and the second it quotes.`, + "", + ]; + const body = windows.flatMap((w, i) => windowBlock(w, i + 1)); + return `${[...head, ...body].flatMap((l) => wrapLine(l)).join("\n").replace(/\n+$/, "")}\n`; +} + +/** + * Windows into batches per reader group, each batch's text under `budget` characters (a window longer than the + * budget is a batch of its own). `exclude` holds window keys a batch already read covers (they are never batched + * again), and `round` names the new batches. Ids are `<group>-<round>-<nnn>`. + */ +export function planBatches( + def: Pick<CaseDefinition, "groups">, + windows: CandidateWindow[], + o: { budget?: number; round: number; exclude?: ReadonlySet<string> }, +): { batches: CaseBatch[]; texts: Map<string, string> } { + const budget = o.budget ?? 60_000; + const labels = new Map(def.groups.map((g) => [g.id, g.label])); + const byGroup = new Map<string, CandidateWindow[]>(); + for (const w of sortWindows(def as CaseDefinition, windows)) { + if (o.exclude?.has(w.key)) continue; + if (!byGroup.has(w.group)) byGroup.set(w.group, []); + byGroup.get(w.group)!.push(w); + } + const batches: CaseBatch[] = []; + const texts = new Map<string, string>(); + for (const [group, ws] of byGroup) { + let n = 0; + let cur: CandidateWindow[] = []; + const flush = () => { + if (!cur.length) return; + const id = `${group}-${o.round}-${String(++n).padStart(3, "0")}`; + const body = batchText({ id, group, round: o.round }, labels.get(group) ?? group, cur); + batches.push({ id, group, round: o.round, windows: cur.map((w) => w.key), chars: body.length, file: `batches/${id}.txt`, state: "pending" }); + texts.set(id, body); + cur = []; + }; + let size = 0; + for (const w of ws) { + const add = windowBlock(w, cur.length + 1).join("\n").length + 1; + if (cur.length && size + add > budget) { + flush(); + size = 0; + } + cur.push(w); + size += add; + } + flush(); + } + return { batches, texts }; +} + +// --------------------------------------------------------------------------------------------------------------- +// Findings, checked + +const words = (s: string) => s.trim().split(/\s+/).filter(Boolean).length; + +/** + * A finding row as a reader (or a person) sent it, every field checked. `row` and `quoteCheck` are the store's to + * set when absent; a quote over QUOTE_WORDS_MAX words, a relevance outside 1–3, a missing field: refused, named. + */ +export function checkFindingRow(raw: unknown): { ok: true; row: Omit<FindingRow, "row"> & { row?: string } } | { ok: false; errors: string[] } { + const r = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>; + const errors: string[] = []; + const s = (k: string, max: number, required = true) => { + const v = r[k]; + if (typeof v !== "string" || (required && !v.trim())) { + if (required || (v !== undefined && typeof v !== "string")) errors.push(`${k} is text`); + return ""; + } + return v.trim().slice(0, max); + }; + const batch = s("batch", 80); + const slug = s("slug", 128); + const id = s("id", 128); + const date = day8(typeof r.date === "string" ? r.date : ""); + if (!date) errors.push("date is YYYYMMDD (or YYYY-MM-DD)"); + const title = s("title", 500, false); + const t = typeof r.t === "number" && Number.isFinite(r.t) && r.t >= 0 ? r.t : NaN; + if (Number.isNaN(t)) errors.push("t is a second (a number ≥ 0)"); + const url = s("url", 2000, false); + const category = s("category", 80); + if (!isRelevance(r.relevance)) errors.push("relevance is 1, 2 or 3"); + const quote = s("quote", 2000); + if (quote && words(quote) > QUOTE_WORDS_MAX) errors.push(`quote is at most ${QUOTE_WORDS_MAX} words (verbatim; this one has ${words(quote)})`); + const summary = s("summary", 1000, false); + const speaker = s("speaker", 200, false); + const confidence = r.confidence === undefined ? "medium" : r.confidence; + if (confidence !== "high" && confidence !== "medium" && confidence !== "low") errors.push("confidence is high, medium or low"); + const round = r.round === undefined ? 1 : r.round; + if (!Number.isInteger(round) || (round as number) < 1) errors.push("round is a whole number ≥ 1"); + if (!isFindingBy(r.by)) errors.push(`by is one of ${FINDING_BY.join(", ")}`); + const quoteCheck = r.quoteCheck === undefined ? "unchecked" : r.quoteCheck; + if (quoteCheck !== "found" && quoteCheck !== "not-found" && quoteCheck !== "unchecked") errors.push("quoteCheck is found, not-found or unchecked"); + let verify: FindingRow["verify"]; + if (r.verify !== undefined) { + const v = (r.verify && typeof r.verify === "object" ? r.verify : {}) as Record<string, unknown>; + if (!isVerifyStatus(v.status)) errors.push(`verify.status is one of ${VERIFY_STATUSES.join(", ")}`); + else verify = { ...(v as object), status: v.status, at: typeof v.at === "string" ? v.at.slice(0, 40) : "" } as FindingRow["verify"]; + } + const rowId = r.row === undefined ? undefined : typeof r.row === "string" && /^f\d{1,7}$/.test(r.row) ? r.row : (errors.push('row is "f<n>"'), undefined); + if (errors.length) return { ok: false, errors }; + return { + ok: true, + row: { + ...(rowId ? { row: rowId } : {}), + batch, + slug, + id, + date, + title, + t, + url, + category, + relevance: r.relevance as FindingRow["relevance"], + quote, + summary, + speaker, + confidence: confidence as FindingRow["confidence"], + round: round as number, + by: r.by as FindingRow["by"], + quoteCheck: quoteCheck as FindingRow["quoteCheck"], + ...(verify ? { verify } : {}), + ...(Array.isArray(r.evidence) ? { evidence: r.evidence as FindingRow["evidence"] } : {}), + }, + }; +} + +/** The text of a row the privacy gate reads: everything a person writes into it. */ +export const rowGateText = (r: Pick<FindingRow, "title" | "quote" | "summary" | "speaker" | "category"> & { verify?: FindingRow["verify"] }): string => + [r.title, r.quote, r.summary, r.speaker, r.category, r.verify?.note ?? "", r.verify?.original?.quote ?? ""].join("\n"); + +// --------------------------------------------------------------------------------------------------------------- +// Merge + +export type MergeSection = { group: string; label: string; rows: FindingRow[] }; + +export type MergeResult = { + sections: MergeSection[]; + /** First seen on a forum and not corroborated: their own section, whatever their group. */ + quarantined: FindingRow[]; + /** Below the relevance floor (kept out of the report, counted). */ + belowFloor: FindingRow[]; + /** A row folded into another: same recording, within MERGE_DEDUPE_SECONDS. */ + duplicates: { row: string; of: string }[]; + minRelevance: number; + total: number; +}; + +const rowNum = (r: FindingRow) => Number(/^f(\d+)$/.exec(r.row)?.[1] ?? 0); + +/** + * The merge (merge.py): rows on the same recording within `seconds` of a kept one are one finding -- the higher + * relevance kept, then the later round, then the earlier row. Then sections by reader group (definition order; + * a group the definition no longer has is its own section at the end), each in date and second order, at or above + * `minRelevance`; `quarantined` rows in their own section. + */ +export function mergeFindings( + def: Pick<CaseDefinition, "groups">, + rows: FindingRow[], + groupOfRow: (r: FindingRow) => string, + o: { minRelevance?: number; seconds?: number } = {}, +): MergeResult { + const min = o.minRelevance ?? MERGE_MIN_RELEVANCE; + const secs = o.seconds ?? MERGE_DEDUPE_SECONDS; + const priority = [...rows].sort((a, b) => b.relevance - a.relevance || b.round - a.round || rowNum(a) - rowNum(b)); + const kept: FindingRow[] = []; + const duplicates: MergeResult["duplicates"] = []; + const byVideo = new Map<string, FindingRow[]>(); + for (const r of priority) { + const k = `${r.slug}/${r.id}`; + const near = (byVideo.get(k) ?? []).find((x) => Math.abs(x.t - r.t) <= secs); + if (near) { + duplicates.push({ row: r.row, of: near.row }); + continue; + } + kept.push(r); + byVideo.set(k, [...(byVideo.get(k) ?? []), r]); + } + const order = (a: FindingRow, b: FindingRow) => a.date.localeCompare(b.date) || a.slug.localeCompare(b.slug) || a.id.localeCompare(b.id) || a.t - b.t; + const quarantined = kept.filter((r) => r.verify?.status === "quarantined").sort(order); + const rest = kept.filter((r) => r.verify?.status !== "quarantined"); + const belowFloor = rest.filter((r) => r.relevance < min).sort(order); + const shown = rest.filter((r) => r.relevance >= min); + const labels = new Map(def.groups.map((g) => [g.id, g.label])); + const groupIds = [...def.groups.map((g) => g.id)]; + for (const r of shown) if (!groupIds.includes(groupOfRow(r))) groupIds.push(groupOfRow(r)); + const sections = groupIds + .map((g) => ({ group: g, label: labels.get(g) ?? g, rows: shown.filter((r) => groupOfRow(r) === g).sort(order) })) + .filter((s) => s.rows.length); + return { sections, quarantined, belowFloor, duplicates: duplicates.sort((a, b) => a.row.localeCompare(b.row)), minRelevance: min, total: rows.length }; +} + +// --------------------------------------------------------------------------------------------------------------- +// The report: cited markdown in the house format (umtool board.mjs exportMarkdown's shape, so it converts as a +// /sweep report and seeds an article), and the same as one HTML page + +const clean = (s: string) => String(s ?? "").replace(/\s+/g, " ").trim(); +const noQuotes = (s: string) => clean(s).replace(/["“”]/g, "'"); + +/** A row's link, at its second. */ +export function findingLink(r: Pick<FindingRow, "url" | "title" | "t">): string { + const label = `${clean(r.title || "recording").replace(/[[\]]/g, "")} @ ${clockOf(r.t)}`; + const url = r.url ? (/[?&](t|start)=/.test(r.url) ? r.url : (platformMomentUrl(r.url, null, r.t) ?? r.url)) : ""; + return url ? `[${label}](${url})` : label; +} + +/** One finding, the board's way: claim (the row's summary), "quote" — link; our note under it. */ +export function findingLine(r: FindingRow): string { + const claim = noQuotes(r.summary).replace(/[.:;,\s]+$/, ""); + const lines = [`- ${claim ? `${claim}: ` : ""}"${noQuotes(r.quote)}" — ${findingLink(r)}`]; + const asides = [`${clean(r.category)}, relevance ${r.relevance}`]; + if (clean(r.speaker)) asides.push(`speaker ${noQuotes(r.speaker)}`); + asides.push(`row ${r.row}`); + if (r.quoteCheck === "not-found") asides.push("quote not found in the window's captions: check it"); + if (r.verify && r.verify.status !== "unverified") asides.push(r.verify.status); + for (const e of r.evidence ?? []) if (e.kind === "forum-attachment") asides.push(`forum attachment${e.post ? `, post #${e.post}` : ""}, unverified`); + lines.push(` Note: ${asides.join(". ")}.`); + return lines.join("\n"); +} + +export type ReportContext = { + title: string; + summary: CaseSummaryText | null; + merged: MergeResult; + /** One line on what was read: the scope, the candidates, the batches. */ + coverage: string; +}; + +/** The merged report as cited markdown. */ +export function reportMarkdown(c: ReportContext): string { + const out = [`# ${clean(c.title)}`, ""]; + if (c.summary?.text.trim()) { + if (c.summary.draft) out.push(`Draft summary, by ${c.summary.model ?? c.summary.by}: not yet reviewed.`, ""); + out.push(c.summary.text.trim().replace(/^#+\s*/gm, ""), ""); + } + const shown = c.merged.sections.reduce((n, s) => n + s.rows.length, 0); + const recordings = new Set([...c.merged.sections.flatMap((s) => s.rows), ...c.merged.quarantined].map((r) => `${r.slug}/${r.id}`)); + out.push( + `${shown} ${shown === 1 ? "finding" : "findings"} from ${recordings.size} ${recordings.size === 1 ? "recording" : "recordings"}, merged from ${c.merged.total} ${c.merged.total === 1 ? "row" : "rows"} ` + + `(relevance ${c.merged.minRelevance} and up; ${c.merged.duplicates.length} folded as duplicates, ${c.merged.belowFloor.length} below the floor). The quotes are verbatim; the summaries are the readers'.`, + "", + ); + for (const s of c.merged.sections) { + out.push(`## ${clean(s.label)}`, ""); + for (const r of s.rows) out.push(findingLine(r)); + out.push(""); + } + if (c.merged.quarantined.length) { + out.push("## Quarantined", "", "First seen on a forum and not corroborated by an independent source: not evidence until something else says so.", ""); + for (const r of c.merged.quarantined) out.push(findingLine(r)); + out.push(""); + } + out.push("## Coverage", "", clean(c.coverage), ""); + return out.join("\n"); +} + +const escHtml = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"); + +/** Inline markdown of the report (links only) as HTML. */ +function inline(s: string): string { + const parts = s.split(/(\[[^\]]*\]\([^)\s]+\))/); + return parts + .map((p) => { + const m = /^\[([^\]]*)\]\(([^)\s]+)\)$/.exec(p); + if (!m) return escHtml(p); + const href = /^https?:\/\//.test(m[2]) ? m[2] : "#"; + return `<a href="${escHtml(href)}">${escHtml(m[1])}</a>`; + }) + .join(""); +} + +/** The report's markdown as one standalone HTML page (no script, no remote asset). */ +export function reportHtml(markdown: string): string { + const lines = markdown.split("\n"); + const body: string[] = []; + let title = "Report"; + let inList = false; + const close = () => { + if (inList) body.push("</ul>"); + inList = false; + }; + for (let i = 0; i < lines.length; i++) { + const l = lines[i]; + if (/^# /.test(l)) { + close(); + title = l.slice(2).trim(); + body.push(`<h1>${inline(title)}</h1>`); + } else if (/^## /.test(l)) { + close(); + body.push(`<h2>${inline(l.slice(3).trim())}</h2>`); + } else if (/^- /.test(l)) { + if (!inList) body.push("<ul>"); + inList = true; + let item = inline(l.slice(2)); + while (lines[i + 1]?.startsWith(" ")) item += `<br><span class="note">${inline(lines[++i].trim())}</span>`; + body.push(`<li>${item}</li>`); + } else if (l.trim()) { + close(); + body.push(`<p>${inline(l.trim())}</p>`); + } else close(); + } + close(); + return [ + "<!doctype html>", + '<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">', + `<title>${escHtml(title)}</title>`, + "<style>body{font:16px/1.5 system-ui,sans-serif;max-width:46rem;margin:2rem auto;padding:0 1rem;color:#1d1d1b;background:#fbfaf7}" + + "h1{font-size:1.6rem}h2{font-size:1.15rem;margin-top:2rem;border-bottom:1px solid #ddd}li{margin:.6rem 0}.note{color:#666;font-size:.88rem}" + + "a{color:#2b5797}@media (prefers-color-scheme:dark){body{background:#161614;color:#e9e7e1}.note{color:#a3a09a}a{color:#8fb3e8}}</style>", + "</head><body>", + ...body, + "</body></html>", + "", + ].join("\n"); +} + +// --------------------------------------------------------------------------------------------------------------- +// Date checks (stage 9) + +export type DatedUpload = { slug: string; id: string; date: string; title: string; captioned: boolean }; + +/** + * The subject's uploads around each key date (±`aroundDays`) and the latest `latest` after it, as a table, with the + * sentence: a response is a finding (relevance ≥ 2, not quarantined) on a subject's own channel dated on or after + * the key date; with none, "no response found in captioned uploads through <the last captioned upload's date>". + */ +export function dateChecks( + def: Pick<CaseDefinition, "keyDates" | "eras" | "subjects">, + uploads: DatedUpload[], + findings: Pick<FindingRow, "row" | "slug" | "date" | "relevance" | "verify">[], + o: { aroundDays?: number; latest?: number } = {}, +): DateCheck[] { + const around = o.aroundDays ?? 14; + const latest = o.latest ?? 10; + const keys = def.keyDates?.length ? def.keyDates : def.eras.map((e) => ({ date: e.from, label: `${e.id} begins` })); + const own = subjectChannels(def); + const ms = (d: string) => Date.UTC(Number(d.slice(0, 4)), Number(d.slice(4, 6)) - 1, Number(d.slice(6, 8))); + const sorted = [...uploads].filter((u) => day8(u.date)).sort((a, b) => day8(a.date).localeCompare(day8(b.date)) || a.id.localeCompare(b.id)); + return keys.map((k) => { + const d = day8(k.date); + const near = sorted.filter((u) => Math.abs(ms(day8(u.date)) - ms(d)) <= around * 86_400_000); + const after = sorted.filter((u) => day8(u.date) >= d).slice(-latest); + const pick = new Map<string, DatedUpload>(); + for (const u of [...near, ...after]) pick.set(`${u.slug}/${u.id}`, u); + const rows = [...pick.values()].sort((a, b) => day8(a.date).localeCompare(day8(b.date)) || a.id.localeCompare(b.id)); + const responses = findings.filter((f) => own.has(f.slug) && day8(f.date) >= d && f.relevance >= 2 && f.verify?.status !== "quarantined"); + const captionedAfter = sorted.filter((u) => u.captioned && day8(u.date) >= d); + let sentence: string; + if (!own.size) sentence = "the case names no channel of the subject's own: nothing to check"; + else if (responses.length) { + const dates = responses.map((f) => day8(f.date)).sort(); + sentence = `response found: ${responses.length} ${responses.length === 1 ? "finding" : "findings"} in uploads from ${dayDashed(dates[0])} to ${dayDashed(dates.at(-1)!)} (rows ${responses.map((f) => f.row).join(", ")})`; + } else if (captionedAfter.length) sentence = `no response found in captioned uploads through ${dayDashed(captionedAfter.at(-1)!.date)}`; + else sentence = `no captioned upload on or after ${dayDashed(d)}: nothing to check yet`; + return { + date: dayDashed(d), + label: k.label, + uploads: rows.map((u) => ({ slug: u.slug, id: u.id, date: day8(u.date), title: u.title, captioned: u.captioned })), + sentence, + }; + }); +} + +export { WINDOW_TRACKS }; diff --git a/common/lib/research/casePrivacy-server.ts b/common/lib/research/casePrivacy-server.ts @@ -0,0 +1,49 @@ +// THE PRIVACY GATE (plans/release-38/research-cases-and-assist.md, stage 6; "Private names are stored as hashes"). +// +// Every write of findings, of the summary, of an export and of a hand-off is scanned against the case's +// `privateNames.sha256` (privateNames-server.ts privateNameHits: every word and 2- and 3-word phrase hashed and +// compared). A hit blocks the write. What it says is COUNTS AND ROW IDS: never the term, never the phrase that +// 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"; + +export type GateItem = { id: string; text: string }; +export type GateResult = { blocked: boolean; hits: number; rows: { id: string; hits: number }[] }; + +/** Scan each item; `rows` names the items with a hit and how many, in the order given. */ +export function privacyGate(items: readonly GateItem[], hashes: readonly string[]): GateResult { + if (!hashes.length) return { blocked: false, hits: 0, rows: [] }; + const rows: GateResult["rows"] = []; + let hits = 0; + for (const it of items) { + const n = privateNameHits(it.text, hashes); + if (!n) continue; + hits += n; + rows.push({ id: it.id, hits: n }); + } + return { blocked: rows.length > 0, hits, rows }; +} + +/** A write the gate refused. `status` 409: the content is what has to change. */ +export class PrivacyBlocked extends Error { + readonly status = 409; + constructor( + readonly what: string, + readonly result: GateResult, + ) { + const ids = result.rows.slice(0, 50).map((r) => r.id); + super( + `the privacy gate blocked ${what}: ${result.hits} private-name ${result.hits === 1 ? "hit" : "hits"} in ` + + `${result.rows.length} ${result.rows.length === 1 ? "item" : "items"} (${ids.join(", ")}${result.rows.length > ids.length ? ", …" : ""}). ` + + `Write [name withheld] in their place and try again.`, + ); + this.name = "PrivacyBlocked"; + } +} + +/** Throw PrivacyBlocked when any item hits. */ +export function assertNoPrivateNames(what: string, items: readonly GateItem[], hashes: readonly string[]): void { + const r = privacyGate(items, hashes); + if (r.blocked) throw new PrivacyBlocked(what, r); +} diff --git a/common/lib/research/caseStore-server.ts b/common/lib/research/caseStore-server.ts @@ -0,0 +1,372 @@ +// 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/<case>/, 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 } from "./casePipeline"; +import { assertNoPrivateNames } from "./casePrivacy-server"; + +const file = (dir: string, name: string) => path.join(/* turbopackIgnore: true */ dir, name); + +async function readText(p: string): Promise<string | null> { + try { + return await readFile(/* turbopackIgnore: true */ p, "utf8"); + } catch (e) { + if ((e as NodeJS.ErrnoException).code === "ENOENT") return null; + throw e; + } +} + +async function readJsonFile<T>(p: string): Promise<T | null> { + 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<void> { + await mkdir(/* turbopackIgnore: true */ path.dirname(p), { recursive: true }); + const tmp = `${p}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`; + 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<T>(lockPath: string, fn: () => Promise<T>): Promise<T> { + 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<CaseDefinition | null> { + const raw = await readJsonFile<unknown>(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<CaseDefinition> { + 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<CaseDefinition> { + 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<CoverageRow[]>(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<DateCheck[]>(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<void> { + 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<CandidateWindow[]> { + 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<CandidateCounts>(file(dir, CASE_FILES.candidateCounts)); + +// ── stage 3: batches ── + +export const readBatches = async (dir: string) => (await readJsonFile<CaseBatch[]>(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<string> { + 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) await writeAtomic(file(dir, b.file), texts.get(b.id)!); + 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<CaseBatch> { + 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<FindingsRead> { + 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<string>(); + 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<n>`, the lot gated. Answers the rows as written. + */ +export async function appendFindings(dir: string, raws: unknown[], hashes: readonly string[]): Promise<FindingRow[]> { + 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<void> { + 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<CaseSummaryText>(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<CaseSummaryText, "at">, hashes: readonly string[], now = new Date()): Promise<CaseSummaryText> { + 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<void> { + 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<CaseStageRuns> { + const s = (await readJsonFile<CaseStageRuns>(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<void> { + await withFileLock(file(dir, `${CASE_FILES.stages}.lock`), async () => { + const cur = (await readJsonFile<CaseStageRuns>(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<T>( + dir: string, + stage: CaseStage, + by: CaseStageRun["by"], + fn: (log: (line: string) => void) => Promise<{ result: T; counts?: Record<string, number> }>, +): Promise<T> { + 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; + } +} diff --git a/common/lib/research/caseStore.test.ts b/common/lib/research/caseStore.test.ts @@ -0,0 +1,180 @@ +// 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 } from "./casePrivacy-server"; +import { + appendFindings, + readBatchText, + readBatches, + readDefinition, + readFindings, + readStages, + rebuildBatches, + runStage, + saveDefinition, + setBatchState, + writeReport, + writeSummary, +} from "./caseStore-server"; +import { 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<string, unknown> = {}) => ({ + 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`, "<p></p>", 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", "<p>R</p>", 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"); +}); diff --git a/common/lib/research/caseTypes.ts b/common/lib/research/caseTypes.ts @@ -11,11 +11,15 @@ // <case>/pipeline.json CaseDefinition (subjects, scope, eras, reader groups, private-name hashes) // <case>/coverage.json CoverageRow[] (stage 1) // <case>/candidates.jsonl CandidateWindow, one per line (stage 2) +// <case>/candidates.counts.json CandidateCounts: per family, year, channel, group, before any read (stage 2) // <case>/batches/index.json CaseBatch[] (stage 3) // <case>/batches/<batch>.txt the batch's WRAPPED text: no line over BATCH_LINE_MAX (stage 3) // <case>/findings.jsonl FindingRow, one per line, appended (stage 4; verify and merge rewrite whole) // <case>/leads.json CaseLead[] (stage 8) // <case>/date-checks.json DateCheck[] (stage 9) +// <case>/summary.json CaseSummaryText: the report's summary, by hand or a model's draft (stage 5) +// <case>/REPORT.md, REPORT.html the merged report as exported (stage 5, behind the privacy gate) +// <case>/stages.json CaseStageRuns: each stage's last run (state, counts, log), CLI or page // // PRIVATE NAMES ARE NEVER TEXT. A case's private terms are stored as `privateNames.sha256` (privateNameHash of // each term, privateNames-server.ts), so no file holds them. The gate hashes every word and every 2- and 3-word phrase of what it checks @@ -28,11 +32,16 @@ export const CASE_FILES = Object.freeze({ definition: "pipeline.json", coverage: "coverage.json", candidates: "candidates.jsonl", + candidateCounts: "candidates.counts.json", batchDir: "batches", batchIndex: "batches/index.json", findings: "findings.jsonl", leads: "leads.json", dateChecks: "date-checks.json", + summary: "summary.json", + report: "REPORT.md", + reportHtml: "REPORT.html", + stages: "stages.json", } as const); /** A batch file's longest line. A reader's file tool truncates long lines and drops the densest windows silently. */ @@ -50,13 +59,30 @@ export const NAME_WITHHELD = "[name withheld]"; // --------------------------------------------------------------------------------------------------------------- // The definition -export type CaseSubject = { name: string; aliases: string[] }; +/** + * `channels` (lane A): the subject's OWN channel slugs -- what a "subject" reader group reads and what the date + * checks (stage 9) list uploads from. Absent: the subject has no channel in the corpus. + */ +export type CaseSubject = { name: string; aliases: string[]; channels?: string[] }; /** What the case reads: channel slugs, channel groups, sites. */ export type CasePipelineScope = { channels: string[]; groups: string[]; sites: string[] }; /** A period of the subject's life with its own vocabulary. `families` maps a family id to a regex SOURCE (flags "iu"). */ -export type CaseEra = { id: string; from: string; to: string; families: Record<string, string> }; +export type CaseEra = { + id: string; + from: string; + to: string; + families: Record<string, string>; + /** + * Lane A, the noise filter for a subject's own late material: on the subject's own channels in this era, only + * these families make a window (the others still count, as noise). Absent: every family does. + */ + strictFamilies?: string[]; +}; + +/** Lane A, stage 9: a date the case turns on (YYYY-MM-DD), checked for the subject's uploads around and after it. */ +export type CaseKeyDate = { date: string; label: string }; /** * A reader group: who reads which windows, with which prompt. `channels` is a list of slugs, or "subject" (the @@ -86,6 +112,8 @@ export type CaseDefinition = { privateNames: PrivateNames; /** `common` goes before every group's own prompt; keyed by group id otherwise. */ readerPrompts: { common: string } & Record<string, string>; + /** Stage 9's dates. Absent or empty: each era's start. */ + keyDates?: CaseKeyDate[]; status: CaseStatus; createdAt: string; updatedAt: string; @@ -96,6 +124,7 @@ export type CaseDefinition = { export type CoverageRow = { channel: string; + /** 0: the listed videos nothing dates (never fetched, never scanned) -- counted, never guessed into a year. */ year: number; listed: number; held: number; @@ -131,10 +160,35 @@ export type CandidateWindow = { hits: CandidateHit[]; /** A family matched the title rather than (or as well as) the words. */ titleHit?: boolean; + /** Lane A: which families matched the title (a title hit has no second to put in `hits`). */ + titleFamilies?: string[]; + /** Lane A: the recording's own page (no time in it); a batch prints it at the window's start. */ + url?: string; /** The window's caption text after rolling-caption dedupe: what a reader reads and the quote check checks. */ text: string; }; +/** Lane A: what a candidate scan counted, before any read. Every number is windows unless it says otherwise. */ +export type CandidateCounts = { + windows: number; + videos: number; + byFamily: Record<string, number>; + byYear: Record<string, number>; + byChannel: Record<string, number>; + byGroup: Record<string, number>; + byEra: Record<string, number>; + /** Recordings whose title a family matched. */ + titleHits: number; + /** Dropped by a noise filter, by filter: noSubject (a coverage window naming no subject), notStrict (a subject's + * own window in a strict era with no strict family), noGroup (no reader group takes it), capped (past the + * per-recording cap). */ + noise: Record<string, number>; + /** Recordings: in scope, dated inside an era, with text to read, and without (still to download or transcribe). */ + scanned: { channels: number; videos: number; inEra: number; withText: number; noText: number; undated: number }; + /** Channels left out, with why (a drive not answering, a social channel, not in the corpus). */ + skipped: { slug: string; reason: string }[]; +}; + // --------------------------------------------------------------------------------------------------------------- // Stage 3: batches @@ -211,6 +265,34 @@ export type FindingRow = { }; // --------------------------------------------------------------------------------------------------------------- +// Stage 5: the summary on top of the merged report (lane A) + +/** Written by hand, or a model's draft -- a draft says so in the report until a person saves it as theirs. */ +export type CaseSummaryText = { text: string; draft: boolean; by: FindingBy; model?: string; at: string }; + +// --------------------------------------------------------------------------------------------------------------- +// Each stage's last run (lane A): the page and the CLI both record here, so either sees the other's run. + +export const CASE_STAGES = ["coverage", "candidates", "batches", "merge", "export", "handoff", "date-checks"] as const; +export type CaseStage = (typeof CASE_STAGES)[number]; + +export type CaseStageRun = { + state: "running" | "done" | "failed"; + startedAt: string; + endedAt?: string; + /** The process that ran it ("umtool" or "cli") and its pid: a "running" whose pid is gone was interrupted. */ + by: "umtool" | "cli"; + pid: number; + /** One line each; never a private name (the gate's own lines are counts and row ids). */ + log: string[]; + error?: string; + /** What it made, as counts. */ + counts?: Record<string, number>; +}; + +export type CaseStageRuns = Partial<Record<CaseStage, CaseStageRun>>; + +// --------------------------------------------------------------------------------------------------------------- // Stage 8: leads; stage 9: absence and date checks export const LEAD_DISPOSITIONS = ["archive", "watch", "never-archive"] as const; @@ -252,6 +334,7 @@ export const isVerifyStatus = isOneOf(VERIFY_STATUSES); export const isLeadDisposition = isOneOf(LEAD_DISPOSITIONS); export const isFindingBy = isOneOf(FINDING_BY); export const isCaseStatus = isOneOf(CASE_STATUSES); +export const isCaseStage = isOneOf(CASE_STAGES); export const isRelevance = (value: unknown): value is Relevance => value === 1 || value === 2 || value === 3; /** A term's words NFKC-normalised, lowercased and single-spaced: what privateNameHash hashes. */