Archilyzer · Source

archilyzer

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

commit a31fe3df8080609dbc0f80e26cab634b87640878
parent 890399339545adcdf093f5dba343003bd9487d6f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 05:26:27 -0500

Merge r38/case-pipeline: research cases as a pipeline beside the board (release 38 lane A) -- coverage per channel and year with gap actions through the editor's ops, candidate windows by era and term family, wrapped batches per reader group, merge with dedupe and sections, the privacy gate over every write and export (private names as sha256 only, withheld from stored windows and batches), date checks; umtool /research/<case>/pipeline and `archilyzer case` (editor/CHANGELOG bullets both kept)

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

Diffstat:
MCOMMANDS.md | 13+++++++++++++
MENVIRONMENT.md | 4++--
Mcommon/bin/archilyzer.ts | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/case.test.ts | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/bin/case.ts | 264+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/caseCorpus.test.ts | 132+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/caseCorpus.ts | 308+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/casePipelineRun.ts | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 4++--
Acommon/lib/research/casePipeline.test.ts | 304+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/research/casePipeline.ts | 980+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/research/casePrivacy-server.ts | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/research/caseStore-server.ts | 428+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/research/caseStore.test.ts | 211+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/research/caseTypes.ts | 102+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Meditor/CHANGELOG.md | 1+
Aumtool/app/api/research/cases/[id]/pipeline/[op]/route.ts | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/research/cases/[id]/pipeline/route.ts | 32++++++++++++++++++++++++++++++++
Aumtool/app/research/[case]/pipeline/page.tsx | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/research/BoardView.tsx | 10++++++++++
Aumtool/components/research/CasePipeline.tsx | 775+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/research.md | 37++++++++++++++++++++++++++++++++++++-
Aumtool/e2e/case-pipeline.spec.ts | 228+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/fixtures/case-fixture.mjs | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/editor-stub.mjs | 22++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Mumtool/lib/research/boards.ts | 4++++
Aumtool/lib/research/case-private.ts | 30++++++++++++++++++++++++++++++
Mumtool/lib/research/handoff.ts | 6++++++
Mumtool/lib/research/hrefs.ts | 8++++++++
Aumtool/lib/research/pipeline-types.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/pipeline.ts | 395+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
32 files changed, 5031 insertions(+), 9 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/ENVIRONMENT.md b/ENVIRONMENT.md @@ -91,8 +91,8 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `NITTER_INSTANCES` | a built-in list | Comma-separated Nitter instances for the X fallback fetcher, in order of preference. | common/social/xNitterFetcher.ts | | `ARCHILYZER_X_BROWSER` | the first of `chromium`, `google-chrome`, `google-chrome-stable`, `chrome` on PATH, else Playwright's bundled Chromium | The Chromium-family browser /settings' "Connect X account" opens (a path, or a name looked up on PATH), and a forum-thread channel's "Connect forum session" too. It is launched without the automation signals, in the X session profile (or the forum host's profile); a value that is not an executable refuses the connect rather than opening another browser. | common/social/xBrowser.ts | | `UMTOOL_MEDIA_DIR` | unset (no media root: a project link's target is kept) | umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md). | common/lib/report/delete.ts, umtool (lib/paths.mjs) | -| `REPORTS_DIR` | `~/reports` (or the parent of `SONG_REPORTS_DIR`) | umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete. | common/lib/report/delete.ts, umtool (lib/paths.mjs) | -| `SONG_REPORTS_DIR` | unset | umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete reads (as umtool does). | common/lib/report/delete.ts, umtool (song/paths.mjs) | +| `REPORTS_DIR` | `~/reports` (or the parent of `SONG_REPORTS_DIR`) | umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete. | common/lib/report/delete.ts, common/bin/case.ts, umtool (lib/paths.mjs) | +| `SONG_REPORTS_DIR` | unset | umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete and `archilyzer case` read (as umtool does). | common/lib/report/delete.ts, common/bin/case.ts, umtool (song/paths.mjs) | | `UMTOOL_URL` | unset (no link; the MCP's `notes` off) | umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled. | editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts | | `TRANSCRIPT_SITE_URL` | — | MCP server: one published archive to read over HTTP. | mcp/src/sources.ts | | `TRANSCRIPT_HUB_URL` | — | MCP server: a hub, federating every archive it lists. | mcp/src/sources.ts | 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 \(f2\)/); + 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,264 @@ +// `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, + withholdStored, + 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 n = (k: number, w: string) => `${k} ${w}${k === 1 ? "" : "s"}`; + +const out = (json: boolean, value: unknown, text: () => string) => { + console.log(json ? JSON.stringify(value, null, 2) : text()); + return 0; +}; + +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: ${n(view.subjects.length, "subject")}, eras ${view.eras.join(", ") || "none"}, groups ${view.groups.join(", ") || "none"}, ${n(view.privateNames, "private name")} (hashed); status ${view.status}` : "not defined yet (archilyzer case define <case> --file pipeline.json)", + `coverage: ${view.coverage} channel-years · candidates: ${view.candidates ?? "not built"} · batches: ${view.batches.total} (${view.batches.pending} pending, ${view.batches.read} read) · findings: ${view.findings.rows}${view.findings.invalid ? ` (${view.findings.invalid} lines do not check)` : ""} · summary: ${summary ? (summary.draft ? "a draft" : "written") : "none"}`, + ...Object.entries(stages).map(([k, s]) => ` ${k}: ${s?.state} ${s?.endedAt ?? s?.startedAt} (${s?.by})${s?.error ? ` — ${s.error}` : ""}`), + ].join("\n"), + ); + } + 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}: ${n(def.subjects.length, "subject")}, ${n(def.eras.length, "era")}, ${n(def.groups.length, "group")} saved (${CASE_FILES.definition}); ${n(def.privateNames.sha256.length, "private name")} kept`); + } + case "private-names": { + const op = positionals[1]; + if (op !== "add" && op !== "remove" && op !== "clear" && op !== "count") throw new CasePipelineError("private-names takes add, remove, clear or count (terms on stdin)"); + if (op === "count") { + const def = await readDefinition(c.dir, c.id); + return out(json, { count: def?.privateNames.sha256.length ?? 0 }, () => `${n(def?.privateNames.sha256.length ?? 0, "private name")} (hashed)`); + } + const terms = op === "clear" ? [] : (await readStdin()).split("\n").map((t) => t.trim()).filter(Boolean); + for (const [i, t] of terms.entries()) { + 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), + ); + // A name added after the candidates and batches were written is withheld from them now. + const withheld = op === "add" ? await withholdStored(c.dir, def.privateNames.sha256) : 0; + return out(json, { changed, count: def.privateNames.sha256.length, withheld }, () => + `${op === "add" ? "added" : "removed"} ${changed}; ${n(def.privateNames.sha256.length, "private name")} (hashed)${withheld ? `; withheld in ${n(withheld, "place")} of the candidates and batches` : ""}`, + ); + } + case "prompt": { + const def = await readDefinition(c.dir, c.id); + 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, () => + [ + `${n(k.windows, "window")} in ${n(k.videos, "recording")} (${n(k.titleHits, "title hit")}) → ${CASE_FILES.candidates}`, + `by family: ${Object.entries(k.byFamily).map(([f, n]) => `${f} ${n}`).join(", ") || "none"}`, + `by year: ${Object.entries(k.byYear).map(([y, n]) => `${y} ${n}`).join(", ") || "none"}`, + `by channel: ${Object.entries(k.byChannel).map(([s, n]) => `${s} ${n}`).join(", ") || "none"}`, + `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${n(b.windows.length, "window")}\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}: ${n(d.uploads.length, "upload")} — ${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,180 @@ +// 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, + rowGateText, + type MergeResult, + type ScanOptions, +} from "../lib/research/casePipeline"; +import { + readBatches, + readCandidateCounts, + readCandidates, + readDefinition, + readFindings, + readSummary, + rebuildBatches, + runStage, + withholdWindow, + writeCandidates, + writeCoverage, + writeDateChecks, + writeReport, +} from "../lib/research/caseStore-server"; +import { assertNoPrivateNames } from "../lib/research/casePrivacy-server"; +import { caseCandidates, caseChannels, caseCoverage, subjectUploads } from "./caseCorpus"; + +type By = CaseStageRun["by"]; + +const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? "" : "s"}`; + +async function definitionOf(dir: string, caseId: string): Promise<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); + // The case's private names never sit in its files: withheld from the windows' words before they are written. + let withheld = 0; + r.windows = r.windows.map((w) => { + const x = withholdWindow(w, def.privateNames.sha256); + withheld += x.replaced; + return x.window; + }); + if (withheld) log(`${withheld} private ${withheld === 1 ? "name" : "names"} withheld in the windows' words`); + await writeCandidates(dir, r.windows, r.counts); + log(`${r.counts.windows} ${r.counts.windows === 1 ? "window" : "windows"} in ${r.counts.videos} ${r.counts.videos === 1 ? "recording" : "recordings"}`); + return { + result: r, + counts: { windows: r.counts.windows, recordings: r.counts.videos, titleHits: r.counts.titleHits, noise: Object.values(r.counts.noise).reduce((a, b) => a + b, 0), noText: r.counts.scanned.noText }, + }; + }); +} + +export async function runBatches(dir: string, caseId: string, by: By, o: { budget?: number } = {}) { + const def = await definitionOf(dir, caseId); + return runStage(dir, "batches", by, async (log) => { + const windows = await readCandidates(dir); + if (!windows.length) throw new CasePipelineError("no candidate windows: build the candidates first", 409); + const r = await rebuildBatches(dir, def, windows, o); + log(`round ${r.round}: ${r.made.length} new ${r.made.length === 1 ? "batch" : "batches"}; ${r.kept.length} kept (a reader's work)`); + return { result: r, counts: { batches: r.batches.length, made: r.made.length, kept: r.kept.length, round: r.round } }; + }); +} + +/** Which group a row belongs to: its batch's, else the group its channel and date would be read by. */ +export function rowGroup(def: CaseDefinition, batches: CaseBatch[]): (r: FindingRow) => string { + const byBatch = new Map(batches.map((b) => [b.id, b.group])); + return (r) => byBatch.get(r.batch) ?? groupFor(def, r.slug, def.eras.find((e) => e.from.replace(/-/g, "") <= r.date && r.date <= e.to.replace(/-/g, ""))?.id ?? "")?.id ?? "unsorted"; +} + +export type MergeView = MergeResult & { invalid: { line: number; errors: string[] }[] }; + +/** The merge as a preview: what the report would hold, nothing written. */ +export async function mergeView(dir: string, caseId: string, o: { minRelevance?: number } = {}): Promise<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; the noise filters dropped ${plural(counts.noise.noSubject + counts.noise.noGroup + counts.noise.capped, "window")} and ${plural(counts.noise.notStrict, "hit")}.` + : "No candidate scan is recorded.", + `Batches: ${batches.length}, ${read} read.`, + ].join(" "); +} + +/** REPORT.md and REPORT.html from the merge and the summary, behind the privacy gate. */ +export async function runExport(dir: string, caseId: string, title: string, by: By, o: { minRelevance?: number; paths?: Paths } = {}) { + const def = await definitionOf(dir, caseId); + return runStage(dir, "export", by, async (log) => { + const merged = await mergeView(dir, caseId, o); + if (merged.invalid.length) log(`${merged.invalid.length} findings ${merged.invalid.length === 1 ? "line does" : "lines do"} not check (lines ${merged.invalid.map((x) => x.line).join(", ")}): left out`); + const summary = await readSummary(dir); + // The gate names the rows first (counts and row ids); the whole markdown is checked again as it is written. + assertNoPrivateNames( + "the export", + [ + ...[...merged.sections.flatMap((x) => x.rows), ...merged.quarantined].map((r) => ({ id: r.row, text: rowGateText(r) })), + { id: "summary", text: summary?.text ?? "" }, + { id: "title", text: title }, + ], + def.privateNames.sha256, + ); + 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/envVars.ts b/common/lib/envVars.ts @@ -127,8 +127,8 @@ const DECLARED: EnvVarDecl[] = [ { name: "NITTER_INSTANCES", audience: "runtime", default: "a built-in list", readBy: "common/social/xNitterFetcher.ts", doc: "Comma-separated Nitter instances for the X fallback fetcher, in order of preference." }, { name: "ARCHILYZER_X_BROWSER", audience: "runtime", default: "the first of `chromium`, `google-chrome`, `google-chrome-stable`, `chrome` on PATH, else Playwright's bundled Chromium", readBy: "common/social/xBrowser.ts", doc: "The Chromium-family browser /settings' \"Connect X account\" opens (a path, or a name looked up on PATH), and a forum-thread channel's \"Connect forum session\" too. It is launched without the automation signals, in the X session profile (or the forum host's profile); a value that is not an executable refuses the connect rather than opening another browser." }, { name: "UMTOOL_MEDIA_DIR", audience: "runtime", default: "unset (no media root: a project link's target is kept)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md)." }, - { name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." }, - { name: "SONG_REPORTS_DIR", audience: "runtime", default: "unset", readBy: "common/lib/report/delete.ts, umtool (song/paths.mjs)", doc: "umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete reads (as umtool does)." }, + { name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, common/bin/case.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." }, + { name: "SONG_REPORTS_DIR", audience: "runtime", default: "unset", readBy: "common/lib/report/delete.ts, common/bin/case.ts, umtool (song/paths.mjs)", doc: "umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete and `archilyzer case` read (as umtool does)." }, { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled." }, { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP." }, { name: "TRANSCRIPT_HUB_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a hub, federating every archive it lists." }, 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,980 @@ +// 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 + * (counted as hits, not windows); + * - 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)); + counts.noise.notStrict += hits.length - kept.length; + 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,90 @@ +// 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 { NAME_WITHHELD, normalizeTerm, stripPossessive } from "./caseTypes"; +import { privateNameHash, privateNameHits } from "./privateNames-server"; + +export type GateItem = { id: string; text: string }; +export type GateResult = { blocked: boolean; hits: number; rows: { id: string; hits: number }[] }; + +/** 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); +} + +/** + * The case's private names taken OUT of a text the case stores (lane A): every word or 2- or 3-word phrase that + * hashes to one of them becomes NAME_WITHHELD (a possessive keeps its ending: "[name withheld]'s"). The windows + * and batches a reader reads are corpus text, which names whom it names; withheld here, the case's files never + * hold a private name, a reader never sees one, and a quote written with [name withheld] still matches its + * window's words (lane B's quote check). + */ +export function withholdPrivateNames(text: string, hashes: readonly string[]): { text: string; replaced: number } { + if (!hashes.length || !text) return { text, replaced: 0 }; + const set = new Set(hashes); + const tokens = [...text.matchAll(/[\p{L}\p{N}'’\-]+/gu)].map((m) => ({ start: m.index ?? 0, end: (m.index ?? 0) + m[0].length, norm: normalizeTerm(m[0]) })); + let out = ""; + let at = 0; + let replaced = 0; + for (let i = 0; i < tokens.length; ) { + let n = 0; + let keep = ""; + for (let k = Math.min(3, tokens.length - i); k >= 1 && !n; k--) { + const words = tokens.slice(i, i + k).map((t) => t.norm); + if (set.has(privateNameHash(words.join(" ")))) n = k; + else { + const last = stripPossessive(words[k - 1]); + if (last !== words[k - 1] && set.has(privateNameHash([...words.slice(0, -1), last].join(" ")))) { + n = k; + keep = text.slice(tokens[i + k - 1].end - 2, tokens[i + k - 1].end); + } + } + } + if (!n) { + i++; + continue; + } + out += text.slice(at, tokens[i].start) + NAME_WITHHELD + keep; + at = tokens[i + n - 1].end; + replaced++; + i += n; + } + return { text: out + text.slice(at), replaced }; +} diff --git a/common/lib/research/caseStore-server.ts b/common/lib/research/caseStore-server.ts @@ -0,0 +1,428 @@ +// 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, wrapText } from "./casePipeline"; +import { assertNoPrivateNames, withholdPrivateNames } 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)); + +/** A window with the case's private names withheld from everything it stores of the corpus's words. */ +export function withholdWindow(w: CandidateWindow, hashes: readonly string[]): { window: CandidateWindow; replaced: number } { + if (!hashes.length) return { window: w, replaced: 0 }; + const t = withholdPrivateNames(w.text, hashes); + const title = withholdPrivateNames(w.title, hashes); + let replaced = t.replaced + title.replaced; + const hits = w.hits.map((h) => { + const m = withholdPrivateNames(h.match, hashes); + replaced += m.replaced; + return m.replaced ? { ...h, match: m.text } : h; + }); + return { window: replaced ? { ...w, text: t.text, title: title.text, hits } : w, replaced }; +} + +/** + * Withhold the case's private names from what it stores of the corpus -- candidates.jsonl and every batch's text + * (re-wrapped: no line over the limit) -- when a name is added after they were written. Findings are a person's or + * a reader's writing and are never changed here: the gate names their rows. Answers how many places changed. + */ +export async function withholdStored(dir: string, hashes: readonly string[]): Promise<number> { + if (!hashes.length) return 0; + let replaced = 0; + const windows = await readCandidates(dir); + if (windows.length) { + const next = windows.map((w) => { + const r = withholdWindow(w, hashes); + replaced += r.replaced; + return r.window; + }); + const counts = await readCandidateCounts(dir); + if (replaced && counts) await writeCandidates(dir, next, counts); + } + await withFileLock(file(dir, `${CASE_FILES.batchIndex}.lock`), async () => { + const batches = await readBatches(dir); + let changed = false; + for (const b of batches) { + const t = await readText(file(dir, b.file)); + if (t === null) continue; + const r = withholdPrivateNames(t, hashes); + if (!r.replaced) continue; + replaced += r.replaced; + const body = wrapText(r.text); + b.chars = body.length; + changed = true; + await writeAtomic(file(dir, b.file), body); + } + if (changed) await writeAtomic(file(dir, CASE_FILES.batchIndex), json(batches)); + }); + return replaced; +} + +// ── stage 3: batches ── + +export const readBatches = async (dir: string) => (await readJsonFile<CaseBatch[]>(file(dir, CASE_FILES.batchIndex))) ?? []; + +/** 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) { + // The windows are withheld when the candidates are written; a name added since is withheld here too. + const body = wrapText(withholdPrivateNames(texts.get(b.id)!, def.privateNames.sha256).text); + b.chars = body.length; + await writeAtomic(file(dir, b.file), body); + } + const batches = [...kept, ...made]; + await writeAtomic(file(dir, CASE_FILES.batchIndex), json(batches)); + return { batches, made, kept, round }; + }); +} + +/** A batch's state, as a reader moves it (lane B: pending → reading → read | failed). */ +export async function setBatchState(dir: string, batchId: string, state: CaseBatch["state"]): Promise<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,211 @@ +// A case's pipeline files (lib/research/caseStore-server.ts) and the privacy gate (casePrivacy-server.ts): the +// definition gated, findings appended with ids never reused, a planted private name blocking findings, summary and +// export with counts and row ids only (never the term), batches rebuilt around a reader's work, a stage's record. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/research/caseStore.test.ts + +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { privateNameHash } from "./privateNames-server"; +import { PrivacyBlocked, privacyGate, withholdPrivateNames } from "./casePrivacy-server"; +import { + appendFindings, + readBatchText, + readBatches, + readDefinition, + readFindings, + readStages, + readCandidates, + rebuildBatches, + runStage, + withholdStored, + writeCandidates, + saveDefinition, + setBatchState, + writeReport, + writeSummary, +} from "./caseStore-server"; +import { emptyCounts, longestLine, normalizeDefinition } from "./casePipeline"; +import { BATCH_LINE_MAX, type CandidateWindow } from "./caseTypes"; + +const PLANTED = "Ottoline Brackenridge"; // invented: the private name the gate must catch +const HASHES = [privateNameHash(PLANTED)]; + +const dirs: string[] = []; +async function caseDir() { + const d = await mkdtemp(path.join(os.tmpdir(), "case-store-")); + dirs.push(d); + return d; +} +test.after(async () => { + for (const d of dirs) await rm(d, { recursive: true, force: true }); +}); + +const row = (over: Record<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"); +}); + +test("the gate looks past a possessive; withholdPrivateNames takes the name out and keeps everything else", () => { + assert.equal(privacyGate([{ id: "x", text: "that was Ottoline Brackenridge’s idea" }], HASHES).blocked, true); + const one = [privateNameHash("Ottoline")]; + const r = withholdPrivateNames("Then OTTOLINE said, and Ottoline's dog barked; Ottolines stayed.", one); + assert.equal(r.text, "Then [name withheld] said, and [name withheld]'s dog barked; Ottolines stayed."); + assert.equal(r.replaced, 2); + assert.equal(withholdPrivateNames(`with ${PLANTED} there`, HASHES).text, "with [name withheld] there"); + assert.equal(withholdPrivateNames("nothing here", HASHES).replaced, 0); +}); + +test("withholdStored: a name added after the candidates and batches were written is taken out of them, findings untouched", async () => { + const dir = await caseDir(); + const def = normalizeDefinition({ groups: [{ id: "own", label: "Own", channels: "subject" }] }, "wren"); + const w = { ...win("a/v@0", "own", 20), title: `With ${PLANTED}`, text: `${"a word ".repeat(26)}then ${PLANTED} spoke` }; + await writeCandidates(dir, [w], emptyCounts()); + await rebuildBatches(dir, def, [w]); + await appendFindings(dir, [row({ summary: `about ${PLANTED}` })], []); + const n = await withholdStored(dir, HASHES); + assert.equal(n, 4, "the window's words and title, and the batch's title and words"); + const [after] = await readCandidates(dir); + assert.match(after.text, /then \[name withheld\] spoke$/); + assert.equal(after.title, "With [name withheld]"); + const batch = await readBatchText(dir, "own-1-001"); + assert.doesNotMatch(batch, /Ottoline/); + assert.ok(longestLine(batch) <= BATCH_LINE_MAX); + assert.match(await readFile(path.join(dir, "findings.jsonl"), "utf8"), /Ottoline/, "a finding is never rewritten: the gate names its row"); +}); diff --git a/common/lib/research/caseTypes.ts b/common/lib/research/caseTypes.ts @@ -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 (HITS of a + * non-strict family on a subject's own channel in a strict era), 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,19 +334,31 @@ 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. */ export const normalizeTerm = (s: string) => s.normalize("NFKC").toLowerCase().trim().split(/\s+/u).join(" "); -/** What the gate hashes: every word of `text` and every 2- and 3-word phrase, each normalizeTerm'd. */ +/** A word's possessive ending, which the gate looks past (lane A): "Ottoline's" is Ottoline. */ +export const stripPossessive = (word: string) => word.replace(/['’]s$/u, ""); + +/** + * What the gate hashes: every word of `text` and every 2- and 3-word phrase, each normalizeTerm'd -- and each + * phrase again with a possessive ending on its last word dropped (lane A: a name in the possessive is the name). + */ export function privateNameCandidates(text: string): string[] { const words = normalizeTerm(text.replace(/[^\p{L}\p{N}'’\-\s]/gu, " ")) .split(" ") .filter(Boolean); const out = new Set<string>(); for (let i = 0; i < words.length; i++) { - for (let n = 1; n <= 3 && i + n <= words.length; n++) out.add(words.slice(i, i + n).join(" ")); + for (let n = 1; n <= 3 && i + n <= words.length; n++) { + const phrase = words.slice(i, i + n); + out.add(phrase.join(" ")); + const last = stripPossessive(phrase[n - 1]); + if (last && last !== phrase[n - 1]) out.add([...phrase.slice(0, -1), last].join(" ")); + } } return [...out]; } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -6,6 +6,7 @@ - **A per-project link policy: cite via one site, these channels direct.** The Ember cut's citeUrls were rewritten by hand twice to send two channels to anilyzer and one to YouTube. A project's **Link policy** (Overview, or `umtool link-policy <p> --via <site> --direct a,b`) now says it once: new clips are written by it, and every clip that breaks it is a check row with a one-press fix (`umtool link-policy <p> --fix` for all). - **The take panel shows the render queue and how long a take will take.** What runs in the machine's heavy slot and what waits there — e2e suites, builds, renders, and what each waits for — read from the slot's own files ("held by e2e suite e2e-editor"), and an ETA for a whole-cut take of the project, fresh and made from the newest take, from how long its past renders took. A take now records its render's own time (`renderSeconds`). - **The walk checks who is speaking against several named voices.** The clip bench's verdict bar shows *Speaker: matches Ember 0.93 / Kirsche 0.83* with the reference sets it used, and **Check speaker** scores the clip (TitaNet-small, local, as a job through the heavy slot); the voices are the project's `speakers.json` (**Add to a voice**, or `umtool speaker-check <p> --set 'Ember=e01,e07'`). +- **A research case runs as a pipeline beside its board.** What a Claude Code session did on a case by hand is now stages on umtool's `/research/<case>/pipeline` and in `archilyzer case <verb> <case>`: the case's definition (subjects and their own channels, scope, eras with term families, reader groups, prompts, key dates); coverage per channel × year (listed, held, transcribed, untranscribed audio; key years marked) with each gap's button asking the editor's own `download-missing`, `transcribe-bucket`, `persist-videos` or `channel-priority` focus, plan first; candidate windows off the live corpus (en-orig before en, families per era, ±W s windows, title hits, noise filters, counts before any read); batches per reader group as wrapped text (no line over 200 characters); finding rows by hand; the merge (one finding per recording within 20 s), a summary, `REPORT.md`/`.html`, a hand-off that pins the findings to the board; and date checks ("no response found in captioned uploads through <date>"). A case's private names are stored only as sha256 (typed on the page they are hashed in the browser; on the CLI they come on stdin), withheld from the candidates and batches the case stores, and the privacy gate blocks any finding, summary, export or hand-off — the board's own included — that names one, saying counts and row ids, never the name. The reading stage (a candidate deck, `case-read`) is the next lane's. Needs a restart of umtool. - **X has a cookie banner like Rumble's, and says how fresh its jar is.** X's banner used to go up only when X answered a fetch with a challenge, so an X fetch on an old jar was simply refused with a sentence the operator saw only in a job's error. Now the fresh-jar rule's refusal (`social.x.maxCookieAgeMinutes`, an hour by default) puts an **X needs fresh cookies** banner on the dashboard — "press Refresh cookies (or Connect X account) on /settings — with the browser login, open x.com in firefox" — with the jar's age under it, read from disk: the exported jar's time, or, with the browser login, when Firefox last sent its x.com `auth_token` (read by the cookie's name from a private copy of Firefox's cookie store; its value is never read). An X fetch refused at its start is offered under **Re-run stopped jobs** once the jar is fresh. Recheck re-reads the age and asks X nothing; the banner clears by itself as soon as an X job passes the rule on a fresh jar. This banner does not itself refuse X jobs (the rule does); a real challenge or login failure from X replaces it with the one that does. gallery-dl's own words are now read more carefully: its "AuthRequired: authenticated cookies needed to access this timeline" (what X answers a logged-out timeline with), "Could not authenticate you", a 401 and an API 403 count as a **login failure** (worded so on the banner and in the refusal), a 429 or "rate limit" is pacing and never raises the banner, and a protected or blocking account, an NSFW or protected tweet and a 403 on a twimg.com media file are about that one account or file — those used to raise X's banner and stop every X job. `pnpm ops get services` now always carries `x` (the jar's source, age, limit and whether an X job could start on it). Needs a restart of the editor. - **Rumble's cookies are checked on a timer, so the banner goes up before a sync fails.** Until now a stale Cloudflare clearance was noticed only when a Rumble sync or clip fetch failed on it. Every 3 hours (stretched a little at random, never shortened) the editor now looks by itself: when Rumble has been idle that long, it asks Rumble once for the last video it answered cleanly — a refusal is checked once more on the previous, different video a minute or more later, because a removed video refuses too, and two different videos refused put the banner up; every banner already up is rechecked once, as its Recheck button does, so it clears by itself after rumble.com was opened in Firefox; and X's jar age is re-read from disk (X jobs queued on an old jar put X's banner up before their start refuses them). Nothing is asked while a job is queued or running on Rumble's queues (its answer is the check), while Rumble is cooling down or held, or while a recheck runs, and a failed check is never retried — it waits for the next tick or a click. Each check is a **Recheck service cookies** job on /jobs. `settings.serviceCookies.recheckIntervalMinutes` (180; 30–1440; 0 turns it off) and `probeServices` (`["rumble"]`; YouTube and Odysee may be added), set with `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`; `pnpm ops get services` shows the timer's last tick under `timer`. Not on an idle boot. Needs a restart of the editor. - **A channel can download only the videos you add.** The operator wanted Harmful Opinions downloaded by hand, with its title filter gone, and nothing said that: `syncIntervalMinutes: 0` stops the listing but the download lane still works the backlog it has — and dropping a filter re-decides every video it had settled, so the whole channel would come down — while a `paused` tier stops every lane, transcription too. Configure → Advanced → **Downloads**: Manual (`downloadMode: "manual"` in config.json; `pnpm ops channel-config --json '{"slug":"<slug>","patch":{"downloadMode":"manual"}}'`, `""` sets it back to Automatic). On a manual channel the download lane skips the channel (its backlog, retries, metadata scan and chat backlog); a sync reads only the newest page of the listing and a full sweep still refreshes the playlist and the maybe-missing set, and neither downloads the new uploads it finds; Download from playlist, Download videos (`download-missing`) and the bucket retries refuse with a notice. What you ask for still downloads — Import, `import-video`, the video page's download and persist buttons, `persist-videos`, clip windows, a whole-recording fetch — and the videos on disk are still transcribed. The channel's report keeps the listed videos it lacks as **Listed, not requested** (`manualNotRequestedIds`) rather than undownloaded work, so no lane, rack figure, dashboard count or group Download button counts them, and a video that leaves the listing unfetched is not raised as never fetched; the channel page says "Manual downloads — only videos you add are downloaded" at the top and the rack row carries a **manual dl** chip. An import still passes the channel's download filter, so set the mode first and then clear the filter. Needs a restart of the editor. diff --git a/umtool/app/api/research/cases/[id]/pipeline/[op]/route.ts b/umtool/app/api/research/cases/[id]/pipeline/[op]/route.ts @@ -0,0 +1,77 @@ +import { addFindings, batchFile, changePrivateNames, gapAction, handoffToBoard, pipelineView, reportFile, saveSummary, startStage } from "@/lib/research/pipeline"; +import { CasePipelineError } from "yt-dlp-transcript-common/lib/research/casePipeline"; +import { fail, ok } from "../../../../_respond"; + +export const dynamic = "force-dynamic"; + +// A CASE'S PIPELINE, its actions (lib/research/pipeline.ts). The door an agent uses too (the MCP's case tools, +// lane D, through UMTOOL_URL); `archilyzer case …` runs the same stages from a shell. +// +// POST coverage | candidates {window?, maxSpan?} | date-checks {aroundDays?, latest?} +// -> { started: true, view }: runs in the background; follow GET ../ +// POST batches {budget?} | export {minRelevance?} +// -> { view } when done +// POST private-names {add?: [hex], remove?: [hex], clear?: true} +// -> { count, changed }: sha256 hex digests ONLY (the page hashes a name +// in the browser); a term is refused +// POST findings {rows: [FindingRow…]} -> { rows } appended: each checked, the whole write behind the gate +// POST summary {text, by?, model?} -> { summary }: a person's (by hand), or a model's draft +// POST handoff {confirm?, minRelevance?} +// -> { plan } / { plan, pinned, duplicates }: the merged findings onto +// the board, one section per reader group, behind the gate +// POST gap {action: download-missing | transcribe | persist | focus, slug, confirm?} +// -> { plan } / { done, route, answer }: the editor's own ops +// GET batch?batch=<id> -> the batch's wrapped text (text/plain) +// GET report?format=md|html[&download=1] +// -> REPORT.md / REPORT.html as exported +// A PrivacyBlocked is a 409 whose words are counts and row ids. +const STAGES = new Set(["coverage", "candidates", "batches", "export", "date-checks"]); + +type Ctx = { params: Promise<{ id: string; op: string }> }; + +export async function POST(request: Request, ctx: Ctx) { + try { + const { id: raw, op } = await ctx.params; + const id = decodeURIComponent(raw); + const body = ((await request.json().catch(() => ({}))) ?? {}) as Record<string, unknown>; + if (typeof body !== "object" || Array.isArray(body)) throw new CasePipelineError("expected a JSON object"); + if (STAGES.has(op)) { + const r = await startStage(id, op, body); + return ok({ ...r, view: await pipelineView(id) }); + } + if (op === "private-names") return ok(await changePrivateNames(id, body)); + if (op === "findings") return ok({ rows: await addFindings(id, body.rows) }); + if (op === "summary") return ok({ summary: await saveSummary(id, body) }); + if (op === "handoff") return ok(await handoffToBoard(id, { confirm: body.confirm === true, minRelevance: body.minRelevance as number | undefined })); + if (op === "gap") return ok(await gapAction(id, body)); + throw new CasePipelineError(`no pipeline action "${op}"`, 404); + } catch (e) { + return fail(e); + } +} + +export async function GET(request: Request, ctx: Ctx) { + try { + const { id: raw, op } = await ctx.params; + const id = decodeURIComponent(raw); + const q = new URL(request.url).searchParams; + if (op === "batch") { + return new Response(await batchFile(id, q.get("batch") ?? ""), { headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } }); + } + if (op === "report") { + const format = q.get("format") === "html" ? "html" : "md"; + const r = await reportFile(id, format); + if (!r) throw new CasePipelineError("nothing exported yet: Export the report first", 404); + return new Response(r.body, { + headers: { + "content-type": format === "html" ? "text/html; charset=utf-8" : "text/markdown; charset=utf-8", + "cache-control": "no-store", + ...(q.get("download") === "1" ? { "content-disposition": `attachment; filename="${r.name}"` } : {}), + }, + }); + } + throw new CasePipelineError(`no pipeline read "${op}"`, 404); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/api/research/cases/[id]/pipeline/route.ts b/umtool/app/api/research/cases/[id]/pipeline/route.ts @@ -0,0 +1,32 @@ +import { pipelineView, saveCaseDefinition } from "@/lib/research/pipeline"; +import { CasePipelineError } from "yt-dlp-transcript-common/lib/research/casePipeline"; +import { fail, ok } from "../../../_respond"; + +export const dynamic = "force-dynamic"; + +// A CASE'S PIPELINE (lib/research/pipeline.ts; plans/release-38/research-cases-and-assist.md, lane A), beside its +// board. The stages and the rest are ./[op]/route.ts. +// GET -> PipelineView (lib/research/pipeline-types.ts): the definition (private names as a count only), each +// stage's file and last run, what the privacy gate says now +// PUT the definition (pipeline.json): { subjects, scope, eras, groups, readerPrompts, keyDates, status, +// privateNames: { note } } -> PipelineView. Private names are never part of it (POST ./private-names). +export async function GET(_request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + return ok(await pipelineView(decodeURIComponent(id))); + } catch (e) { + return fail(e); + } +} + +export async function PUT(request: Request, ctx: { params: Promise<{ id: string }> }) { + try { + const { id } = await ctx.params; + const body = (await request.json().catch(() => null)) as unknown; + if (!body || typeof body !== "object" || Array.isArray(body)) throw new CasePipelineError("expected the definition as a JSON object"); + await saveCaseDefinition(decodeURIComponent(id), body); + return ok(await pipelineView(decodeURIComponent(id))); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/app/research/[case]/pipeline/page.tsx b/umtool/app/research/[case]/pipeline/page.tsx @@ -0,0 +1,46 @@ +import Link from "next/link"; +import AppHeader from "@/components/shell/AppHeader"; +import AppRail from "@/components/shell/AppRail"; +import CasePipeline from "@/components/research/CasePipeline"; +import { EmptyState } from "@/components/ui/empty-state"; +import { pipelineView } from "@/lib/research/pipeline"; +import { researchCaseHref, researchHref } from "@/lib/research/hrefs"; +import type { PipelineView } from "@/lib/research/pipeline-types"; + +export const dynamic = "force-dynamic"; + +// A CASE'S PIPELINE (plans/release-38/research-cases-and-assist.md, lane A), beside its board at +// /research/<case>: the stages -- define, coverage, candidates, batches, the read, merge, the privacy gate, +// export and hand-off, date checks -- each with its manual path and its buttons. The page is the client's +// (components/research/CasePipeline.tsx); this reads the first frame. +export default async function CasePipelinePage({ params }: { params: Promise<{ case: string }> }) { + const { case: raw } = await params; + const id = decodeURIComponent(raw); + let view: PipelineView | null = null; + let error: { status: number; message: string } | null = null; + try { + view = await pipelineView(id); + } catch (e) { + error = { status: (e as { status?: number }).status ?? 500, message: (e as Error).message }; + } + return ( + <div className="flex h-full flex-col"> + <AppRail active="research" /> + {view ? ( + <CasePipeline initial={view} /> + ) : ( + <> + <AppHeader crumbs={[{ href: researchHref(), label: "Research" }, { href: researchCaseHref(id), label: id }, { label: "Pipeline" }]} /> + <div className="px-7 pt-6"> + <EmptyState title={error?.status === 404 ? `No case “${id}”` : "This case's pipeline cannot be read"}> + <span role="alert">{error?.message}</span>{" "} + <Link href={researchHref()} className="ink-link"> + Research + </Link> + </EmptyState> + </div> + </> + )} + </div> + ); +} diff --git a/umtool/components/research/BoardView.tsx b/umtool/components/research/BoardView.tsx @@ -17,6 +17,7 @@ import { researchCaseApi, researchCaseExportApi, researchCaseQuoteApi, + researchCasePipelineHref, researchCaseVerifyApi, researchFromCaseHref, researchHref, @@ -627,6 +628,15 @@ export default function BoardView({ initial }: { initial: CaseView }) { </div> {view.localOnly > 0 && <p className="mt-2 text-[12px] text-doubt-text">{view.localOnly} local-only: no article (it could be published); a video stays local.</p>} </div> + <div> + <span className="micro">Pipeline</span> + <p className="mb-0 mt-1.5 text-[12px] text-muted"> + Coverage, candidate windows, batches, findings, the merge and its privacy gate, date checks.{" "} + <Link prefetch={false} href={researchCasePipelineHref(doc.id)} className="ink-link" data-case-pipeline=""> + Open the case pipeline + </Link> + </p> + </div> <dl data-case-facts="" className="m-0 grid grid-cols-[auto_minmax(0,1fr)] gap-x-3.5 gap-y-1.5 text-[12.5px]"> <dt className="text-muted">Scope</dt> <dd className="m-0 text-text-2">{scopeLine}</dd> diff --git a/umtool/components/research/CasePipeline.tsx b/umtool/components/research/CasePipeline.tsx @@ -0,0 +1,775 @@ +"use client"; + +import Link from "next/link"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import AppHeader from "@/components/shell/AppHeader"; +import { badgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { Field, Input, Select, Textarea } from "@/components/ui/field"; +import { Panel } from "@/components/ui/panel"; +import { Table, TD, TH } from "@/components/ui/table"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { privateNameHashWeb, privateTermProblem } from "yt-dlp-transcript-common/lib/research/casePipeline"; +import type { CaseStage, CaseStageRun } from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { researchCaseHref, researchCasePipelineApi, researchHref } from "@/lib/research/hrefs"; +import type { PipelineView } from "@/lib/research/pipeline-types"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// THE CASE PIPELINE (plans/release-38/research-cases-and-assist.md, lane A): one panel per stage, in order, each +// with its manual path (what a person does by hand) and its buttons. Every change is the API's +// (app/api/research/cases/[id]/pipeline/**) and the page redraws from what it answers; a long stage runs in the +// background and the page follows its record (stages.json) until it ends -- a run from `archilyzer case …` shows +// here the same way. +// +// PRIVATE NAMES never leave this page as text: a typed name is hashed here (Web Crypto) and only the hash is +// posted; the field is a password field, so a screenshot shows dots. What the page shows of them is a count, and +// what the gate blocked as counts and row ids. +// +// Stage 4 (the read: the candidate deck, the case-read task, the quote check) is lane B's: until it lands, its +// panel is the manual path -- the reader prompts to copy and a box for finding rows. +// --------------------------------------------------------------------------- + +const nf = new Intl.NumberFormat("en-US"); +const plural = (n: number, w: string) => `${nf.format(n)} ${w}${n === 1 ? "" : "s"}`; +const STAGE_NAV: { id: string; label: string }[] = [ + { id: "define", label: "Define" }, + { id: "coverage", label: "1 Coverage" }, + { id: "candidates", label: "2 Candidates" }, + { id: "batches", label: "3 Batches" }, + { id: "read", label: "4 Read" }, + { id: "merge", label: "5 Merge" }, + { id: "privacy", label: "6 Privacy" }, + { id: "export", label: "Export" }, + { id: "date-checks", label: "9 Date checks" }, +]; + +async function call<T>(url: string, method: string, body?: unknown): Promise<T> { + const r = await fetch(url, { method, headers: { "content-type": "application/json" }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), cache: "no-store" }); + const j = (await r.json().catch(() => null)) as (T & { error?: string }) | null; + if (!r.ok) throw new Error(j?.error ?? `HTTP ${r.status}`); + return j as T; +} + +function RunState({ run }: { run?: CaseStageRun }) { + if (!run) return <span className={badgeVariants({ variant: "info", size: "sm" })}>not run</span>; + const when = (run.endedAt ?? run.startedAt).replace("T", " ").slice(0, 16); + return ( + <span className="flex items-center gap-2" data-stage-state={run.state}> + <span className={badgeVariants({ variant: run.state === "failed" ? "blocking" : run.state === "running" ? "state" : "neutral", size: "sm" })}>{run.state}</span> + <span className="font-mono text-[11px] text-muted"> + {when} · {run.by} + </span> + </span> + ); +} + +function StageLog({ run }: { run?: CaseStageRun }) { + if (!run || (!run.log.length && !run.error)) return null; + return ( + <div className="mt-2 rounded-[3px] bg-panel-2 px-2.5 py-1.5 font-mono text-[11px] leading-relaxed text-text-2" data-stage-log=""> + {run.log.slice(-8).map((l, i) => ( + <div key={i}>{l}</div> + ))} + {run.error && ( + <div role="alert" className="text-reject-text"> + {run.error} + </div> + )} + </div> + ); +} + +function Manual({ children }: { children: React.ReactNode }) { + return <p className="mb-2 mt-0 text-[12px] text-muted">By hand: {children}</p>; +} + +function Counts({ title, of }: { title: string; of: Record<string, number> }) { + const e = Object.entries(of); + return ( + <div> + <div className="micro mb-1">{title}</div> + {e.length ? ( + <ul className="m-0 list-none p-0 font-mono text-[11.5px] text-text-2"> + {e.map(([k, n]) => ( + <li key={k}> + {k} <span className="text-meter">{nf.format(n)}</span> + </li> + ))} + </ul> + ) : ( + <span className="text-[12px] text-muted-2">none</span> + )} + </div> + ); +} + +type Plan = { title: string; what: string; detail?: unknown; confirm: () => Promise<void> }; + +/** The editable part of a definition, as the editor's JSON shows it (never the private-name hashes). */ +function editable(def: PipelineView["definition"]) { + return { + subjects: def.subjects, + scope: def.scope, + eras: def.eras, + groups: def.groups, + readerPrompts: def.readerPrompts, + keyDates: def.keyDates ?? [], + status: def.status, + privateNames: { note: def.privateNames.note }, + }; +} + +export default function CasePipeline({ initial }: { initial: PipelineView }) { + const hydrated = useHydrated(); + const [view, setView] = useState(initial); + const [busy, setBusy] = useState<string | null>(null); + const [status, setStatus] = useState<{ text: string; tone?: "error" } | null>(null); + const [plan, setPlan] = useState<Plan | null>(null); + const [batchShown, setBatchShown] = useState<{ id: string; text: string } | null>(null); + const [defText, setDefText] = useState(() => JSON.stringify(editable(initial.definition), null, 2)); + const [defError, setDefError] = useState<string | null>(null); + const [term, setTerm] = useState(""); + const [rowsText, setRowsText] = useState(""); + const [summaryText, setSummaryText] = useState(initial.summary?.text ?? ""); + const [W, setW] = useState("30"); + const [budget, setBudget] = useState("60000"); + const [minRel, setMinRel] = useState("2"); + const id = view.case.id; + const api = useCallback((op?: string) => researchCasePipelineApi(id, op), [id]); + + const refresh = useCallback(async () => { + const v = await call<PipelineView>(api(), "GET"); + setView(v); + return v; + }, [api]); + + const anyRunning = Object.values(view.stages).some((s) => s?.state === "running"); + useEffect(() => { + if (!anyRunning) return; + const t = setInterval(() => void refresh().catch(() => {}), 1200); + return () => clearInterval(t); + }, [anyRunning, refresh]); + + const act = useCallback( + async (label: string, fn: () => Promise<string | void>) => { + setBusy(label); + setStatus(null); + try { + const text = await fn(); + if (text) setStatus({ text }); + } catch (e) { + setStatus({ text: (e as Error).message, tone: "error" }); + } finally { + setBusy(null); + } + }, + [], + ); + + const runStage = (stage: CaseStage, body: Record<string, unknown> = {}) => + act(stage, async () => { + let r: { started: boolean; view: PipelineView }; + try { + r = await call<{ started: boolean; view: PipelineView }>(api(stage), "POST", body); + } catch (e) { + // A refused stage still left its record (a failed run): draw it. + await refresh().catch(() => {}); + throw e; + } + setView(r.view); + const run = r.view.stages[stage]; + if (run?.state === "failed") throw new Error(run.error ?? `${stage} failed`); + return r.started ? `${stage}: started` : `${stage}: done`; + }); + + const saveDefinition = () => + act("define", async () => { + let body: unknown; + try { + body = JSON.parse(defText); + } catch (e) { + setDefError(`not JSON: ${(e as Error).message}`); + return; + } + try { + const v = await call<PipelineView>(api(), "PUT", body); + setView(v); + setDefText(JSON.stringify(editable(v.definition), null, 2)); + setDefError(null); + return "definition saved"; + } catch (e) { + setDefError((e as Error).message); + } + }); + + const privateNames = (op: "add" | "remove" | "clear") => + act("private", async () => { + let body: Record<string, unknown> = { clear: true }; + if (op !== "clear") { + const problem = privateTermProblem(term); + if (problem) throw new Error(problem); + body = { [op]: [await privateNameHashWeb(term)] }; + } + const r = await call<{ count: number; changed: number; withheld: number }>(api("private-names"), "POST", body); + setTerm(""); + await refresh(); + return op === "add" + ? r.changed + ? `added: ${plural(r.count, "private name")} (hashed)${r.withheld ? `; withheld in ${plural(r.withheld, "place")} of the candidates and batches` : ""}` + : `already there: ${plural(r.count, "private name")}` : op === "remove" ? (r.changed ? `removed: ${r.count} left` : "that name was not there") : "every private name removed"; + }); + + const addRows = () => + act("findings", async () => { + const rows = rowsText + .split("\n") + .filter((l) => l.trim()) + .map((l, i) => { + try { + return JSON.parse(l) as unknown; + } catch { + throw new Error(`line ${i + 1} is not JSON`); + } + }); + const r = await call<{ rows: { row: string }[] }>(api("findings"), "POST", { rows }); + setRowsText(""); + await refresh(); + return `${r.rows.length} ${r.rows.length === 1 ? "row" : "rows"} added: ${r.rows.map((x) => x.row).join(", ")}`; + }); + + const saveSummary = () => + act("summary", async () => { + await call(api("summary"), "POST", { text: summaryText }); + await refresh(); + return "summary saved as yours"; + }); + + const showBatch = (b: string) => + act("batch", async () => { + const r = await fetch(`${api("batch")}?batch=${encodeURIComponent(b)}`, { cache: "no-store" }); + if (!r.ok) throw new Error((await r.json().catch(() => null))?.error ?? `HTTP ${r.status}`); + setBatchShown({ id: b, text: await r.text() }); + }); + + const askGap = (action: "download-missing" | "transcribe" | "persist" | "focus", slug = "") => + act("gap", async () => { + const r = await call<{ plan: { route: string; request: unknown; what: string; dryRun?: unknown; dryRunError?: string } }>(api("gap"), "POST", { action, slug }); + setPlan({ + title: action === "focus" ? "Focus the case" : `${action} · ${slug}`, + what: r.plan.what, + detail: { route: r.plan.route, request: r.plan.request, ...(r.plan.dryRun ? { dryRun: r.plan.dryRun } : {}), ...(r.plan.dryRunError ? { dryRunError: r.plan.dryRunError } : {}) }, + confirm: async () => { + await call(api("gap"), "POST", { action, slug, confirm: true }); + setStatus({ text: `asked the editor: ${r.plan.route.replace("/api/ops/", "")}${slug ? ` ${slug}` : ""}` }); + }, + }); + }); + + const askHandoff = () => + act("handoff", async () => { + const r = await call<{ plan: { findings: number; sections: { label: string; rows: number }[]; quarantinedLeftOut: number; blocked: { hits: number; rows: string[] } | null } }>(api("handoff"), "POST", { minRelevance: Number(minRel) }); + if (r.plan.blocked) throw new Error(`the privacy gate blocks the hand-off: ${r.plan.blocked.hits} private-name hits in ${r.plan.blocked.rows.length} rows (${r.plan.blocked.rows.join(", ")})`); + setPlan({ + title: "Hand off to the board", + what: `Pin ${r.plan.findings} ${r.plan.findings === 1 ? "finding" : "findings"} to the board, one section per reader group${r.plan.quarantinedLeftOut ? `; ${r.plan.quarantinedLeftOut} quarantined left out` : ""}. The board's own hand-offs then draft the article or start the video.`, + detail: r.plan.sections, + confirm: async () => { + const c = await call<{ pinned: number; duplicates: number }>(api("handoff"), "POST", { confirm: true, minRelevance: Number(minRel) }); + setStatus({ text: `pinned ${c.pinned} to the board${c.duplicates ? ` (${c.duplicates} already there)` : ""}` }); + }, + }); + }); + + const s = view.stages; + const def = view.definition; + const counts = view.candidates.counts; + const keyYears = useMemo(() => new Set(view.keyYears), [view.keyYears]); + const gateFindings = view.gate.findings; + const shownFindings = view.merge?.sections.reduce((n, x) => n + x.rows.length, 0) ?? 0; + const dis = !hydrated || busy !== null; + + return ( + <> + <AppHeader + crumbs={[{ href: researchHref(), label: "Research" }, { href: researchCaseHref(id), label: view.case.title }, { label: "Pipeline" }]} + meta={ + <> + <span className="micro mr-2">Research · case pipeline</span> + <span data-pipeline-meta=""> + {view.defined ? `${plural(def.subjects.length, "subject")} · ${plural(def.eras.length, "era")} · ${plural(def.groups.length, "reader group")} · ${plural(view.channels.slugs.length, "channel")} · status ${def.status}` : "not defined yet"} + </span> + </> + } + actions={ + <Link prefetch={false} href={researchCaseHref(id)} className={buttonVariants({ variant: "outline", size: "sm" })}> + The board + </Link> + } + below={ + <nav aria-label="Stages" className="flex flex-wrap gap-x-3 gap-y-1 text-[12px]"> + {STAGE_NAV.map((n) => ( + <a key={n.id} href={`#stage-${n.id}`} className="ink-link"> + {n.label} + </a> + ))} + </nav> + } + /> + <div className="min-h-0 flex-1 overflow-auto px-7 pb-10 pt-3 max-md:px-4" data-pipeline=""> + <div className="mx-auto grid max-w-[1100px] gap-4"> + {status && ( + <div role={status.tone === "error" ? "alert" : "status"} data-pipeline-status="" className={cn("sticky top-0 z-10 rounded-[3px] border bg-panel px-3 py-2 text-[12.5px] shadow-sm", status.tone === "error" ? "border-reject-text text-reject-text" : "border-seam-2 text-text-2")}> + {status.text} + </div> + )} + + {/* ── Define ── */} + <Panel id="stage-define" title="Define the case" aside={<span className="font-mono text-[11px] text-muted">{view.stored}pipeline.json</span>}> + <Manual> + the subjects (and their own channels), the scope (channels, <code>site:group</code> groups, sites), the eras with their term families (regex; a strict + family for a subject&apos;s own late material), the reader groups (a list of channels, &quot;subject&quot; or &quot;coverage&quot;), the reader prompts and the key dates. Or + <code> archilyzer case define {id} --file pipeline.json</code>. + </Manual> + <Field label="Definition (JSON)" error={defError ?? undefined}> + <Textarea aria-label="Definition" rows={14} spellCheck={false} className="font-mono text-[12px]" value={defText} onChange={(e) => setDefText(e.target.value)} /> + </Field> + <div className="mt-2 flex flex-wrap items-center gap-2"> + <button type="button" disabled={dis} className={buttonVariants({ variant: "go", size: "sm" })} onClick={saveDefinition}> + Save the definition + </button> + <span className="text-[12px] text-muted">{view.channels.slugs.length ? `reads ${view.channels.slugs.join(", ")}` : "no channel in scope yet"}</span> + {view.channels.problems.map((p) => ( + <span key={p} className="text-[12px] text-doubt-text"> + {p} + </span> + ))} + </div> + <div className="mt-4 border-t border-seam pt-3" data-private-names=""> + <div className="micro mb-1">Private names</div> + <p className="mb-2 mt-0 text-[12px] text-muted"> + A name typed here is hashed in this browser and only its hash is stored: no file holds it, and nothing shows it again. The gate blocks findings, the + summary, the export and a hand-off that name one. + </p> + <div className="flex flex-wrap items-end gap-2"> + <Field label="A private name (at most three words)"> + <Input type="password" autoComplete="off" aria-label="A private name" value={term} onChange={(e) => setTerm(e.target.value)} className="w-[260px]" /> + </Field> + <button type="button" disabled={dis || !term.trim()} className={buttonVariants({ size: "sm" })} onClick={() => void privateNames("add")}> + Add + </button> + <button type="button" disabled={dis || !term.trim()} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => void privateNames("remove")}> + Remove + </button> + <button type="button" disabled={dis || !view.privateNames} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => void privateNames("clear")}> + Remove all + </button> + <span className="font-mono text-[12px] text-meter" data-private-count=""> + {view.privateNames} hashed + </span> + </div> + </div> + </Panel> + + {/* ── 1 Coverage ── */} + <Panel id="stage-coverage" title="1 · Coverage" aside={<RunState run={s.coverage} />}> + <Manual>per channel and year, what is listed, held, transcribed and held as audio with no transcript; the key years (an era touches them) are marked. A gap&apos;s button asks the editor&apos;s own action, plan first.</Manual> + <div className="flex flex-wrap items-center gap-2"> + <button type="button" disabled={dis || !view.defined || s.coverage?.state === "running"} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void runStage("coverage")}> + Count coverage + </button> + <button type="button" disabled={dis || !view.defined || !view.editor} className={buttonVariants({ size: "sm" })} onClick={() => void askGap("focus")} title={view.editor ? undefined : "umtool has no WORKER_TOKEN: the editor cannot be asked"}> + Focus the case{def.scope.sites.length ? `'s site (${def.scope.sites[0]})` : "'s channels"} + </button> + </div> + <StageLog run={s.coverage} /> + {view.coverage.rows.length > 0 && ( + <div className="mt-3 grid gap-3"> + <Table aria-label="Coverage"> + <thead> + <tr> + <TH>Channel</TH> + <TH>Year</TH> + <TH className="text-right">Listed</TH> + <TH className="text-right">Held</TH> + <TH className="text-right">Transcribed</TH> + <TH className="text-right">Audio, no transcript</TH> + </tr> + </thead> + <tbody> + {view.coverage.rows.map((r) => ( + <tr key={`${r.channel}:${r.year}`} data-key-year={r.key ? "" : undefined} className={r.key ? "bg-panel-2" : undefined}> + <TD>{r.channel}</TD> + <TD> + <span className="font-mono">{r.year || "undated"}</span> + {r.key && <span className={cn(badgeVariants({ variant: "meter", size: "sm" }), "ml-2")}>key</span>} + </TD> + <TD numeric>{nf.format(r.listed)}</TD> + <TD numeric>{nf.format(r.held)}</TD> + <TD numeric>{nf.format(r.transcribed)}</TD> + <TD numeric className={r.untranscribedAudio ? "text-doubt-text" : undefined}> + {nf.format(r.untranscribedAudio)} + </TD> + </tr> + ))} + </tbody> + </Table> + <div className="grid gap-1.5" aria-label="Gaps"> + {view.coverage.gaps.map((g) => ( + <div key={g.slug} className="flex flex-wrap items-center gap-2 text-[12.5px]" data-gap={g.slug}> + <span className="min-w-[160px] font-medium text-text-2">{g.slug}</span> + <button type="button" disabled={dis || !g.missing || !view.editor} className={buttonVariants({ size: "sm" })} onClick={() => void askGap("download-missing", g.slug)}> + Download missing ({nf.format(g.missing)}) + </button> + <button type="button" disabled={dis || !g.untranscribedAudio || !view.editor} className={buttonVariants({ size: "sm" })} onClick={() => void askGap("transcribe", g.slug)}> + Transcribe ({nf.format(g.untranscribedAudio)}) + </button> + <button type="button" disabled={dis || !g.keyHeld || !view.editor} className={buttonVariants({ size: "sm" })} onClick={() => void askGap("persist", g.slug)}> + Persist the key period ({nf.format(g.keyHeld)} held) + </button> + </div> + ))} + </div> + </div> + )} + </Panel> + + {/* ── 2 Candidates ── */} + <Panel id="stage-candidates" title="2 · Candidates" aside={<RunState run={s.candidates} />}> + <Manual>the scope&apos;s transcripts searched for each era&apos;s families (en-orig before en; rolling captions folded; title hits), ±W s windows merged, the noise filters applied — counted before anything is read. Deterministic: the same corpus gives the same windows.</Manual> + <div className="flex flex-wrap items-end gap-2"> + <Field label="W (seconds either side)"> + <Input aria-label="Window seconds" className="w-[90px]" value={W} onChange={(e) => setW(e.target.value)} inputMode="numeric" /> + </Field> + <button type="button" disabled={dis || !view.defined || !def.eras.length || s.candidates?.state === "running"} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void runStage("candidates", { window: Number(W) })}> + Find candidates + </button> + </div> + <StageLog run={s.candidates} /> + {counts && ( + <div className="mt-3 grid gap-3" data-candidate-counts=""> + <p className="m-0 text-[13px]"> + <span className="font-mono text-meter">{nf.format(counts.windows)}</span> windows in <span className="font-mono text-meter">{nf.format(counts.videos)}</span> recordings ·{" "} + {nf.format(counts.titleHits)} title hits · scanned {nf.format(counts.scanned.videos)} recordings in {counts.scanned.channels} channels, {nf.format(counts.scanned.inEra)} in an era, {nf.format(counts.scanned.withText)} with words,{" "} + <span className={counts.scanned.noText ? "text-doubt-text" : undefined}>{nf.format(counts.scanned.noText)} with none yet</span> + </p> + <div className="grid grid-cols-[repeat(auto-fill,minmax(160px,1fr))] gap-3"> + <Counts title="By family" of={counts.byFamily} /> + <Counts title="By year" of={counts.byYear} /> + <Counts title="By channel" of={counts.byChannel} /> + <Counts title="By group" of={counts.byGroup} /> + <Counts title="Noise (dropped)" of={counts.noise} /> + </div> + {counts.skipped.map((x) => ( + <span key={x.slug} className="text-[12px] text-doubt-text"> + skipped {x.slug}: {x.reason} + </span> + ))} + {view.candidates.sample.length > 0 && ( + <details> + <summary className="cursor-pointer text-[12.5px] text-text-2"> + The first {view.candidates.sample.length} of {nf.format(view.candidates.total)} windows + </summary> + <ol className="m-0 mt-2 grid list-none gap-2 p-0"> + {view.candidates.sample.map((w) => ( + <li key={w.key} className="border-l-2 border-seam-2 pl-2.5 text-[12px]" data-window={w.key}> + <div className="font-mono text-[11px] text-muted"> + {w.key} · {w.date} · {w.group} · {w.track} + {w.titleHit ? " · title hit" : ""} + </div> + <div className="text-text-2">{w.title}</div> + <div className="text-muted">{w.text}</div> + </li> + ))} + </ol> + </details> + )} + </div> + )} + </Panel> + + {/* ── 3 Batches ── */} + <Panel id="stage-batches" title="3 · Batches" aside={<RunState run={s.batches} />}> + <Manual> + the windows grouped per reader group under a character budget, written as wrapped text — no line over 200 characters, so a reader&apos;s file tool never drops the densest windows. A batch a reader has begun is kept; new windows make the next round. Or <code>archilyzer case batch {id} &lt;batch&gt;</code>. + </Manual> + <div className="flex flex-wrap items-end gap-2"> + <Field label="Budget (characters a batch)"> + <Input aria-label="Batch budget" className="w-[110px]" value={budget} onChange={(e) => setBudget(e.target.value)} inputMode="numeric" /> + </Field> + <button type="button" disabled={dis || !view.candidates.total} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void runStage("batches", { budget: Number(budget) })}> + Make batches + </button> + </div> + <StageLog run={s.batches} /> + {view.batches.length > 0 && ( + <Table aria-label="Batches" className="mt-3"> + <thead> + <tr> + <TH>Batch</TH> + <TH>Group</TH> + <TH className="text-right">Round</TH> + <TH className="text-right">Windows</TH> + <TH className="text-right">Characters</TH> + <TH>State</TH> + <TH /> + </tr> + </thead> + <tbody> + {view.batches.map((b) => ( + <tr key={b.id} data-batch={b.id}> + <TD className="font-mono">{b.id}</TD> + <TD>{b.group}</TD> + <TD numeric>{b.round}</TD> + <TD numeric>{b.windows.length}</TD> + <TD numeric>{nf.format(b.chars)}</TD> + <TD> + <span className={badgeVariants({ variant: b.state === "read" ? "neutral" : b.state === "failed" ? "blocking" : "state", size: "sm" })}>{b.state}</span> + </TD> + <TD> + <button type="button" disabled={dis} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => void showBatch(b.id)}> + Read the text + </button> + </TD> + </tr> + ))} + </tbody> + </Table> + )} + </Panel> + + {/* ── 4 Read (lane B) ── */} + <Panel id="stage-read" title="4 · Read" aside={<span className="font-mono text-[11px] text-muted">{view.findings.rows.length} rows</span>}> + <Manual> + read a batch with its group&apos;s prompt (the naming rule is always in it) and write one finding row per quote — verbatim, at most 45 words, the window&apos;s key and second. Paste the rows below (one JSON object a line), or + <code> archilyzer case findings {id} --file rows.jsonl</code>. The candidate deck and the case-read readers are the next lane&apos;s. + </Manual> + {Object.keys(view.prompts).length > 0 && ( + <details className="mb-2"> + <summary className="cursor-pointer text-[12.5px] text-text-2">Reader prompts</summary> + <div className="mt-2 grid gap-2"> + {Object.entries(view.prompts).map(([g, p]) => ( + <div key={g}> + <div className="micro">{g}</div> + <pre className="m-0 whitespace-pre-wrap rounded-[3px] bg-panel-2 px-2.5 py-1.5 text-[11.5px] text-text-2" data-prompt={g}> + {p} + </pre> + </div> + ))} + </div> + </details> + )} + <Field label="Finding rows (JSON lines)"> + <Textarea aria-label="Finding rows" rows={4} spellCheck={false} className="font-mono text-[11.5px]" value={rowsText} onChange={(e) => setRowsText(e.target.value)} placeholder='{"batch":"own-1-001","slug":"…","id":"…","date":"20150310","title":"…","t":31,"url":"…","category":"…","relevance":3,"quote":"…","summary":"…","speaker":"…","confidence":"high","round":1,"by":"hand"}' /> + </Field> + <button type="button" disabled={dis || !rowsText.trim()} className={cn(buttonVariants({ size: "sm" }), "mt-2")} onClick={addRows}> + Add rows + </button> + {view.findings.invalid.length > 0 && ( + <p role="alert" className="mt-2 text-[12px] text-reject-text"> + {view.findings.invalid.length} lines of findings.jsonl do not check: {view.findings.invalid.map((x) => `line ${x.line} (${x.errors.join("; ")})`).join(" · ")} + </p> + )} + {view.findings.rows.length > 0 && ( + <Table aria-label="Findings" className="mt-3"> + <thead> + <tr> + <TH>Row</TH> + <TH>Recording</TH> + <TH className="text-right">Rel.</TH> + <TH>Quote</TH> + <TH>By</TH> + <TH>Check</TH> + </tr> + </thead> + <tbody> + {view.findings.rows.map((r) => ( + <tr key={r.row} data-finding={r.row} className={gateFindings.rows.some((x) => x.id === r.row) ? "bg-[color-mix(in_srgb,var(--reject-text)_8%,transparent)]" : undefined}> + <TD className="font-mono">{r.row}</TD> + <TD> + <span className="font-mono text-[11px]"> + {r.slug}/{r.id} @ {Math.floor(r.t)}s + </span> + <div className="text-muted">{r.date}</div> + </TD> + <TD numeric>{r.relevance}</TD> + <TD>{r.quote}</TD> + <TD>{r.by}</TD> + <TD>{r.quoteCheck}{r.verify ? ` · ${r.verify.status}` : ""}</TD> + </tr> + ))} + </tbody> + </Table> + )} + </Panel> + + {/* ── 5 Merge ── */} + <Panel id="stage-merge" title="5 · Merge" aside={<span className="font-mono text-[11px] text-muted">{shownFindings} in the report</span>}> + <Manual>the same recording within 20 s is one finding (the higher relevance, then the later round); sections by reader group; relevance 2 and up by default; the quarantined in their own section. A preview: nothing is written until Export.</Manual> + <Field label="Relevance floor" className="w-[150px]"> + <Select aria-label="Relevance floor" value={minRel} onChange={(e) => setMinRel(e.target.value)}> + <option value="1">1 and up</option> + <option value="2">2 and up</option> + <option value="3">3 only</option> + </Select> + </Field> + {view.merge && ( + <div className="mt-2 grid gap-2 text-[12.5px]" data-merge=""> + {view.merge.sections.map((sec) => ( + <div key={sec.group}> + <span className="font-medium">{sec.label}</span> <span className="font-mono text-meter">{sec.rows.length}</span> — <span className="font-mono text-[11px] text-muted">{sec.rows.map((r) => r.row).join(", ")}</span> + </div> + ))} + {view.merge.quarantined.length > 0 && ( + <div> + <span className="font-medium">Quarantined</span> <span className="font-mono text-meter">{view.merge.quarantined.length}</span> + </div> + )} + <div className="text-muted"> + {view.merge.duplicates.length} folded as duplicates ({view.merge.duplicates.map((d) => `${d.row} → ${d.of}`).join(", ") || "none"}) · {view.merge.belowFloor.length} below the floor · {view.merge.total} rows + </div> + </div> + )} + <div className="mt-3 border-t border-seam pt-3"> + <Field label="Summary (on top of the report)" hint={view.summary?.draft ? `A draft by ${view.summary.model ?? view.summary.by}: saving it here makes it yours.` : "Written by hand. A model's draft is marked as a draft until a person saves it."}> + <Textarea aria-label="Summary" rows={4} value={summaryText} onChange={(e) => setSummaryText(e.target.value)} /> + </Field> + <button type="button" disabled={dis || !summaryText.trim()} className={cn(buttonVariants({ size: "sm" }), "mt-2")} onClick={saveSummary}> + Save the summary + </button> + {view.summary?.draft && <span className={cn(badgeVariants({ variant: "open", size: "sm" }), "ml-2")}>draft</span>} + </div> + </Panel> + + {/* ── 6 Privacy gate ── */} + <Panel id="stage-privacy" title="6 · Privacy gate" aside={<span className="font-mono text-[11px] text-muted">{plural(view.privateNames, "private name")} (hashed)</span>}> + <Manual>every write of findings, the summary, the export and a hand-off is checked against the case&apos;s private names (every word and 2- and 3-word phrase, hashed). A hit blocks it and names the rows — never the name. Write [name withheld] in its place.</Manual> + <div data-gate={gateFindings.blocked || view.gate.summary.blocked ? "blocked" : "clear"} className="text-[12.5px]"> + {gateFindings.blocked ? ( + <p role="alert" className="m-0 text-reject-text"> + Blocked: {gateFindings.hits} private-name {gateFindings.hits === 1 ? "hit" : "hits"} in {gateFindings.rows.length} {gateFindings.rows.length === 1 ? "row" : "rows"} ({gateFindings.rows.map((r) => `${r.id} ×${r.hits}`).join(", ")}). + </p> + ) : ( + <p className="m-0 text-text-2">{view.privateNames ? `Clear: no finding names a private name (${view.findings.rows.length} rows read).` : "No private names in this case yet."}</p> + )} + {view.gate.summary.blocked && ( + <p role="alert" className="m-0 mt-1 text-reject-text"> + The summary names a private name ({view.gate.summary.hits} {view.gate.summary.hits === 1 ? "hit" : "hits"}). + </p> + )} + </div> + </Panel> + + {/* ── Export and hand-off ── */} + <Panel id="stage-export" title="Export and hand-off" aside={<RunState run={s.export} />}> + <Manual> + the merge and the summary as REPORT.md (cited markdown in the house format: it converts as a /sweep report) and REPORT.html; or pin the merged findings to the board, whose own hand-offs then draft the article or start the video. Or <code>archilyzer case export {id}</code>. + </Manual> + <div className="flex flex-wrap items-center gap-2"> + <button type="button" disabled={dis || !view.defined} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void runStage("export", { minRelevance: Number(minRel) })}> + Export the report + </button> + <button type="button" disabled={dis || !shownFindings} className={buttonVariants({ size: "sm" })} onClick={askHandoff}> + Hand off to the board + </button> + {view.report.exists && ( + <> + <a className="ink-link text-[12.5px]" href={`${api("report")}?format=md`} target="_blank" rel="noreferrer"> + REPORT.md + </a> + <a className="ink-link text-[12.5px]" href={`${api("report")}?format=html`} target="_blank" rel="noreferrer"> + REPORT.html + </a> + </> + )} + </div> + <StageLog run={s.export} /> + </Panel> + + {/* ── 9 Date checks ── */} + <Panel id="stage-date-checks" title="9 · Absence and date checks" aside={<RunState run={s["date-checks"]} />}> + <Manual>the subject&apos;s own uploads around each key date and the latest after it, captioned or not, and whether any finding is a response.</Manual> + <button type="button" disabled={dis || !view.defined || s["date-checks"]?.state === "running"} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void runStage("date-checks")}> + Check the dates + </button> + <StageLog run={s["date-checks"]} /> + <div className="mt-3 grid gap-4"> + {view.dateChecks.map((d) => ( + <div key={`${d.date}:${d.label}`} data-date-check={d.date}> + <div className="text-[13px]"> + <span className="font-mono">{d.date}</span> <span className="font-medium">{d.label}</span> + </div> + <p className="m-0 text-[12.5px] text-text-2" data-date-sentence=""> + {d.sentence} + </p> + {d.uploads.length > 0 && ( + <Table aria-label={`Uploads around ${d.date}`} className="mt-1"> + <thead> + <tr> + <TH>Date</TH> + <TH>Recording</TH> + <TH>Title</TH> + <TH>Captioned</TH> + </tr> + </thead> + <tbody> + {d.uploads.map((u) => ( + <tr key={`${u.slug}/${u.id}`}> + <TD className="font-mono"> + {u.date} + {u.date >= d.date.replace(/-/g, "") ? " ·after" : " ·before"} + </TD> + <TD className="font-mono text-[11px]"> + {u.slug}/{u.id} + </TD> + <TD>{u.title}</TD> + <TD>{u.captioned ? "yes" : "no"}</TD> + </tr> + ))} + </tbody> + </Table> + )} + </div> + ))} + </div> + </Panel> + </div> + </div> + + <Dialog open={!!plan} onClose={() => setPlan(null)} title={plan?.title ?? ""}> + {plan && ( + <div className="grid gap-3 px-4 py-3 text-[13px]"> + <p className="m-0">{plan.what}</p> + {plan.detail !== undefined && <pre className="m-0 max-h-[260px] overflow-auto rounded-[3px] bg-panel-2 px-2.5 py-1.5 text-[11px]">{JSON.stringify(plan.detail, null, 2)}</pre>} + <div className="flex gap-2"> + <button + type="button" + className={buttonVariants({ variant: "go", size: "sm" })} + onClick={() => + void act("confirm", async () => { + await plan.confirm(); + setPlan(null); + await refresh(); + }) + } + > + Confirm + </button> + <button type="button" className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => setPlan(null)}> + Cancel + </button> + </div> + </div> + )} + </Dialog> + <Dialog open={!!batchShown} onClose={() => setBatchShown(null)} title={batchShown ? `Batch ${batchShown.id}` : ""} className="w-[min(900px,calc(100vw-32px))]"> + {batchShown && ( + <pre className="m-0 max-h-[70vh] overflow-auto px-4 py-3 font-mono text-[11.5px] leading-relaxed" data-batch-text=""> + {batchShown.text} + </pre> + )} + </Dialog> + </> + ); +} diff --git a/umtool/docs/research.md b/umtool/docs/research.md @@ -76,6 +76,41 @@ claim line and note on each. Create's **From a board** lines open the same plans. +## A case's pipeline, `/research/<case>/pipeline` (release 38) + +Beside the board (its side panel's **Open the case pipeline**): the research a Claude Code session did on a case, as +stages, each with its manual path and its buttons. The stages are common's (`controller/casePipelineRun.ts`), so +`archilyzer case <verb> <case>` (COMMANDS.md) runs the same ones from a shell, and `stages.json` shows either's run to +the other. The files sit beside `case.json`, never in it (`common/lib/research/caseTypes.ts` `CASE_FILES`). + +- **Define** — `pipeline.json`: subjects (and their own channels), scope (channels, `<site>:<group>` groups, sites), + eras with term families (regex, flags `iu`; `strictFamilies` for a subject's own late material), reader groups (a + list of slugs, `"subject"` or `"coverage"`; an era), reader prompts, key dates. Edited as JSON, checked whole. +- **Private names** — typed into a password field, hashed in the browser, and only the sha256 is posted and stored + (`privateNames.sha256`). The page shows a count. Once a name is in, it is withheld (`[name withheld]`) from the + candidates and batches the case stores, so no file of the case holds it. +- **1 Coverage** — per channel × year: listed, held, transcribed, untranscribed audio; key years (an era touches them) + marked. Each channel's gap buttons ask the editor's own ops, plan first: **Download missing** (`download-missing`), + **Transcribe** (`transcribe-bucket`), **Persist the key period** (`persist-videos`, its plan the dryRun), and **Focus + the case** (`channel-priority` focus: the case's first site, else its channels). +- **2 Candidates** — the scope's held recordings dated in an era, read through the caption-track rule (en-orig before + en), each era's families matched, ±W s windows merged, title hits, the noise filters (a coverage window must name a + subject; strict families on a subject's own channel), counted per family, year, channel and group before any read. +- **3 Batches** — per reader group under a character budget, written as wrapped text (no line over 200). A batch a + reader has begun is kept; new windows make the next round. **Read the text** shows one. +- **4 Read** — lane B's deck and `case-read` readers come next; until then the reader prompts (the naming rule always + in them) and a box for finding rows as JSON lines. +- **5 Merge** — the same recording within 20 s is one finding (higher relevance, then later round); sections by + group; relevance 2 and up; the quarantined in their own section. The **Summary** is a person's (or a model's, marked + a draft). +- **6 Privacy gate** — every write of findings, the summary, the export and a hand-off is checked against the + hashes; a hit blocks it and names the rows, never the name. The board's own export and hand-offs are gated by the + same names. +- **Export and hand-off** — `REPORT.md` (the house format) and `REPORT.html`; **Hand off to the board** pins the merged + findings to the board, one section per reader group, and the board's hand-offs take it from there. +- **9 Date checks** — the subject's uploads around each key date and the latest after it, captioned or not, and the + sentence ("no response found in captioned uploads through <date>", or the findings that are one). + ## Agent runs, `/research/runs` and `/research/runs/<article>/<n>` `/research/runs` lists every sweep iteration of the article store, newest first. A run page shows what a sweep did, @@ -107,5 +142,5 @@ Held counts are kept 5 minutes per channel ("Held counts from 3 min ago (kept 5 ## Routes `/api/research/{sources,scope,search,window,coverage,log,media,fetch}`, `/api/research/cases[/<id>[/quotes[/<qid>] -|/verify|/export.md|/handoff]]`, `/api/research/runs/<article>/<n>[/board]` — JSON, `no-store`, errors in words (400 bad +|/verify|/export.md|/handoff|/pipeline[/<op>]]]` (the pipeline's ops are listed in its route), `/api/research/runs/<article>/<n>[/board]` — JSON, `no-store`, errors in words (400 bad input, 404 nothing there, 409 an unreadable file, 502 a source that cannot be read). diff --git a/umtool/e2e/case-pipeline.spec.ts b/umtool/e2e/case-pipeline.spec.ts @@ -0,0 +1,228 @@ +import { test, expect, type Page } from "@playwright/test"; +import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { PIPELINE_CASE, PIPELINE_DEFINITION, PLANTED, SUBJECT_CHANNEL, TALK_CHANNEL } from "./fixtures/case-fixture.mjs"; +import { researchCaseHref, researchCasePipelineApi, researchCasePipelineHref } from "../lib/research/hrefs"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// THE CASE PIPELINE (plans/release-38/research-cases-and-assist.md, lane A) on its fixture +// (e2e/fixtures/case-fixture.mjs): from the board to the pipeline; the definition saved; a private name typed, +// stored only as a hash; coverage per channel × year with the key years and a gap's button asking the editor +// (stubbed) after its plan; candidates and their counts; batches whose every line is at most 200 characters; +// finding rows by hand, one refused by the gate; the gate blocking the export of a row written before the name was +// added, by row id and never the name; the export once the row is withheld; the hand-off to the board; the date +// checks' sentence. E2E_SHOTS_DIR, when set, collects a screenshot of each stage. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const CASE_DIR = path.join(FIXTURE, ".umtool", "research", PIPELINE_CASE); +// The stub writes its log on its first request; before that there is none. +const stubLog = (): { route?: string; slug?: string }[] => { + try { + return JSON.parse(readFileSync(path.join(FIXTURE, "editor-stub.requests.json"), "utf8")); + } catch { + return []; + } +}; +// A background stage ends in well under a second; the first poll of a route can wait on its compile. +const STAGE = { timeout: 30_000 }; +const SHOTS = process.env.E2E_SHOTS_DIR; + +/** The case's files whose text names the planted private name, relative to the case dir. */ +function filesNaming(term: string, dir = CASE_DIR, base = CASE_DIR): string[] { + return readdirSync(dir).flatMap((name) => { + const p = path.join(dir, name); + if (statSync(p).isDirectory()) return filesNaming(term, p, base); + return readFileSync(p, "utf8").toLowerCase().includes(term.toLowerCase()) ? [path.relative(base, p)] : []; + }); +} + +async function shot(page: Page, name: string, stage?: string) { + if (!SHOTS) return; + if (stage) await page.locator(`#stage-${stage}`).scrollIntoViewIfNeeded(); + await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false }); +} + +const status = (page: Page) => page.locator("[data-pipeline-status]"); +const stageState = (page: Page, stage: string) => page.locator(`#stage-${stage} [data-stage-state]`); + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, [researchCasePipelineHref(PIPELINE_CASE), researchCasePipelineApi(PIPELINE_CASE), researchCaseHref(PIPELINE_CASE)]); +}); + +test("a case through its pipeline: define, coverage, candidates, batches, findings, the privacy gate, export, hand-off, date checks", async ({ page }) => { + test.setTimeout(180_000); + await page.setViewportSize({ width: 1366, height: 900 }); + + // From the board. + await page.goto(researchCaseHref(PIPELINE_CASE)); + await page.locator("[data-case-pipeline]").click(); + await expect(page).toHaveURL(new RegExp(`/research/${PIPELINE_CASE}/pipeline`)); + await expect(page.locator("[data-pipeline-meta]")).toHaveText("not defined yet"); + + // Define: a private name in the definition is refused; the definition itself saves. + const defBox = page.getByRole("textbox", { name: "Definition" }); + await defBox.fill(JSON.stringify({ ...PIPELINE_DEFINITION, privateNames: { note: "x", sha256: ["a".repeat(64)] } })); + await page.getByRole("button", { name: "Save the definition" }).click(); + await expect(page.locator("#stage-define [role=alert]")).toContainText("never saved with the definition"); + await defBox.fill(JSON.stringify(PIPELINE_DEFINITION, null, 2)); + await page.getByRole("button", { name: "Save the definition" }).click(); + await expect(page.locator("[data-pipeline-meta]")).toContainText("1 subject · 2 eras · 2 reader groups · 2 channels"); + await shot(page, "01-define", "define"); + + // Coverage: per channel × year; the key years marked; a gap's button plans, then asks the editor. + await page.getByRole("button", { name: "Count coverage" }).click(); + await expect(stageState(page, "coverage")).toHaveAttribute("data-stage-state", "done", STAGE); + const cov = page.getByRole("table", { name: "Coverage" }); + const own2015 = cov.locator("tr", { hasText: SUBJECT_CHANNEL }).filter({ hasText: "2015" }); + await expect(own2015).toHaveAttribute("data-key-year", ""); + await expect(own2015.locator("td")).toHaveText([SUBJECT_CHANNEL, /2015\s*key/, "2", "2", "1", "1"]); + await expect(cov.locator("tr", { hasText: "undated" })).toHaveCount(1); + await shot(page, "02-coverage", "coverage"); + const gap = page.locator(`[data-gap="${SUBJECT_CHANNEL}"]`); + await gap.getByRole("button", { name: /Download missing \(2\)/ }).click(); + const dialog = page.getByRole("dialog"); + await expect(dialog).toContainText(`download every listed video ${SUBJECT_CHANNEL} does not hold`); + await expect(dialog).toContainText('"/api/ops/download-missing"'); + expect(stubLog().some((r) => r.route === "download-missing")).toBe(false); + await dialog.getByRole("button", { name: "Confirm" }).click(); + await expect(status(page)).toHaveText(`asked the editor: download-missing ${SUBJECT_CHANNEL}`); + await expect.poll(() => stubLog().filter((r) => r.route === "download-missing").map((r) => r.slug)).toEqual([SUBJECT_CHANNEL]); + await gap.getByRole("button", { name: /Persist the key period/ }).click(); + await expect(dialog).toContainText('"toFetch"'); + await dialog.getByRole("button", { name: "Cancel" }).click(); + + // Candidates: counted before any read; the talk show's line that names no subject is noise. + await page.getByRole("button", { name: "Find candidates" }).click(); + await expect(stageState(page, "candidates")).toHaveAttribute("data-stage-state", "done", STAGE); + const counts = page.locator("[data-candidate-counts]"); + await expect(counts).toContainText("3 windows in 3 recordings"); + await expect(counts).toContainText("noSubject 1"); + await expect(counts).toContainText("notStrict 1"); + await shot(page, "03-candidates", "candidates"); + + // Batches: per group, wrapped -- no line over 200 characters, on the page and on disk. + await page.getByRole("button", { name: "Make batches" }).click(); + await expect(page.locator("[data-batch]")).toHaveCount(2); + await expect(page.locator('[data-batch="own-1-001"]')).toContainText("pending"); + await page.locator('[data-batch="talk-1-001"]').getByRole("button", { name: "Read the text" }).click(); + const text = (await page.locator("[data-batch-text]").textContent()) ?? ""; + expect(text).toContain("Naming rule"); + expect(text).toContain("Wren Halloway stopped by the lantern shop"); + expect(Math.max(...text.split("\n").map((l) => l.length))).toBeLessThanOrEqual(200); + for (const b of ["own-1-001", "talk-1-001"]) { + const onDisk = readFileSync(path.join(CASE_DIR, "batches", `${b}.txt`), "utf8"); + expect(Math.max(...onDisk.split("\n").map((l) => l.length))).toBeLessThanOrEqual(200); + } + await shot(page, "04-batches"); + await page.keyboard.press("Escape"); + + // Findings by hand, before any private name: the talk-show row names a private person. + const row = (o: Record<string, unknown>) => + JSON.stringify({ batch: "own-1-001", slug: SUBJECT_CHANNEL, id: "lw-2015a", date: "20150310", title: "Opening the lantern shop", t: 120, url: "https://www.youtube.com/watch?v=lw-2015a", 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 }); + const rows = [ + row({}), + row({ t: 126, relevance: 2, quote: "I built every lantern here myself", summary: "She built the lanterns" }), + row({ batch: "talk-1-001", slug: TALK_CHANNEL, id: "ht-2015a", date: "20150320", title: "Harbor Talk 12", t: 186, url: "https://www.youtube.com/watch?v=ht-2015a", quote: `she was with ${PLANTED} that day`, summary: "The host says who she was with", speaker: "host" }), + row({ id: "lw-2021a", date: "20210305", title: "Closing the shop", t: 240, quote: "the lantern shop is closing for good", summary: "She closes the shop" }), + ]; + await page.getByRole("textbox", { name: "Finding rows" }).fill(rows.join("\n")); + await page.getByRole("button", { name: "Add rows" }).click(); + await expect(status(page)).toHaveText("4 rows added: f1, f2, f3, f4"); + + // The private name, typed: hashed in the browser, posted as a hash, shown as a count. + const posted: string[] = []; + page.on("request", (r) => { + if (r.url().includes("/pipeline/private-names")) posted.push(r.postData() ?? ""); + }); + await page.getByLabel("A private name", { exact: true }).fill(PLANTED); + await page.getByRole("button", { name: "Add", exact: true }).click(); + await expect(page.locator("[data-private-count]")).toHaveText("1 hashed"); + expect(posted.join("")).not.toMatch(/Ottoline|Brackenridge/i); + expect(posted.join("")).toMatch(/"add":\["[0-9a-f]{64}"\]/); + expect(readFileSync(path.join(CASE_DIR, "pipeline.json"), "utf8")).not.toMatch(/Ottoline|Brackenridge/i); + // The candidates and batches written before it are withheld now; only the row a person wrote still names it. + await expect(status(page)).toContainText("added: 1 private name (hashed); withheld in"); + expect(filesNaming(PLANTED)).toEqual(["findings.jsonl"]); + + // The gate: row f3 is blocked, by id; a new row naming the name is refused at the write. + const gate = page.locator("[data-gate]"); + await expect(gate).toHaveAttribute("data-gate", "blocked"); + await expect(gate).toContainText("in 1 row (f3 ×"); + await page.getByRole("textbox", { name: "Finding rows" }).fill(row({ t: 300, summary: `Again with ${PLANTED}` })); + await page.getByRole("button", { name: "Add rows" }).click(); + await expect(status(page)).toContainText("the privacy gate blocked these findings"); + await expect(status(page)).toContainText("(f5)"); + await expect(status(page)).not.toContainText("Ottoline"); + await shot(page, "05-privacy-gate", "privacy"); + + // The export is blocked, naming the row, never the name; nothing is written. + await page.getByRole("button", { name: "Export the report" }).click(); + await expect(status(page)).toContainText("the privacy gate blocked the export"); + await expect(status(page)).toContainText("in 1 item (f3)"); + await expect(stageState(page, "export")).toHaveAttribute("data-stage-state", "failed", STAGE); + await expect(page.locator("#stage-export [data-stage-log]")).not.toContainText("Ottoline"); + expect(readFileSync(path.join(CASE_DIR, "stages.json"), "utf8")).not.toMatch(/Ottoline|Brackenridge/i); + await shot(page, "06-export-blocked", "export"); + + // A person withholds the name in the row (lane C's correction; here, the file), and the export goes through. + const f = path.join(CASE_DIR, "findings.jsonl"); + writeFileSync(f, readFileSync(f, "utf8").replace(PLANTED, "[name withheld]")); + await page.getByRole("textbox", { name: "Summary" }).fill("What Wren said about the shop, from opening to closing."); + await page.getByRole("button", { name: "Save the summary" }).click(); + await expect(status(page)).toHaveText("summary saved as yours"); + await expect(gate).toHaveAttribute("data-gate", "clear"); + await expect(page.locator("[data-merge]")).toContainText("Her own words 2"); + await expect(page.locator("[data-merge]")).toContainText("What others said 1"); + await expect(page.locator("[data-merge]")).toContainText("f2 → f1"); + await page.getByRole("button", { name: "Export the report" }).click(); + await expect(stageState(page, "export")).toHaveAttribute("data-stage-state", "done", STAGE); + const md = readFileSync(path.join(CASE_DIR, "REPORT.md"), "utf8"); + expect(md).toMatch(/^# Wren and the lantern shop\n\nWhat Wren said about the shop/); + expect(md).toContain('## Her own words\n\n- She opens the shop: "welcome to the lantern shop" — [Opening the lantern shop @ 2:00](https://www.youtube.com/watch?v=lw-2015a&t=120s)'); + expect(md).toContain('"she was with [name withheld] that day"'); + expect(md).not.toMatch(/Ottoline|Brackenridge/i); + expect(filesNaming(PLANTED)).toEqual([]); + const html = await (await page.request.get(`${researchCasePipelineApi(PIPELINE_CASE, "report")}?format=html`)).text(); + expect(html).toContain("<h2>Her own words</h2>"); + await shot(page, "07-export", "export"); + + // Hand off to the board: plan, confirm, the board holds the findings in sections. + await page.getByRole("button", { name: "Hand off to the board" }).click(); + await expect(dialog).toContainText("Pin 3 findings to the board"); + await dialog.getByRole("button", { name: "Confirm" }).click(); + await expect(status(page)).toHaveText("pinned 3 to the board"); + const board = JSON.parse(readFileSync(path.join(CASE_DIR, "case.json"), "utf8")) as { sections: { title: string }[]; quotes: { text: string; claim: string }[] }; + expect(board.sections.map((s) => s.title)).toEqual(["Her own words", "What others said"]); + expect(board.quotes.map((q) => q.claim)).toContain("She closes the shop"); + + // Date checks: the subject's uploads around the key date, and the sentence. + await page.getByRole("button", { name: "Check the dates" }).click(); + await expect(stageState(page, "date-checks")).toHaveAttribute("data-stage-state", "done", STAGE); + await expect(page.locator('[data-date-check="2021-03-01"] [data-date-sentence]')).toHaveText("response found: 1 finding in uploads from 2021-03-05 to 2021-03-05 (rows f4)"); + await shot(page, "08-date-checks", "date-checks"); +}); + +test("the API refuses a private name sent as text, and the board's own exits are gated by the case's names", async ({ request }) => { + const r = await request.post(researchCasePipelineApi(PIPELINE_CASE, "private-names"), { data: { add: [PLANTED] } }); + expect(r.status()).toBe(400); + expect((await r.json()).error).toContain("sha256 hex digests only"); + // The board exports what was pinned: clear now (the row was withheld before the hand-off). + const ok = await request.get(`/api/research/cases/${PIPELINE_CASE}/export.md`); + expect(ok.status()).toBe(200); + // A pinned note naming the private person blocks the board's export, by quote id. + const doc = JSON.parse(readFileSync(path.join(CASE_DIR, "case.json"), "utf8")); + doc.quotes[0].note = `ask ${PLANTED}`; + writeFileSync(path.join(CASE_DIR, "case.json"), JSON.stringify(doc, null, 2)); + const blocked = await request.get(`/api/research/cases/${PIPELINE_CASE}/export.md`); + expect(blocked.status()).toBe(409); + const err = (await blocked.json()).error as string; + expect(err).toContain(`(${doc.quotes[0].id})`); + expect(err).not.toMatch(/Ottoline|Brackenridge/i); +}); diff --git a/umtool/e2e/fixtures/case-fixture.mjs b/umtool/e2e/fixtures/case-fixture.mjs @@ -0,0 +1,85 @@ +// THE CASE PIPELINE fixture (plans/release-38/research-cases-and-assist.md, lane A): two channels in the +// fixture's CHANNELS_DIR with words on disk -- a subject's own and a talk show that covers her -- and an empty +// board, `lantern-case`, that the pipeline sits beside. case-pipeline.spec.ts defines it, counts its coverage, +// finds its candidates, batches them, writes finding rows by hand, watches the privacy gate block a planted +// private name, and exports. +// +// INVENTED, every word: no channel, recording, person or line here is real. PLANTED is the private name the gate +// must catch; it is in one talk-show line and never in a definition. +import { mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +export const PIPELINE_CASE = "lantern-case"; +export const PLANTED = "Ottoline Brackenridge"; +export const SUBJECT_CHANNEL = "lantern-wren"; +export const TALK_CHANNEL = "harbor-talk"; + +const ts = (s) => { + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}.000`; +}; +const vtt = (cues) => "WEBVTT\n\n" + cues.map(([a, t]) => `${ts(a)} --> ${ts(a + 3)}\n${t}\n`).join("\n"); +const write = (p, body) => { + mkdirSync(path.dirname(p), { recursive: true }); + writeFileSync(p, body); +}; +// Filler around each said line, every 6 s, so a window has words either side. +function lines(say, duration = 600) { + const fill = ["okay where were we", "the tide is out", "we got letters about the ferry", "let me read the next one", "the fog came in early", "thanks for calling in"]; + const at = new Map(say); + const out = []; + for (let t = 0, i = 0; t < duration; t += 6) out.push([t, at.get(t) ?? fill[i++ % fill.length]]); + return out; +} + +export function makeCaseFixture({ channels, reportsRoot }) { + const video = (slug, id, date, title, files) => { + const dir = path.join(channels, slug, "data", id); + write(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title, upload_date: date, duration: 600, webpage_url: `https://www.youtube.com/watch?v=${id}` })); + for (const [n, b] of Object.entries(files)) write(path.join(dir, n), b); + }; + const channel = (slug, name, playlist) => { + write(path.join(channels, slug, "config.json"), JSON.stringify({ handling: "youtube", name })); + write(path.join(channels, slug, "playlist"), playlist.map((id) => `https://www.youtube.com/watch?v=${id}`).join("\n") + "\n"); + }; + // The subject's own: two transcribed (en-orig beside a served en that rewrites a line), one held as audio only, + // one listed and never fetched. + channel(SUBJECT_CHANNEL, "Lantern Wren", ["lw-2015a", "lw-2015b", "lw-2015c", "lw-2016x", "lw-2021a"]); + video(SUBJECT_CHANNEL, "lw-2015a", "20150310", "Opening the lantern shop", { + "transcript.en-orig.vtt": vtt(lines([[120, "welcome to the lantern shop"], [126, "I built every lantern here myself"]])), + "transcript.en.vtt": vtt([[120, "welcome to the candle store"]]), + }); + video(SUBJECT_CHANNEL, "lw-2015b", "20150601", "A quiet week", { "audio.opus": "fixture audio" }); + video(SUBJECT_CHANNEL, "lw-2021a", "20210305", "Closing the shop", { "transcript.en-orig.vtt": vtt(lines([[240, "the lantern shop is closing for good"], [300, "wren here with an update"]])) }); + // The talk show: one recording names her and the shop; one mentions the shop only (coverage noise). + channel(TALK_CHANNEL, "Harbor Talk", ["ht-2015a", "ht-2015b"]); + video(TALK_CHANNEL, "ht-2015a", "20150320", "Harbor Talk 12", { + "transcript.en.vtt": vtt(lines([[180, "Wren Halloway stopped by the lantern shop"], [186, `she was with ${PLANTED} that day`]])), + }); + video(TALK_CHANNEL, "ht-2015b", "20150402", "Harbor Talk 13", { "transcript.en.vtt": vtt(lines([[60, "the lantern shop downtown had a sale"]])) }); + // The board, empty: the pipeline is defined on the page. + const at = "2026-11-01T12:00:00.000Z"; + write( + path.join(reportsRoot, ".umtool", "research", PIPELINE_CASE, "case.json"), + `${JSON.stringify({ format: "umtool-research-case", version: 1, id: PIPELINE_CASE, title: "Wren and the lantern shop", scope: { source: "" }, search: null, sessions: [], sections: [], quotes: [], notes: "", handoffs: [], counters: { quote: 0, section: 0 }, createdAt: at, updatedAt: at }, null, 2)}\n`, + ); +} + +/** The definition the spec types (no private name in it). */ +export const PIPELINE_DEFINITION = { + subjects: [{ name: "Wren Halloway", aliases: ["Wren"], channels: [SUBJECT_CHANNEL] }], + scope: { channels: [TALK_CHANNEL], groups: [], sites: [] }, + eras: [ + { id: "shop", from: "2015-01-01", to: "2016-12-31", families: { shop: "lantern shop", name: "\\bwren\\b" } }, + { id: "closing", from: "2021-01-01", to: "2021-12-31", families: { shop: "lantern shop", name: "\\bwren\\b" }, strictFamilies: ["shop"] }, + ], + groups: [ + { id: "own", label: "Her own words", channels: "subject" }, + { id: "talk", label: "What others said", channels: "coverage" }, + ], + readerPrompts: { common: "Quote verbatim, at most 45 words.", own: "She is the speaker unless said otherwise." }, + keyDates: [{ date: "2021-03-01", label: "the shop closes" }], + status: "gathering", + privateNames: { note: "a private person named on the talk show" }, +}; diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -1307,6 +1307,28 @@ const server = http.createServer((req, res) => { // narration crossed the wire and landed under the card, not how it sounds. // An engine other than kokoro / espeak-ng / orpheus is refused, as the // editor refuses one it does not have. + // THE CASE PIPELINE'S GAP BUTTONS (release 38 lane A, case-pipeline.spec.ts): the editor's own actions, + // recorded and answered as queued -- download-missing, transcribe-bucket, persist-videos (its dryRun answers + // the buckets) and channel-priority's focus. + if (req.method === "POST" && ["/api/ops/download-missing", "/api/ops/transcribe-bucket", "/api/ops/persist-videos", "/api/ops/channel-priority"].includes(url.pathname)) { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + let body = {}; + try { + body = raw ? JSON.parse(raw) : {}; + } catch { + return json(res, 400, { ok: false, error: "malformed JSON body" }); + } + requests.push({ route: url.pathname.slice("/api/ops/".length), ...body, authorization: auth }); + record(); + if (url.pathname === "/api/ops/persist-videos" && body.dryRun) { + return json(res, 200, { ok: true, dryRun: true, buckets: { saved: [], wrongHeight: [], toFetch: (body.items ?? []).map((i) => i.id), noUrl: [], unknown: [] } }); + } + json(res, 200, { ok: true, jobId: `stub-${url.pathname.slice("/api/ops/".length)}-${nextJob++}` }); + }); + return; + } if (req.method === "POST" && url.pathname === "/api/ops/tts") { let raw = ""; req.on("data", (c) => (raw += c)); diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -39,6 +39,7 @@ import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs"; import { makeUiOpsFixture } from "./ui-ops-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs"; +import { makeCaseFixture } from "./case-fixture.mjs"; import { makeDigestContextFixture } from "./digest-context-fixture.mjs"; import { makeRunTraceFixture } from "./run-trace-fixture.mjs"; import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs"; @@ -2352,6 +2353,8 @@ const { pub: RESEARCH_PUBLIC } = makeResearchFixture({ dest, channels: CHANNELS makeDigestContextFixture({ dest, channels: CHANNELS }); // R2: a research board with a drifted quote and an `en`-track one (REPORTS_ROOT is dest). makeBoardFixture({ reportsRoot: dest, pub: RESEARCH_PUBLIC }); +// Release 38 lane A: a case pipeline over two channels with words on disk, beside an empty board. +makeCaseFixture({ channels: CHANNELS, reportsRoot: dest }); // R3: transparent runs -- a traced sweep, an imported turns-only one with two // run starts, and one still running. makeRunTraceFixture({ articles: ARTICLES, source: `local:${RESEARCH_PUBLIC}` }); diff --git a/umtool/lib/research/boards.ts b/umtool/lib/research/boards.ts @@ -20,6 +20,7 @@ import { removeQuote, storedPath, } from "./cases.mjs"; +import { boardGate } from "./case-private"; import { windowOf } from "./corpus"; import { citationText, isoDate, trackOf } from "./facets.mjs"; import { readLog } from "./log.mjs"; @@ -319,6 +320,9 @@ export async function caseView(id: string): Promise<CaseView> { /** The board as cited markdown (house format; it converts as a /sweep report). */ export async function exportCase(id: string): Promise<{ doc: CaseDoc; markdown: string }> { const view = await caseView(id); + // The case pipeline's privacy gate (lib/research/case-private.ts): a 409 naming quote ids, never the name. + const blocked = await boardGate(view.case, "this export"); + if (blocked) throw blocked; return { doc: view.case, markdown: exportMarkdown(view.case, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) }), diff --git a/umtool/lib/research/case-private.ts b/umtool/lib/research/case-private.ts @@ -0,0 +1,30 @@ +import { readDefinition } from "yt-dlp-transcript-common/lib/research/caseStore-server"; +import { PrivacyBlocked, privacyGate } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; +import { REPORTS_ROOT } from "../paths.mjs"; +import { caseDir } from "./cases.mjs"; +import type { CaseDoc } from "./case-types"; + +// The board's own exits behind the case pipeline's privacy gate (plans/release-38/research-cases-and-assist.md, +// stage 6): a board whose case has private names (pipeline.json `privateNames.sha256`) neither exports nor hands +// off a quote, claim or note that names one. The refusal is counts and quote ids, never the name. In a module of +// its own so boards.ts and handoff.ts can ask without importing the pipeline. + +/** The case's private-name hashes; none when it has no pipeline (or it cannot be read: the pipeline says why). */ +export async function casePrivateHashes(id: string): Promise<string[]> { + try { + return (await readDefinition(caseDir(REPORTS_ROOT, id), id))?.privateNames.sha256 ?? []; + } catch { + return []; + } +} + +/** The gate over a board's quotes (their words, claims and notes): null when clear, else the refusal. */ +export async function boardGate(doc: Pick<CaseDoc, "id" | "quotes" | "notes" | "title">, what: string): Promise<PrivacyBlocked | null> { + const hashes = await casePrivateHashes(doc.id); + if (!hashes.length) return null; + const r = privacyGate( + [{ id: "the case's notes", text: `${doc.title}\n${doc.notes}` }, ...doc.quotes.map((q) => ({ id: q.id, text: [q.text, q.claim, q.note].join("\n") }))], + hashes, + ); + return r.blocked ? new PrivacyBlocked(what, r) : null; +} diff --git a/umtool/lib/research/handoff.ts b/umtool/lib/research/handoff.ts @@ -14,6 +14,7 @@ import { isLocalOnly } from "./rules.mjs"; import { runHref } from "./runs-hrefs"; import { CaseError, recordHandoff } from "./cases.mjs"; import { boardGroups, caseView, mutateBoard } from "./boards"; +import { boardGate } from "./case-private"; import type { ArticlePlan, CaseDoc, VideoPlan } from "./case-types"; // --------------------------------------------------------------------------- @@ -123,6 +124,9 @@ export async function planArticle( if (seeded && model && !model.startsWith("claude-")) refusals.push(`a seeded sweep runs on a Claude model, not ${model}: the local pipeline writes its report from scratch`); const seed = seeded ? exportMarkdown(doc, { sourceLabel: view.sourceLabel ?? undefined, ...(view.reading ? { read: view.reading.read } : {}) }) : ""; + // The case pipeline's privacy gate: quote ids and counts, never the name. + const blocked = seeded ? await boardGate(doc, "this hand-off") : null; + if (blocked) refusals.push(blocked.message); return { plan: { to: "article", @@ -264,6 +268,8 @@ export async function planVideo(id: string, over: { slug?: string; title?: strin if (local) warnings.push(`${local} local-only ${local === 1 ? "quote" : "quotes"}: this project must never be published`); const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length; if (drifted) warnings.push(`${drifted} drifted or missing at the last re-verify: their windows are the pinned seconds`); + const blocked = await boardGate(doc, "this hand-off"); + if (blocked) refusals.push(blocked.message); const siteOrigin = originOf(doc); if (!siteOrigin) warnings.push("no one viewer origin in the quotes' links: set provenance.siteOrigin before the build"); return { diff --git a/umtool/lib/research/hrefs.ts b/umtool/lib/research/hrefs.ts @@ -35,6 +35,14 @@ export function researchCaseHref(id: string): string { return `/research/${enc(id)}`; } +/** A case's pipeline (release 38): its stages beside the board. */ +export function researchCasePipelineHref(id: string, stage?: string): string { + return `/research/${enc(id)}/pipeline${stage ? `#stage-${stage}` : ""}`; +} + +/** The pipeline's API (app/api/research/cases/[id]/pipeline/[op]/route.ts documents it). */ +export const researchCasePipelineApi = (id: string, op?: string) => `/api/research/cases/${enc(id)}/pipeline${op ? `/${enc(op)}` : ""}`; + /** Research with a case's scope and query, pins going to the case. */ export function researchFromCaseHref(c: { id: string; scope: Partial<Scope> & { query?: string } }): string { const { query, ...scope } = c.scope; diff --git a/umtool/lib/research/pipeline-types.ts b/umtool/lib/research/pipeline-types.ts @@ -0,0 +1,56 @@ +import type { + CandidateCounts, + CandidateWindow, + CaseBatch, + CaseDefinition, + CaseStageRuns, + CaseSummaryText, + CoverageRow, + DateCheck, + FindingRow, +} from "yt-dlp-transcript-common/lib/research/caseTypes"; +import type { MergeView } from "yt-dlp-transcript-common/controller/casePipelineRun"; +import type { GateResult } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; + +// What the case pipeline page reads (lib/research/pipeline.ts pipelineView). Types only: the page imports them. + +/** A channel's coverage summed over its years, with what its gap buttons would ask for. */ +export type PipelineGap = { + slug: string; + listed: number; + held: number; + transcribed: number; + untranscribedAudio: number; + /** Listed and not held: what download-missing fetches. */ + missing: number; + /** Held in a key year: what "persist the key period" looks at. */ + keyHeld: number; +}; + +export type PipelineView = { + case: { id: string; title: string }; + stored: string; + defined: boolean; + /** The definition with its private-name hashes left out (never sent to a page). */ + definition: CaseDefinition; + /** How many private names the case holds (hashed). */ + privateNames: number; + channels: { slugs: string[]; problems: string[] }; + keyYears: number[]; + eraSpan: { from: string; to: string } | null; + coverage: { rows: CoverageRow[]; gaps: PipelineGap[] }; + candidates: { counts: CandidateCounts | null; total: number; sample: CandidateWindow[] }; + batches: CaseBatch[]; + findings: { rows: FindingRow[]; invalid: { line: number; errors: string[] }[] }; + merge: MergeView | null; + /** What the privacy gate says of the findings and the summary now: counts and row ids. */ + gate: { findings: GateResult; summary: GateResult }; + summary: CaseSummaryText | null; + report: { exists: boolean }; + dateChecks: DateCheck[]; + stages: CaseStageRuns; + /** Each reader group's prompt as a reader gets it (the naming rule always last). */ + prompts: Record<string, string>; + /** umtool can ask the editor (a WORKER_TOKEN is set). */ + editor: boolean; +}; diff --git a/umtool/lib/research/pipeline.ts b/umtool/lib/research/pipeline.ts @@ -0,0 +1,395 @@ +import path from "node:path"; +import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; +import { CASE_FILES, CASE_STAGES, type CaseDefinition, type CaseStage, type FindingRow } from "yt-dlp-transcript-common/lib/research/caseTypes"; +import { + CasePipelineError, + emptyDefinition, + eraSpan, + findingLink, + keyYears, + readerPrompt, + rowGateText, +} from "yt-dlp-transcript-common/lib/research/casePipeline"; +import { PrivacyBlocked, privacyGate } from "yt-dlp-transcript-common/lib/research/casePrivacy-server"; +import { + appendFindings, + mutateDefinition, + readBatchText, + readBatches, + readCandidateCounts, + readCandidates, + readCoverage, + readDateChecks, + readDefinition, + readFindings, + readReport, + readReportHtml, + readStages, + readSummary, + saveDefinition, + withholdStored, + writeSummary, +} from "yt-dlp-transcript-common/lib/research/caseStore-server"; +import { caseChannels } from "yt-dlp-transcript-common/controller/caseCorpus"; +import { mergeView, runBatches, runCandidates, runCoverage, runDateChecks, runExport } from "yt-dlp-transcript-common/controller/casePipelineRun"; +import { readDateAndTitle } from "yt-dlp-transcript-common/controller/channelCoverage"; +import { heldVideoIds } from "yt-dlp-transcript-common/controller/videoCues"; +import { CHANNELS_DIR, REPORTS_ROOT, SITES_DIR } from "../paths.mjs"; +import { askEditor } from "../articles/generation"; +import { addQuote, caseDir, storedPath } from "./cases.mjs"; +import { mutateBoard, readCase } from "./boards"; +import type { PipelineGap, PipelineView } from "./pipeline-types"; + +// --------------------------------------------------------------------------- +// A CASE'S PIPELINE, umtool's side (plans/release-38/research-cases-and-assist.md, lane A): the stages of +// common/controller/casePipelineRun.ts bound to the case's directory under REPORTS_ROOT (beside the board's +// case.json, which only cases.mjs writes) and to the corpus umtool reads (CHANNELS_DIR, read-only). The page is +// /research/<case>/pipeline; the routes are app/api/research/cases/[id]/pipeline/**; `archilyzer case …` runs +// the same stages from a shell, and stages.json shows either's run to the other. +// +// A long stage (coverage, candidates, date checks) runs in the background of this process and the page follows +// stages.json; one run per case and stage at a time. The quick ones answer when done. +// +// The private names: only their HASHES reach the server (the page hashes a typed term in the browser, +// casePipeline.ts privateNameHashWeb), and the view never sends them back -- a count, and what the gate blocked, +// as counts and row ids. +// --------------------------------------------------------------------------- + +/** The corpus as the stages read it: umtool's CHANNELS_DIR and SITES_DIR, and the index beside the channels. */ +export function corpusPaths(): Paths { + const base = getPaths(); + const channelsUnderCorpus = path.resolve(CHANNELS_DIR) === path.resolve(base.channelsDir); + return { + ...base, + channelsDir: CHANNELS_DIR, + sitesDir: SITES_DIR, + // A fixture's channels (or a TRANSCRIPTS_DIR's) date from their own index, never the checkout's. + lmdbPath: channelsUnderCorpus ? base.lmdbPath : path.join(/* turbopackIgnore: true */ path.dirname(CHANNELS_DIR), "index.mdb"), + }; +} + +const dirOf = (id: string) => caseDir(REPORTS_ROOT, id); + +async function ensureCase(id: string): Promise<{ id: string; title: string; dir: string }> { + const doc = await readCase(id); + return { id: doc.id, title: doc.title, dir: dirOf(doc.id) }; +} + +async function definitionOrEmpty(c: { id: string; dir: string }): Promise<{ def: CaseDefinition; defined: boolean }> { + const def = await readDefinition(c.dir, c.id); + return def ? { def, defined: true } : { def: emptyDefinition(c.id), defined: false }; +} + +// ── the view ── + +const running = ((globalThis as { __umtoolCaseStages?: Set<string> }).__umtoolCaseStages ??= new Set<string>()); + +function gapsOf(rows: Awaited<ReturnType<typeof readCoverage>>): PipelineGap[] { + const by = new Map<string, PipelineGap>(); + for (const r of rows) { + const g = by.get(r.channel) ?? { slug: r.channel, listed: 0, held: 0, transcribed: 0, untranscribedAudio: 0, missing: 0, keyHeld: 0 }; + g.listed += r.listed; + g.held += r.held; + g.transcribed += r.transcribed; + g.untranscribedAudio += r.untranscribedAudio; + if (r.key) g.keyHeld += r.held; + by.set(r.channel, g); + } + for (const g of by.values()) g.missing = Math.max(0, g.listed - g.held); + return [...by.values()].sort((a, b) => a.slug.localeCompare(b.slug)); +} + +export async function pipelineView(id: string): Promise<PipelineView> { + const c = await ensureCase(id); + const { def, defined } = await definitionOrEmpty(c); + const [coverage, counts, windows, batches, findings, summary, dateChecks, stages, report] = await Promise.all([ + readCoverage(c.dir), + readCandidateCounts(c.dir), + readCandidates(c.dir), + readBatches(c.dir), + readFindings(c.dir), + readSummary(c.dir), + readDateChecks(c.dir), + readStages(c.dir), + readReport(c.dir), + ]); + const hashes = def.privateNames.sha256; + const merge = defined ? await mergeView(c.dir, c.id).catch(() => null) : null; + const channels = defined ? await caseChannels(corpusPaths(), def).catch((e: Error) => ({ slugs: [], problems: [e.message] })) : { slugs: [], problems: [] }; + for (const s of CASE_STAGES) if (running.has(`${c.id}:${s}`) && stages[s]?.state !== "running") running.delete(`${c.id}:${s}`); + return { + case: { id: c.id, title: c.title }, + stored: storedPath(c.id), + defined, + definition: { ...def, privateNames: { sha256: [], note: def.privateNames.note } }, + privateNames: hashes.length, + channels, + keyYears: [...keyYears(def)].sort(), + eraSpan: eraSpan(def), + coverage: { rows: coverage, gaps: gapsOf(coverage) }, + candidates: { counts, total: windows.length, sample: windows.slice(0, 40).map((w) => ({ ...w, text: w.text.length > 600 ? `${w.text.slice(0, 600)}…` : w.text })) }, + batches, + findings: { rows: findings.rows, invalid: findings.invalid }, + merge, + gate: { + findings: privacyGate(findings.rows.map((r) => ({ id: r.row, text: rowGateText(r) })), hashes), + summary: privacyGate(summary ? [{ id: "summary", text: summary.text }] : [], hashes), + }, + summary, + report: { exists: report !== null }, + dateChecks, + stages, + prompts: Object.fromEntries([["common", readerPrompt(def, "common")], ...def.groups.map((g) => [g.id, readerPrompt(def, g.id)])]), + editor: !!process.env.WORKER_TOKEN?.trim(), + }; +} + +// ── the definition and its private names ── + +/** Save the definition from the page's editor. The private-name hashes are never part of it: they are kept. */ +export async function saveCaseDefinition(id: string, body: unknown): Promise<CaseDefinition> { + const c = await ensureCase(id); + const raw = (body && typeof body === "object" ? body : {}) as Record<string, unknown>; + const pn = raw.privateNames as Record<string, unknown> | undefined; + if (pn && ("terms" in pn || (Array.isArray(pn.sha256) && pn.sha256.length))) { + throw new CasePipelineError("private names are never saved with the definition: add them in the Private names box, which keeps only their hashes"); + } + const prev = await readDefinition(c.dir, c.id); + return saveDefinition(c.dir, c.id, { ...raw, privateNames: { sha256: prev?.privateNames.sha256 ?? [], note: typeof pn?.note === "string" ? pn.note : (prev?.privateNames.note ?? "") } }); +} + +const HEX = /^[0-9a-f]{64}$/; + +/** Add, remove or clear private-name hashes (hex digests; a term never reaches this). Answers the count. */ +export async function changePrivateNames(id: string, body: { add?: unknown; remove?: unknown; clear?: unknown }): Promise<{ count: number; changed: number; withheld: number }> { + const c = await ensureCase(id); + const hexes = (v: unknown) => { + if (v === undefined) return []; + if (!Array.isArray(v) || v.some((h) => typeof h !== "string" || !HEX.test(h))) throw new CasePipelineError("private names arrive as sha256 hex digests only: the page hashes a name before it sends it"); + return v as string[]; + }; + const add = hexes(body.add); + const remove = hexes(body.remove); + let changed = 0; + const def = await mutateDefinition( + c.dir, + c.id, + (d) => { + const before = new Set(d.privateNames.sha256); + let next = body.clear === true ? [] : [...before]; + next = [...new Set([...next, ...add])].filter((h) => !remove.includes(h)); + changed = [...new Set([...before, ...next])].filter((h) => before.has(h) !== next.includes(h)).length; + d.privateNames.sha256 = next; + }, + () => emptyDefinition(c.id), + ); + // A name added after the candidates and batches were written is withheld from them now. + const withheld = add.length ? await withholdStored(c.dir, def.privateNames.sha256) : 0; + return { count: def.privateNames.sha256.length, changed, withheld }; +} + +// ── the stages ── + +export type StageBody = { window?: number; maxSpan?: number; budget?: number; minRelevance?: number; aroundDays?: number; latest?: number }; + +const num = (v: unknown, name: string, min: number, max: number): number | undefined => { + if (v === undefined || v === null || v === "") return undefined; + const n = Number(v); + if (!Number.isFinite(n) || n < min || n > max) throw new CasePipelineError(`${name} is a number from ${min} to ${max}`); + return n; +}; + +/** + * Run a stage. coverage, candidates and date-checks start in the background (`{ started: true }`; the page follows + * stages.json); batches and export answer when done. A stage already running for this case is a 409. + */ +export async function startStage(id: string, stage: string, body: StageBody = {}): Promise<{ started: boolean }> { + const c = await ensureCase(id); + if (!(CASE_STAGES as readonly string[]).includes(stage) || stage === "handoff") throw new CasePipelineError(`not a stage: ${stage} (coverage, candidates, batches, export, date-checks)`, 404); + const key = `${c.id}:${stage}`; + if (running.has(key) || (await readStages(c.dir))[stage as CaseStage]?.state === "running") throw new CasePipelineError(`${stage} is already running for this case`, 409); + const paths = corpusPaths(); + const run = (): Promise<unknown> => { + switch (stage as CaseStage) { + case "coverage": + return runCoverage(c.dir, c.id, paths, "umtool"); + case "candidates": + return runCandidates(c.dir, c.id, paths, "umtool", { W: num(body.window, "window", 5, 600), maxSpan: num(body.maxSpan, "maxSpan", 30, 3600) }); + case "batches": + return runBatches(c.dir, c.id, "umtool", { budget: num(body.budget, "budget", 2000, 400_000) }); + case "export": + return runExport(c.dir, c.id, c.title, "umtool", { minRelevance: num(body.minRelevance, "minRelevance", 1, 3), paths }); + case "date-checks": + return runDateChecks(c.dir, c.id, paths, "umtool", { aroundDays: num(body.aroundDays, "aroundDays", 1, 365), latest: num(body.latest, "latest", 1, 100) }); + default: + throw new CasePipelineError(`not a stage: ${stage}`, 404); + } + }; + // The definition must exist before anything runs (each runner checks it; asked here so a background stage refuses at once). + if (!(await readDefinition(c.dir, c.id))) throw new CasePipelineError("define the case first: its subjects, eras and reader groups", 409); + if (stage === "batches" || stage === "export") { + await run(); + return { started: false }; + } + running.add(key); + void run() + .catch(() => {}) + .finally(() => running.delete(key)); + // Let the stage write "running" before the page asks again. + await new Promise((r) => setTimeout(r, 50)); + return { started: true }; +} + +// ── findings, the summary, the report ── + +/** Append finding rows by hand (or an agent's, lane D), checked and gated. */ +export async function addFindings(id: string, rows: unknown): Promise<FindingRow[]> { + const c = await ensureCase(id); + if (!Array.isArray(rows)) throw new CasePipelineError("rows is a list of finding rows"); + const def = await readDefinition(c.dir, c.id); + return appendFindings(c.dir, rows, def?.privateNames.sha256 ?? []); +} + +/** The summary written on the page: a person's, so never a draft. A model's draft arrives with `by` set. */ +export async function saveSummary(id: string, body: { text?: unknown; by?: unknown; model?: unknown }) { + const c = await ensureCase(id); + if (typeof body.text !== "string") throw new CasePipelineError("summary: { text }"); + const by = body.by === undefined ? "hand" : body.by; + if (by !== "hand" && by !== "api" && by !== "local" && by !== "code") throw new CasePipelineError("by is hand, api, local or code"); + const def = await readDefinition(c.dir, c.id); + return writeSummary(c.dir, { text: body.text, draft: by !== "hand", by, ...(typeof body.model === "string" && body.model ? { model: body.model } : {}) }, def?.privateNames.sha256 ?? []); +} + +export async function batchFile(id: string, batch: string): Promise<string> { + const c = await ensureCase(id); + return readBatchText(c.dir, batch); +} + +/** REPORT.md or REPORT.html as exported, or null. */ +export async function reportFile(id: string, format: "md" | "html"): Promise<{ body: string; name: string } | null> { + const c = await ensureCase(id); + const body = format === "html" ? await readReportHtml(c.dir) : await readReport(c.dir); + return body === null ? null : { body, name: `${c.id}-${format === "html" ? CASE_FILES.reportHtml : CASE_FILES.report}` }; +} + +// ── the hand-off: the merged findings onto the board ── + +/** + * The merge's findings pinned to the case's board, one board section per reader group -- the board's own hand-offs + * (an article, a video) then take them, as they take any pin. Plan first (`confirm` false: what would be pinned, + * and what the gate says); behind the privacy gate; the quarantined are never pinned (not evidence). A finding + * already on the board (the same recording and second) is not pinned twice. + */ +export async function handoffToBoard(id: string, o: { confirm?: boolean; minRelevance?: number } = {}) { + const c = await ensureCase(id); + const def = await readDefinition(c.dir, c.id); + if (!def) throw new CasePipelineError("define the case first", 409); + const merged = await mergeView(c.dir, c.id, { minRelevance: num(o.minRelevance, "minRelevance", 1, 3) }); + const rows = merged.sections.flatMap((s) => s.rows.map((r) => ({ r, label: s.label }))); + const gate = privacyGate(rows.map(({ r }) => ({ id: r.row, text: rowGateText(r) })), def.privateNames.sha256); + const plan = { + sections: merged.sections.map((s) => ({ label: s.label, rows: s.rows.length })), + findings: rows.length, + quarantinedLeftOut: merged.quarantined.length, + blocked: gate.blocked ? { hits: gate.hits, rows: gate.rows.map((x) => x.id) } : null, + }; + if (!o.confirm) return { plan, pinned: 0, duplicates: 0 }; + if (!rows.length) throw new CasePipelineError("no finding to hand off: the merge has none at this relevance", 409); + if (gate.blocked) throw new PrivacyBlocked("the hand-off", gate); + const windows = await readCandidates(c.dir); + const r = await mutateBoard(c.id, (doc) => { + let pinned = 0; + let duplicates = 0; + for (const { r: f, label } of rows) { + let sec = doc.sections.find((s) => s.title === label); + if (!sec) { + sec = { id: `s${++doc.counters.section}`, title: label }; + doc.sections.push(sec); + } + const w = windows.find((x) => x.slug === f.slug && x.id === f.id && x.from <= f.t && f.t <= x.to); + const link = /\]\((.+)\)$/.exec(findingLink(f))?.[1] ?? null; + const res = addQuote(doc, { + text: f.quote, + cite: { kind: "video", source: "", channel: f.slug, video: f.id, title: f.title, date: f.date, t: f.t, end: Math.min(w?.to ?? f.t + 15, f.t + 30), url: link, track: w?.track ?? "" }, + claim: f.summary, + note: `${f.category} · relevance ${f.relevance} · ${f.speaker ? `speaker ${f.speaker} · ` : ""}row ${f.row}${f.quoteCheck === "not-found" ? " · quote not found in the captions" : ""}`, + section: sec.id, + ...(f.by === "hand" ? {} : { by: "agent" as const }), + }); + if (res.duplicate) duplicates++; + else pinned++; + } + return { pinned, duplicates }; + }); + return { plan, ...r.result }; +} + +// ── the gaps: existing editor ops, plan then confirm ── + +/** Held recordings of `slug` dated inside an era: what "persist the key period" saves. */ +async function keyPeriodIds(def: CaseDefinition, slug: string): Promise<string[]> { + const span = eraSpan(def); + if (!span) return []; + const dataDir = path.join(/* turbopackIgnore: true */ CHANNELS_DIR, slug, "data"); + const ids = [...(await heldVideoIds(dataDir))].sort(); + const out: string[] = []; + for (const vid of ids) { + const d = (await readDateAndTitle(path.join(/* turbopackIgnore: true */ dataDir, vid))).uploadDate ?? ""; + if (d && def.eras.some((e) => e.from.replace(/-/g, "") <= d && d <= e.to.replace(/-/g, ""))) out.push(vid); + } + return out; +} + +export type GapAction = "download-missing" | "transcribe" | "persist" | "focus"; + +/** + * A coverage gap's button: the editor's own action, asked over its ops API (WORKER_TOKEN) -- download-missing, + * transcribe-bucket, persist-videos (the key period's held recordings; the plan is its dryRun), and + * channel-priority's focus (the case's site, else its channels). Without `confirm` it answers the request it + * would send and asks nothing (persist's plan asks the editor's dryRun). + */ +export async function gapAction(id: string, body: { action?: unknown; slug?: unknown; confirm?: unknown }) { + const c = await ensureCase(id); + const def = await readDefinition(c.dir, c.id); + if (!def) throw new CasePipelineError("define the case first", 409); + const action = body.action as GapAction; + const slug = typeof body.slug === "string" ? body.slug : ""; + const scoped = (await caseChannels(corpusPaths(), def)).slugs; + if (action !== "focus" && !scoped.includes(slug)) throw new CasePipelineError(`"${slug}" is not a channel of this case`); + let route: string; + let request: Record<string, unknown>; + let what: string; + if (action === "download-missing") { + route = "/api/ops/download-missing"; + request = { slug }; + what = `download every listed video ${slug} does not hold (paced, on its platform's queue)`; + } else if (action === "transcribe") { + route = "/api/ops/transcribe-bucket"; + request = { slug }; + what = `transcribe ${slug}'s "downloaded, not transcribed" bucket on the transcription queue`; + } else if (action === "persist") { + const ids = await keyPeriodIds(def, slug); + if (!ids.length) throw new CasePipelineError(`${slug} holds nothing dated inside the case's eras`, 409); + route = "/api/ops/persist-videos"; + request = { items: ids.map((v) => ({ slug, id: v })) }; + what = `save ${ids.length} of ${slug}'s recordings from the case's eras to the saved-video store (one job per channel; saved ones are skipped)`; + } else if (action === "focus") { + route = "/api/ops/channel-priority"; + request = def.scope.sites.length ? { focus: { kind: "site", siteId: def.scope.sites[0] } } : { focus: { kind: "channels", slugs: scoped } }; + what = def.scope.sites.length ? `put the site ${def.scope.sites[0]}'s channels ahead in every lane` : `put the case's ${scoped.length} channels ahead in every lane`; + } else throw new CasePipelineError("action is download-missing, transcribe, persist or focus"); + if (body.confirm !== true) { + const plan: Record<string, unknown> = { route, request, what }; + if (action === "persist") { + try { + plan.dryRun = await askEditor(route, { method: "POST", body: { ...request, dryRun: true } }); + } catch (e) { + plan.dryRunError = (e as Error).message; + } + } + return { plan }; + } + const answer = await askEditor(route, { method: "POST", body: request }); + return { done: true, route, answer }; +} +