// Learned spellings (umtool R6.3), the editor's side: the one writer of // learned.json; `report-schedule` learn (the plan, the job's door), unlearn // (blocked, never relearned) and promote-alias (the plan, then the alias file // written through the alias writer — global and a site's — in a temp dir); a // create and a change of terms starting a pass; the tick running a pass before // tier 0 only when one is due (and going on when it fails); a triage run's // heard spelling and uses written. Temp stores only; no model. // // Run with: node_modules/.bin/tsx --test controller/learnedSpellings.test.ts import { after, test } from "node:test"; import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { sanitizeGeneration } from "../lib/generationSettings"; import { readLearned } from "../lib/report/draft/triage/learnedStore"; import { readSchedule } from "../lib/report/schedule/store"; import { TRIAGE_FORMAT, TRIAGE_VERSION, escalationOf, type TriageFile } from "../lib/report/draft/triage/types"; import type { LearnedSpelling } from "../lib/report/draft/triage/learned"; import { createTriageRun } from "../lib/report/draft/triage/store"; import { createSchedule, parseCreate } from "./reportSchedule"; import { runTick, type TickDeps, type TickSteps } from "./reportTick"; import { reportScheduleAction as action, type EnqueueLearnFn } from "./reportScheduleOps"; import { applyTriageLearning, recordLearnPass } from "./learnedSpellings"; // eslint-disable-next-line @typescript-eslint/no-explicit-any const ask = (b: Record, d: Parameters[1]): Promise => action(b, d); const ROOTS: string[] = []; after(() => { for (const r of ROOTS) rmSync(r, { recursive: true, force: true }); }); const NOW = new Date("2026-10-14T12:00:00.000Z"); const CHAN = "synth-kitchen"; function store() { const root = mkdtempSync(path.join(tmpdir(), "learned-ops-")); ROOTS.push(root); const paths = { articlesDir: path.join(root, "reports"), exportIndexDir: path.join(root, ".export-index"), generationUsageFile: path.join(root, "usage.jsonl"), jobsDir: path.join(root, ".jobs"), globalAliasesFile: path.join(root, "search-aliases.json"), sitesDir: path.join(root, "sites"), } as unknown as Paths; mkdirSync(paths.articlesDir, { recursive: true }); mkdirSync(path.join(paths.sitesDir, "synthalyzer"), { recursive: true }); writeFileSync(path.join(paths.sitesDir, "synthalyzer", "site.json"), JSON.stringify({ title: "Synthalyzer" })); return paths; } const gen = () => sanitizeGeneration({ routes: { sweep: "api" } }); function depsOf(paths: Paths, steps: Partial = {}, now: Date = NOW, extra: Partial & { enqueueLearn?: EnqueueLearnFn } = {}): TickDeps & { enqueueLearn?: EnqueueLearnFn } { return { paths, now: () => now, settings: () => ({ generation: gen() }), knownChannels: async () => [CHAN], steps: { fetchAndBuild: async () => ({ ok: true }), refresh: async () => ({ status: "no-change", usd: 0 }), generateEdition: async () => ({ status: "quiet", usd: 0, matched: 0 }), ...steps, }, ...extra, }; } const ctx = () => ({ log: () => {}, signal: new AbortController().signal }); const WATCH = { shape: "watch", id: "pia-watch", topic: "Pia watch", question: "Who joined the show?", channels: [CHAN], terms: "Pia Tartlet|contest", regex: true, cadence: "daily 06:00", tz: "UTC" }; const learnedOf = (spelling: string, over: Partial = {}): LearnedSpelling => ({ spelling, means: "Pia Tartlet", quote: "my friend pia tart lit is joining us later", recording: "b-02", channel: CHAN, start: 5, hits: 2, source: "proposed", at: NOW.toISOString(), ...over, }); async function withLearned(paths: Paths, spellings: string[]) { const s = (await readSchedule("pia-watch", paths))!; await recordLearnPass(s, { pass: { at: NOW.toISOString(), trigger: "ops", status: "done", model: "qwen3:8b", names: ["Pia Tartlet"], notAsked: [], proposed: spellings.length, kept: 0, dropped: 0, usd: 0 }, kept: spellings.map((x) => learnedOf(x)), dropped: [], termsKey: "re:Pia Tartlet|contest" }, paths, NOW); } test("learn: the plan names what it asks about; a create and a change of terms start a pass; no door — refused as not wired", async () => { const paths = store(); const started: [string, string][] = []; const enqueueLearn: EnqueueLearnFn = async (id, trigger) => { started.push([id, trigger]); return { ok: true, jobId: `job-${started.length}`, plan: { names: ["Pia Tartlet"] } as never }; }; const made = await ask({ action: "create", ...WATCH }, depsOf(paths, {}, NOW, { enqueueLearn })); assert.equal(made.ok, true, made.error); assert.deepEqual(made.learn, { jobId: "job-1", names: ["Pia Tartlet"] }); const plan = await ask({ action: "learn", id: "pia-watch", dryRun: true }, depsOf(paths)); assert.equal(plan.ok, true, plan.error); assert.deepEqual(plan.plan.names, ["Pia Tartlet"]); assert.equal(plan.plan.due, "create"); assert.equal(plan.plan.refused, null); assert.equal(plan.plan.provider, "local"); const refused = await ask({ action: "learn", id: "pia-watch" }, depsOf(paths)); assert.equal(refused.ok, false); assert.match(refused.error, /not wired/); const now = await ask({ action: "learn", id: "pia-watch" }, depsOf(paths, {}, NOW, { enqueueLearn })); assert.deepEqual([now.ok, now.jobId], [true, "job-2"]); // A change of terms starts one; a change of anything else does not. const u1 = await ask({ action: "update", id: "pia-watch", topic: "Pia, watched" }, depsOf(paths, {}, NOW, { enqueueLearn })); assert.equal(u1.learn, undefined); const u2 = await ask({ action: "update", id: "pia-watch", terms: "Pia Tartlet|Ross Crumb" }, depsOf(paths, {}, NOW, { enqueueLearn })); assert.equal(u2.learn.jobId, "job-3"); assert.deepEqual(started.map((x) => x[1]), ["create", "ops", "terms"]); // A series without triage first has nothing to learn for. await ask({ action: "create", shape: "series", id: "plain", topic: "Plain", channels: [CHAN], terms: "Pia Tartlet", cadence: "daily 06:00", tz: "UTC" }, depsOf(paths, {}, NOW, { enqueueLearn })); const p2 = await ask({ action: "learn", id: "plain", dryRun: true }, depsOf(paths)); assert.match(p2.plan.refused, /does not triage/); assert.equal(started.length, 3); }); test("unlearn: removed and blocked — refused when it was never learned, or is removed already", async () => { const paths = store(); await createSchedule(parseCreate(WATCH), depsOf(paths)); await withLearned(paths, ["pia tart lit", "Pea Tartlet"]); const out = await ask({ action: "unlearn", id: "pia-watch", spelling: "Pia Tart Lit" }, depsOf(paths)); assert.equal(out.ok, true, out.error); assert.equal(out.removed.spelling, "pia tart lit"); const f = await readLearned(paths, { shape: "watch", id: "pia-watch" }); assert.deepEqual(f?.learned.map((l) => l.spelling), ["Pea Tartlet"]); assert.deepEqual(f?.blocked.map((b) => b.spelling), ["pia tart lit"]); assert.match((await ask({ action: "unlearn", id: "pia-watch", spelling: "pia tart lit" }, depsOf(paths))).error, /removed already/); assert.match((await ask({ action: "unlearn", id: "pia-watch", spelling: "never" }, depsOf(paths))).error, /has not learned "never"/); // The file sits beside the schedule. assert.ok(readFileSync(path.join(paths.articlesDir, ".series", "pia-watch", "learned.json"), "utf8").includes("Pea Tartlet")); }); test("promote-alias: the plan (nothing written), then the alias written through the writer — global, then a site's trigger", async () => { const paths = store(); await createSchedule(parseCreate(WATCH), depsOf(paths)); await withLearned(paths, ["pia tart lit"]); const plan = await ask({ action: "promote-alias", id: "pia-watch", spelling: "pia tart lit" }, depsOf(paths)); assert.equal(plan.ok, true, plan.error); assert.equal(plan.confirmed, false); assert.equal(plan.plan.action, "new"); assert.equal(plan.plan.to, "global"); assert.deepEqual(plan.plan.sites, ["synthalyzer"]); assert.equal(plan.plan.alias.note, "learned by watch pia-watch from synth-kitchen/b-02 at 0:05"); assert.throws(() => readFileSync(paths.globalAliasesFile, "utf8")); const done = await ask({ action: "promote-alias", id: "pia-watch", spelling: "pia tart lit", confirm: true }, depsOf(paths)); assert.equal(done.confirmed, true, done.error); const global = JSON.parse(readFileSync(paths.globalAliasesFile, "utf8")); // The seeded defaults stay (an absent global file reads as them), the new alias after them. assert.deepEqual(global.aliases.at(-1), { id: "pia-tartlet", label: "Pia Tartlet", triggers: ["pia tartlet", "pia tart lit"], suggestion: "\\bPia Tartlet\\b|\\bpia tart lit\\b", useRegex: true, enabled: true, note: "learned by watch pia-watch from synth-kitchen/b-02 at 0:05" }); const f = await readLearned(paths, { shape: "watch", id: "pia-watch" }); assert.deepEqual(f?.learned[0]?.promoted && { to: f.learned[0].promoted.to, alias: f.learned[0].promoted.alias }, { to: "global", alias: "pia-tartlet" }); // Promoted again: refused, the alias fires already. assert.match((await ask({ action: "promote-alias", id: "pia-watch", spelling: "pia tart lit", confirm: true }, depsOf(paths))).error, /already fires/); // A site's list with an alias naming her: the spelling added as its trigger. writeFileSync(path.join(paths.sitesDir, "synthalyzer", "search-aliases.json"), JSON.stringify({ aliases: [{ id: "pia", label: "Pia Tartlet", triggers: ["pia tartlet"], suggestion: "\\bpia tartlet\\b", useRegex: true }] })); const site = await ask({ action: "promote-alias", id: "pia-watch", spelling: "pia tart lit", site: "synthalyzer", confirm: true }, depsOf(paths)); assert.equal(site.promoted.action, "trigger", site.error); const sa = JSON.parse(readFileSync(path.join(paths.sitesDir, "synthalyzer", "search-aliases.json"), "utf8")); assert.deepEqual(sa.aliases[0].triggers, ["pia tartlet", "pia tart lit"]); assert.equal(sa.aliases[0].suggestion, "\\bpia tartlet\\b|\\bpia tart lit\\b"); assert.match((await ask({ action: "promote-alias", id: "pia-watch", spelling: "pia tart lit", site: "nowhere" }, depsOf(paths))).error, /no site "nowhere"/); assert.match((await ask({ action: "promote-alias", id: "pia-watch", spelling: "unknown" }, depsOf(paths))).error, /has not learned/); }); // ─── the tick ─── function triageStub(paths: Paths, calls: string[]): NonNullable { return async (input) => { calls.push("triage"); const f = await createTriageRun( (k): TriageFile => ({ format: TRIAGE_FORMAT, version: TRIAGE_VERSION, owner: input.schedule.id, k, status: "done", model: "qwen3:8b", provider: "local", question: input.schedule.question, scope: { channels: input.scope.channels }, terms: input.schedule.scope.terms ?? null, regex: true, topics: [], threshold: { strong: 1, weak: 3 }, since: input.since, knownCount: null, createdAt: NOW.toISOString(), tier0: { candidates: [{ id: "b-02", channel: CHAN, title: "Pie talk", date: "2026-10-08", matches: 1, by: ["learned"], learned: ["pia tart lit"] }], scanned: 4, newCount: 4, cut: [], partial: false, unreached: [], perQuery: [], newBy: "date" }, tier1: { model: "qwen3:8b", flags: [], dismissed: [{ id: "b-02", stage: "judge", reason: "not relevant to the question" }], read: 1, windows: 1, chunks: 1, usd: 0 }, escalation: escalationOf([], { strong: 1, weak: 3 }), learned: { n: 1, spellings: ["pia tart lit"] }, cost: { tier0: 0, tier1: 0 }, summary: "1 candidate · 0 flagged · 1 dismissed · terms + 1 learned — below the threshold", warnings: [], }), paths, input.schedule.id, ); return { status: "done", file: f }; }; } test("the tick: a pass before tier 0 only when one is due; its failure is a warning; the triage's uses written", async () => { const paths = store(); await createSchedule(parseCreate(WATCH), depsOf(paths)); const calls: string[] = []; const learn: NonNullable = async (input) => { calls.push(`learn:${input.trigger}`); await withLearned(paths, ["pia tart lit"]); return { status: "done", added: 1, total: 1, jobId: "learn-job" }; }; const t1 = await runTick("pia-watch", { trigger: "now", jobId: "j1" }, depsOf(paths, { learn, triage: triageStub(paths, calls) }), ctx()); assert.deepEqual(calls, ["learn:create", "triage"]); assert.deepEqual(t1.learn, { trigger: "create", status: "done", added: 1, total: 1, jobId: "learn-job" }); assert.equal(t1.triage?.learned, 1); assert.equal(t1.status, "no-change"); // The triage job's write (the stub stands in for the job: applyTriageLearning is what it calls). const { readTriageFile } = await import("../lib/report/draft/triage/store"); await applyTriageLearning((await readTriageFile("pia-watch", 1, paths))!, paths, NOW); const f = await readLearned(paths, { shape: "watch", id: "pia-watch" }); assert.deepEqual(f?.learned[0]?.uses, [{ k: 1, at: NOW.toISOString(), candidates: 1, flagged: 0 }]); // Not due a day later: no pass. calls.length = 0; const t2 = await runTick("pia-watch", { trigger: "now", jobId: "j2" }, depsOf(paths, { learn, triage: triageStub(paths, calls) }, new Date("2026-10-15T12:00:00.000Z")), ctx()); assert.deepEqual(calls, ["triage"]); assert.equal(t2.learn, undefined); // A week on, it is due; a failed pass is a warning and the triage still runs. calls.length = 0; const failing: NonNullable = async (input) => { calls.push(`learn:${input.trigger}`); return { status: "failed", reason: "ollama is down" }; }; const t3 = await runTick("pia-watch", { trigger: "now", jobId: "j3" }, depsOf(paths, { learn: failing, triage: triageStub(paths, calls) }, new Date("2026-10-22T12:00:00.000Z")), ctx()); assert.deepEqual(calls, ["learn:weekly", "triage"]); assert.equal(t3.status, "no-change"); assert.match(t3.warnings?.join("\n") ?? "", /the proposal pass failed: ollama is down/); }); test("applyTriageLearning: a heard spelling the run confirmed is kept; a blocked one is not; a run of no schedule learns nothing", async () => { const paths = store(); await createSchedule(parseCreate(WATCH), depsOf(paths)); const base = { format: TRIAGE_FORMAT, version: TRIAGE_VERSION, owner: "pia-watch", k: 3, status: "done", model: "m", provider: "local", question: "Q", scope: { channels: [CHAN] }, terms: "Pia", regex: false, topics: [], threshold: { strong: 1, weak: 3 }, since: null, knownCount: null, createdAt: "t", cost: { tier0: 0, tier1: 0 }, summary: "", warnings: [] } as TriageFile; const heard = learnedOf("pia tartlit", { source: "heard", k: 3 }); const r = await applyTriageLearning({ ...base, learning: { kept: [heard], dropped: [{ spelling: "pie", means: "Pia Tartlet", source: "heard", reason: "no-hits", why: "none", at: "t" }] } }, paths, NOW); assert.deepEqual(r?.added.map((l) => l.spelling), ["pia tartlit"]); const f = await readLearned(paths, { shape: "watch", id: "pia-watch" }); assert.deepEqual(f?.learned.map((l) => [l.spelling, l.source, l.k]), [["pia tartlit", "heard", 3]]); assert.deepEqual(f?.dropped.map((d) => d.reason), ["no-hits"]); assert.equal(await applyTriageLearning({ ...base, owner: "no-such" }, paths, NOW), null); }); test("add-spelling (release 32): a spelling by hand — a watched name, proved by code, kept as hand; refusals; a removed one unblocked", async () => { const paths = store(); await createSchedule(parseCreate(WATCH), depsOf(paths)); const proved: string[] = []; const proveSpelling = async (i: { spelling: string; means: string; at: string }) => { proved.push(i.spelling); if (i.spelling === "Pya Tortlet") return { ok: false as const, reason: "no-hits" as const, why: "does not occur in scope (4 recordings counted)" }; return { ok: true as const, spelling: learnedOf(i.spelling, { means: i.means, source: "hand" as const, at: i.at }) }; }; const d = { ...depsOf(paths), proveSpelling }; // No prover: refused as not wired. assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "pia tart lit", means: "Pia Tartlet" }, depsOf(paths))).error, /not wired/); const out = await ask({ action: "add-spelling", id: "pia-watch", spelling: "pia tart lit", means: "Pia Tartlet" }, d); assert.equal(out.ok, true, out.error); assert.deepEqual([out.added.spelling, out.added.source, out.unblocked], ["pia tart lit", "hand", false]); const f = await readLearned(paths, { shape: "watch", id: "pia-watch" }); assert.deepEqual(f?.learned.map((l) => [l.spelling, l.source]), [["pia tart lit", "hand"]]); // Refusals, each before any count: not a watched name, the name itself, the terms find it, learned already. assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "pie tart", means: "Someone" }, d)).error, /one of the watched names: "Pia Tartlet"/); assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "pia tartlet", means: "Pia Tartlet" }, d)).error, /the name itself/); assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "the contest", means: "Pia Tartlet" }, d)).error, /terms already find/); assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "Pia Tart Lit", means: "Pia Tartlet" }, d)).error, /learned "Pia Tart Lit" already/); assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "a b c d e", means: "Pia Tartlet" }, d)).error, /too long/); assert.deepEqual(proved, ["pia tart lit"]); // Not in scope: refused with the count's words; nothing written. assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "Pya Tortlet", means: "Pia Tartlet" }, d)).error, /not kept: does not occur in scope/); // A removed spelling added back by hand: the block lifted. await ask({ action: "unlearn", id: "pia-watch", spelling: "pia tart lit" }, depsOf(paths)); const back = await ask({ action: "add-spelling", id: "pia-watch", spelling: "pia tart lit", means: "Pia Tartlet" }, d); assert.deepEqual([back.ok, back.unblocked], [true, true]); const g = await readLearned(paths, { shape: "watch", id: "pia-watch" }); assert.deepEqual([g?.learned.length, g?.blocked.length], [1, 0]); });