// LEARNED SPELLINGS — THE PROPOSAL PASS AND THE CONFIRMATION (umtool R6.3). // Nothing is learned on the model's word: // // count every pending spelling counted in scope at once, UNCAPPED: the // corpus's `countPhrases` (mcp/src/enumerate.ts — the scope's // listing, then enumerate_matches restricted to its ids in // batches a cap can never cut), else enumerate_matches per // spelling over the listing's ids in the same batches. No hits: // dropped ("no-hits"). A count that could not read everything and // found nothing is "unread" (asked again next pass), never "none" // judge the judge reads up to CONFIRM_WINDOWS windows where it occurs // (newest first; a heard span's own window first) and must say it // means the watched name, quoting the line. The quote must be // VERBATIM in that window and hold the spelling, and be in the // transcript's cues near it (R2's word check). Kept when at least // 2 of the windows read say so (keptByWindows); with a single // window, that yes and at least 3 recordings in scope. Each // window's verdict is kept on the spelling (or its drop) // // proposeSpellings asks the model for mis-hearings of each name (parseProposals // checks them); runLearnPass is the whole pass. Pure over the corpus tools, the // model (`ask`) and the readers it is handed. import { holdsWords, windowAround, type WordCue } from "../../quoteWords"; import { mmss } from "../reportOps"; import { locate, parseTranscripts, windowsOf, type ParsedTranscript } from "../tasks/sweep-pipeline"; import type { CorpusToolsLike } from "../tasks/types"; import type { ListFn, EnumerateFn } from "../refresh/delta"; import { CONFIRM_SCHEMA, CONFIRM_SYSTEM, CONFIRM_WINDOWS, PROPOSALS_PER_NAME, PROPOSE_SYSTEM, confirmUser, holdsSpelling, normSpelling, parseProposals, proposeSchema, proposeUser, spellingKey, spellingPattern, type LearnedDrop, type LearnedDropReason, type LearnedSpelling, type SpellingSource, type SpellingWindow, type TriageHeard, } from "./learned"; // ─── the count ─── export type PhraseExample = { id: string; channel: string | null; channelSlug: string | null; date: string | null; title: string | null; start: number | null; text: string | null }; export type PhraseCount = { recordings: number; lines: number; examples: PhraseExample[] }; /** Each phrase's count over a scope; `complete` false: some of the scope was not read (said in `problems`). */ export type PhraseCounts = { counts: Record; complete: boolean; problems: string[]; listed: number }; export type CountPhrasesArgs = { phrases: string[]; channels?: string[]; date_from?: string; date_to?: string; examples?: number }; export type CountPhrasesFn = (args: CountPhrasesArgs) => Promise; // The ids one restricted enumerate reads: well under its 2,000-recording cap. export const COUNT_ID_BATCH = 1000; /** * A corpus without `countPhrases`: the scope LISTED (uncapped), then each * phrase through enumerate_matches restricted to the listing's ids, in * batches the cap cannot cut. Slower (a scan per phrase); the same answer. */ export function countViaEnumerate(list: ListFn, enumerate: EnumerateFn): CountPhrasesFn { return async (a) => { const listing = await list({ ...(a.channels?.length ? { channels: a.channels } : {}), ...(a.date_from ? { date_from: a.date_from } : {}), ...(a.date_to ? { date_to: a.date_to } : {}) }); const rows = listing.rows.filter((r) => r.hasTranscript !== false); const byId = new Map(rows.map((r) => [r.id, r])); const ids = [...byId.keys()]; const problems = [...listing.problems]; let complete = listing.complete; const counts: Record = {}; for (const p of a.phrases) { const c: PhraseCount = { recordings: 0, lines: 0, examples: [] }; for (let i = 0; i < ids.length; i += COUNT_ID_BATCH) { const e = await enumerate({ query: spellingPattern(p), regex: true, ...(a.channels?.length ? { channels: a.channels } : {}), ids: ids.slice(i, i + COUNT_ID_BATCH), content_types: ["video"] }); if (e.partial) { complete = false; problems.push(`"${p}": a restricted count hit its cap`); } for (const r of e.rows) { if (r.kind === "post" || !byId.has(r.id)) continue; c.recordings++; c.lines += r.matches ?? 0; const l = byId.get(r.id)!; c.examples.push({ id: r.id, channel: l.channel, channelSlug: l.channelSlug, date: l.date, title: l.title, start: null, text: null }); } } c.examples.sort((x, y) => String(y.date ?? "").localeCompare(String(x.date ?? ""))); c.examples = c.examples.slice(0, a.examples ?? 10); counts[p] = c; } return { counts, complete, problems, listed: rows.length }; }; } // ─── the confirmation ─── export type Ask = (system: string, user: string, schema: object, what: string) => Promise; export type PendingSpelling = { spelling: string; means: string; source: SpellingSource; k?: number; heard?: TriageHeard }; export type ConfirmInput = { pending: PendingSpelling[]; question: string; scope: { channels: string[]; from?: string; to?: string }; at: string; windows?: number; origin?: string | null; }; export type ConfirmDeps = { corpus: Pick; ask: Ask; count: CountPhrasesFn; cuesOf?: (channel: string, id: string) => Promise; log?: (line: string) => void; signal?: AbortSignal; }; export type ConfirmResult = { kept: LearnedSpelling[]; dropped: LearnedDrop[]; counted: PhraseCounts | null; judged: number }; type Line = [number, string]; const clean = (s: unknown) => String(s ?? "") .replace(/["“”]/g, "") .replace(/\s+/g, " ") .trim() .replace(/^\[[\d:|]+\]\s*/, ""); const oneLine = (s: unknown, max = 200) => String(s ?? "").replace(/\s+/g, " ").trim().slice(0, max); // The lines around the first one holding the spelling (at most 4 each side). function excerptAround(win: readonly Line[], spelling: string): Line[] | null { const i = win.findIndex(([, t]) => holdsSpelling(t, spelling)); if (i < 0) return null; return win.slice(Math.max(0, i - 4), i + 5); } /** The slug in a moment_base (`?v=%2F&t=`), else null. */ const slugOfBase = (base: string | null) => { const m = base ? /[?&]v=([^&%/]+)(?:%2F|\/)/i.exec(base) : null; return m ? decodeURIComponent(m[1]!) : null; }; /** Count, then judge: what is kept (with its proving line) and what is dropped, each with its reason. */ export async function confirmSpellings(i: ConfirmInput, d: ConfirmDeps): Promise { const kept: LearnedSpelling[] = []; const dropped: LearnedDrop[] = []; const log = (l: string) => d.log?.(l); const maxWindows = i.windows ?? CONFIRM_WINDOWS; // One per spelling (the first asked wins: a heard span and a proposal of the same spelling are one). const seen = new Set(); const pending = i.pending.filter((p) => { const k = spellingKey(p.spelling); if (!k || seen.has(k)) return false; seen.add(k); return true; }); if (!pending.length) return { kept, dropped, counted: null, judged: 0 }; const drop = (p: PendingSpelling, reason: LearnedDropReason, why: string, windows?: SpellingWindow[]) => { dropped.push({ spelling: p.spelling, means: p.means, source: p.source, reason, why, at: i.at, ...(p.k ? { k: p.k } : {}), ...(windows?.length ? { windows } : {}) }); log(` learn: "${p.spelling}" (${p.means}) dropped — ${why}`); }; let counted: PhraseCounts; try { counted = await d.count({ phrases: pending.map((p) => p.spelling), channels: i.scope.channels, ...(i.scope.from ? { date_from: i.scope.from } : {}), ...(i.scope.to ? { date_to: i.scope.to } : {}), examples: Math.max(10, maxWindows * 3) }); } catch (e) { if (d.signal?.aborted) throw e; for (const p of pending) drop(p, "unread", `the count could not run: ${oneLine((e as Error).message)}`); return { kept, dropped, counted: null, judged: 0 }; } log(`learn: counted ${pending.length} spelling(s) over ${counted.listed.toLocaleString("en-US")} recording(s) in scope${counted.complete ? "" : ` — partial: ${counted.problems.join("; ")}`}`); let judged = 0; for (const p of pending) { d.signal?.throwIfAborted(); const c = counted.counts[p.spelling] ?? { recordings: 0, lines: 0, examples: [] }; if (!c.recordings) { if (counted.complete) drop(p, "no-hits", `does not occur in scope (${counted.listed.toLocaleString("en-US")} recordings counted)`); else drop(p, "unread", `not found in what the count read (partial: ${counted.problems.join("; ")})`); continue; } // The windows to read: a heard span's own recording first, then the newest. const ids: { id: string; slug: string | null; title: string | null; date: string | null }[] = []; if (p.heard) ids.push({ id: p.heard.id, slug: p.heard.channel, title: p.heard.title, date: null }); for (const ex of [...c.examples].sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? "")))) { if (ids.length >= maxWindows) break; if (!ids.some((x) => x.id === ex.id)) ids.push({ id: ex.id, slug: ex.channelSlug, title: ex.title, date: ex.date }); } const verdicts: SpellingWindow[] = []; let proved: LearnedSpelling | null = null; let parsed: Map; try { parsed = parseTranscripts(await d.corpus.call("get_transcripts", { video_ids: ids.slice(0, maxWindows).map((x) => x.id), query: spellingPattern(p.spelling), regex: true, link_style: "base", channels: i.scope.channels })); } catch (e) { if (d.signal?.aborted) throw e; drop(p, "unread", `its windows could not be read: ${oneLine((e as Error).message)}`); continue; } // Every window available (up to N) is read and its verdict kept; the // decision is keptByWindows' (a majority of them). for (const x of ids.slice(0, maxWindows)) { const t = parsed.get(x.id); if (!t) continue; const wins = windowsOf(t.lines); let excerpt: Line[] | null = null; for (const w of wins) { excerpt = excerptAround(w, p.spelling); if (excerpt) break; } if (!excerpt) continue; d.signal?.throwIfAborted(); judged++; const title = t.title ?? x.title ?? x.id; let ans: { means?: unknown; quote?: unknown; reason?: unknown }; try { ans = await d.ask(CONFIRM_SYSTEM, confirmUser({ spelling: p.spelling, means: p.means, question: i.question, title, excerpt: excerpt.map(([s, l]) => `[${mmss(s)}] ${l}`).join("\n") }), CONFIRM_SCHEMA, `learn ${p.spelling} @ ${x.id}`); } catch (e) { if (d.signal?.aborted) throw e; log(` learn: "${p.spelling}" @ ${x.id}: the model's answer failed — ${oneLine((e as Error).message, 160)}`); continue; } const reason = oneLine(ans.reason) || "(no reason given)"; if (ans.means !== true) { verdicts.push({ recording: x.id, start: excerpt[0]![0], means: false, verbatim: true, reason }); log(` learn: "${p.spelling}" @ ${x.id}: not the name — ${reason}`); continue; } const quote = clean(ans.quote); const sec = quote ? locate(quote, excerpt) : null; let ok = sec !== null && holdsSpelling(quote, p.spelling); const slug = x.slug ?? slugOfBase(t.momentBase); let at = sec ?? excerpt[0]![0]; if (ok && slug && d.cuesOf) { const cues = await d.cuesOf(slug, x.id).catch(() => null); if (cues?.length) { const win = windowAround(cues, at, 30); ok = holdsWords(win.cues.map((q) => q.text).join(" "), quote); if (ok) { const hit = win.cues.find((q) => holdsSpelling(q.text, p.spelling)); if (hit) at = hit.t; } } } verdicts.push({ recording: x.id, start: at, means: true, verbatim: ok, reason, ...(quote ? { quote } : {}) }); log(` learn: "${p.spelling}" @ ${x.id} ${mmss(at)}: means ${p.means}${ok ? ` — “${quote}”` : " — but its line is not verbatim"}`); if (!ok || proved) continue; proved = { spelling: normSpelling(p.spelling), means: p.means, quote, recording: x.id, channel: slug, title, start: at, ...(t.momentBase ? { url: `${t.momentBase}${Math.floor(at)}` } : {}), hits: c.recordings, lines: c.lines, ...(counted.complete ? {} : { partial: true }), source: p.source, at: i.at, ...(p.k ? { k: p.k } : {}), }; } const decision = keptByWindows(verdicts, c.recordings); if (decision.keep && proved) { kept.push({ ...(proved as LearnedSpelling), windows: verdicts }); log(` learn: "${p.spelling}" means ${p.means} — kept (${decision.why}; ${c.recordings} recording(s); “${(proved as LearnedSpelling).quote}” ${(proved as LearnedSpelling).recording} @ ${mmss((proved as LearnedSpelling).start)})`); } else drop(p, decision.reason ?? "unread", decision.why, verdicts); } return { kept, dropped, counted, judged }; } /** One window the judge read for a spelling: where, its verdict, and whether its quoted line was verbatim. */ export type { SpellingWindow }; // A spelling read in a single window needs this many recordings in scope. export const ONE_WINDOW_MIN_HITS = 3; /** * The confirmation's rule (the operator's ruling, R6.3 review): kept when at * least 2 of the windows read (up to 3) say it means the name, each with a * verbatim quoted line; with only 1 window read, that one yes AND at least * ONE_WINDOW_MIN_HITS recordings in scope. Else the reason: not verbatim (the * judge agreed, its lines were not in the transcript), too few (one yes, too * few recordings), not the name, or unread (no window). */ export function keptByWindows(ws: readonly SpellingWindow[], hits: number): { keep: boolean; why: string; reason?: LearnedDropReason } { const read = ws.length; const yes = ws.filter((w) => w.means && w.verbatim).length; const means = ws.filter((w) => w.means).length; if (!read) return { keep: false, reason: "unread", why: "no window holding it could be read" }; const said = `${yes} of ${read} window${read === 1 ? "" : "s"} read said it means the name, quoting a verbatim line`; if (read >= 2 ? yes >= 2 : yes === 1 && hits >= ONE_WINDOW_MIN_HITS) return { keep: true, why: said }; if (read >= 2 ? means >= 2 : means === 1 && hits >= ONE_WINDOW_MIN_HITS) return { keep: false, reason: "not-verbatim", why: `${said}: the judge said so in ${means}, but its lines were not verbatim in the window or the cues` }; if (read === 1 && means === 1) return { keep: false, reason: "too-few", why: `${said}, but it occurs in only ${hits} recording${hits === 1 ? "" : "s"}: one window needs ${ONE_WINDOW_MIN_HITS}` }; const no = ws.find((w) => !w.means); return { keep: false, reason: "not-the-name", why: `${said} (needs 2)${no ? `: ${no.reason}` : ""}` }; } // ─── the proposal pass ─── export type ProposeResult = { proposed: PendingSpelling[]; dropped: LearnedDrop[]; asked: number }; /** Ask the model for each name's likely mis-hearings (checked by parseProposals). */ export async function proposeSpellings( i: { names: string[]; question: string; known: ReadonlySet; at: string; k?: number; covered?: (spelling: string) => boolean }, d: { ask: Ask; log?: (line: string) => void; signal?: AbortSignal }, ): Promise { const k = i.k ?? PROPOSALS_PER_NAME; const proposed: PendingSpelling[] = []; const dropped: LearnedDrop[] = []; const known = new Set(i.known); let asked = 0; for (const name of i.names) { d.signal?.throwIfAborted(); asked++; let ans: unknown; try { ans = await d.ask(PROPOSE_SYSTEM, proposeUser(name, i.question, k), proposeSchema(k), `propose ${name}`); } catch (e) { if (d.signal?.aborted) throw e; d.log?.(`learn: proposals for "${name}" failed — ${oneLine((e as Error).message, 160)}`); continue; } const r = parseProposals(name, ans, { k, known, ...(i.covered ? { covered: i.covered } : {}) }); for (const s of r.spellings) { known.add(spellingKey(s)); proposed.push({ spelling: s, means: name, source: "proposed" }); } for (const x of r.dropped) dropped.push({ spelling: x.spelling, means: name, source: "proposed", reason: x.reason, why: x.why, at: i.at }); d.log?.(`learn: "${name}" → ${r.spellings.length ? r.spellings.map((s) => `"${s}"`).join(", ") : "nothing new"}`); } return { proposed, dropped, asked }; } export type LearnPassResult = { proposed: PendingSpelling[]; kept: LearnedSpelling[]; dropped: LearnedDrop[]; counted: PhraseCounts | null; judged: number }; /** The whole pass: propose for each name, then confirm every proposal. */ export async function runLearnPass( i: { names: string[]; question: string; scope: ConfirmInput["scope"]; known: ReadonlySet; at: string; k?: number; windows?: number; covered?: (spelling: string) => boolean }, d: ConfirmDeps, ): Promise { const p = await proposeSpellings({ names: i.names, question: i.question, known: i.known, at: i.at, ...(i.k ? { k: i.k } : {}), ...(i.covered ? { covered: i.covered } : {}) }, d); const c = await confirmSpellings({ pending: p.proposed, question: i.question, scope: i.scope, at: i.at, ...(i.windows ? { windows: i.windows } : {}) }, d); return { proposed: p.proposed, kept: c.kept, dropped: [...p.dropped, ...c.dropped], counted: c.counted, judged: c.judged }; } // ─── a spelling added by hand (release 32 R2) ─── export type HandProof = { ok: true; spelling: LearnedSpelling } | { ok: false; reason: LearnedDropReason; why: string }; /** * A spelling a PERSON says means a watched name: counted in scope (uncapped, the * same count a proposal gets) and its proving line found by code — the first * line holding it, in the newest recordings that do (up to `windows`). No judge: * the person's word is the judge's. Not kept when it does not occur in scope, or * when no line holding it could be read. */ export async function proveByHand( i: { spelling: string; means: string; scope: { channels: string[]; from?: string; to?: string }; at: string; windows?: number }, d: { corpus: Pick; count: CountPhrasesFn }, ): Promise { const spelling = normSpelling(i.spelling); const counted = await d.count({ phrases: [spelling], channels: i.scope.channels, ...(i.scope.from ? { date_from: i.scope.from } : {}), ...(i.scope.to ? { date_to: i.scope.to } : {}), examples: 10 }); const c = counted.counts[spelling] ?? { recordings: 0, lines: 0, examples: [] }; if (!c.recordings) { return counted.complete ? { ok: false, reason: "no-hits", why: `does not occur in scope (${counted.listed.toLocaleString("en-US")} recordings counted)` } : { ok: false, reason: "unread", why: `not found in what the count read (partial: ${counted.problems.join("; ")})` }; } const ids = [...c.examples].sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? ""))).slice(0, i.windows ?? CONFIRM_WINDOWS); const parsed = parseTranscripts(await d.corpus.call("get_transcripts", { video_ids: ids.map((x) => x.id), query: spellingPattern(spelling), regex: true, link_style: "base", channels: i.scope.channels })); for (const x of ids) { const t = parsed.get(x.id); const line = t?.lines.find((l) => l && holdsSpelling(l[1], spelling)); if (!t || !line) continue; const at = line[0]; return { ok: true, spelling: { spelling, means: i.means, quote: clean(line[1]), recording: x.id, channel: x.channelSlug ?? slugOfBase(t.momentBase), title: t.title ?? x.title ?? x.id, start: at, ...(t.momentBase ? { url: `${t.momentBase}${Math.floor(at)}` } : {}), hits: c.recordings, lines: c.lines, ...(counted.complete ? {} : { partial: true }), source: "hand", at: i.at, }, }; } return { ok: false, reason: "unread", why: `counted in ${c.recordings} recording(s), but no line holding it could be read` }; }