// 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, forumAttachmentLabel, isCaseStatus, isFindingBy, isRelevance, isVerifyStatus, normalizeTerm, type CandidateCounts, type CandidateHit, type CandidateWindow, type CaseBatch, type CaseDefinition, type CaseEra, type CaseEvidence, type CaseSummaryText, type DateCheck, type FindingRow, type ReaderGroup, type WindowTrack, } from "./caseTypes"; import { evidenceSection } from "./caseEvidence"; /** 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, 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; 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; 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; 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 ":", not "${badGroup}"`); const eraIds = new Set(); const eras: CaseEra[] = (Array.isArray(r.eras) ? r.eras : []).map((e, i) => { const o = (e && typeof e === "object" ? e : {}) as Record; 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; const families: Record = {}; 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(); const groups: ReaderGroup[] = (Array.isArray(r.groups) ? r.groups : []).map((g, i) => { const o = (g && typeof g === "object" ? g : {}) as Record; 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; 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; 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; 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 { 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, 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): { 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): Set { const out = new Set(); 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): Set => 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, 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): 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(`(? 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, 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(); 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, 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, 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 ), 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 `--`. */ export function planBatches( def: Pick, windows: CandidateWindow[], o: { budget?: number; round: number; exclude?: ReadonlySet }, ): { batches: CaseBatch[]; texts: Map } { const budget = o.budget ?? 60_000; const labels = new Map(def.groups.map((g) => [g.id, g.label])); const byGroup = new Map(); 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(); 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 & { row?: string } } | { ok: false; errors: string[] } { const r = (raw && typeof raw === "object" ? raw : {}) as Record; 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; 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"'), 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 & { 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, 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(); 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): 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); // One label everywhere (caseTypes.ts forumAttachmentLabel): the post's "#N" in its thread when known. for (const e of r.evidence ?? []) if (e.kind === "forum-attachment") asides.push(forumAttachmentLabel(e.position, e.post)); 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; /** Lane C: evidence.json's rows, listed in an Evidence section (caseEvidence.ts). */ evidence?: readonly CaseEvidence[]; }; /** 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(...evidenceSection(c.evidence ?? [])); out.push("## Coverage", "", clean(c.coverage), ""); return out.join("\n"); } const escHtml = (s: string) => s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); /** 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 `${escHtml(m[1])}`; }) .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(""); 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(`

${inline(title)}

`); } else if (/^## /.test(l)) { close(); body.push(`

${inline(l.slice(3).trim())}

`); } else if (/^- /.test(l)) { if (!inList) body.push("
    "); inList = true; let item = inline(l.slice(2)); while (lines[i + 1]?.startsWith(" ")) item += `
    ${inline(lines[++i].trim())}`; body.push(`
  • ${item}
  • `); } else if (l.trim()) { close(); body.push(`

    ${inline(l.trim())}

    `); } else close(); } close(); return [ "", '', `${escHtml(title)}`, "", "", ...body, "", "", ].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 ". */ export function dateChecks( def: Pick, uploads: DatedUpload[], findings: Pick[], 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(); 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 };