// TRIAGE, TIER 0 — code, $0 (umtool R6; R6.1): the candidates. // // new a recording in scope the owner's last completed triage did NOT // see — by ID, not by publish date, so an old recording whose // transcript lands late is new (R5's late-transcript gap, closed). // With no last run, new is "uploaded on or after `since`". // candidate a new recording that matches the terms (enumerate_matches, // alias-aware), OR whose digest topic tags match the topics; with // neither terms nor topics, every new recording // // R6.1 — NO SILENT ZEROS. What exists in scope is LISTED, never scanned with // one capped enumerate_matches("."): the corpus's `listRecordings` (each // channel's transcripts manifest, dated by the summaries index — uncapped), // else enumerate_matches per channel (capped: said). The terms query is // BOUNDED: restricted to the new ids (`ids`: only the pages holding them are // read), and on a first run also by `date_from = since`. Any cap hit, or a // channel not listed in full, makes tier 0 `partial` with what was not // reached — and a partial run's seen set is never stored (`seen: null`), so // the next run does not count what this one missed as known. // // The listing is the set this run SAW, which becomes the next run's `known` — // less the candidates past the cap, which stay new. Posts are not candidates // (a triage reads transcript windows). // // R6.2 — SEEN MEANS JUDGE-ABLE. A build's manifests list a recording before // its transcript lands (metadata only). Such a recording (the listing's // `hasTranscript: false`) is neither new nor seen this run: it stays out of // seen.json, so the run after its transcript lands counts it new by id — the // late transcript R6's by-id rule exists to catch. An id an earlier run // stored as seen while it had no text (before R6.2) is dropped from the set // this run stores, so it heals the same way. Unknown (`null`, the enumerate // fallback): judge-able, as before. // // Pure over the list and enumerate functions and the topic reader it is handed. import { type EnumerateFn, type ListFn, type RecordingListing } from "../refresh/delta"; import { learnedAlternation, learnedWords, spellingPattern } from "./learned"; import { listedWords, type TriageCandidate, type TriageTier0 } from "./types"; // The untranscribed ids triage.json names (the count is whole). const UNTRANSCRIBED_IDS_KEPT = 50; export type Tier0Input = { scope: { channels: string[]; from?: string; to?: string }; terms: string | null; regex?: boolean; topics: string[]; // The ids the last completed run saw; null: none yet (then `since`). known: ReadonlySet | null; since: string | null; // Named by the caller: no scan, these are the candidates. ids?: string[]; // The most candidates tier 1 judges (the rest are cut, left new). max: number; // The most new recordings whose digest tags are read for the topics. maxTopicReads?: number; // R6.3: the spellings the watch learned — escaped literal alternatives of // the candidate query ("terms + N learned"), never a regex of their own. learned?: string[]; }; export type Tier0Deps = { enumerate: EnumerateFn; // Every recording in scope, uncapped (the corpus's listRecordings). Absent: // enumerate_matches per channel, its cap said. list?: ListFn; // A recording's digest topic tags (null: no digest). Absent: topics unread. topicsOf?: (id: string, channel: string | null) => Promise; signal?: AbortSignal; log?: (line: string) => void; }; export type Tier0Result = { tier0: TriageTier0; // What the next run counts as known (null: leave seen.json as it is — a // partial run, or ids named). seen: string[] | null; // The scope listing's ids (for the trace). scannedIds: string[]; }; 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; }; const wordsOf = (s: string) => ` ${s .toLowerCase() .replace(/[^\p{L}\p{N}]+/gu, " ") .trim()} `; /** Does a digest tag match a topic? Equal, or one holds the other as whole words (case and punctuation aside). */ export function tagMatches(tag: string, topic: string): boolean { const t = wordsOf(tag); const p = wordsOf(topic); if (t.trim() === "" || p.trim() === "") return false; return t === p || t.includes(p) || p.includes(t); } /** * R6.2: a listing split into what a triage can judge now and what waits for * its transcript (`hasTranscript: false`). Unknown (null/absent) is judge-able. */ export function splitByTranscript(rows: readonly R[]): { judgeable: R[]; waiting: R[] } { const judgeable: R[] = []; const waiting: R[] = []; for (const r of rows) (r.hasTranscript === false ? waiting : judgeable).push(r); return { judgeable, waiting }; } /** * The set a run stores as seen.json (R6.1, R6.2): everything known, plus * everything listed that can be judged — less the candidates past the cap * (they stay new) and less what is listed without a transcript (new once * transcribed; a known id among them, stored before R6.2, is dropped, so it * heals). A PARTIAL run stores nothing (null): what it did not reach must not * become known, so the next run falls back to the last complete run's set (or * to its `since`). */ export function nextSeen(o: { partial: boolean; known: Iterable | null; judgeable: Iterable; cut: Iterable; waiting: Iterable }): string[] | null { if (o.partial) return null; const drop = new Set([...o.cut, ...o.waiting]); return [...new Set([...(o.known ?? []), ...o.judgeable])].filter((id) => !drop.has(id)); } export async function triageCandidates(i: Tier0Input, d: Tier0Deps): Promise { const log = (l: string) => d.log?.(l); if (i.ids?.length) { const ids = [...new Set(i.ids)]; const candidates: TriageCandidate[] = ids.slice(0, i.max).map((id) => ({ id, channel: null, title: null, date: null, matches: null, by: ["ids"] })); return { tier0: { candidates, scanned: 0, newCount: ids.length, cut: ids.slice(i.max), partial: false, unreached: [], perQuery: [], newBy: "ids" }, seen: null, scannedIds: [], }; } const { channels } = i.scope; const since = i.known ? null : ymdOf(i.since); // The scope, listed: what this run SAW (the whole scope — on a first run // too, or the next run would count everything older as new). const listing = await listScope(i.scope, d); d.signal?.throwIfAborted(); const rows = listing.rows; const perQuery: TriageTier0["perQuery"] = [{ query: listing.by === "manifests" ? "(every recording, listed)" : "(any recording)", n: rows.length, partial: !listing.complete }]; // R6.2: listed with no transcript text yet — not judge-able, so not new and // not seen (new on the run after its transcript lands). const { judgeable, waiting } = splitByTranscript(rows); const isNew = (id: string, date: string | null) => (i.known ? !i.known.has(id) : since ? !!date && date >= since : true); const fresh = judgeable.filter((r) => isNew(r.id, ymdOf(r.date))); const byId = new Map(fresh.map((r) => [r.id, r])); log(`tier 0: ${listedWords({ scanned: rows.length, untranscribed: waiting.length })}`); log( `tier 0: ${rows.length} recording(s) in scope (${listing.by === "manifests" ? "listed from the build's manifests" : "enumerated per channel"}), ${fresh.length} new ${i.known ? `since the last run (by id; ${i.known.size} known)` : since ? `uploaded on or after ${since}` : "(no last run, no since: all)"}${listing.complete ? "" : ` — PARTIAL: ${listing.problems.join("; ")}`}`, ); let partial = !listing.complete; const unreached = new Set(listing.unreached); const problems = [...listing.problems]; const found = new Map(); const terms = i.terms?.trim() || null; const topics = i.topics.map((t) => t.trim()).filter(Boolean); if (terms && fresh.length) { // Bounded: only the new recordings' pages are read (and, on a first run, // from `since`) — never the whole scope, whose scan would hit the cap. const args: Record = { query: terms, ...(i.regex ? { regex: true } : {}), ...(channels.length ? { channels } : {}), ...(i.scope.to ? { date_to: i.scope.to } : {}), ...(since ? { date_from: i.scope.from && i.scope.from > since ? i.scope.from : since } : i.scope.from ? { date_from: i.scope.from } : {}), ids: [...byId.keys()], content_types: ["video"], }; let n = 0; try { const e = await d.enumerate(args); if (e.partial) { partial = true; problems.push(`the terms query hit its cap`); } for (const u of e.unreached) unreached.add(u); for (const row of e.rows) { if (row.kind === "post" || !byId.has(row.id)) continue; n++; const r = byId.get(row.id)!; found.set(row.id, { id: row.id, channel: row.channel ?? r.channel ?? null, title: row.title ?? r.title ?? null, date: ymdOf(row.date) ?? ymdOf(r.date), matches: row.matches ?? null, by: ["terms"] }); } perQuery.push({ query: terms, n, partial: e.partial }); } catch (err) { partial = true; problems.push(`the terms query could not run: ${(err as Error).message}`); perQuery.push({ query: terms, n: 0, partial: true, error: (err as Error).message }); } log(`tier 0: terms ${JSON.stringify(terms)}: ${n} new recording(s) match (of ${fresh.length} new, read by id)`); } else if (terms) { perQuery.push({ query: terms, n: 0, partial: false }); log(`tier 0: terms ${JSON.stringify(terms)}: no new recording to read`); } // R6.3: the learned spellings, as one query of escaped literals over the // same new ids (and dates), then — with several — each over what matched, // so a candidate names the spellings that brought it. const learned = [...new Set((i.learned ?? []).map((x) => x.trim()).filter(Boolean))]; let learnedMatched = 0; if (learned.length && terms && fresh.length) { const bounds: Record = { ...(channels.length ? { channels } : {}), ...(i.scope.to ? { date_to: i.scope.to } : {}), ...(since ? { date_from: i.scope.from && i.scope.from > since ? i.scope.from : since } : i.scope.from ? { date_from: i.scope.from } : {}), content_types: ["video"], }; const alt = learnedAlternation(learned)!; const bySpelling = new Map(); const lines = new Map(); try { const e = await d.enumerate({ query: alt, regex: true, ...bounds, ids: [...byId.keys()] }); if (e.partial) { partial = true; problems.push("the learned spellings' query hit its cap"); } for (const u of e.unreached) unreached.add(u); const hit = e.rows.filter((r) => r.kind !== "post" && byId.has(r.id)); for (const r of hit) lines.set(r.id, r.matches ?? 0); if (hit.length && learned.length === 1) bySpelling.set(learned[0]!, hit.map((r) => r.id)); else if (hit.length) { for (const sp of learned) { const e2 = await d.enumerate({ query: spellingPattern(sp), regex: true, ...bounds, ids: hit.map((r) => r.id) }); bySpelling.set(sp, e2.rows.filter((r) => r.kind !== "post" && lines.has(r.id)).map((r) => r.id)); } } for (const r of hit) { const spellings = learned.filter((sp) => bySpelling.get(sp)?.includes(r.id)); const had = found.get(r.id); if (had) { if (!had.by.includes("learned")) had.by.push("learned"); had.learned = spellings; } else { const b = byId.get(r.id)!; found.set(r.id, { id: r.id, channel: r.channel ?? b.channel ?? null, title: r.title ?? b.title ?? null, date: ymdOf(r.date) ?? ymdOf(b.date), matches: r.matches ?? null, by: ["learned"], learned: spellings }); learnedMatched++; } } perQuery.push({ query: `(${learnedWords(learned.length, false)})`, n: hit.length, partial: e.partial }); log(`tier 0: ${learnedWords(learned.length)}: ${hit.length} new recording(s) match a learned spelling, ${learnedMatched} of them no term does`); } catch (err) { partial = true; problems.push(`the learned spellings' query could not run: ${(err as Error).message}`); perQuery.push({ query: `(${learnedWords(learned.length, false)})`, n: 0, partial: true, error: (err as Error).message }); } } if (topics.length && d.topicsOf) { let reads = 0; let hits = 0; const max = i.maxTopicReads ?? 200; for (const r of fresh) { if (reads >= max) break; d.signal?.throwIfAborted(); reads++; const tags = await d.topicsOf(r.id, r.channelSlug ?? r.channel).catch(() => null); const matched = (tags ?? []).filter((t) => topics.some((p) => tagMatches(t, p))); if (!matched.length) continue; hits++; const had = found.get(r.id); if (had) { had.by.push("topics"); had.tags = matched; } else { found.set(r.id, { id: r.id, channel: r.channel, title: r.title, date: ymdOf(r.date), matches: null, by: ["topics"], tags: matched }); } } log(`tier 0: topics ${topics.join(", ")}: ${hits} of ${reads} new recording(s) read carry a matching digest tag${fresh.length > reads ? ` (${fresh.length - reads} not read: the cap)` : ""}`); } else if (topics.length) { log("tier 0: topics given but no digest reader here: topics not matched"); } if (!terms && !topics.length) { for (const r of fresh) found.set(r.id, { id: r.id, channel: r.channel, title: r.title, date: ymdOf(r.date), matches: null, by: ["new"] }); } const ranked = [...found.values()].sort( (a, b) => b.by.length - a.by.length || (b.matches ?? 0) - (a.matches ?? 0) || String(b.date ?? "").localeCompare(String(a.date ?? "")) || a.id.localeCompare(b.id), ); const candidates = ranked.slice(0, i.max); const cut = ranked.slice(i.max).map((c) => c.id); const scannedIds = rows.map((r) => r.id); // Seen: nextSeen's rule (known + judge-able, less cut and waiting; partial: none). const seen = nextSeen({ partial, known: i.known, judgeable: judgeable.map((r) => r.id), cut, waiting: waiting.map((r) => r.id) }); if (partial) log(`tier 0: PARTIAL${unreached.size ? ` — not reached: ${[...unreached].join(", ")}` : ""}: this run's seen set is not kept`); return { tier0: { candidates, scanned: rows.length, newCount: fresh.length, ...(waiting.length ? { untranscribed: waiting.length, untranscribedIds: waiting.slice(0, UNTRANSCRIBED_IDS_KEPT).map((r) => r.id) } : {}), cut, partial, unreached: [...unreached].sort(), perQuery, newBy: i.known ? "id" : "date", listedBy: listing.by, ...(problems.length ? { problems } : {}), ...(learned.length && terms ? { learned: { spellings: learned, matched: learnedMatched } } : {}), }, seen, scannedIds, }; } type ScopeRow = { id: string; channel: string | null; channelSlug?: string | null; date: string | null; title: string | null; hasTranscript?: boolean | null }; /** * Every recording in scope: the corpus's uncapped listing when it has one, * else enumerate_matches(".") per channel — each capped, and a capped one * said (the channel named), never taken for the whole channel. */ async function listScope(scope: Tier0Input["scope"], d: Tier0Deps): Promise<{ rows: ScopeRow[]; complete: boolean; unreached: string[]; problems: string[]; by: "manifests" | "enumerate" }> { const dates = { ...(scope.from ? { date_from: scope.from } : {}), ...(scope.to ? { date_to: scope.to } : {}) }; if (d.list) { const l: RecordingListing = await d.list({ ...(scope.channels.length ? { channels: scope.channels } : {}), ...dates }); return { rows: l.rows, complete: l.complete, unreached: l.unreached, problems: l.problems, by: "manifests" }; } const rows: ScopeRow[] = []; const unreached: string[] = []; const problems: string[] = []; const groups = scope.channels.length ? scope.channels.map((c) => [c]) : [[]]; for (const chs of groups) { d.signal?.throwIfAborted(); const e = await d.enumerate({ query: ".", regex: true, ...(chs.length ? { channels: chs } : {}), ...dates, content_types: ["video"] }); for (const r of e.rows) if (r.kind !== "post") rows.push({ id: r.id, channel: r.channel, date: r.date, title: r.title }); if (e.partial) { const where = e.unreached.length ? e.unreached : chs.length ? chs : ["the scope"]; unreached.push(...where); problems.push(`${chs.length ? chs.join(", ") : "the scope"}: the listing hit enumerate's cap after ${e.rows.length} recording(s) (not reached: ${where.join(", ")})`); } } return { rows, complete: problems.length === 0, unreached, problems, by: "enumerate" }; }