// WHAT CHANGED (umtool R4, stage 2 — deterministic, no model): the basis's // enumerations run again over the corpus as it is now, and every quote the // report cites read again at its cite. // // candidates deltaCandidates(basis-like, corpus, {known?, since?}): // the match set now, the recordings new against `known` // (or, without one, uploaded on or after `since`), the ones // whose matching lines changed, the ones no longer matched. // Callable on its own with a scope and a "since" point — // umtool's daily suggestion and R6's tier 0 are exactly it. // quotes recheckQuotes(cited, readers): R2's word check // (lib/report/quoteWords.ts) at each cite, on every track the // record has; a source gone from the archive or from its // platform; en vs en-orig. // computeDelta both, as one RefreshDelta. // // Pure over the corpus tools and readers it is handed. import { checkWordsInWindow, enOrigDifference, holdsWords, windowAround, type WordCue } from "../../quoteWords"; import { enumerateOf, type EnumeratedRow } from "../tasks/trace"; import type { CorpusToolsLike } from "../tasks/types"; import { queryKey } from "./basis"; import type { CitedQuote, MatchedRow, QuoteRecheck, RefreshBasis, RefreshDelta, RefreshQuery } from "./types"; import { goneState } from "../../../sourceGone"; export type CandidateScope = { channels: string[]; from?: string; to?: string }; export type Candidates = { // The match set now: each recording with its matching lines, summed over the queries. matchedSet: Record; rows: Map; newIds: string[]; changed: string[]; unmatched: string[]; partial: boolean; unreached: string[]; // Each query's own answer (its matched count), for the log. perQuery: { query: string; n: number; partial: boolean; error?: string }[]; }; // One enumeration's answer, as data: its rows, whether the scan was capped, // the channels a capped scan never reached. // `unreached`: the channels a capped scan never reached, and the one it // stopped inside ("TheQuartering (stopped at page 12 of 29)"). export type EnumeratedAnswer = { rows: EnumeratedRow[]; partial: boolean; unreached: string[] }; // enumerate_matches as a function: the corpus tools' (enumerateViaTools), or // a caller's own over the MCP's engine (umtool's daily check). export type EnumerateFn = (args: Record) => Promise; // R6.1 — EVERY RECORDING IN A SCOPE, from an UNCAPPED source: each channel's // transcripts manifest (every record the build ships, by id) dated by the // summaries index. Never one capped enumerate_matches(".") — a scan that // stops at its cap and calls what it read "the scope" is a silent zero. // `complete` false: some channel was not listed in full (`unreached`, with // why in `problems`), so what is missing is NOT "nothing new". // R6.2: `hasTranscript` — does the build carry transcript text for it (the // stats index's `hasTranscript`, or the record's own cues when its page was // read)? false: listed but not judge-able yet; null/absent: the build does // not say (read as judge-able, as before R6.2). export type ListedRecording = { id: string; channel: string | null; channelSlug: string | null; date: string | null; title: string | null; hasTranscript?: boolean | null }; export type RecordingListing = { rows: ListedRecording[]; complete: boolean; unreached: string[]; problems: string[] }; /** R6.2: does a transcript record (a shard page's) carry transcript text — at least one cue? */ export function recordHasText(rec: { cues?: unknown } | null | undefined): boolean { return !!rec && Array.isArray(rec.cues) && rec.cues.length > 0; } /** R6.2: a stats index entry's word on transcript text; null when there is no entry or it does not say. */ export function statHasText(stat: { hasTranscript?: unknown } | null | undefined): boolean | null { return stat && typeof stat.hasTranscript === "boolean" ? stat.hasTranscript : null; } export type ListArgs = { channels?: string[]; date_from?: string; date_to?: string }; export type ListFn = (args: ListArgs) => Promise; /** enumerate_matches through the corpus tools, its answer read back as data. */ export const enumerateViaTools = (corpus: Pick): EnumerateFn => async (args) => { const e = enumerateOf(await corpus.call("enumerate_matches", args)); return { rows: e.rows, partial: e.partial, unreached: [...(e.stopped ? [e.stopped] : []), ...e.unreached] }; }; /** The enumerate_matches arguments of one query under a scope. */ export function enumerateArgs(q: RefreshQuery, scope: CandidateScope): Record { const channels = q.channels?.length ? q.channels : scope.channels; const from = q.from ?? scope.from; const to = q.to ?? scope.to; return { query: q.query, ...(channels.length ? { channels } : {}), ...(from ? { date_from: from } : {}), ...(to ? { date_to: to } : {}), ...(q.regex ? { regex: true } : {}), }; } // An upload date as YYYY-MM-DD ("20260105", "2026-01-05", …), or null. const ymdOf = (d: string | null | undefined): string | null => { const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(String(d ?? "").trim()); return m ? `${m[1]}-${m[2]}-${m[3]}` : null; }; /** * The candidates: every query run once over `scope`; new = matched now and * not in `known` (and, when `since` is given, uploaded on or after it — with * no `known`, `since` alone decides); changed = in both, their counts known * and different; unmatched = known, not matched now (only said of a complete * scan). */ export async function deltaCandidates( basis: { queries: readonly RefreshQuery[]; scope: CandidateScope }, corpus: Pick | EnumerateFn, // R6.1: `ids` restricts every query to those recordings (a bounded scan). o: { known?: Record; since?: string | null; ids?: readonly string[]; signal?: AbortSignal } = {}, ): Promise { const run = typeof corpus === "function" ? corpus : enumerateViaTools(corpus); const seen = new Set(); const perId = new Map(); const rows = new Map(); const perQuery: Candidates["perQuery"] = []; let partial = false; const unreached = new Set(); for (const q of basis.queries) { o.signal?.throwIfAborted(); const key = queryKey(q); if (seen.has(key)) continue; seen.add(key); let e: EnumeratedAnswer; const args = enumerateArgs(q, basis.scope); // R6.1: with no known set, "new" is by upload date — the scan is bounded // by it (a whole-scope scan would hit the cap and miss the newest). const sinceDay = !o.known && o.since ? ymdOf(o.since) : null; if (sinceDay) { const had = ymdOf(args.date_from as string | undefined); if (!had || had < sinceDay) args.date_from = sinceDay; } if (o.ids?.length) args.ids = [...o.ids]; try { e = await run(args); } catch (err) { // One query that cannot run is said, and makes the scan partial. partial = true; perQuery.push({ query: q.query, n: 0, partial: true, error: (err as Error).message }); continue; } if (e.partial) partial = true; for (const c of e.unreached) unreached.add(c); perQuery.push({ query: q.query, n: e.rows.length, partial: e.partial }); for (const r of e.rows) { if (r.kind === "post") continue; const had = perId.get(r.id); perId.set(r.id, had === undefined ? r.matches : had === null || r.matches === null ? null : had + r.matches); if (!rows.has(r.id)) rows.set(r.id, { id: r.id, channel: r.channel, date: ymdOf(r.date), title: r.title, matches: null }); } } const matchedSet = Object.fromEntries(perId); for (const [id, row] of rows) row.matches = perId.get(id) ?? null; const known = o.known; const since = o.since ? ymdOf(o.since) : null; const isNew = (id: string) => { if (known && id in known) return false; if (since) { const d = rows.get(id)?.date; return !!d && d >= since; } return !!known; }; const newIds = [...perId.keys()].filter(isNew); const changed = known ? [...perId.keys()].filter((id) => { if (!(id in known)) return false; const was = known[id]; const now = perId.get(id); return was !== null && was !== undefined && now !== null && now !== undefined && was !== now; }) : []; const unmatched = known && !partial ? Object.keys(known).filter((id) => !perId.has(id)) : []; return { matchedSet, rows, newIds, changed, unmatched, partial, unreached: [...unreached].sort(), perQuery }; } // ─── the quotes ─── // A recording as a refresh reads it: its cues (the primary track) and every // track it has (named: `transcript.en.vtt`, `transcript.en-orig.vtt`, // `transcript.json` …), and its platform state when it is not available. export type RecordRead = { cues: readonly WordCue[]; tracks?: { name: string; cues: readonly WordCue[] }[]; state?: string | null; platform?: string | null }; export type QuoteReaders = { // The recording (the disk, the build); null: not in the archive. recordOf: (channel: string, id: string) => Promise; // A post's text; null: not in the archive. Absent: posts are not read. postTextOf?: (channel: string, id: string) => Promise; }; const isEn = (name: string) => /(^|[./])en\.vtt$/.test(name) || /\.en\.vtt$/.test(name); const isEnOrig = (name: string) => /en-orig/.test(name); /** Every quoted citation, read again at its cite. */ export async function recheckQuotes(cited: readonly CitedQuote[], readers: QuoteReaders, o: { span?: number; signal?: AbortSignal } = {}): Promise { const span = o.span ?? 30; const out: QuoteRecheck[] = []; const records = new Map>(); for (const c of cited) { o.signal?.throwIfAborted(); const base = { citation: c.citation, kind: c.kind, channel: c.channel, id: c.id, ...(c.start !== undefined ? { start: c.start } : {}), quote: c.quote }; try { if (c.kind === "post") { if (!readers.postTextOf) { out.push({ ...base, status: "unreadable", message: "posts are not read here" }); continue; } const text = await readers.postTextOf(c.channel, c.id); if (text === null) out.push({ ...base, status: "missing", message: `no post ${c.id} in ${c.channel} now` }); else out.push(holdsWords(text, c.quote) ? { ...base, status: "ok" } : { ...base, status: "drifted", now: text.slice(0, 3000) }); continue; } const key = `${c.channel}/${c.id}`; let p = records.get(key); if (!p) { p = readers.recordOf(c.channel, c.id); records.set(key, p); } const rec = await p; if (!rec || (!rec.cues.length && !(rec.tracks ?? []).some((t) => t.cues.length))) { out.push({ ...base, status: "missing", message: rec ? `${key} has no transcript now` : `${key} is not in the archive now` }); continue; } // A recording "gone" from its platform: the one reading (lib/sourceGone.ts). const state = goneState(rec.state) ?? undefined; const t = c.start ?? 0; const cite = { t, end: c.end ?? t }; // The primary first, then every other track: the words on any of them stand. const tracks = [rec.cues, ...(rec.tracks ?? []).map((x) => x.cues)].filter((x) => x.length); let verdict = checkWordsInWindow(c.quote, cite, windowAround(tracks[0]!, t, span)); for (let i = 1; i < tracks.length && verdict.status !== "ok"; i++) { const v = checkWordsInWindow(c.quote, cite, windowAround(tracks[i]!, t, span)); if (v.status === "ok") verdict = v; } const en = (rec.tracks ?? []).find((x) => isEn(x.name) && !isEnOrig(x.name)); const orig = (rec.tracks ?? []).find((x) => isEnOrig(x.name)); const enOrig = en && orig ? enOrigDifference(en.cues, orig.cues, cite) : null; const extra = { ...(state ? { state, ...(rec.platform ? { platform: rec.platform } : {}) } : {}), ...(enOrig ? { enOrig } : {}) }; if (verdict.status === "ok") { out.push(verdict.nowAt !== undefined ? { ...base, status: "moved", nowAt: verdict.nowAt, ...extra } : { ...base, status: "ok", ...extra }); } else { out.push({ ...base, status: "drifted", now: verdict.now, ...(verdict.nowAt !== undefined ? { nowAt: verdict.nowAt } : {}), ...(verdict.empty ? { message: `no cues within ${span} s of the cite now` } : {}), ...extra }); } } catch (e) { if (o.signal?.aborted) throw e; out.push({ ...base, status: "unreadable", message: (e as Error).message }); } } return out; } /** Stage 2: the candidates and the quotes, as one delta. */ export async function computeDelta( basis: RefreshBasis, corpus: Pick, readers: QuoteReaders, o: { now?: Date; signal?: AbortSignal } = {}, ): Promise { const cand = await deltaCandidates(basis, corpus, { known: basis.knownComplete ? basis.known : undefined, since: basis.knownComplete ? null : basis.at, ...(o.signal ? { signal: o.signal } : {}), }); // Without the whole old set, "new" is by upload date; the cited are never new. const newIds = cand.newIds.filter((id) => !(id in basis.known)); const quotes = await recheckQuotes(basis.cited, readers, o.signal ? { signal: o.signal } : {}); const drifted = quotes.filter((q) => q.status === "drifted").map((q) => q.citation); const deleted = [...new Set(quotes.filter((q) => q.status === "missing" || q.state).map((q) => `${q.channel}/${q.id}`))]; const goneFromArchive = [...new Set(quotes.filter((q) => q.status === "missing").map((q) => `${q.channel}/${q.id}`))]; const removed = new Map(); for (const q of quotes) { const source = `${q.channel}/${q.id}`; if (q.status !== "missing" && q.state && !removed.has(source)) removed.set(source, { source, state: q.state, platform: q.platform ?? null }); } const enOrig = quotes.filter((q) => q.enOrig).map((q) => q.citation); const changed = basis.countsKnown ? cand.changed : []; const status = newIds.length || changed.length || drifted.length || deleted.length ? "changed" : "no-change"; return { at: (o.now ?? new Date()).toISOString(), status, matched: Object.keys(cand.matchedSet).length, newIds, new: newIds.map((id) => cand.rows.get(id)!).filter(Boolean), changed: basis.countsKnown ? cand.changed : [], changedTracked: basis.countsKnown, ...(basis.countsKnown ? {} : { changedSince: basis.at }), unmatched: cand.unmatched, drifted, deleted, goneFromArchive, removedOnPlatform: [...removed.values()], enOrig, quotes, partial: cand.partial, unreached: cand.unreached, matchedSet: cand.matchedSet, }; }