// A WATCH'S LEARNED SPELLINGS — THE ONE WRITER (umtool R6.3; plans/umtool- // redesign.md "R6.3 — Learned spellings"). learned.json lives beside the // schedule (lib/report/draft/triage/learnedStore.ts); every write of it is // here, a read-patch-write under the article store's lock, written whole and // atomically: // // applyTriageLearning after a triage run: the heard spans its confirmation // kept (and what it dropped), and each spelling's use // this run (its candidates, how many were flagged) // recordLearnPass after a proposal pass (controller/reportLearn.ts): // what it kept and dropped, the pass, the terms it // asked about and when // unlearnSpelling `report-schedule {"action":"unlearn"}`: removed, and // never learned again // promoteAlias `report-schedule {"action":"promote-alias"}`: the // plan, unless confirm — then the alias written // through the editor's alias writer (aliasesStore: // global, or one site's) and the spelling marked // addSpellingByHand `report-schedule {"action":"add-spelling"}` (release // 32 R2): a person's spelling of a watched name, counted // in scope and its proving line found by code // (triage/confirm.ts proveByHand), kept with source // "hand" — no model, no judge // // Nothing here runs a model; the pass is controller/reportLearn.ts's job. import { writeJsonAtomic } from "../lib/jsonFile-server"; import type { Paths } from "../lib/paths"; import { withArticleStoreLock } from "../lib/report/registry"; import { readScheduleById } from "../lib/report/schedule/store"; import type { Schedule } from "../lib/report/schedule/types"; import { readGlobalAliases, readSiteAliases, writeGlobalAliases, writeSiteAliases } from "../lib/aliasesStore"; import { coerceAliasConfig, type SearchAlias } from "../lib/searchAliases"; import { isValidSiteId, listSiteIds } from "../lib/site"; import { LEARNED_CAP, SPELLING_MAX_CHARS, SPELLING_MAX_WORDS, coveredByTerms, namesOf, normSpelling, termKeys, PASSES_KEPT, emptyLearned, learnedCite, mergeLearned, planAliasPromotion, recordUses, spellingKey, unlearnIn, type LearnedDrop, type LearnedFile, type LearnedPass, type LearnedSpelling, } from "../lib/report/draft/triage/learned"; import { learnedFilePath, readLearned } from "../lib/report/draft/triage/learnedStore"; import type { TriageFile } from "../lib/report/draft/triage/types"; import type { HandProof } from "../lib/report/draft/triage/confirm"; export class LearnedInputError extends Error {} const fail = (msg: string): never => { throw new LearnedInputError(msg); }; type LearnedPathsFull = Pick; async function scheduleOf(id: string, paths: LearnedPathsFull): Promise { const r = await readScheduleById(id, paths); if (!r) fail(`no schedule "${id}"`); if (!r!.ok) fail(`the schedule "${id}" does not read (${r!.file}): ${(r as { problem: string }).problem}`); return (r as { schedule: Schedule }).schedule; } /** The one write: read learned.json (or start one), patch, write it whole — under the article store's lock. */ export async function mutateLearned(s: Pick, paths: LearnedPathsFull, fn: (f: LearnedFile) => LearnedFile, now: Date = new Date()): Promise { return withArticleStoreLock(async () => { const cur = (await readLearned(paths, s)) ?? emptyLearned(s.id, now.toISOString()); const next = { ...fn(cur), owner: s.id, updatedAt: now.toISOString() }; await writeJsonAtomic(learnedFilePath(paths, s), next, { mkdir: true }); return next; }, paths); } /** Each learned spelling's use in a triage run: the candidates it matched, and how many of them were flagged. */ export function usesOf(f: TriageFile): Map { const flagged = new Set((f.tier1?.flags ?? []).map((x) => x.id)); const out = new Map(); for (const c of f.tier0?.candidates ?? []) { for (const sp of c.learned ?? []) { const u = out.get(sp) ?? { candidates: 0, flagged: 0 }; u.candidates++; if (flagged.has(c.id)) u.flagged++; out.set(sp, u); } } return out; } /** * After a triage run (the job's): the heard spans its confirmation kept and * dropped, and each learned spelling's use. A run whose owner is no schedule * (a triage asked by hand) learns nothing. Answers what was added, or null. */ export async function applyTriageLearning(f: TriageFile, paths: LearnedPathsFull, now: Date = new Date()): Promise<{ added: LearnedSpelling[]; dropped: LearnedDrop[] } | null> { const r = await readScheduleById(f.owner, paths).catch(() => null); if (!r?.ok) return null; const uses = usesOf(f); const kept = f.learning?.kept ?? []; const drops = f.learning?.dropped ?? []; if (!uses.size && !kept.length && !drops.length) return null; let out: { added: LearnedSpelling[]; dropped: LearnedDrop[] } = { added: [], dropped: [] }; await mutateLearned( r.schedule, paths, (cur) => { const m = mergeLearned(cur, { kept, dropped: drops, at: now.toISOString(), cap: LEARNED_CAP }); out = { added: m.added, dropped: m.dropped }; return recordUses(m.file, f.k, now.toISOString(), uses); }, now, ); return out; } /** After a proposal pass: what it kept and dropped, the pass itself, and — when it completed — the terms it asked about. */ export async function recordLearnPass( s: Pick, o: { pass: LearnedPass; kept: LearnedSpelling[]; dropped: LearnedDrop[]; termsKey: string | null }, paths: LearnedPathsFull, now: Date = new Date(), ): Promise<{ file: LearnedFile; added: LearnedSpelling[]; dropped: LearnedDrop[] }> { let out: { added: LearnedSpelling[]; dropped: LearnedDrop[] } = { added: [], dropped: [] }; const file = await mutateLearned( s, paths, (cur) => { const m = mergeLearned(cur, { kept: o.kept, dropped: o.dropped, at: now.toISOString(), cap: LEARNED_CAP }); out = { added: m.added, dropped: m.dropped }; const pass = { ...o.pass, kept: m.added.length, dropped: m.dropped.length }; return { ...m.file, passes: [...m.file.passes, pass].slice(-PASSES_KEPT), ...(o.pass.status === "done" ? { proposedAt: o.pass.at, termsKey: o.termsKey } : {}), }; }, now, ); return { file, ...out }; } /** Remove a learned spelling and block it from being learned again. Refused when the watch never learned or blocked it. */ export async function unlearnSpelling(id: string, spelling: string, deps: { paths: LearnedPathsFull; now?: () => Date }): Promise<{ removed: LearnedSpelling | null; blocked: string }> { if (typeof spelling !== "string" || !spelling.trim()) fail('"spelling" names the learned spelling to remove'); const s = await scheduleOf(id, deps.paths); const cur = await readLearned(deps.paths, s); const key = spellingKey(spelling); if (!cur?.learned.some((l) => spellingKey(l.spelling) === key)) { if (cur?.blocked.some((b) => spellingKey(b.spelling) === key)) fail(`"${spelling}" is removed already (and will not be learned again)`); fail(`"${id}" has not learned "${spelling}"`); } let removed: LearnedSpelling | null = null; const now = deps.now?.() ?? new Date(); await mutateLearned( s, deps.paths, (f) => { const u = unlearnIn(f, spelling, now.toISOString()); removed = u.removed; return u.file; }, now, ); return { removed, blocked: spelling.trim() }; } // ─── promote to a search alias ─── export type PromotePlan = { id: string; spelling: string; means: string; // Where it goes: "global" (search-aliases.json) or a site's id. to: string; file: string; action: "new" | "trigger" | "none"; alias: SearchAlias; before: SearchAlias | null; why: string; cite: string; // The sites it could go to instead. sites: string[]; refused: string | null; }; async function promoteContext(id: string, spelling: string, site: string | null, paths: Paths): Promise<{ s: Schedule; learned: LearnedSpelling; plan: PromotePlan }> { if (typeof spelling !== "string" || !spelling.trim()) fail('"spelling" names the learned spelling to promote'); if (site !== null && !isValidSiteId(site)) fail(`"site" is a site's id: not ${JSON.stringify(site)}`); const s = await scheduleOf(id, paths); const f = await readLearned(paths, s); const l = f?.learned.find((x) => spellingKey(x.spelling) === spellingKey(spelling)); if (!l) fail(`"${id}" has not learned "${spelling}"`); const sites = listSiteIds(paths); if (site !== null && !sites.includes(site)) fail(`no site "${site}" (sites: ${sites.join(", ") || "none"})`); const aliases = site === null ? readGlobalAliases(paths).aliases : readSiteAliases(paths, site).aliases; const p = planAliasPromotion(aliases, l!, id); return { s, learned: l!, plan: { id, spelling: l!.spelling, means: l!.means, to: site ?? "global", file: site === null ? "search-aliases.json" : `sites/${site}/search-aliases.json`, action: p.action, alias: p.alias, before: p.before, why: p.why, cite: learnedCite(l!), sites, refused: p.action === "none" ? p.why : null, }, }; } /** What promoting would write (nothing written). */ export async function planPromoteAlias(id: string, spelling: string, site: string | null, deps: { paths: Paths }): Promise { return (await promoteContext(id, spelling, site, deps.paths)).plan; } /** * Promote (the operator's confirm): the plan made again, the alias list read, * patched and written whole through the alias writer (aliasesStore, coerced as * the editor's /aliases page saves it), then the spelling marked promoted. */ export async function promoteAlias(id: string, spelling: string, site: string | null, deps: { paths: Paths; now?: () => Date }): Promise { const { s, plan } = await promoteContext(id, spelling, site, deps.paths); if (plan.refused) fail(plan.refused); const read = site === null ? readGlobalAliases(deps.paths) : readSiteAliases(deps.paths, site); const aliases = plan.before ? read.aliases.map((a) => (a.id === plan.before!.id ? plan.alias : a)) : [...read.aliases, plan.alias]; const config = coerceAliasConfig({ aliases }); if (site === null) writeGlobalAliases(deps.paths, config); else writeSiteAliases(deps.paths, site, config); const now = deps.now?.() ?? new Date(); await mutateLearned( s, deps.paths, (f) => ({ ...f, learned: f.learned.map((l) => (spellingKey(l.spelling) === spellingKey(spelling) ? { ...l, promoted: { to: plan.to, alias: plan.alias.id, at: now.toISOString() } } : l)) }), now, ); return plan; } // ─── a spelling added by hand (release 32 R2) ─── /** Proves a hand spelling over the watch's scope (the editor binds it to its corpus: reportLearn.ts handProver). */ export type HandProver = (i: { spelling: string; means: string; scope: { channels: string[]; from?: string; to?: string }; at: string }) => Promise; /** * ADD A SPELLING BY HAND: `spelling` is how the transcripts write `means`, one of * the names the watch's terms watch. Refused when it is not a spelling (words, * at most SPELLING_MAX_WORDS), is the name itself, the terms already find it, it * is learned already, or the watch is at its cap; then counted in scope and its * proving line found (`prove`, code only) — refused when it does not occur. A * spelling the operator removed is the operator's to add back: adding it by hand * lifts the block. Answers what was kept. */ export async function addSpellingByHand( id: string, input: { spelling?: unknown; means?: unknown }, deps: { paths: LearnedPathsFull; prove: HandProver; now?: () => Date }, ): Promise<{ added: LearnedSpelling; unblocked: boolean }> { const spelling = normSpelling(input.spelling); const means = typeof input.means === "string" ? input.means.trim() : ""; if (!spelling) fail('"spelling" is how the transcripts write the name'); const s = await scheduleOf(id, deps.paths); const names = namesOf(s.scope.terms ?? null, s.scope.regex === true); if (!names.length) fail(`"${id}" watches no name: its terms have no capitalised literal alternative`); if (!names.includes(means)) fail(`"means" is one of the watched names: ${names.map((n) => `"${n}"`).join(", ")}`); const key = spellingKey(spelling); const words = key.split(" ").filter(Boolean).length; if (!key || !/^[\p{L}\p{N}][\p{L}\p{N}' .&-]*$/u.test(spelling)) fail(`"${spelling}" is not a spelling (words only)`); if (spelling.length > SPELLING_MAX_CHARS || words > SPELLING_MAX_WORDS) fail(`"${spelling}" is too long (at most ${SPELLING_MAX_WORDS} words, ${SPELLING_MAX_CHARS} characters)`); if (key === spellingKey(means)) fail(`"${spelling}" is the name itself`); if (termKeys(s).includes(key) || coveredByTerms(s.scope.terms, s.scope.regex === true)(spelling)) fail(`the terms already find "${spelling}"`); const cur = await readLearned(deps.paths, s); if (cur?.learned.some((l) => spellingKey(l.spelling) === key)) fail(`"${id}" has learned "${spelling}" already`); if ((cur?.learned.length ?? 0) >= LEARNED_CAP) fail(`the watch keeps at most ${LEARNED_CAP} spellings: remove one first`); const now = deps.now?.() ?? new Date(); const proof = await deps.prove({ spelling, means, scope: { channels: s.scope.channels, ...(s.scope.from ? { from: s.scope.from } : {}) }, at: now.toISOString() }); if (!proof.ok) fail(`"${spelling}" is not kept: ${proof.why}`); const added = (proof as Extract).spelling; let unblocked = false; await mutateLearned( s, deps.paths, (f) => { const blocked = f.blocked.filter((b) => spellingKey(b.spelling) !== key); unblocked = blocked.length !== f.blocked.length; const m = mergeLearned({ ...f, blocked }, { kept: [added], dropped: [], at: now.toISOString(), cap: LEARNED_CAP }); if (!m.added.length) fail(`"${spelling}" is not kept: ${m.dropped.at(-1)?.why ?? "the watch refused it"}`); return m.file; }, now, ); return { added, unblocked }; }