// LEARNED SPELLINGS (umtool R6.3; plans/umtool-redesign.md "R6.3 — Learned // spellings"). Transcripts are AI-made and mishear names ("Melanie Mack" for // Melonie Mac, "Warsi" for Warski). A watch that searches only the spellings // it was given misses those lines, so it learns its own: // // proposed the triage model lists likely mis-hearings of each name-like // alternative in the terms (namesOf): when a schedule is made or // its terms change, on `report-schedule {"action":"learn"}`, and // at most weekly in a tick, before tier 0 // heard tier 1's judge reports a span it takes for a mis-hearing of a // watched name (`heard: [{span, means}]`), verbatim // // NOTHING IS LEARNED ON THE MODEL'S WORD (./confirm.ts): a heard span must be // verbatim in its window and in the cues; every spelling must occur in scope // (an uncapped count over the listing, enumerate_matches with `ids`); then the // judge reads up to CONFIRM_WINDOWS windows where it occurs and must say it // means the watched name, quoting the line (checked verbatim). What it keeps // joins the candidate query as an escaped literal alternative — never a regex // — on this watch only, capped (LEARNED_CAP). A spelling whose candidates are // dismissed run after run is SUGGESTED for removal, never removed on its own. // // The file is `learned.json` beside the schedule (./learnedStore.ts); its ONE // writer is controller/learnedSpellings.ts. Pure: no node imports, so umtool's // pages read these shapes and words too. import { wordsOf } from "../../quoteWords"; import type { SearchAlias } from "../../../searchAliases"; import { slugifyAliasId } from "../../../searchAliases"; export const LEARNED_FORMAT = "archilyzer-learned"; export const LEARNED_VERSION = 1; // The most spellings a watch keeps. export const LEARNED_CAP = 20; // The most mis-hearings the model proposes for one name (K). export const PROPOSALS_PER_NAME = 5; // The most windows the judge reads to confirm one spelling (N). export const CONFIRM_WINDOWS = 3; // Runs with candidates from a spelling, all dismissed, before it is suggested for removal. export const SUGGEST_REMOVE_AFTER = 4; // A tick proposes again when the last pass is at least this old. export const PROPOSE_EVERY_DAYS = 7; // The most names one proposal pass asks about. export const NAMES_PER_PASS = 16; // What the file keeps of its history. export const USES_KEPT = 8; export const DROPPED_KEPT = 100; export const PASSES_KEPT = 10; // A spelling is at most this many words and characters. export const SPELLING_MAX_WORDS = 4; export const SPELLING_MAX_CHARS = 48; // "hand" (release 32 R2): added by a person in umtool ("Add spelling"): counted in // scope and its proving line found by code, no model; the person's word is the judge's. export type SpellingSource = "proposed" | "heard" | "hand"; /** One tick's use of a spelling: the candidates it matched in triage run `k`, and how many were flagged. */ export type LearnedUse = { k: number; at: string; candidates: number; flagged: number }; /** A spelling the watch learned, with the line that proved it. */ export type LearnedSpelling = { spelling: string; // The watched name it means (one of namesOf's). means: string; // The proving line, verbatim in the transcript (code-checked), and where. quote: string; recording: string; channel: string | null; title?: string | null; start: number; url?: string; // The recordings in scope it occurs in (an uncapped count), and its lines. hits: number; lines?: number; // The count was partial (a channel not listed in full): "at least". partial?: boolean; source: SpellingSource; at: string; // The triage run that heard it (source "heard"). k?: number; // The last USES_KEPT runs whose candidates it matched. uses?: LearnedUse[]; // Promoted to a search alias (the operator's act): where, and the alias id. promoted?: { to: string; alias: string; at: string }; // Each window the judge read to confirm it, with its verdict. windows?: SpellingWindow[]; }; export type LearnedDropReason = "no-hits" | "not-the-name" | "not-verbatim" | "too-few" | "known" | "blocked" | "cap" | "invalid" | "unread"; /** One window the judge read to confirm a spelling: where, its verdict, its quoted line and whether that was verbatim. */ export type SpellingWindow = { recording: string; start: number; means: boolean; verbatim: boolean; reason: string; quote?: string }; /** A spelling that was not learned, and why (with each window's verdict, when the judge read any). */ export type LearnedDrop = { spelling: string; means: string; source: SpellingSource; reason: LearnedDropReason; why: string; at: string; k?: number; windows?: SpellingWindow[] }; /** One proposal pass. */ export type LearnedPass = { at: string; trigger: "create" | "terms" | "weekly" | "ops"; status: "done" | "failed" | "cancelled"; model: string; names: string[]; // Names past NAMES_PER_PASS: not asked this pass. notAsked: string[]; proposed: number; kept: number; dropped: number; usd: number; jobId?: string; error?: string; }; export type LearnedFile = { format: typeof LEARNED_FORMAT; version: typeof LEARNED_VERSION; owner: string; // The terms the last proposal pass asked about (termsKey), and when. termsKey: string | null; proposedAt: string | null; learned: LearnedSpelling[]; // Removed by the operator: never learned again. blocked: { spelling: string; means?: string; at: string }[]; // The newest DROPPED_KEPT drops, oldest first. dropped: LearnedDrop[]; passes: LearnedPass[]; updatedAt: string; }; export const emptyLearned = (owner: string, at: string): LearnedFile => ({ format: LEARNED_FORMAT, version: LEARNED_VERSION, owner, termsKey: null, proposedAt: null, learned: [], blocked: [], dropped: [], passes: [], updatedAt: at, }); /** A learned.json read loosely: null when it is not one. */ export function parseLearned(v: unknown, owner: string): LearnedFile | null { const o = v as Partial | null; if (!o || typeof o !== "object" || o.format !== LEARNED_FORMAT || o.owner !== owner || !Array.isArray(o.learned)) return null; return { ...emptyLearned(owner, typeof o.updatedAt === "string" ? o.updatedAt : ""), ...o, learned: o.learned.filter((l) => l && typeof l.spelling === "string" && typeof l.means === "string"), blocked: Array.isArray(o.blocked) ? o.blocked : [], dropped: Array.isArray(o.dropped) ? o.dropped : [], passes: Array.isArray(o.passes) ? o.passes : [], } as LearnedFile; } // ─── the names a watch watches ─── const META = /[\\.*+?[\](){}|^$]/; /** A regex's top-level alternatives ("a|(b|c)|d" → a, (b|c), d), escapes and classes respected. */ export function splitAlternatives(re: string): string[] { const out: string[] = []; let depth = 0; let inClass = false; let cur = ""; for (let i = 0; i < re.length; i++) { const ch = re[i]!; if (ch === "\\") { cur += ch + (re[i + 1] ?? ""); i++; continue; } if (inClass) { if (ch === "]") inClass = false; cur += ch; continue; } if (ch === "[") inClass = true; else if (ch === "(") depth++; else if (ch === ")") depth = Math.max(0, depth - 1); else if (ch === "|" && depth === 0) { out.push(cur); cur = ""; continue; } cur += ch; } out.push(cur); return out.map((s) => s.trim()).filter(Boolean); } /** An alternative as literal text, its word-boundary and line anchors stripped; null when it holds any other regex syntax. */ export function literalOf(alt: string): string | null { let s = alt.trim(); for (;;) { const before = s; s = s.replace(/^\^/, "").replace(/\$$/, "").replace(/^\\b/, "").replace(/\\b$/, "").trim(); if (s === before) break; } if (!s || META.test(s)) return null; return s.replace(/\s+/g, " "); } /** * The names a watch's terms watch: each literal alternative (its `\b` and * line anchors aside) with a capital letter — a proper name, the kind a * transcript mishears. A lowercase word or phrase, a regex class, a quantifier * or a group is skipped. In the order given; no repeats. */ export function namesOf(terms: string | null | undefined, regex: boolean): string[] { const t = (terms ?? "").trim(); if (!t) return []; const alts = regex ? splitAlternatives(t).map(literalOf) : [t.replace(/\s+/g, " ")]; const seen = new Set(); const caps: string[] = []; for (const a of alts) { if (!a) continue; const key = spellingKey(a); if (!key || seen.has(key)) continue; if (!/\p{Lu}/u.test(a)) continue; seen.add(key); caps.push(a); } return caps; } /** The names a schedule's terms watch, split into one pass's (NAMES_PER_PASS) and the rest. */ export function namesForPass(s: { scope: { terms?: string; regex?: boolean } }): { names: string[]; notAsked: string[] } { const all = namesOf(s.scope.terms ?? null, s.scope.regex === true); return { names: all.slice(0, NAMES_PER_PASS), notAsked: all.slice(NAMES_PER_PASS) }; } /** Every literal alternative of the terms, as spelling keys (a proposal or a heard span equal to one is not new). */ export function termKeys(s: { scope: { terms?: string; regex?: boolean } }): string[] { const t = s.scope.terms?.trim(); if (!t) return []; const alts = s.scope.regex ? splitAlternatives(t).map(literalOf) : [t]; return alts.filter((x): x is string => !!x).map(spellingKey).filter(Boolean); } /** The terms a proposal pass asked about, as one key (a change of terms means a new pass). */ export const termsKey = (terms: string | null | undefined, regex: boolean): string | null => { const t = (terms ?? "").trim(); return t ? `${regex ? "re" : "lit"}:${t}` : null; }; // ─── spellings as text and as a query ─── /** A spelling as the file keeps it: quotes and brackets stripped, spaces collapsed. */ export const normSpelling = (s: unknown): string => String(s ?? "") .replace(/["“”‘’`«»]/g, (c) => (c === "’" || c === "‘" ? "'" : "")) .replace(/^[\s'.,;:!?-]+|[\s'.,;:!?-]+$/g, "") .replace(/\s+/g, " ") .trim(); /** Two spellings are one when their words are (case and punctuation aside). */ export const spellingKey = (s: string): string => wordsOf(s); const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&"); /** A spelling as an ESCAPED LITERAL pattern (never a regex of its own), whole words where it starts or ends with one. */ export function spellingPattern(spelling: string): string { const s = normSpelling(spelling); const lead = /^[A-Za-z0-9_]/.test(s) ? "\\b" : ""; const tail = /[A-Za-z0-9_]$/.test(s) ? "\\b" : ""; return `${lead}${escapeRe(s)}${tail}`; } /** The learned spellings as one alternation of escaped literals; null when none. */ export function learnedAlternation(spellings: readonly string[]): string | null { const parts = [...new Set(spellings.map(normSpelling).filter(Boolean))].map(spellingPattern); return parts.length ? parts.join("|") : null; } /** * The candidate query with the learned spellings joined: the terms (a regex as * it is, literal terms escaped) OR each learned spelling as an escaped literal. * A regex query either way once anything is learned; the terms alone (as * given) when nothing is. */ export function joinedQuery(terms: string | null | undefined, regex: boolean, learned: readonly string[]): { query: string; regex: boolean } | null { const t = (terms ?? "").trim(); const alt = learnedAlternation(learned); if (!alt) return t ? { query: t, regex } : null; if (!t) return { query: alt, regex: true }; return { query: `(?:${regex ? t : escapeRe(t)})|${alt}`, regex: true }; } /** Does a line hold this spelling (as the query matches it)? */ export function holdsSpelling(text: string, spelling: string): boolean { try { return new RegExp(spellingPattern(spelling), "i").test(text); } catch { return false; } } /** * Does the terms' own query already find this spelling (the literal terms as * a substring, a regex as it is, case aside — as enumerate matches them)? A * spelling it finds adds nothing ("Melanie Mack" under "Melanie Mac"). */ export function coveredByTerms(terms: string | null | undefined, regex: boolean): (spelling: string) => boolean { const t = (terms ?? "").trim(); if (!t) return () => false; if (!regex) return (s) => s.toLowerCase().includes(t.toLowerCase()); let re: RegExp; try { re = new RegExp(t, "i"); } catch { return () => false; } return (s) => re.test(s); } /** "terms + 3 learned" (the tick log's and triage.json's words). */ export const learnedWords = (n: number, terms = true): string => (n ? `${terms ? "terms + " : ""}${n} learned` : terms ? "terms" : "no learned spelling"); // ─── the proposal (the model) ─── export const PROPOSE_SYSTEM = "Automatic speech recognition often mishears names. Given a name, list the likely ways a transcript misspells " + "it: sound-alikes, the name split into words or joined into one, a dropped or added letter, a common word it is " + "heard as. Each spelling is how it would appear in a transcript, one to four words, without quotes. Do not repeat " + "the name itself, do not explain, and give at most the number asked for, the most likely first."; export const proposeSchema = (k = PROPOSALS_PER_NAME) => ({ type: "object", properties: { spellings: { type: "array", maxItems: k, items: { type: "string" } } }, required: ["spellings"], }); export const proposeUser = (name: string, question: string, k = PROPOSALS_PER_NAME) => `Name: ${name}\nContext: the transcripts are searched for this question — ${question}\nGive at most ${k} likely mis-hearings of "${name}".`; /** * The model's proposals for one name, checked: a spelling that is the name * itself, already known (in the terms, learned or blocked), repeated, too * long, or not words is put aside with its reason; at most `k` kept. */ export function parseProposals( name: string, answer: unknown, o: { k?: number; known?: ReadonlySet; covered?: (spelling: string) => boolean } = {}, ): { spellings: string[]; dropped: { spelling: string; reason: LearnedDropReason; why: string }[] } { const k = o.k ?? PROPOSALS_PER_NAME; const raw = Array.isArray((answer as { spellings?: unknown })?.spellings) ? ((answer as { spellings: unknown[] }).spellings) : []; const spellings: string[] = []; const dropped: { spelling: string; reason: LearnedDropReason; why: string }[] = []; const seen = new Set([spellingKey(name)]); for (const r of raw) { const s = normSpelling(typeof r === "string" ? r : (r as { spelling?: unknown })?.spelling); if (!s) continue; const key = spellingKey(s); const words = key.split(" ").filter(Boolean).length; if (!key || !/^[\p{L}\p{N}][\p{L}\p{N}' .&-]*$/u.test(s)) dropped.push({ spelling: s, reason: "invalid", why: "not a spelling (words only)" }); else if (s.length > SPELLING_MAX_CHARS || words > SPELLING_MAX_WORDS) dropped.push({ spelling: s, reason: "invalid", why: `too long (at most ${SPELLING_MAX_WORDS} words)` }); else if (key === spellingKey(name)) continue; else if (seen.has(key)) continue; else if (o.known?.has(key)) dropped.push({ spelling: s, reason: "known", why: "already in the terms, learned or removed" }); else if (o.covered?.(s)) dropped.push({ spelling: s, reason: "known", why: "the terms already match it" }); else if (spellings.length >= k) continue; else { seen.add(key); spellings.push(s); } } return { spellings, dropped }; } // ─── the confirmation (the judge) ─── export const CONFIRM_SYSTEM = "An automatic transcript often misspells names: a name is heard as a sound-alike, split or joined, or with a " + "letter dropped or added. You are given a NAME, a SPELLING and a transcript excerpt where the spelling occurs. " + "Decide whether the given spelling, there, is the transcript's misspelling of the name: the speaker means that " + "person or thing. Answer means = false when it plainly means something else there: an ordinary word, or another " + "person (a different first name, surname or title beside it). Answer means = true when the speaker is most likely " + "talking about the name. Copy the line holding the spelling EXACTLY, character for character, without the " + "bracketed timestamp, and give one short reason."; export const CONFIRM_SCHEMA = { type: "object", properties: { means: { type: "boolean" }, quote: { type: "string" }, reason: { type: "string" } }, required: ["means", "quote", "reason"], }; export const confirmUser = (o: { spelling: string; means: string; question: string; title: string; excerpt: string }) => `Name: ${o.means}\nSpelling in the transcript: ${o.spelling}\nThe transcripts are searched for: ${o.question}\n\nVideo: ${o.title}\n\nTranscript excerpt:\n${o.excerpt}\n\nIs "${o.spelling}" here the transcript's misspelling of "${o.means}"?`; // ─── heard spans (the triage judge's extra field) ─── /** The rule the window judge gets when the watch has names. */ export const heardRule = (names: readonly string[]) => ` (6) The transcript may mishear these watched names: ${names.map((n) => `"${n}"`).join(", ")}. If a span in the ` + "excerpt looks like a mis-hearing of one of them (a sound-alike, split or joined words, a dropped or added " + "letter), list it in heard: the span copied exactly (one to four words) and the watched name it means. Never list " + "a name spelled correctly; leave heard empty when there is none."; /** The judge's schema with `heard`. */ export function withHeard(schema: Record): Record { const props = (schema.properties ?? {}) as Record; return { ...schema, properties: { ...props, heard: { type: "array", maxItems: 3, items: { type: "object", properties: { span: { type: "string" }, means: { type: "string" } }, required: ["span", "means"] }, }, }, }; } /** A span tier 1 reported and code checked verbatim. */ export type TriageHeard = { span: string; means: string; id: string; channel: string | null; title: string | null; at: number; // The window line holding it. line: string; checked: "cues" | "window"; }; /** A reported span put aside, and why. */ export type TriageHeardDropped = { span: string; means: string; id: string; reason: string }; // ─── the file's rules (pure; the controller writes) ─── /** Every spelling the watch knows (learned, blocked) and the names' own, as keys. */ export function knownKeys(f: LearnedFile | null, names: readonly string[]): Set { return new Set([...(f?.learned ?? []).map((l) => spellingKey(l.spelling)), ...(f?.blocked ?? []).map((b) => spellingKey(b.spelling)), ...names.map(spellingKey)]); } /** * Confirmed spellings merged in: a spelling already learned or blocked is * dropped ("known", "blocked"), and past the cap ("cap"). Answers the new file * and what was added and dropped. */ export function mergeLearned( f: LearnedFile, o: { kept: readonly LearnedSpelling[]; dropped: readonly LearnedDrop[]; at: string; cap?: number }, ): { file: LearnedFile; added: LearnedSpelling[]; dropped: LearnedDrop[] } { const cap = o.cap ?? LEARNED_CAP; const learned = [...f.learned]; const keys = new Set(learned.map((l) => spellingKey(l.spelling))); const blocked = new Set(f.blocked.map((b) => spellingKey(b.spelling))); const added: LearnedSpelling[] = []; const dropped: LearnedDrop[] = [...o.dropped]; for (const l of o.kept) { const key = spellingKey(l.spelling); const drop = (reason: LearnedDropReason, why: string) => dropped.push({ spelling: l.spelling, means: l.means, source: l.source, reason, why, at: o.at, ...(l.k ? { k: l.k } : {}) }); if (blocked.has(key)) drop("blocked", "removed by the operator: never relearned"); else if (keys.has(key)) continue; else if (learned.length >= cap) drop("cap", `the watch keeps at most ${cap} spellings`); else { keys.add(key); learned.push(l); added.push(l); } } return { file: { ...f, learned, dropped: [...f.dropped, ...dropped].slice(-DROPPED_KEPT), updatedAt: o.at }, added, dropped }; } /** One triage run's use of each spelling: the candidates it matched and how many of them were flagged. */ export function recordUses(f: LearnedFile, k: number, at: string, uses: ReadonlyMap): LearnedFile { if (!uses.size) return f; const byKey = new Map([...uses].map(([s, u]) => [spellingKey(s), u])); return { ...f, learned: f.learned.map((l) => { const u = byKey.get(spellingKey(l.spelling)); if (!u || !u.candidates) return l; const prior = (l.uses ?? []).filter((x) => x.k !== k); return { ...l, uses: [...prior, { k, at, candidates: u.candidates, flagged: u.flagged }].slice(-USES_KEPT) }; }), updatedAt: at, }; } /** Its last SUGGEST_REMOVE_AFTER runs with candidates all ended with none flagged: suggest removing (never removed on its own). */ export function suggestRemoving(l: Pick): boolean { const last = (l.uses ?? []).filter((u) => u.candidates > 0).slice(-SUGGEST_REMOVE_AFTER); return last.length >= SUGGEST_REMOVE_AFTER && last.every((u) => u.flagged === 0); } /** * The spellings a run's query carries: the learned ones whose name is still * among the terms' names (a name dropped from the terms leaves its spellings * idle, listed, not used), at most the cap. */ export function activeLearned(f: LearnedFile | null, names: readonly string[], cap = LEARNED_CAP): LearnedSpelling[] { const keys = new Set(names.map(spellingKey)); return (f?.learned ?? []).filter((l) => keys.has(spellingKey(l.means))).slice(0, cap); } /** Remove a spelling and block it from being learned again. */ export function unlearnIn(f: LearnedFile, spelling: string, at: string): { file: LearnedFile; removed: LearnedSpelling | null } { const key = spellingKey(spelling); const removed = f.learned.find((l) => spellingKey(l.spelling) === key) ?? null; const blocked = f.blocked.some((b) => spellingKey(b.spelling) === key) ? f.blocked : [...f.blocked, { spelling: removed?.spelling ?? normSpelling(spelling), ...(removed ? { means: removed.means } : {}), at }]; return { file: { ...f, learned: f.learned.filter((l) => spellingKey(l.spelling) !== key), blocked, updatedAt: at }, removed }; } /** Why a tick should propose now, or null: never proposed, the terms changed, or a week since the last pass. */ export function learnDue(f: LearnedFile | null, key: string | null, now: Date, everyDays = PROPOSE_EVERY_DAYS): "create" | "terms" | "weekly" | null { if (!key) return null; if (!f?.proposedAt) return "create"; if (f.termsKey !== key) return "terms"; const last = Date.parse(f.proposedAt); return !Number.isFinite(last) || now.getTime() - last >= everyDays * 86_400_000 ? "weekly" : null; } // ─── promote to a search alias (plan-then-confirm; the operator's act) ─── /** Where a learned spelling was proved: "/ at mm:ss". */ export function learnedCite(l: Pick): string { const s = Math.max(0, Math.floor(l.start)); const mm = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; return `${l.channel ? `${l.channel}/` : ""}${l.recording} at ${mm}`; } export type AliasPromotion = { // new: a new alias for the name; trigger: the spelling added to the alias // that already names it; none: that alias already fires on it. action: "new" | "trigger" | "none"; alias: SearchAlias; before: SearchAlias | null; why: string; }; /** * What promoting a learned spelling would write to an alias list: a trigger * (and, when its regex does not already match it, an escaped alternative in its * suggestion) on the alias that names the same thing — its label or a trigger * is the name — else a new alias for the name, its triggers the name and the * spelling, its suggestion both as escaped literals. The note says where it * was learned. */ export function planAliasPromotion(aliases: readonly SearchAlias[], l: Pick, watch: string): AliasPromotion { const name = spellingKey(l.means); const spell = normSpelling(l.spelling); const note = `learned by watch ${watch} from ${learnedCite(l)}`; const names = (a: SearchAlias) => spellingKey(a.label) === name || a.triggers.some((t) => spellingKey(t) === name); const existing = aliases.find(names) ?? null; if (existing) { const hasTrigger = existing.triggers.some((t) => spellingKey(t) === spellingKey(spell)); let fires = false; try { fires = existing.useRegex ? new RegExp(existing.suggestion, "i").test(spell) : existing.suggestion.toLowerCase().includes(spell.toLowerCase()); } catch { fires = false; } if (hasTrigger && fires) return { action: "none", alias: existing, before: existing, why: `"${existing.label}" already fires on "${spell}" and its suggestion matches it` }; const suggestion = fires ? existing.suggestion : existing.useRegex ? `${existing.suggestion}|${spellingPattern(spell)}` : existing.suggestion; const alias: SearchAlias = { ...existing, triggers: hasTrigger ? existing.triggers : [...existing.triggers, spell.toLowerCase()], suggestion, note: existing.note ? `${existing.note}; "${spell}" ${note}` : note, }; return { action: "trigger", alias, before: existing, why: `"${spell}" added to "${existing.label}"${hasTrigger ? "" : " as a trigger"}${suggestion !== existing.suggestion ? ", and to its suggestion as an escaped literal" : ""}`, }; } const taken = new Set(aliases.map((a) => a.id)); const base = slugifyAliasId(l.means); let id = base; for (let n = 2; taken.has(id); n++) id = `${base}-${n}`; const alias: SearchAlias = { id, label: l.means, triggers: [l.means.toLowerCase(), spell.toLowerCase()], suggestion: `${spellingPattern(l.means)}|${spellingPattern(spell)}`, useRegex: true, enabled: true, note, }; return { action: "new", alias, before: null, why: `a new alias "${l.means}" firing on "${l.means}" and "${spell}"` }; }