// RESEARCH CASES AS A PIPELINE -- the contract (plans/release-38/research-cases-and-assist.md, lane 0). // Every r38 lane codes against these shapes: A (coverage, candidates, batches, merge, the privacy gate, date // checks), B (the read: by hand, `case-read`, the quote check), C (verify, leads, evidence, polite retries) and D // (the MCP's case tools). Types, constants and guards only: no I/O, and safe for a client component. The one hash // the gate and the case page must agree on, privateNameHash, is in privateNames-server.ts. // // A case is umtool's board (umtool/lib/research/cases.mjs, `REPORTS_ROOT/.umtool/research//case.json`, // "umtool-research-case" v1). The pipeline lives BESIDE it in the same directory, never inside case.json: the // board's store has one writer and its own version, and every stage below writes a file of its own. // // /pipeline.json CaseDefinition (subjects, scope, eras, reader groups, private-name hashes) // /coverage.json CoverageRow[] (stage 1) // /candidates.jsonl CandidateWindow, one per line (stage 2) // /candidates.counts.json CandidateCounts: per family, year, channel, group, before any read (stage 2) // /batches/index.json CaseBatch[] (stage 3) // /batches/.txt the batch's WRAPPED text: no line over BATCH_LINE_MAX (stage 3) // /findings.jsonl FindingRow, one per line, appended (stage 4; verify and merge rewrite whole) // /leads.json CaseLead[] (stage 8) // /date-checks.json DateCheck[] (stage 9) // /evidence.json CaseEvidence[] (stage 10; lane C's extension) // /summary.json CaseSummaryText: the report's summary, by hand or a model's draft (stage 5) // /REPORT.md, REPORT.html the merged report as exported (stage 5, behind the privacy gate) // /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 // (privateNameCandidates) and blocks on a match; what it reports is counts and row ids, never the term. export const CASE_PIPELINE_FORMAT = "archilyzer-case-pipeline"; export const CASE_PIPELINE_VERSION = 1; 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", evidence: "evidence.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. */ export const BATCH_LINE_MAX = 200; /** A finding's quote: verbatim, at most this many words. */ export const QUOTE_WORDS_MAX = 45; /** Merge: two rows on the same video closer than this (seconds) are one finding. */ export const MERGE_DEDUPE_SECONDS = 20; /** Merge: the report's default floor. */ export const MERGE_MIN_RELEVANCE = 2; /** What the naming rule replaces a private name with, in every reader prompt and every surface. */ export const NAME_WITHHELD = "[name withheld]"; // --------------------------------------------------------------------------------------------------------------- // The definition /** * `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; /** * 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 * subjects' own channels) or "coverage" (everyone else in scope, where a mention of a subject at all is the bar). */ export type ReaderGroup = { id: string; label: string; channels: string[] | "subject" | "coverage"; era?: string }; export type PrivateNames = { /** privateNameHash of each term, lowercase hex. The terms themselves are never stored. */ sha256: string[]; /** Why these names are withheld, in words that do not contain them. */ note: string; }; export const CASE_STATUSES = ["defining", "gathering", "reading", "merging", "verifying", "done"] as const; export type CaseStatus = (typeof CASE_STATUSES)[number]; export type CaseDefinition = { format: typeof CASE_PIPELINE_FORMAT; version: typeof CASE_PIPELINE_VERSION; /** The umtool case id it sits beside. */ case: string; subjects: CaseSubject[]; scope: CasePipelineScope; eras: CaseEra[]; groups: ReaderGroup[]; privateNames: PrivateNames; /** `common` goes before every group's own prompt; keyed by group id otherwise. */ readerPrompts: { common: string } & Record; /** Stage 9's dates. Absent or empty: each era's start. */ keyDates?: CaseKeyDate[]; status: CaseStatus; createdAt: string; updatedAt: string; }; // --------------------------------------------------------------------------------------------------------------- // Stage 1: coverage, per channel × year 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; transcribed: number; /** Held with audio but no transcript. */ untranscribedAudio: number; /** The year contains one of the case's key periods (an era's span). */ key?: boolean; }; // --------------------------------------------------------------------------------------------------------------- // Stage 2: candidate windows /** The text a window was read from; en-orig is preferred over en, then a whisper/parakeet transcript, then cues. */ export const WINDOW_TRACKS = ["en-orig", "en", "transcript", "cues"] as const; export type WindowTrack = (typeof WINDOW_TRACKS)[number]; export type CandidateHit = { t: number; family: string; match: string }; export type CandidateWindow = { /** `/@`: stable across rebuilds of the same scan. */ key: string; slug: string; id: string; /** YYYYMMDD. */ date: string; title: string; from: number; to: number; era: string; group: string; track: WindowTrack; 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; byYear: Record; byChannel: Record; byGroup: Record; byEra: Record; /** 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; /** 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 export type CaseBatch = { /** `--`. */ id: string; group: string; round: number; /** CandidateWindow keys, in reading order. */ windows: string[]; chars: number; /** Relative to the case dir: batches/.txt. */ file: string; state: "pending" | "reading" | "read" | "failed"; }; // --------------------------------------------------------------------------------------------------------------- // Stage 4: findings export type Relevance = 1 | 2 | 3; /** Who wrote a row: a person's hand on the candidate deck, or a `case-read` route. */ export const FINDING_BY = ["hand", "api", "local", "code"] as const; export type FindingBy = (typeof FINDING_BY)[number]; /** * The quote check: the row's quote, normalised, is in its window's caption text, or it is not. A row whose quote is * not found is KEPT and flagged, never dropped: a garbled caption is still evidence to check. */ export type QuoteCheck = "found" | "not-found" | "unchecked"; /** * Stage 7. `quarantined`: first seen on a forum and not corroborated by an independent source (operator, * 2026-10-20: forum joke culture). It has its own report section. */ export const VERIFY_STATUSES = ["unverified", "verified", "corrected", "disputed", "quarantined"] as const; export type VerifyStatus = (typeof VERIFY_STATUSES)[number]; export type FindingVerify = { status: VerifyStatus; at: string; /** "audio" when an audio check (a window transcribed and diffed) decided it. */ how?: "captions" | "audio" | "hand"; note?: string; /** "Corrected by hand" keeps what the reader wrote. */ original?: { quote: string; speaker?: string }; /** Lane C: the last audio check -- the window transcribed through the editor and its words diffed with the quote. */ audio?: AudioCheck; }; /** An audio check's outcome: what the worker heard, and how much of the quote it holds. */ export type AudioCheck = { at: string; /** The editor's transcribe-file job. */ job: string; /** The window's transcript (private names already NAME_WITHHELD). */ text: string; /** The quote's words found in order in the transcript, of all its words. */ matched: number; words: number; /** The worker that heard it, as the editor names it. */ worker?: string; }; /** A forum post's attachment or screenshot, shown everywhere as "forum attachment, post #N, unverified". */ export type FindingEvidence = { kind: "forum-attachment" | "wayback"; post?: string; url: string; capturedAt?: string; /** Lane C: the CaseEvidence row it came from, and a forum post's position in its thread (the "#N"). */ evidence?: string; position?: number; }; export type FindingRow = { /** `f`: unique in the case, never reused. */ row: string; batch: string; slug: string; id: string; date: string; title: string; t: number; url: string; category: string; relevance: Relevance; /** Verbatim, at most QUOTE_WORDS_MAX words. Private names already NAME_WITHHELD. */ quote: string; summary: string; speaker: string; confidence: "high" | "medium" | "low"; round: number; by: FindingBy; quoteCheck: QuoteCheck; verify?: FindingVerify; evidence?: FindingEvidence[]; }; // --------------------------------------------------------------------------------------------------------------- // 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; }; export type CaseStageRuns = Partial>; // --------------------------------------------------------------------------------------------------------------- // Stage 8: leads; stage 9: absence and date checks export const LEAD_DISPOSITIONS = ["archive", "watch", "never-archive"] as const; export type LeadDisposition = (typeof LEAD_DISPOSITIONS)[number]; export type CaseLead = { /** The account or URL, normalised (`x:@handle`, a host+path). */ key: string; url: string; platform: string; /** How often the scope's posts link it. */ count: number; role?: string; /** Unset until a person decides. `never-archive` feeds the case's private names; `archive` creates the channel. */ disposition?: LeadDisposition; /** The channel `archive` created. */ channel?: string; }; // --------------------------------------------------------------------------------------------------------------- // Stage 10: evidence capture (lane C's extension: the contract named FindingEvidence but no file for the captures) /** Wayback captures at chosen dates; a forum post's attachments or screenshot. */ export const EVIDENCE_KINDS = ["wayback", "forum-attachment"] as const; export type EvidenceKind = (typeof EVIDENCE_KINDS)[number]; /** * planned: not asked yet. queued: the editor's job is running. captured: held. excluded: the Wayback Machine answered * 403 for the URL (EXCLUDED_SENTENCE). failed: the job or the editor said no (its words in `message`). */ export const EVIDENCE_STATES = ["planned", "queued", "captured", "excluded", "failed"] as const; export type EvidenceState = (typeof EVIDENCE_STATES)[number]; export type CaseEvidence = { /** `e`: unique in the case, never reused. */ id: string; kind: EvidenceKind; /** wayback: the page's own URL. forum-attachment: the post's permalink. */ url: string; /** wayback: the date chosen, YYYYMMDD (the capture nearest it). */ at?: string; /** The channel it went into (a Wayback pages channel), or the forum channel the post is in. */ slug?: string; /** forum-attachment: the post's id, and its "#N" in the thread when the forum gives one. */ post?: string; position?: number; state: EvidenceState; /** The editor's job (import-page, capture-posts). */ job?: string; /** wayback: the capture landed on, and the records it made. */ captureTs?: string; records?: string[]; /** forum-attachment: the files captured, relative to the channel's posts-media//. */ files?: string[]; /** The refusal's code ("excluded", …) and the sentence shown for it. */ refusal?: string; message?: string; /** The finding rows it is evidence for. */ findings?: string[]; note?: string; createdAt: string; updatedAt: string; }; /** What a Wayback 403 means, in every surface (the editor's WAYBACK_EXCLUDED_PHRASE; a test keeps them equal). */ export const EXCLUDED_SENTENCE = "excluded from the Wayback Machine (cause unknown)"; /** A forum attachment's label, in every surface: never shown as anything but unverified. */ export function forumAttachmentLabel(position?: number | null, post?: string | null): string { const n = typeof position === "number" && position > 0 ? String(position) : post ? post : "?"; return `forum attachment, post #${n}, unverified`; } /** The label a finding's evidence or an evidence row carries. */ export function evidenceLabel(e: { kind: EvidenceKind; position?: number; post?: string; capturedAt?: string; captureTs?: string; state?: EvidenceState }): string { if (e.kind === "forum-attachment") return forumAttachmentLabel(e.position, e.post); if (e.state === "excluded") return EXCLUDED_SENTENCE; const ts = e.captureTs ?? e.capturedAt; return ts && /^\d{8}/.test(ts) ? `Wayback capture, ${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)}` : "Wayback capture"; } export type DateCheck = { /** The key date checked, YYYY-MM-DD. */ date: string; label: string; /** The subject's uploads in the window around it. */ uploads: { slug: string; id: string; date: string; title: string; captioned: boolean }[]; /** "no response found in captioned uploads through ", or what was found. */ sentence: string; }; // --------------------------------------------------------------------------------------------------------------- // Guards, and what the private-name gate hashes const isOneOf = (list: readonly T[]) => (value: unknown): value is T => typeof value === "string" && (list as readonly string[]).includes(value); export const isVerifyStatus = isOneOf(VERIFY_STATUSES); export const isEvidenceKind = isOneOf(EVIDENCE_KINDS); export const isEvidenceState = isOneOf(EVIDENCE_STATES); 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(" "); /** 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(); for (let i = 0; i < words.length; i++) { 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]; }