commit 8936b76260e7decd323d81b5b6781628a0e3123f
parent 9f82dee680ccf34b714e3b51548de24b9865dc7f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 21:37:47 -0400
common, mcp, editor: learned spellings (R6.3) — a watch's proposal pass (the triage model's likely mis-hearings of each name in its terms), tier 1's heard spans, both confirmed by code (verbatim, an uncapped count in scope via the listing and enumerate's ids) and the judge (it means the name, the line quoted) before learned.json keeps them; learned spellings join the candidate query as escaped literals ("terms + N learned"), capped, suggest-removing; report-schedule learn / unlearn / promote-alias (the alias writer, plan then confirm); a tick proposes before tier 0 when due; mcp countPhrases; tests (common +18, mcp +1); COMMANDS.md
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
23 files changed, 2577 insertions(+), 20 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -148,7 +148,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait` |
| `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` |
| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the claim, its quotes, the transcript within the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues (answered pairs are skipped). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
-| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'` |
+| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Melanie Mack"}'` |
### Usage, flags and environment
diff --git a/common/controller/learnedSpellings.test.ts b/common/controller/learnedSpellings.test.ts
@@ -0,0 +1,262 @@
+// 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<string, unknown>, d: Parameters<typeof action>[1]): Promise<any> => 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<TickSteps> = {}, now: Date = NOW, extra: Partial<TickDeps> & { 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> = {}): 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<TickSteps["triage"]> {
+ 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<TickSteps["learn"]> = 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<TickSteps["learn"]> = 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);
+});
diff --git a/common/controller/learnedSpellings.ts b/common/controller/learnedSpellings.ts
@@ -0,0 +1,241 @@
+// 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
+//
+// 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,
+ 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";
+
+export class LearnedInputError extends Error {}
+
+const fail = (msg: string): never => {
+ throw new LearnedInputError(msg);
+};
+
+type LearnedPathsFull = Pick<Paths, "articlesDir">;
+
+async function scheduleOf(id: string, paths: LearnedPathsFull): Promise<Schedule> {
+ 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<Schedule, "shape" | "id">, paths: LearnedPathsFull, fn: (f: LearnedFile) => LearnedFile, now: Date = new Date()): Promise<LearnedFile> {
+ 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<string, { candidates: number; flagged: number }> {
+ const flagged = new Set((f.tier1?.flags ?? []).map((x) => x.id));
+ const out = new Map<string, { candidates: number; flagged: number }>();
+ 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<Schedule, "shape" | "id">,
+ 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<PromotePlan> {
+ 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<PromotePlan> {
+ 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;
+}
diff --git a/common/controller/reportLearn.ts b/common/controller/reportLearn.ts
@@ -0,0 +1,247 @@
+// A WATCH'S PROPOSAL PASS — LEARNED SPELLINGS AS AN EDITOR JOB (umtool R6.3).
+//
+// planLearn what a pass would ask about (nothing written): the watch's
+// names (namesOf its terms, capitalised first, at most
+// NAMES_PER_PASS — the rest said), the model it runs on, the
+// spellings it has and has blocked, when it last proposed and
+// whether a tick would propose now (learnDue)
+// enqueueLearn ONE `report-draft` job (task "learn") on the triage
+// model's lane — `draft:local` by default, through the GPU
+// arbiter, ollama unloaded at the end; `draft:api` for the
+// extractor, metered and held to the caps — that runs the
+// pass (lib/report/draft/triage/confirm.ts runLearnPass) over
+// the newest build holding the scope and records it through
+// the one writer (./learnedSpellings.ts recordLearnPass). Its
+// log ends `@@report-draft {…, task: "learn", learn: {…}}`
+//
+// Callers: `report-schedule {"action":"learn"}` (the operator's), a create or a
+// change of terms (controller/reportScheduleOps.ts), and a tick before tier 0
+// when a pass is due — never proposed, terms changed, or a week since the last
+// (controller/reportTick.ts learnStep).
+
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { getRegistry } from "../jobs/registry";
+import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys";
+import { getSettings } from "../lib/settings";
+import { capFor, triageModelOf, type GenerationSettings } from "../lib/generationSettings";
+import { Meter, providerOf, structuredAnswer, unloadOllama } from "../lib/llm";
+import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues";
+import { usageOf } from "../lib/report/draft/tasks/run";
+import { enumerateViaTools } from "../lib/report/draft/refresh/delta";
+import { countViaEnumerate, runLearnPass } from "../lib/report/draft/triage/confirm";
+import {
+ CONFIRM_WINDOWS,
+ LEARNED_CAP,
+ NAMES_PER_PASS,
+ PROPOSALS_PER_NAME,
+ knownKeys,
+ learnDue,
+ namesForPass,
+ termKeys,
+ termsKey,
+ type LearnedPass,
+} from "../lib/report/draft/triage/learned";
+import { readLearned } from "../lib/report/draft/triage/learnedStore";
+import { readScheduleById } from "../lib/report/schedule/store";
+import { triagesFirst, type Schedule } from "../lib/report/schedule/types";
+import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
+import { recordLearnPass } from "./learnedSpellings";
+import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, resolveCorpus, type ReportDraftDeps } from "./reportDraft";
+
+export const LEARN_TASK = "learn" as const;
+export { namesForPass, termKeys };
+
+export type LearnTrigger = LearnedPass["trigger"];
+
+export type LearnPlan = {
+ id: string;
+ // The names this pass asks about, and the ones past the per-pass cap.
+ names: string[];
+ notAsked: string[];
+ model: string;
+ provider: "api" | "local";
+ perName: number;
+ windows: number;
+ cap: number;
+ learned: number;
+ blocked: number;
+ lastPass: LearnedPass | null;
+ proposedAt: string | null;
+ // Why a tick would propose now (create: never proposed; terms; weekly), or null.
+ due: LearnTrigger | null;
+ refused: string | null;
+};
+
+const round4 = (v: number) => Math.round(v * 10_000) / 10_000;
+
+async function scheduleOf(id: string, paths: ReportDraftDeps["paths"]): Promise<Schedule> {
+ const r = await readScheduleById(id, paths);
+ if (!r) throw new Error(`no schedule "${id}"`);
+ if (!r.ok) throw new Error(`the schedule "${id}" does not read (${r.file}): ${r.problem}`);
+ return r.schedule;
+}
+
+/** What a pass would ask (nothing written). */
+export async function planLearn(id: string, deps: { paths: ReportDraftDeps["paths"]; settings?: () => { generation: GenerationSettings }; now?: () => Date }): Promise<LearnPlan> {
+ const s = await scheduleOf(id, deps.paths);
+ const gen = (deps.settings ?? getSettings)().generation;
+ const model = triageModelOf(gen);
+ const f = await readLearned(deps.paths, s);
+ const { names, notAsked } = namesForPass(s);
+ const key = termsKey(s.scope.terms, s.scope.regex === true);
+ const refused = !triagesFirst(s)
+ ? `"${id}" does not triage: a learned spelling is a watch's (or a schedule with triage first)`
+ : !names.length
+ ? `"${id}" has no name in its terms to learn spellings of (a literal alternative with a capital letter, or a phrase)`
+ : null;
+ return {
+ id,
+ names,
+ notAsked,
+ model,
+ provider: providerOf(model) === "local" ? "local" : "api",
+ perName: PROPOSALS_PER_NAME,
+ windows: CONFIRM_WINDOWS,
+ cap: LEARNED_CAP,
+ learned: f?.learned.length ?? 0,
+ blocked: f?.blocked.length ?? 0,
+ lastPass: f?.passes.at(-1) ?? null,
+ proposedAt: f?.proposedAt ?? null,
+ due: refused ? null : learnDue(f, key, deps.now?.() ?? new Date()),
+ refused,
+ };
+}
+
+export type LearnEnqueued = { ok: true; jobId: string; plan: LearnPlan; result: Extract<StreamActionResult, { ok: true }> } | { ok: false; error: string; plan?: LearnPlan };
+
+/** Enqueue the pass (refused when the plan refuses, or the API caps do). */
+export async function enqueueLearn(id: string, trigger: LearnTrigger, deps: ReportDraftDeps): Promise<LearnEnqueued> {
+ let plan: LearnPlan;
+ try {
+ plan = await planLearn(id, deps);
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+ if (plan.refused) return { ok: false, error: plan.refused, plan };
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ let maxUsd: number | undefined;
+ if (plan.provider === "api") {
+ try {
+ maxUsd = capFor(gen.caps, "sweep");
+ } catch (e) {
+ return { ok: false, error: (e as Error).message, plan };
+ }
+ const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily);
+ if (refusal) return { ok: false, error: refusal, plan };
+ }
+ const result = await runManagedFunction({
+ kind: REPORT_DRAFT_JOB_KIND,
+ queueKey: plan.provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE,
+ paths,
+ fn: (onLog, signal, _setProgress, ctx) => runLearnJob({ id, trigger, plan, maxUsd, jobId: ctx.jobId, onLog, signal }, deps),
+ });
+ if (!result.ok) return { ok: false, error: result.error, plan };
+ return { ok: true, jobId: result.jobId, plan, result: result as Extract<StreamActionResult, { ok: true }> };
+}
+
+async function runLearnJob(
+ o: { id: string; trigger: LearnTrigger; plan: LearnPlan; maxUsd?: number; jobId: string; onLog: (l: string) => void; signal: AbortSignal },
+ deps: ReportDraftDeps,
+): Promise<void> {
+ const { id, plan, onLog, signal } = o;
+ const paths = deps.paths;
+ const gen = (deps.settings ?? getSettings)().generation;
+ const now = () => deps.now?.() ?? new Date();
+ const s = await scheduleOf(id, paths);
+ const model = plan.model;
+ onLog(`learn ${id} (${o.trigger}) on ${model} (${plan.provider === "api" ? `the Claude API, cap $${o.maxUsd}` : "the local model, through the GPU arbiter"}): ${plan.names.length} name(s) — ${plan.names.map((n) => `"${n}"`).join(", ")}${plan.notAsked.length ? `; ${plan.notAsked.length} not asked this pass (the per-pass cap of ${NAMES_PER_PASS})` : ""}`);
+ const meter = new Meter({ ...(o.maxUsd !== undefined ? { maxUsd: o.maxUsd } : {}) });
+ const at = now().toISOString();
+ let status: LearnedPass["status"] = "done";
+ let error: string | undefined;
+ let kept: Awaited<ReturnType<typeof runLearnPass>>["kept"] = [];
+ let dropped: Awaited<ReturnType<typeof runLearnPass>>["dropped"] = [];
+ let proposed = 0;
+ let corpus: Awaited<ReturnType<ReportDraftDeps["corpusTools"]>> | null = null;
+ try {
+ const where = await resolveCorpus({}, s.scope.channels, paths, gen);
+ onLog(`corpus ${where.source}${where.build ? ` (build ${where.build})` : ""}`);
+ corpus = await deps.corpusTools(where.source);
+ const llm = llmConfigOf(gen, paths, plan.provider === "local" ? { onLog, signal } : undefined);
+ const ask = <T,>(system: string, user: string, schema: object) => structuredAnswer<T>({ llm, model, system, user, schema, meter, signal });
+ const f = await readLearned(paths, s);
+ const known = new Set([...knownKeys(f, plan.names), ...termKeys(s)]);
+ const c = corpus;
+ const count = c.countPhrases ? (a: Parameters<NonNullable<typeof c.countPhrases>>[0]) => c.countPhrases!(a) : c.listRecordings ? countViaEnumerate((a) => c.listRecordings!(a), enumerateViaTools(c)) : null;
+ if (!count) throw new Error("this corpus cannot count a spelling in scope (no listing)");
+ const r = await runLearnPass(
+ { names: plan.names, question: s.question, scope: { channels: s.scope.channels, ...(s.scope.from ? { from: s.scope.from } : {}) }, known, at },
+ { corpus: c, ask, count, cuesOf: corpusCuesOf(c), log: onLog, signal },
+ );
+ kept = r.kept;
+ dropped = r.dropped;
+ proposed = r.proposed.length;
+ } catch (e) {
+ status = signal.aborted ? "cancelled" : "failed";
+ error = signal.aborted ? "cancelled" : (e as Error).message;
+ onLog(`learn ${status}: ${error}`);
+ } finally {
+ await corpus?.close().catch(() => {});
+ if (plan.provider === "local") {
+ await unloadOllama({ baseUrl: gen.ollamaUrl || paths.ollamaUrl }, model).then(
+ () => onLog(`unloaded ${model} from ollama`),
+ (e) => onLog(`ollama unload failed: ${(e as Error).message}`),
+ );
+ }
+ }
+ const usd = round4(meter.usd);
+ const pass: LearnedPass = { at, trigger: o.trigger, status, model, names: plan.names, notAsked: plan.notAsked, proposed, kept: 0, dropped: 0, usd, jobId: o.jobId, ...(error ? { error } : {}) };
+ const rec = await recordLearnPass(s, { pass, kept, dropped, termsKey: termsKey(s.scope.terms, s.scope.regex === true) }, paths, now());
+ if (plan.provider === "api") {
+ const t = now();
+ const rows: GenerationUsageRow[] = Object.entries(meter.summary().byModel)
+ .filter(([, x]) => x.calls > 0)
+ .map(([m, x]) => {
+ const u = usageOf(x);
+ return { at: t.toISOString(), day: utcDay(t), jobId: o.jobId, article: id, iteration: 0, task: LEARN_TASK, model: m, inputTokens: u.inputTokens, outputTokens: u.outputTokens, cacheReadTokens: u.cacheReadTokens ?? 0, cacheWriteTokens: u.cacheWriteTokens ?? 0, usd: round4(u.usd) };
+ });
+ await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`));
+ }
+ const summary =
+ status === "done"
+ ? `${proposed} proposed · ${rec.added.length} learned · ${rec.dropped.length} dropped${rec.added.length ? ` (${rec.added.map((l) => `"${l.spelling}" → ${l.means}`).join(", ")})` : ""}`
+ : `${status}: ${error}`;
+ onLog(`learn ${id}: ${summary}; ${rec.file.learned.length} learned in all`);
+ onLog(`${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: id, iteration: 0, task: LEARN_TASK, status, summary, usd, learn: { proposed, learned: rec.added.map((l) => l.spelling), dropped: rec.dropped.length, total: rec.file.learned.length } })}`);
+ if (status === "cancelled" || signal.aborted) throw new Error("cancelled");
+ if (status === "failed") throw new Error(summary);
+}
+
+/** The pass as a tick step: enqueued and awaited (a cancelled tick cancels it). */
+export function learnStep(draft: ReportDraftDeps, calls: { enqueueLearn?: typeof enqueueLearn } = {}) {
+ const enqueue = calls.enqueueLearn ?? enqueueLearn;
+ return async (input: { schedule: Schedule; trigger: LearnTrigger }, ctx: { log: (l: string) => void; signal: AbortSignal }): Promise<{ status: "done" | "failed" | "cancelled"; reason?: string; jobId?: string; added?: number; total?: number }> => {
+ const out = await enqueue(input.schedule.id, input.trigger, draft);
+ if (!out.ok) return { status: "failed", reason: out.error };
+ void out.result.stream.cancel();
+ ctx.log(`learn ${input.schedule.id} (${input.trigger}): job ${out.jobId}`);
+ const stop = () => getRegistry().cancel(out.jobId);
+ ctx.signal.addEventListener("abort", stop, { once: true });
+ let d: { status: string };
+ try {
+ d = await out.result.done;
+ } finally {
+ ctx.signal.removeEventListener("abort", stop);
+ }
+ const f = await readLearned(draft.paths, input.schedule).catch(() => null);
+ const last = f?.passes.at(-1);
+ const ok = d.status === "done" && last?.status === "done";
+ return {
+ status: ok ? "done" : ctx.signal.aborted || d.status === "cancelled" ? "cancelled" : "failed",
+ jobId: out.jobId,
+ ...(last ? { added: last.kept, total: f!.learned.length } : {}),
+ ...(!ok ? { reason: last?.error ?? `the learn job ended ${d.status}` } : {}),
+ };
+ };
+}
diff --git a/common/controller/reportScheduleOps.ts b/common/controller/reportScheduleOps.ts
@@ -24,6 +24,18 @@
// run k on), seen.json, the quiet
// editions they covered — the plan
// unless confirm: true
+// {"action": "learn", "id", "dryRun"?} (R6.3) the proposal pass now: the
+// plan (the names it asks about,
+// the model) and its job; dryRun:
+// the plan only. A create (of a
+// schedule that triages) and a
+// change of terms start one too
+// {"action": "unlearn", "id", "spelling"} (R6.3) remove a learned spelling;
+// it is never learned again
+// {"action": "promote-alias", "id", (R6.3) a learned spelling as a
+// "spelling", "site"?, "confirm"?} search alias (global, or a
+// site's) through the alias
+// writer: the plan unless confirm
import { getSettings } from "../lib/settings";
import { ArticleRegistryError } from "../lib/report/registry";
@@ -46,8 +58,12 @@ import {
} from "./reportSchedule";
import { enqueueTick, type TickDeps } from "./reportTick";
import { isReportScheduleArmed } from "./reportScheduleRunner";
+import { LearnedInputError, planPromoteAlias, promoteAlias, unlearnSpelling } from "./learnedSpellings";
+import { planLearn, type LearnPlan, type LearnTrigger } from "./reportLearn";
+import { triagesFirst } from "../lib/report/schedule/types";
+import { namesForPass } from "../lib/report/draft/triage/learned";
-export const REPORT_SCHEDULE_ACTIONS = ["list", "create", "update", "pause", "resume", "delete", "tick-now", "reset-triage"] as const;
+export const REPORT_SCHEDULE_ACTIONS = ["list", "create", "update", "pause", "resume", "delete", "tick-now", "reset-triage", "learn", "unlearn", "promote-alias"] as const;
export type ReportScheduleActionName = (typeof REPORT_SCHEDULE_ACTIONS)[number];
export const REPORT_SCHEDULE_BODY_KEYS = [
@@ -74,6 +90,8 @@ export const REPORT_SCHEDULE_BODY_KEYS = [
"topics",
"threshold",
"k",
+ "spelling",
+ "site",
] as const;
export type ScheduleView = Schedule & {
@@ -105,10 +123,20 @@ const idOf = (b: Record<string, unknown>): string => {
return b.id.trim();
};
+/** R6.3: the proposal pass's door — the editor's enqueueLearn, bound to its deps. Absent: a learn is refused as not wired. */
+export type EnqueueLearnFn = (id: string, trigger: LearnTrigger) => Promise<{ ok: true; jobId: string; plan: LearnPlan } | { ok: false; error: string; plan?: LearnPlan }>;
+
+// After a create or a change of terms: a pass when the schedule triages and its terms name someone.
+async function learnAfter(id: string, trigger: LearnTrigger, s: { shape: string; triageFirst?: boolean; scope: { terms?: string; regex?: boolean } }, enqueue: EnqueueLearnFn | undefined) {
+ if (!enqueue || !triagesFirst(s as Parameters<typeof triagesFirst>[0]) || !namesForPass(s).names.length) return {};
+ const out = await enqueue(id, trigger).catch((e: Error) => ({ ok: false as const, error: e.message }));
+ return { learn: out.ok ? { jobId: out.jobId, names: out.plan.names } : { refused: out.error } };
+}
+
/** One `report-schedule` ask. Input errors answer `{ok: false, error}` (a 400); nothing throws for them. */
export async function reportScheduleAction(
body: Record<string, unknown>,
- deps: TickDeps & { lane?: () => LaneView },
+ deps: TickDeps & { lane?: () => LaneView; enqueueLearn?: EnqueueLearnFn },
): Promise<Ok | Refused> {
const action = body.action;
if (typeof action !== "string" || !(REPORT_SCHEDULE_ACTIONS as readonly string[]).includes(action)) {
@@ -140,11 +168,41 @@ export async function reportScheduleAction(
return { ok: true, plan };
}
const { plan, schedule } = await createSchedule(input, deps);
- return { ok: true, plan, schedule: viewOf(schedule, now) };
+ return { ok: true, plan, schedule: viewOf(schedule, now), ...(await learnAfter(schedule.id, "create", schedule, deps.enqueueLearn)) };
}
case "update": {
- const s = await updateSchedule(idOf(body), parseUpdate(body), deps);
- return { ok: true, schedule: viewOf(s, now) };
+ const id = idOf(body);
+ const before = await readScheduleById(id, deps.paths).catch(() => null);
+ const s = await updateSchedule(id, parseUpdate(body), deps);
+ const termsChanged = before?.ok && (before.schedule.scope.terms !== s.scope.terms || (before.schedule.scope.regex === true) !== (s.scope.regex === true));
+ return { ok: true, schedule: viewOf(s, now), ...(termsChanged ? await learnAfter(id, "terms", s, deps.enqueueLearn) : {}) };
+ }
+ case "learn": {
+ const id = idOf(body);
+ if (body.dryRun === true || !deps.enqueueLearn) {
+ const plan = await planLearn(id, deps);
+ if (body.dryRun === true) return { ok: true, plan };
+ return { ok: false, error: plan.refused ?? "not wired: no proposal pass (R6.3) in this process" };
+ }
+ const out = await deps.enqueueLearn(id, "ops");
+ if (!out.ok) return { ok: false, error: out.error };
+ return { ok: true, plan: out.plan, jobId: out.jobId };
+ }
+ case "unlearn": {
+ const id = idOf(body);
+ const out = await unlearnSpelling(id, String(body.spelling ?? ""), deps);
+ return { ok: true, removed: out.removed, blocked: out.blocked };
+ }
+ case "promote-alias": {
+ const id = idOf(body);
+ const site = body.site === undefined || body.site === null || body.site === "" || body.site === "global" ? null : typeof body.site === "string" ? body.site.trim() : "";
+ if (site === "") throw new ScheduleInputError('"site" is a site\'s id (or absent: the global aliases)');
+ if (body.confirm !== true) {
+ const plan = await planPromoteAlias(id, String(body.spelling ?? ""), site, deps);
+ return { ok: true, confirmed: false, plan };
+ }
+ const plan = await promoteAlias(id, String(body.spelling ?? ""), site, deps);
+ return { ok: true, confirmed: true, promoted: plan };
}
case "pause":
case "resume": {
@@ -185,7 +243,9 @@ export async function reportScheduleAction(
}
}
} catch (e) {
- if (e instanceof ScheduleInputError || e instanceof CadenceError) return { ok: false, error: (e as Error).message };
+ if (e instanceof ScheduleInputError || e instanceof CadenceError || e instanceof LearnedInputError) return { ok: false, error: (e as Error).message };
+ // A schedule the learn plan cannot read is input-shaped too.
+ if (/^no schedule "|does not read/.test((e as Error).message)) return { ok: false, error: (e as Error).message, ...(/^no schedule "/.test((e as Error).message) ? { status: 404 } : {}) };
// The registry's own refusals (the store busy, a bad id) are input-shaped too.
if (e instanceof ArticleRegistryError) return { ok: false, error: (e as Error).message };
if (/maxUsd/.test((e as Error).message)) return { ok: false, error: (e as Error).message };
diff --git a/common/controller/reportTick.ts b/common/controller/reportTick.ts
@@ -76,6 +76,8 @@ import { listSchedules } from "../lib/report/schedule/store";
import { triagesFirst } from "../lib/report/schedule/types";
import { readTriageFile } from "../lib/report/draft/triage/store";
import { partialWords, tickTriageOf, type TickTriage, type TriageFile } from "../lib/report/draft/triage/types";
+import { learnDue, learnedWords, namesForPass, termsKey } from "../lib/report/draft/triage/learned";
+import { readLearned } from "../lib/report/draft/triage/learnedStore";
import { enqueueReportDraft, type ReportDraftDeps } from "./reportDraft";
import { fetchScope, readRefreshFile } from "./reportRefresh";
import {
@@ -154,8 +156,14 @@ export type TickSteps = {
generateEdition(input: EditionInput, ctx: StepCtx): Promise<StepOutcome>;
// R6: the cheap pass that flags what is worth a sweep (triage first, a watch).
triage?(input: TriageStepInput, ctx: StepCtx): Promise<TriageStepOutcome>;
+ // R6.3: the proposal pass (learned spellings), run before tier 0 when one is
+ // due — never proposed, the terms changed, a week since the last.
+ learn?(input: LearnStepInput, ctx: StepCtx): Promise<LearnStepOutcome>;
};
+export type LearnStepInput = { schedule: Schedule; trigger: "create" | "terms" | "weekly" };
+export type LearnStepOutcome = { status: "done" | "failed" | "cancelled"; reason?: string; jobId?: string; added?: number; total?: number };
+
// Steps that refuse, saying so: what a deps without R4's wiring (r4Steps
// below) gets — a test, or a process with no editor door.
export const NOT_WIRED_FETCH = "not wired: no fetch-and-build step (R4's stage 1) in this process";
@@ -521,7 +529,7 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
...(run.missed ? { missed: run.missed } : {}),
};
const finish = async (o: Partial<Tick> & { status: TickStatus; usd: number }): Promise<Tick> => {
- const tick: Tick = { ...base, ...o, minutes: Math.round(((Date.now() - t0) / 60_000) * 100) / 100 };
+ const tick: Tick = { ...base, ...(learnLine ? { learn: learnLine } : {}), ...o, minutes: Math.round(((Date.now() - t0) / 60_000) * 100) / 100 };
await recordTick(id, tick, deps);
ctx.log(`${REPORT_TICK_RESULT_MARKER}${JSON.stringify({ schedule: id, ...tick })}`);
return tick;
@@ -532,6 +540,9 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
const tri: { file: TriageFile | null } = { file: null };
const triageLine = (o: { tier2Usd?: number; capped?: string } = {}): { triage?: TickTriage } => (tri.file ? { triage: tickTriageOf(tri.file, o) } : {});
const tier1Usd = () => tri.file?.cost.tier1 ?? 0;
+ // R6.3: the proposal pass this tick ran, for its line.
+ let learnLine: Tick["learn"] | undefined;
+ const learned = (): { learn?: Tick["learn"] } => (learnLine ? { learn: learnLine } : {});
try {
ctx.log(`${s.shape} ${id}: ${run.trigger === "now" ? "ticked now" : `the ${run.scheduledFor} window`}${run.missed ? ` (stands in for ${run.missed} missed)` : ""}`);
// Stage 1 over a scope; what it skipped is the tick's warnings.
@@ -553,10 +564,27 @@ export async function runTick(id: string, run: TickRun, deps: TickDeps, ctx: Ste
// or the tick's end (below the threshold, the cap, a failure).
const triage = async (o: { onBelow: (why: string) => Promise<Tick> }): Promise<{ ids: string[]; ref: { owner: string; k: number } } | { done: Tick }> => {
if (!deps.steps.triage) return { done: await finish({ status: "failed", usd: 0, reason: "not wired: no triage step (R6) in this process", ...warned() }) };
+ // R6.3: before tier 0, a proposal pass when one is due. Its failure is a
+ // warning, never the tick's: the triage runs on what is learned.
+ if (deps.steps.learn && namesForPass(s).names.length) {
+ const lf = await readLearned(deps.paths, s).catch(() => null);
+ const due = learnDue(lf, termsKey(s.scope.terms, s.scope.regex === true), now);
+ if (due) {
+ ctx.log(`learn: a proposal pass is due (${due === "create" ? "never proposed" : due === "terms" ? "the terms changed" : "a week since the last"})`);
+ const l = await deps.steps.learn({ schedule: s, trigger: due }, ctx);
+ learnLine = { trigger: due, status: l.status, ...(l.added !== undefined ? { added: l.added } : {}), ...(l.total !== undefined ? { total: l.total } : {}), ...(l.jobId ? { jobId: l.jobId } : {}) };
+ if (l.status === "cancelled" || ctx.signal.aborted) return { done: await finish({ status: "cancelled", usd: 0, reason: "cancelled", ...learned(), ...warned() }) };
+ if (l.status !== "done") {
+ warnings.push(`the proposal pass failed: ${l.reason ?? "no reason"} — the triage runs on what is learned`);
+ ctx.log(`warning: the proposal pass failed: ${l.reason ?? "no reason"}`);
+ } else ctx.log(`learn: ${l.added ?? 0} learned (${l.total ?? 0} in all)`);
+ }
+ }
const back = addDays(today, -cadenceDays(s.cadence));
const since = s.scope.from && s.scope.from > back ? s.scope.from : back;
const t = await deps.steps.triage({ schedule: s, scope: { channels: s.scope.channels, ...(s.scope.from ? { from: s.scope.from } : {}) }, since }, ctx);
tri.file = t.file;
+ if (t.file?.learned?.n) ctx.log(`triage ${t.file.owner}/${t.file.k}: ${learnedWords(t.file.learned.n)}`);
if (t.status !== "done" || !t.file) {
return { done: await finish({ status: t.status === "cancelled" ? "cancelled" : "failed", usd: tier1Usd(), reason: `the triage ${t.status === "cancelled" ? "was cancelled" : "failed"}${t.reason ? `: ${t.reason}` : ""}`, ...triageLine(), ...warned() }) };
}
diff --git a/common/controller/reportTriage.ts b/common/controller/reportTriage.ts
@@ -34,6 +34,10 @@ import { createTriageRun, readTriageFile, writeTriageFile } from "../lib/report/
import { runTriage } from "../lib/report/draft/triage/task";
import { DEFAULT_TRIAGE_THRESHOLD, TRIAGE_FORMAT, TRIAGE_VERSION, cleanThreshold, partialWords, type TriageFile } from "../lib/report/draft/triage/types";
import { usageOf } from "../lib/report/draft/tasks/run";
+import { activeLearned, knownKeys, learnedWords, namesForPass, termKeys, type LearnedSpelling } from "../lib/report/draft/triage/learned";
+import { readLearned } from "../lib/report/draft/triage/learnedStore";
+import { readScheduleById } from "../lib/report/schedule/store";
+import { applyTriageLearning } from "./learnedSpellings";
import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, resolveCorpus, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft";
@@ -138,6 +142,19 @@ async function runTriageJob(
}
let corpus: (CorpusToolsLike & { close(): Promise<void> }) | null = null;
let ran: Awaited<ReturnType<typeof runTriage>> | null = null;
+ // R6.3: the schedule's learned spellings (their name still in its terms)
+ // join the candidate query; its names are what the judge listens for.
+ let learned: LearnedSpelling[] = [];
+ let names: string[] = [];
+ let known: Set<string> | undefined;
+ const sched = await readScheduleById(body.article, paths).catch(() => null);
+ if (sched?.ok && !body.ids?.length) {
+ names = namesForPass(sched.schedule).names;
+ const lf = await readLearned(paths, sched.schedule).catch(() => null);
+ learned = activeLearned(lf, names);
+ known = new Set([...knownKeys(lf, names), ...termKeys(sched.schedule)]);
+ if (learned.length) onLog(`${learnedWords(learned.length)}: ${learned.map((l) => `"${l.spelling}" (${l.means})`).join(", ")}`);
+ }
try {
const where = await resolveCorpus(body, body.channels ?? [], paths, gen);
onLog(`corpus ${where.source}${where.build ? ` (build ${where.build})` : ""}; links on ${where.origin}`);
@@ -151,6 +168,9 @@ async function runTriageJob(
maxCandidates: body.maxCandidates ?? gen.triage.maxCandidates,
...(o.maxUsd !== undefined ? { maxUsd: o.maxUsd } : {}),
origin: where.origin,
+ ...(learned.length ? { learned } : {}),
+ ...(names.length ? { names } : {}),
+ ...(known ? { known } : {}),
},
{
llm: llmConfigOf(gen, paths, provider === "local" ? { onLog, signal } : undefined),
@@ -204,6 +224,15 @@ async function runTriageJob(
await appendGenerationUsage(paths.generationUsageFile, rows).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`));
}
const f = ran!.file;
+ // R6.3: what this run heard and confirmed, and each learned spelling's use —
+ // written to the schedule's learned.json by its one writer.
+ if (f.status === "done") {
+ const learnt = await applyTriageLearning(f, paths, deps.now?.() ?? new Date()).catch((e: Error) => {
+ onLog(`learned.json not updated: ${e.message}`);
+ return null;
+ });
+ if (learnt?.added.length) onLog(`learned ${learnt.added.length}: ${learnt.added.map((l) => `"${l.spelling}" → ${l.means}`).join(", ")}`);
+ }
const marker: TriageMarker = {
k,
status: f.status,
diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts
@@ -17,6 +17,7 @@ import type { ResearchEditor } from "../research/tools";
import type { DeckChecks } from "./deckChecks";
import type { RefreshHooks } from "../refresh/fetch";
import type { ListArgs, RecordingListing } from "../refresh/delta";
+import type { CountPhrasesArgs, PhraseCounts } from "../triage/confirm";
// The iterations store's paths (S4 takes them on every call).
export type StorePaths = NonNullable<Parameters<typeof readIteration>[2]>;
@@ -30,6 +31,10 @@ export type CorpusToolsLike = {
// the corpus can say (mcp/src/callTool.ts). Absent: a triage lists the scope
// per channel through enumerate_matches, and says when that was capped.
listRecordings?(args: ListArgs): Promise<RecordingListing>;
+ // R6.3: each phrase's count in a scope, uncapped (the listing, then
+ // enumerate_matches restricted to its ids in batches), in ONE scan — what a
+ // learned spelling is confirmed with. Absent: one restricted scan a phrase.
+ countPhrases?(args: CountPhrasesArgs): Promise<PhraseCounts>;
};
// A quote problem an outside verifier found (the editor's verify-quotes over
diff --git a/common/lib/report/draft/triage/confirm.ts b/common/lib/report/draft/triage/confirm.ts
@@ -0,0 +1,321 @@
+// 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). One window that
+// passes keeps the spelling with its proving line; else dropped —
+// "not-the-name" (the judge said so, its reason kept) or
+// "not-verbatim" (it said yes but its line is not in the window)
+//
+// 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 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<string, PhraseCount>; 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<PhraseCounts>;
+
+// 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<string, PhraseCount> = {};
+ 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 = <T>(system: string, user: string, schema: object, what: string) => Promise<T>;
+
+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<CorpusToolsLike, "call">;
+ ask: Ask;
+ count: CountPhrasesFn;
+ cuesOf?: (channel: string, id: string) => Promise<readonly WordCue[] | null>;
+ 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=<slug>%2F<id>&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<ConfirmResult> {
+ 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<string>();
+ 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) => {
+ dropped.push({ spelling: p.spelling, means: p.means, source: p.source, reason, why, at: i.at, ...(p.k ? { k: p.k } : {}) });
+ 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: { means: boolean; reason: string; verbatim: boolean }[] = [];
+ let proved: LearnedSpelling | null = null;
+ let parsed: Map<string, ParsedTranscript>;
+ 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;
+ }
+ for (const x of ids.slice(0, maxWindows)) {
+ if (proved) break;
+ 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({ means: false, reason, verbatim: true });
+ 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({ means: true, reason, verbatim: ok });
+ if (!ok) 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 } : {}),
+ };
+ }
+ if (proved) {
+ kept.push(proved);
+ log(` learn: "${p.spelling}" means ${p.means} — kept (${c.recordings} recording(s); “${proved.quote}” ${proved.recording} @ ${mmss(proved.start)})`);
+ } else if (verdicts.some((v) => v.means && !v.verbatim)) drop(p, "not-verbatim", "the judge said it means the name, but its line is not verbatim in the window or the cues");
+ else if (verdicts.length) drop(p, "not-the-name", `judged not the name in ${verdicts.length} window(s): ${verdicts[0]!.reason}`);
+ else drop(p, "unread", "no window holding it could be read");
+ }
+ return { kept, dropped, counted, judged };
+}
+
+// ─── 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<string>; at: string; k?: number },
+ d: { ask: Ask; log?: (line: string) => void; signal?: AbortSignal },
+): Promise<ProposeResult> {
+ 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 });
+ 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<string>; at: string; k?: number; windows?: number },
+ d: ConfirmDeps,
+): Promise<LearnPassResult> {
+ const p = await proposeSpellings({ names: i.names, question: i.question, known: i.known, at: i.at, ...(i.k ? { k: i.k } : {}) }, 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 };
+}
diff --git a/common/lib/report/draft/triage/judge.ts b/common/lib/report/draft/triage/judge.ts
@@ -22,6 +22,7 @@ import { mmss } from "../reportOps";
import { chunksOf, EXTRACT_SCHEMA, EXTRACT_SYSTEM, locate, parseTranscripts, windowsOf, type ParsedTranscript } from "../tasks/sweep-pipeline";
import { momentHref } from "../tasks/links";
import type { CorpusToolsLike } from "../tasks/types";
+import { heardRule, holdsSpelling, normSpelling, spellingKey, withHeard, type TriageHeard, type TriageHeardDropped } from "./learned";
import { STRONG_SCORE, type TriageCandidate, type TriageDismissal, type TriageFlag, type TriageScore, type TriageWindow } from "./types";
export const TRIAGE_READ_BATCH = 8;
@@ -41,6 +42,11 @@ export type JudgeInput = {
origin?: string | null;
maxChunksPerRecording?: number;
maxFlagsPerRecording?: number;
+ // R6.3: the watched names. The judge also reports a span it takes for a
+ // mis-hearing of one (`heard`), checked verbatim here; `known` (spelling
+ // keys: the names, the learned and removed spellings) are not reported.
+ names?: string[];
+ known?: ReadonlySet<string>;
};
export type JudgeTrace = (e: { t: "batch"; k: number; of: number; ids: string[]; lines: string[]; model: string; usd: number } | { t: "check"; quote: string; cite: { channel?: string; video?: string; start?: number; url?: string }; ok: boolean; reason: string; stage: "triage"; dropped?: boolean; claim?: string }) => void;
@@ -70,6 +76,9 @@ export type JudgeResult = {
chunks: number;
// Why it stopped before every candidate was judged, and the ids not judged.
stopped?: { reason: string; ids: string[] };
+ // R6.3: the spans it heard as a watched name, verbatim (code-checked), and the ones put aside.
+ heard: TriageHeard[];
+ heardDropped: TriageHeardDropped[];
};
type Line = [number, string];
@@ -111,6 +120,11 @@ export async function judgeCandidates(i: JudgeInput, d: JudgeDeps): Promise<Judg
const terms = i.terms?.trim() || null;
const words = [...(terms && !i.regex ? [terms] : []), ...i.topics].map((t) => t.trim()).filter(Boolean).slice(0, 8);
const queryArgs: Record<string, unknown> = terms && i.regex ? { query: terms, regex: true, ...(words.length ? { queries: words } : {}) } : words.length ? { queries: words } : {};
+ const names = (i.names ?? []).map((n) => n.trim()).filter(Boolean);
+ const system = names.length ? `${EXTRACT_SYSTEM}${heardRule(names)}` : EXTRACT_SYSTEM;
+ const schema = names.length ? withHeard(EXTRACT_SCHEMA) : EXTRACT_SCHEMA;
+ const heard: TriageHeard[] = [];
+ const heardDropped: TriageHeardDropped[] = [];
const cueCache = new Map<string, Promise<readonly WordCue[] | null>>();
const cues = (slug: string, id: string) => {
const key = `${slug}/${id}`;
@@ -183,15 +197,26 @@ export async function judgeCandidates(i: JudgeInput, d: JudgeDeps): Promise<Judg
const span = spanOf(ch);
const excerpt = ch.map(([s, t]) => `[${mmss(s)}] ${t}`).join("\n");
const user = `Research question: ${i.question}\n\nVideo: ${title}${c.channel ? ` (${c.channel}${c.date ? `, ${c.date}` : ""})` : ""}\n\nTranscript excerpt:\n${excerpt}`;
- let ans: { relevant?: unknown; items?: unknown };
+ let ans: { relevant?: unknown; items?: unknown; heard?: unknown };
try {
- ans = await d.ask(EXTRACT_SYSTEM, user, EXTRACT_SCHEMA, `triage ${c.id}@${ch[0]![0]}`);
+ ans = await d.ask(system, user, schema, `triage ${c.id}@${ch[0]![0]}`);
} catch (e) {
if (d.signal?.aborted) throw e;
dismissed.push({ id: c.id, title, channel: slug, window: span, stage: "judge", reason: `the model's answer failed: ${oneLine((e as Error).message, 160)}` });
lines.push(`${c.id} @ ${mmss(span.start)}: the model's answer failed — ${oneLine((e as Error).message, 160)}`);
continue;
}
+ if (names.length && Array.isArray(ans.heard)) {
+ for (const h of await checkHeard(ans.heard, { id: c.id, title, slug, chunk: ch, names, known: i.known, cues, already: heard })) {
+ if ("reason" in h) {
+ heardDropped.push(h);
+ lines.push(`${c.id}: heard “${h.span}” as ${h.means} [put aside: ${h.reason}]`);
+ } else {
+ heard.push(h);
+ lines.push(`${c.id} @ ${mmss(h.at)}: heard “${h.span}” as ${h.means} [verbatim${h.checked === "cues" ? " in the cues" : " in its window"}]`);
+ }
+ }
+ }
const items = Array.isArray(ans.items) ? (ans.items as { quote?: unknown; claim?: unknown; on_topic?: unknown; strength?: unknown }[]) : [];
if (!ans.relevant || !items.length) {
dismissed.push({ id: c.id, title, channel: slug, window: span, stage: "judge", reason: opening ? "not relevant to the question (its opening read: no word matched)" : "not relevant to the question" });
@@ -261,5 +286,70 @@ export async function judgeCandidates(i: JudgeInput, d: JudgeDeps): Promise<Judg
const k = b / TRIAGE_READ_BATCH + 1;
d.trace?.({ t: "batch", k, of: batches, ids: batch.map((c) => c.id), lines, model: d.model, usd: (d.usd?.() ?? 0) - before });
}
- return { flags, dismissed, read, windows: nWindows, chunks: nChunks, ...(stopped ? { stopped } : {}) };
+ return { flags, dismissed, read, windows: nWindows, chunks: nChunks, ...(stopped ? { stopped } : {}), heard, heardDropped };
+}
+
+/**
+ * R6.3: the spans the judge says it heard as a watched name, checked by code —
+ * the name one of the watched ones, the span not the name itself nor a
+ * spelling already known, at most four words, VERBATIM in the chunk it read
+ * (`locate`, whole words) and in the transcript's cues near that second
+ * (when they read). Answers each kept span, or the span with why it was put
+ * aside.
+ */
+export async function checkHeard(
+ raw: unknown[],
+ o: {
+ id: string;
+ title: string | null;
+ slug: string | null;
+ chunk: readonly Line[];
+ names: readonly string[];
+ known?: ReadonlySet<string>;
+ cues: (slug: string, id: string) => Promise<readonly WordCue[] | null>;
+ already?: readonly TriageHeard[];
+ },
+): Promise<(TriageHeard | TriageHeardDropped)[]> {
+ const out: (TriageHeard | TriageHeardDropped)[] = [];
+ const byKey = new Map(o.names.map((n) => [spellingKey(n), n]));
+ const done = new Set((o.already ?? []).map((h) => spellingKey(h.span)));
+ for (const r of raw.slice(0, 3)) {
+ const span = normSpelling((r as { span?: unknown })?.span);
+ const meansRaw = String((r as { means?: unknown })?.means ?? "").trim();
+ const means = byKey.get(spellingKey(meansRaw));
+ const key = spellingKey(span);
+ if (!span || !key) continue;
+ if (!means) {
+ out.push({ span, means: meansRaw, id: o.id, reason: "not a watched name" });
+ continue;
+ }
+ if (byKey.has(key) || o.known?.has(key) || done.has(key)) continue;
+ if (key.split(" ").length > 4) {
+ out.push({ span, means, id: o.id, reason: "too long (at most 4 words)" });
+ continue;
+ }
+ const sec = locate(span, o.chunk);
+ if (sec === null) {
+ out.push({ span, means, id: o.id, reason: "not verbatim in its window" });
+ continue;
+ }
+ const line = o.chunk.find(([s, t]) => s === sec && holdsSpelling(t, span))?.[1] ?? o.chunk.find(([s]) => s === sec)?.[1] ?? "";
+ let checked: TriageHeard["checked"] = "window";
+ let at = sec;
+ if (o.slug) {
+ const all = await o.cues(o.slug, o.id);
+ if (all?.length) {
+ const v = checkWordsInWindow(span, { t: sec, end: sec }, windowAround(all, sec, 30));
+ if (v.status !== "ok") {
+ out.push({ span, means, id: o.id, reason: `not in the transcript's cues near ${mmss(sec)}` });
+ continue;
+ }
+ checked = "cues";
+ if (v.nowAt !== undefined) at = v.nowAt;
+ }
+ }
+ done.add(key);
+ out.push({ span, means, id: o.id, channel: o.slug, title: o.title, at, line, checked });
+ }
+ return out;
}
diff --git a/common/lib/report/draft/triage/learned.test.ts b/common/lib/report/draft/triage/learned.test.ts
@@ -0,0 +1,414 @@
+// Learned spellings (umtool R6.3): the names a watch's terms watch; the
+// model's proposals checked; spellings escaped into the candidate query
+// (never a regex); tier 0's candidates a learned spelling brings, named; the
+// judge's heard spans checked verbatim; the confirmation dropping a spelling
+// with no hits, one the judge says is not the name, one whose line is not
+// verbatim — and keeping one with its proving line; the cap; suggest
+// removing; unlearn blocks a relearn; the alias a promotion would write; a
+// triage run end to end that hears, confirms and keeps a spelling. Stubs
+// only: no model, no corpus on disk.
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import type { EnumeratedAnswer, EnumerateFn, ListFn } from "../refresh/delta";
+import type { CorpusToolsLike } from "../tasks/types";
+import { EXTRACT_SYSTEM } from "../tasks/sweep-pipeline";
+import { confirmSpellings, countViaEnumerate, runLearnPass, type CountPhrasesFn } from "./confirm";
+import { checkHeard, judgeCandidates } from "./judge";
+import {
+ CONFIRM_SYSTEM,
+ LEARNED_CAP,
+ PROPOSE_SYSTEM,
+ SUGGEST_REMOVE_AFTER,
+ activeLearned,
+ emptyLearned,
+ holdsSpelling,
+ joinedQuery,
+ learnDue,
+ learnedAlternation,
+ learnedWords,
+ mergeLearned,
+ namesOf,
+ parseProposals,
+ planAliasPromotion,
+ recordUses,
+ spellingPattern,
+ suggestRemoving,
+ termsKey,
+ unlearnIn,
+ type LearnedSpelling,
+} from "./learned";
+import { createTriageRun, readTriageFile } from "./store";
+import { runTriage } from "./task";
+import { triageCandidates } from "./tier0";
+import { TRIAGE_FORMAT, TRIAGE_VERSION, type TriageFile } from "./types";
+
+const tmp = await mkdtemp(path.join(os.tmpdir(), "learned-"));
+after(() => rm(tmp, { recursive: true, force: true }));
+
+// ─── a corpus, stubbed (synthetic names: nothing here is a real person) ───
+
+type Rec = { id: string; date: string; title: string; lines: string[] };
+const CHAN = "synth-kitchen";
+const NAME = "Synth Kitchen";
+const RECS: Rec[] = [
+ { id: "a-01", date: "20261001", title: "Guest night", lines: ["tonight Pia Tartlet is on the show", "she brought the pies", "thanks Pia"] },
+ // The mis-hearing: "pia tart lit" for Pia Tartlet.
+ { id: "b-02", date: "20261008", title: "Pie talk", lines: ["welcome back everyone", "my friend pia tart lit is joining us later", "she runs the bakery downtown"] },
+ { id: "c-03", date: "20261010", title: "Market day", lines: ["the tart lit up the whole room", "we sold out by noon", "see you next week"] },
+ { id: "d-04", date: "20261012", title: "Late stream", lines: ["pia tart lit could not make it tonight", "so it is just me", "we will bake bread"] },
+];
+const ymd = (d: string) => `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`;
+const matcher = (args: Record<string, unknown>) => {
+ const q = String(args.query);
+ if (args.regex === true) {
+ const re = new RegExp(q, "i");
+ return (l: string) => re.test(l);
+ }
+ return (l: string) => l.toLowerCase().includes(q.toLowerCase());
+};
+
+function enumerateOver(recs: Rec[]): EnumerateFn & { calls: Record<string, unknown>[] } {
+ const calls: Record<string, unknown>[] = [];
+ const fn = (async (args: Record<string, unknown>): Promise<EnumeratedAnswer> => {
+ calls.push(args);
+ const any = args.query === "." && args.regex === true;
+ const m = matcher(args);
+ const ids = Array.isArray(args.ids) ? new Set(args.ids as string[]) : null;
+ const rows = recs
+ .filter((r) => !ids || ids.has(r.id))
+ .map((r) => ({ r, n: any ? 1 : r.lines.filter(m).length }))
+ .filter((x) => x.n > 0)
+ .map(({ r, n }) => ({ id: r.id, kind: "video" as const, channel: NAME, date: ymd(r.date), matches: n, title: r.title }));
+ return { rows, partial: false, unreached: [] };
+ }) as EnumerateFn & { calls: Record<string, unknown>[] };
+ fn.calls = calls;
+ return fn;
+}
+
+const listOver =
+ (recs: Rec[]): ListFn =>
+ async () => ({ rows: recs.map((r) => ({ id: r.id, channel: NAME, channelSlug: CHAN, date: ymd(r.date), title: r.title, hasTranscript: true })), complete: true, unreached: [], problems: [] });
+
+const stamp = (s: number) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}|${s}`;
+
+function corpusOver(recs: Rec[]): CorpusToolsLike {
+ return {
+ source: "local:/fake/out",
+ tools: [],
+ async call(name, args = {}) {
+ if (name === "get_transcripts") {
+ const ids = (args.video_ids as string[]) ?? [];
+ const re = typeof args.query === "string" && args.regex === true ? new RegExp(args.query, "i") : null;
+ const qs = [...(Array.isArray(args.queries) ? (args.queries as string[]) : []), ...(typeof args.query === "string" && !re ? [args.query] : [])].map((q) => q.toLowerCase());
+ return ids
+ .map((id) => {
+ const r = recs.find((x) => x.id === id);
+ if (!r) return `## ${id}\n- video_id: ${id}\n(not found)`;
+ const any = !re && !qs.length;
+ const lines = r.lines.map((t, i) => ({ s: i * 5, t })).filter((l) => any || re?.test(l.t) || qs.some((q) => l.t.toLowerCase().includes(q)));
+ return [`## ${r.title}`, `- video_id: ${id}`, `- moment_base: https://synth.example/?v=${CHAN}%2F${id}&t=`, ...lines.map((l) => `[${stamp(l.s)}] ${l.t}`)].join("\n");
+ })
+ .join("\n---\n");
+ }
+ throw new Error(`the stub has no ${name}`);
+ },
+ };
+}
+const cuesOver = (recs: Rec[]) => async (_c: string, id: string) => {
+ const r = recs.find((x) => x.id === id);
+ return r ? r.lines.map((text, i) => ({ start: i * 5, end: i * 5 + 4.8, text })) : null;
+};
+
+type Asked = { system: string; user: string };
+function askScript(answer: (a: Asked) => unknown) {
+ const asked: Asked[] = [];
+ const ask = async <T,>(system: string, user: string): Promise<T> => {
+ asked.push({ system, user });
+ return answer({ system, user }) as T;
+ };
+ return { ask, asked };
+}
+
+const learnedOf = (spelling: string, over: Partial<LearnedSpelling> = {}): 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: "2026-10-14T00:00:00.000Z",
+ ...over,
+});
+
+// ─── names, proposals, the query ───
+
+test("namesOf: a watch's name-like alternatives — capitalised or several words; regex classes skipped; \\b anchors stripped", () => {
+ const terms = "co-?host|co host|guest host|\\bguests?\\b|Melonie|\\bMelanie\\b|Melanie Mac|Hannah Claire|[Gg]othix|Styx|joining the show";
+ assert.deepEqual(namesOf(terms, true), ["Melonie", "Melanie", "Melanie Mac", "Hannah Claire", "Styx", "co host", "guest host", "joining the show"]);
+ assert.deepEqual(namesOf("Pia Tartlet", false), ["Pia Tartlet"]);
+ assert.deepEqual(namesOf("contest", false), []);
+ assert.deepEqual(namesOf("(Pia|Pea) Tartlet|Pia Tartlet", true), ["Pia Tartlet"]);
+ assert.equal(termsKey("Pia Tartlet", false), "lit:Pia Tartlet");
+ assert.equal(termsKey("", true), null);
+});
+
+test("parseProposals: the name itself, a repeat, a known spelling, junk and long phrases are put aside; at most k", () => {
+ const known = new Set(["pia tart"]);
+ const r = parseProposals("Pia Tartlet", { spellings: ["Pia Tartlet", "pia tart lit", "\"Pea Tartlet\"", "pia tart lit", "Pia Tart", "<b>x</b>", "one two three four five", "Pia Tartlett", "Peter Tart", "P Tartlet"] }, { k: 3, known });
+ assert.deepEqual(r.spellings, ["pia tart lit", "Pea Tartlet", "Pia Tartlett"]);
+ assert.deepEqual(r.dropped.map((d) => d.reason).sort(), ["invalid", "invalid", "known"]);
+ assert.deepEqual(parseProposals("X", null).spellings, []);
+});
+
+test("a spelling is an ESCAPED literal in the query, never a regex — joined to regex terms or escaped literal terms", () => {
+ assert.equal(spellingPattern("pia tart lit"), "\\bpia tart lit\\b");
+ assert.equal(spellingPattern("Mr. T (live)"), "\\bMr\\. T \\(live\\)");
+ assert.equal(spellingPattern("a+b.*"), "\\ba\\+b\\.\\*");
+ assert.equal(learnedAlternation(["pia tart lit", "Pea Tartlet", "pia tart lit"]), "\\bpia tart lit\\b|\\bPea Tartlet\\b");
+ assert.equal(learnedAlternation([]), null);
+ assert.deepEqual(joinedQuery("Pia|Tartlet", true, []), { query: "Pia|Tartlet", regex: true });
+ assert.deepEqual(joinedQuery("Pia|Tartlet", true, ["pia tart lit"]), { query: "(?:Pia|Tartlet)|\\bpia tart lit\\b", regex: true });
+ assert.deepEqual(joinedQuery("Pia (Tartlet)", false, ["x.y"]), { query: "(?:Pia \\(Tartlet\\))|\\bx\\.y\\b", regex: true });
+ // A regex-looking spelling matches only itself.
+ assert.equal(holdsSpelling("we said a+b today", "a+b"), true);
+ assert.equal(holdsSpelling("we said aab today", "a+b"), false);
+ assert.equal(holdsSpelling("the tart lit up", "pia tart lit"), false);
+ assert.equal(learnedWords(2), "terms + 2 learned");
+});
+
+// ─── tier 0 ───
+
+test("tier 0: the learned spellings join the candidate query (escaped, bounded by the new ids); a candidate they alone bring names them", async () => {
+ const enumerate = enumerateOver(RECS);
+ const r = await triageCandidates(
+ { scope: { channels: [CHAN] }, terms: "Pia Tartlet", topics: [], known: new Set(["a-01"]), since: null, max: 40, learned: ["pia tart lit", "Pea Tartlet"] },
+ { enumerate, list: listOver(RECS) },
+ );
+ const byId = Object.fromEntries(r.tier0.candidates.map((c) => [c.id, c]));
+ assert.deepEqual(Object.keys(byId).sort(), ["b-02", "d-04"]);
+ assert.deepEqual(byId["b-02"]!.by, ["learned"]);
+ assert.deepEqual(byId["b-02"]!.learned, ["pia tart lit"]);
+ assert.deepEqual(r.tier0.learned, { spellings: ["pia tart lit", "Pea Tartlet"], matched: 2 });
+ const learnedQ = enumerate.calls.find((c) => String(c.query).includes("pia tart lit") && String(c.query).includes("|"));
+ assert.equal(learnedQ?.query, "\\bpia tart lit\\b|\\bPea Tartlet\\b");
+ assert.equal(learnedQ?.regex, true);
+ assert.deepEqual((learnedQ?.ids as string[]).sort(), ["b-02", "c-03", "d-04"]);
+ // "the tart lit up" (c-03) is not the spelling: whole words.
+ assert.equal(byId["c-03"], undefined);
+});
+
+// ─── tier 1: heard spans ───
+
+test("the judge's heard spans: verbatim in the window and the cues, a watched name — else put aside with why", async () => {
+ const chunk: [number, string][] = RECS[1]!.lines.map((t, i) => [i * 5, t]);
+ const out = await checkHeard(
+ [
+ { span: "pia tart lit", means: "Pia Tartlet" },
+ { span: "pia tartlit", means: "Pia Tartlet" },
+ { span: "the bakery", means: "Someone Else" },
+ { span: "Pia Tartlet", means: "Pia Tartlet" },
+ ],
+ { id: "b-02", title: "Pie talk", slug: CHAN, chunk, names: ["Pia Tartlet"], cues: cuesOver(RECS) },
+ );
+ assert.deepEqual(out[0], { span: "pia tart lit", means: "Pia Tartlet", id: "b-02", channel: CHAN, title: "Pie talk", at: 5, line: "my friend pia tart lit is joining us later", checked: "cues" });
+ assert.deepEqual(out.slice(1).map((x) => ("reason" in x ? x.reason : "kept")), ["not verbatim in its window", "not a watched name"]);
+ // A span the cues do not hold near that second is put aside too.
+ const drift = await checkHeard([{ span: "pia tart lit", means: "Pia Tartlet" }], { id: "b-02", title: "Pie talk", slug: CHAN, chunk, names: ["Pia Tartlet"], cues: async () => [{ start: 0, text: "something else entirely" }] });
+ assert.match((drift[0] as { reason: string }).reason, /not in the transcript's cues/);
+});
+
+test("judgeCandidates with names: the prompt asks for heard spans; a verbatim one is kept beside the flags", async () => {
+ const { ask, asked } = askScript(() => ({ relevant: false, items: [], heard: [{ span: "pia tart lit", means: "Pia Tartlet" }, { span: "pia tartlit", means: "Pia Tartlet" }] }));
+ const j = await judgeCandidates(
+ { question: "Who joined the show?", candidates: [{ id: "b-02", channel: NAME, title: "Pie talk", date: "2026-10-08", matches: 1, by: ["learned"] }], terms: "Pia Tartlet|\\bpia tart lit\\b", regex: true, topics: [], channels: [CHAN], names: ["Pia Tartlet"] },
+ { corpus: corpusOver(RECS), ask, model: "qwen3:8b", cuesOf: cuesOver(RECS) },
+ );
+ assert.match(asked[0]!.system, /mishear these watched names: "Pia Tartlet"/);
+ assert.equal(j.heard.length, 1);
+ assert.equal(j.heard[0]!.span, "pia tart lit");
+ assert.deepEqual(j.heardDropped.map((h) => h.reason), ["not verbatim in its window"]);
+ // Without names, the judge's prompt is the sweep pipeline's own.
+ const plain = askScript(() => ({ relevant: false, items: [] }));
+ await judgeCandidates({ question: "Q?", candidates: [{ id: "b-02", channel: NAME, title: "Pie talk", date: null, matches: 1, by: ["terms"] }], terms: "pia", topics: [], channels: [CHAN] }, { corpus: corpusOver(RECS), ask: plain.ask, model: "m" });
+ assert.equal(plain.asked[0]!.system, EXTRACT_SYSTEM);
+});
+
+// ─── the confirmation ───
+
+test("confirmSpellings: no hits, judged not the name, a line not verbatim — dropped with their reasons; one kept with its proving line", async () => {
+ const count = countViaEnumerate(listOver(RECS), enumerateOver(RECS));
+ const { ask } = askScript(({ system, user }) => {
+ assert.equal(system, CONFIRM_SYSTEM);
+ if (/Spelling in the transcript: tart lit/.test(user)) return { means: false, quote: "the tart lit up the whole room", reason: "a tart that lit up, not her" };
+ if (/Spelling in the transcript: could not/.test(user)) return { means: true, quote: "she could not ever make it", reason: "invented" };
+ return { means: true, quote: "pia tart lit could not make it tonight", reason: "the guest who could not come" };
+ });
+ const r = await confirmSpellings(
+ {
+ pending: [
+ { spelling: "Pea Tartlet", means: "Pia Tartlet", source: "proposed" },
+ { spelling: "tart lit", means: "Pia Tartlet", source: "proposed" },
+ { spelling: "could not", means: "Pia Tartlet", source: "proposed" },
+ { spelling: "pia tart lit", means: "Pia Tartlet", source: "proposed" },
+ ],
+ question: "Who joined the show?",
+ scope: { channels: [CHAN] },
+ at: "2026-10-14T00:00:00.000Z",
+ },
+ { corpus: corpusOver(RECS), ask, count, cuesOf: cuesOver(RECS) },
+ );
+ assert.deepEqual(
+ r.dropped.map((d) => [d.spelling, d.reason]),
+ [
+ ["Pea Tartlet", "no-hits"],
+ ["tart lit", "not-the-name"],
+ ["could not", "not-verbatim"],
+ ],
+ );
+ assert.match(r.dropped[1]!.why, /a tart that lit up/);
+ assert.equal(r.kept.length, 1);
+ assert.deepEqual(
+ { spelling: r.kept[0]!.spelling, means: r.kept[0]!.means, quote: r.kept[0]!.quote, recording: r.kept[0]!.recording, start: r.kept[0]!.start, hits: r.kept[0]!.hits, source: r.kept[0]!.source },
+ // The newest window first (d-04).
+ { spelling: "pia tart lit", means: "Pia Tartlet", quote: "pia tart lit could not make it tonight", recording: "d-04", start: 0, hits: 2, source: "proposed" },
+ );
+ assert.equal(r.kept[0]!.url, "https://synth.example/?v=synth-kitchen%2Fd-04&t=0");
+});
+
+test("confirmSpellings: a count that read part of the scope and found nothing is unread, never no-hits", async () => {
+ const count: CountPhrasesFn = async (a) => ({ counts: Object.fromEntries(a.phrases.map((p) => [p, { recordings: 0, lines: 0, examples: [] }])), complete: false, problems: ["Other (stopped at page 2 of 5)"], listed: 10 });
+ const r = await confirmSpellings({ pending: [{ spelling: "x y", means: "X Y", source: "proposed" }], question: "Q?", scope: { channels: [CHAN] }, at: "t" }, { corpus: corpusOver(RECS), ask: askScript(() => ({})).ask, count });
+ assert.equal(r.dropped[0]!.reason, "unread");
+});
+
+test("runLearnPass: proposals asked per name, checked, then confirmed", async () => {
+ const count = countViaEnumerate(listOver(RECS), enumerateOver(RECS));
+ const { ask, asked } = askScript(({ system }) =>
+ system === PROPOSE_SYSTEM ? { spellings: ["pia tart lit", "Pia Tartlet", "Pea Tartlet"] } : { means: true, quote: "pia tart lit could not make it tonight", reason: "her" },
+ );
+ const r = await runLearnPass({ names: ["Pia Tartlet"], question: "Who joined?", scope: { channels: [CHAN] }, known: new Set(), at: "t" }, { corpus: corpusOver(RECS), ask, count, cuesOf: cuesOver(RECS) });
+ assert.deepEqual(r.proposed.map((p) => p.spelling), ["pia tart lit", "Pea Tartlet"]);
+ assert.deepEqual(r.kept.map((k) => k.spelling), ["pia tart lit"]);
+ assert.deepEqual(r.dropped.map((d) => [d.spelling, d.reason]), [["Pea Tartlet", "no-hits"]]);
+ assert.match(asked[0]!.user, /Name: Pia Tartlet/);
+});
+
+// ─── the file's rules ───
+
+test("mergeLearned: the cap, a blocked spelling never relearned; unlearn blocks; recordUses and suggest removing", () => {
+ let f = emptyLearned("w", "t0");
+ const many = Array.from({ length: LEARNED_CAP + 2 }, (_, i) => learnedOf(`spelling ${i}`));
+ const m = mergeLearned(f, { kept: many, dropped: [], at: "t1" });
+ assert.equal(m.file.learned.length, LEARNED_CAP);
+ assert.deepEqual(m.dropped.map((d) => d.reason), ["cap", "cap"]);
+ f = mergeLearned(emptyLearned("w", "t0"), { kept: [learnedOf("pia tart lit")], dropped: [], at: "t1" }).file;
+ const u = unlearnIn(f, "Pia Tart Lit", "t2");
+ assert.equal(u.removed?.spelling, "pia tart lit");
+ assert.equal(u.file.learned.length, 0);
+ const again = mergeLearned(u.file, { kept: [learnedOf("pia tart lit", { source: "heard" })], dropped: [], at: "t3" });
+ assert.equal(again.added.length, 0);
+ assert.equal(again.dropped[0]!.reason, "blocked");
+ // Uses: four runs with candidates, none flagged → suggest removing.
+ let g = mergeLearned(emptyLearned("w", "t0"), { kept: [learnedOf("pia tart lit")], dropped: [], at: "t1" }).file;
+ for (let k = 1; k < SUGGEST_REMOVE_AFTER; k++) g = recordUses(g, k, `t${k}`, new Map([["pia tart lit", { candidates: 1, flagged: 0 }]]));
+ assert.equal(suggestRemoving(g.learned[0]!), false);
+ g = recordUses(g, 9, "t9", new Map([["pia tart lit", { candidates: 0, flagged: 0 }]]));
+ assert.equal(suggestRemoving(g.learned[0]!), false);
+ g = recordUses(g, SUGGEST_REMOVE_AFTER, "t", new Map([["PIA tart lit", { candidates: 2, flagged: 0 }]]));
+ assert.equal(suggestRemoving(g.learned[0]!), true);
+ g = recordUses(g, 10, "t", new Map([["pia tart lit", { candidates: 1, flagged: 1 }]]));
+ assert.equal(suggestRemoving(g.learned[0]!), false);
+ // Active: a spelling whose name left the terms is idle.
+ assert.deepEqual(activeLearned(g, ["Pia Tartlet"]).length, 1);
+ assert.deepEqual(activeLearned(g, ["Someone Else"]).length, 0);
+});
+
+test("learnDue: never proposed, the terms changed, a week since the last pass", () => {
+ const now = new Date("2026-10-14T00:00:00.000Z");
+ assert.equal(learnDue(null, "lit:X", now), "create");
+ const f = { ...emptyLearned("w", "t"), proposedAt: "2026-10-10T00:00:00.000Z", termsKey: "lit:X" };
+ assert.equal(learnDue(f, "lit:X", now), null);
+ assert.equal(learnDue(f, "lit:Y", now), "terms");
+ assert.equal(learnDue({ ...f, proposedAt: "2026-10-07T00:00:00.000Z" }, "lit:X", now), "weekly");
+ assert.equal(learnDue(f, null, now), null);
+});
+
+test("planAliasPromotion: a new alias for the name, or the spelling added to the alias that names it", () => {
+ const l = learnedOf("pia tart lit");
+ const fresh = planAliasPromotion([], l, "w");
+ assert.equal(fresh.action, "new");
+ assert.deepEqual(fresh.alias, {
+ 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 w from synth-kitchen/b-02 at 0:05",
+ });
+ const existing = { id: "pia", label: "Pia Tartlet", triggers: ["pia tartlet"], suggestion: "\\bpia tartlet\\b", useRegex: true, enabled: true, note: "her name" };
+ const add = planAliasPromotion([existing], l, "w");
+ assert.equal(add.action, "trigger");
+ assert.deepEqual(add.alias.triggers, ["pia tartlet", "pia tart lit"]);
+ assert.equal(add.alias.suggestion, "\\bpia tartlet\\b|\\bpia tart lit\\b");
+ assert.equal(add.alias.note, 'her name; "pia tart lit" learned by watch w from synth-kitchen/b-02 at 0:05');
+ const none = planAliasPromotion([add.alias], l, "w");
+ assert.equal(none.action, "none");
+ // A taken id gets a suffix.
+ assert.equal(planAliasPromotion([{ ...existing, id: "pia-tartlet", label: "Other", triggers: ["other"] }], l, "w").alias.id, "pia-tartlet-2");
+});
+
+// ─── a triage run end to end ───
+
+test("runTriage with learned spellings and names: terms + N learned, the heard span confirmed and kept for the job to write", async () => {
+ const paths = { articlesDir: path.join(tmp, "reports-run") };
+ const at = "2026-10-14T00:00:00.000Z";
+ const f0 = await createTriageRun(
+ (k): TriageFile => ({
+ format: TRIAGE_FORMAT,
+ version: TRIAGE_VERSION,
+ owner: "pia-watch",
+ k,
+ status: "queued",
+ model: "qwen3:8b",
+ provider: "local",
+ question: "Who joined the show?",
+ scope: { channels: [CHAN] },
+ terms: "Pia Tartlet|tonight",
+ regex: true,
+ topics: [],
+ threshold: { strong: 1, weak: 3 },
+ since: "2026-10-01",
+ knownCount: null,
+ createdAt: at,
+ cost: { tier0: 0, tier1: 0 },
+ summary: "queued",
+ warnings: [],
+ }),
+ paths,
+ "pia-watch",
+ );
+ const { ask } = askScript(({ system, user }) => {
+ if (system === CONFIRM_SYSTEM) return { means: true, quote: /d-04|Late stream/.test(user) ? "pia tart lit could not make it tonight" : "my friend pia tart lit is joining us later", reason: "the guest" };
+ if (/Late stream/.test(user)) return { relevant: true, items: [{ quote: "pia tart lit could not make it tonight", claim: "The guest could not come.", on_topic: true, strength: 3 }], heard: [{ span: "pia tart lit", means: "Pia Tartlet" }] };
+ return { relevant: false, items: [] };
+ });
+ const enumerate = enumerateOver(RECS);
+ const { file } = await runTriage(
+ { owner: "pia-watch", k: f0.k, learned: [learnedOf("Pea Tartlet")], names: ["Pia Tartlet"], known: new Set(["pia tartlet", "pea tartlet"]) },
+ { llm: {} as never, corpus: corpusOver(RECS), paths, ask, enumerate, list: listOver(RECS), cuesOf: cuesOver(RECS), now: () => new Date(at) },
+ );
+ assert.equal(file.status, "done");
+ assert.deepEqual(file.learned, { n: 1, spellings: ["Pea Tartlet"] });
+ assert.match(file.summary, /· terms \+ 1 learned —/);
+ assert.equal(file.heard?.[0]?.span, "pia tart lit");
+ assert.deepEqual(file.learning?.kept.map((l) => [l.spelling, l.source, l.k, l.recording]), [["pia tart lit", "heard", f0.k, "d-04"]]);
+ const back = await readTriageFile("pia-watch", f0.k, paths);
+ assert.equal(back?.learning?.kept.length, 1);
+});
diff --git a/common/lib/report/draft/triage/learned.ts b/common/lib/report/draft/triage/learned.ts
@@ -0,0 +1,560 @@
+// 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 (capitalised first).
+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;
+
+export type SpellingSource = "proposed" | "heard";
+
+/** 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 };
+};
+
+export type LearnedDropReason = "no-hits" | "not-the-name" | "not-verbatim" | "known" | "blocked" | "cap" | "invalid" | "unread";
+
+/** A spelling that was not learned, and why. */
+export type LearnedDrop = { spelling: string; means: string; source: SpellingSource; reason: LearnedDropReason; why: string; at: string; k?: number };
+
+/** 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<LearnedFile> | 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 name-like alternatives of a watch's terms: a literal alternative (its
+ * `\b` anchors aside) with a capital letter, or a phrase of several words —
+ * the ones a transcript can mishear. A regex class, a quantifier or a group
+ * is skipped. Capitalised first, then 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<string>();
+ const caps: string[] = [];
+ const phrases: string[] = [];
+ for (const a of alts) {
+ if (!a) continue;
+ const key = spellingKey(a);
+ if (!key || seen.has(key)) continue;
+ const capital = /\p{Lu}/u.test(a);
+ const multi = key.includes(" ");
+ if (!capital && !multi) continue;
+ seen.add(key);
+ (capital ? caps : phrases).push(a);
+ }
+ return [...caps, ...phrases];
+}
+
+/** 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;
+ }
+}
+
+/** "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<string> } = {}): { 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<string>([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 (spellings.length >= k) continue;
+ else {
+ seen.add(key);
+ spellings.push(s);
+ }
+ }
+ return { spellings, dropped };
+}
+
+// ─── the confirmation (the judge) ───
+
+export const CONFIRM_SYSTEM =
+ "You read an excerpt of an automatic transcript, which often mishears names. Say whether the given spelling, " +
+ "where it occurs in the excerpt, is the transcript's mis-hearing of the given name (the same person or thing), " +
+ "or something else (another word, another person). Copy the line holding the spelling EXACTLY, character for " +
+ "character, without the bracketed timestamp. Answer means = true only when the excerpt makes it clear; 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}`;
+
+// ─── 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<string, unknown>): Record<string, unknown> {
+ const props = (schema.properties ?? {}) as Record<string, unknown>;
+ 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<string> {
+ 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<string, { candidates: number; flagged: number }>): 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<LearnedSpelling, "uses">): 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: "<channel>/<recording> at mm:ss". */
+export function learnedCite(l: Pick<LearnedSpelling, "channel" | "recording" | "start">): 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<LearnedSpelling, "spelling" | "means" | "channel" | "recording" | "start">, 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}"` };
+}
diff --git a/common/lib/report/draft/triage/learnedStore.ts b/common/lib/report/draft/triage/learnedStore.ts
@@ -0,0 +1,32 @@
+// WHERE A WATCH'S LEARNED SPELLINGS LIVE (umtool R6.3), and their read.
+// Server-only (node:fs).
+//
+// series, watch reports/.series/<id>/learned.json beside series.json
+// living reports/<article>/learned.json beside schedule.json
+//
+// Beside the schedule, so it goes where the schedule goes (a series' delete
+// removes its directory; a living schedule's delete removes it with
+// schedule.json). ONE WRITER: controller/learnedSpellings.ts, under the
+// article store's lock, atomically. Reads are lock-free (a write replaces the
+// file whole).
+
+import path from "node:path";
+import type { Paths } from "../../../paths";
+import { readJsonFile } from "../../../jsonFile-server";
+import { livingFile, seriesDir } from "../../schedule/store";
+import { parseLearned, type LearnedFile } from "./learned";
+
+export const LEARNED_FILENAME = "learned.json";
+
+export type LearnedPaths = Pick<Paths, "articlesDir">;
+
+/** learned.json of a schedule (its shape decides where). */
+export function learnedFilePath(paths: LearnedPaths, s: { shape: string; id: string }): string {
+ return s.shape === "living" ? path.join(path.dirname(livingFile(paths, s.id)), LEARNED_FILENAME) : path.join(seriesDir(paths, s.id), LEARNED_FILENAME);
+}
+
+/** A schedule's learned spellings, or null (none yet, or not a learned file). */
+export async function readLearned(paths: LearnedPaths, s: { shape: string; id: string }): Promise<LearnedFile | null> {
+ const r = await readJsonFile(learnedFilePath(paths, s));
+ return r.ok ? parseLearned(r.value, s.id) : null;
+}
diff --git a/common/lib/report/draft/triage/task.ts b/common/lib/report/draft/triage/task.ts
@@ -25,6 +25,8 @@ import { enumerateViaTools, type EnumerateFn, type ListFn } from "../refresh/del
import { openTrace, NO_TRACE, type RunTracer } from "../tasks/trace";
import type { CorpusToolsLike } from "../tasks/types";
import { judgeCandidates } from "./judge";
+import { confirmSpellings, countViaEnumerate, type CountPhrasesFn } from "./confirm";
+import { joinedQuery, learnedWords, type LearnedSpelling } from "./learned";
import { readTriageFile, readTriageSeen, triageTracePath, writeTriageFile, writeTriageSeen, type TriagePaths } from "./store";
import { triageCandidates } from "./tier0";
import { TRIAGE_SEEN_FORMAT, escalationOf, partialWords, triageLine, type TriageFile, type TriageWindow } from "./types";
@@ -40,6 +42,13 @@ export type TriageRunInput = {
maxCandidates?: number;
maxUsd?: number;
origin?: string | null;
+ // R6.3: the watch's learned spellings (active ones: their name is in the
+ // terms) — escaped alternatives of the candidate query — and the watched
+ // names the judge reports mis-hearings of; `known` (spelling keys: the
+ // names, learned and removed spellings) are not reported again.
+ learned?: LearnedSpelling[];
+ names?: string[];
+ known?: ReadonlySet<string>;
};
export type TriageRunDeps = {
@@ -53,6 +62,9 @@ export type TriageRunDeps = {
enumerate?: EnumerateFn;
// Every recording in scope, uncapped (default: the corpus tools' listRecordings, when they have it).
list?: ListFn;
+ // R6.3: each phrase's uncapped count in scope (default: the corpus tools'
+ // countPhrases, else the listing and enumerate_matches by ids).
+ count?: CountPhrasesFn;
// The model, stubbed (tests); default structuredAnswer on the run's model.
ask?: <T>(system: string, user: string, schema: object, what: string) => Promise<T>;
now?: () => Date;
@@ -152,6 +164,11 @@ export async function runTriage(input: TriageRunInput, deps: TriageRunDeps): Pro
const seen = input.ids?.length ? null : await readTriageSeen(owner, paths);
const known = seen ? new Set(seen.ids) : null;
file.knownCount = seen ? seen.ids.length : null;
+ const learned = (input.learned ?? []).map((l) => l.spelling);
+ if (learned.length && file.terms) {
+ file.learned = { n: learned.length, spellings: learned };
+ log(`tier 0: ${learnedWords(learned.length)} (${learned.map((x) => `"${x}"`).join(", ")})`);
+ }
const t0r = await triageCandidates(
{
scope: file.scope,
@@ -162,6 +179,7 @@ export async function runTriage(input: TriageRunInput, deps: TriageRunDeps): Pro
since: file.since,
...(input.ids?.length ? { ids: input.ids } : {}),
max: input.maxCandidates ?? DEFAULT_MAX_CANDIDATES,
+ ...(learned.length ? { learned } : {}),
},
{ enumerate, ...(list ? { list } : {}), topicsOf, ...(deps.signal ? { signal: deps.signal } : {}), log },
);
@@ -178,8 +196,21 @@ export async function runTriage(input: TriageRunInput, deps: TriageRunDeps): Pro
log(`tier 0: ${t0r.tier0.candidates.length} candidate(s) of ${t0r.tier0.newCount} new (${t0r.tier0.scanned} in scope)`);
// ─── tier 1 ───
+ // The judge's windows: around the terms and the learned spellings alike.
+ const jq = joinedQuery(file.terms, file.regex, learned);
const j = await judgeCandidates(
- { question: file.question, candidates: t0r.tier0.candidates, terms: file.terms, regex: file.regex, topics: file.topics, channels: file.scope.channels, ...(input.windows ? { windows: input.windows } : {}), origin: input.origin ?? null },
+ {
+ question: file.question,
+ candidates: t0r.tier0.candidates,
+ terms: jq?.query ?? file.terms,
+ regex: jq?.regex ?? file.regex,
+ topics: file.topics,
+ channels: file.scope.channels,
+ ...(input.windows ? { windows: input.windows } : {}),
+ origin: input.origin ?? null,
+ ...(input.names?.length ? { names: input.names } : {}),
+ ...(input.known ? { known: input.known } : {}),
+ },
{
corpus: deps.corpus,
ask,
@@ -199,13 +230,31 @@ export async function runTriage(input: TriageRunInput, deps: TriageRunDeps): Pro
const left = new Set(j.stopped.ids);
if (seenIds) seenIds = seenIds.filter((id) => !left.has(id));
}
+ // R6.3: what the judge heard as a watched name, confirmed by code and the
+ // judge before anything is learned (the job writes what is kept).
+ if (j.heard.length) file.heard = j.heard;
+ if (j.heardDropped.length) file.heardDropped = j.heardDropped;
+ if (j.heard.length && !j.stopped) {
+ const count = deps.count ?? deps.corpus.countPhrases?.bind(deps.corpus) ?? (list ? countViaEnumerate(list, enumerate) : null);
+ if (count) {
+ log(`learn: ${j.heard.length} span(s) heard as a watched name — confirming`);
+ const c = await confirmSpellings(
+ { pending: j.heard.map((h) => ({ spelling: h.span, means: h.means, source: "heard" as const, k, heard: h })), question: file.question, scope: file.scope, at: now().toISOString(), origin: input.origin ?? null },
+ { corpus: deps.corpus, ask, count, ...(deps.cuesOf ? { cuesOf: deps.cuesOf } : {}), log, ...(deps.signal ? { signal: deps.signal } : {}) },
+ );
+ file.learning = { kept: c.kept, dropped: c.dropped };
+ file.tier1.usd = round4(meter.usd);
+ } else {
+ file.warnings.push(`${j.heard.length} heard span(s) not confirmed: this corpus cannot count them`);
+ }
+ }
trace({ t: "cost", step: "tier 1", tier: 1, usd: round4(meter.usd), model: file.model, total: round4(meter.usd) });
// ─── the decision ───
file.escalation = escalationOf(j.flags, file.threshold);
file.cost = { tier0: 0, tier1: round4(meter.usd) };
const part = partialWords(file.tier0);
- file.summary = `${part ? `partial (${part}) · ` : ""}${triageLine(file)} — ${file.escalation.escalate ? "escalate" : "below the threshold"}: ${file.escalation.why}`;
+ file.summary = `${part ? `partial (${part}) · ` : ""}${triageLine(file)}${file.learned ? ` · ${learnedWords(file.learned.n)}` : ""} — ${file.escalation.escalate ? "escalate" : "below the threshold"}: ${file.escalation.why}`;
log(`tier 1: ${j.flags.length} flag(s), ${j.dismissed.length} dismissed; ${file.summary}`);
trace({
t: "triage",
diff --git a/common/lib/report/draft/triage/tier0.ts b/common/lib/report/draft/triage/tier0.ts
@@ -34,6 +34,7 @@
// 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).
@@ -53,6 +54,9 @@ export type Tier0Input = {
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 = {
@@ -193,6 +197,57 @@ export async function triageCandidates(i: Tier0Input, d: Tier0Deps): Promise<Tie
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<string, unknown> = {
+ ...(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<string, string[]>();
+ const lines = new Map<string, number>();
+ 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;
@@ -242,6 +297,7 @@ export async function triageCandidates(i: Tier0Input, d: Tier0Deps): Promise<Tie
newBy: i.known ? "id" : "date",
listedBy: listing.by,
...(problems.length ? { problems } : {}),
+ ...(learned.length && terms ? { learned: { spellings: learned, matched: learnedMatched } } : {}),
},
seen,
scannedIds,
diff --git a/common/lib/report/draft/triage/types.ts b/common/lib/report/draft/triage/types.ts
@@ -22,6 +22,8 @@
// the schedule (a series', a watch's, a living report's id). The editor's
// `report-draft {"task":"triage"}` job is their ONE writer.
+import type { LearnedDrop, LearnedSpelling, TriageHeard, TriageHeardDropped } from "./learned";
+
export const TRIAGE_FORMAT = "archilyzer-triage";
export const TRIAGE_VERSION = 1;
export const TRIAGE_SEEN_FORMAT = "archilyzer-triage-seen";
@@ -56,10 +58,12 @@ export type TriageCandidate = {
matches: number | null;
// terms: the terms (or aliases) match; topics: a digest topic tag matches;
// new: no terms or topics were given, so every new recording is one; ids:
- // named by the caller.
- by: ("terms" | "topics" | "new" | "ids")[];
+ // named by the caller; learned (R6.3): a spelling the watch learned matches.
+ by: ("terms" | "topics" | "new" | "ids" | "learned")[];
// The digest tags that matched the topics.
tags?: string[];
+ // R6.3: the learned spellings that match it.
+ learned?: string[];
};
/** A line tier 1 flagged: worth a look. */
@@ -135,6 +139,9 @@ export type TriageTier0 = {
// the ids are the first few. Absent: none.
untranscribed?: number;
untranscribedIds?: string[];
+ // R6.3: the learned spellings the candidate query carried ("terms + N
+ // learned") and how many new recordings they matched.
+ learned?: { spellings: string[]; matched: number };
};
export type TriageTier1 = {
@@ -178,6 +185,14 @@ export type TriageFile = {
summary: string;
error?: string;
warnings: string[];
+ // R6.3: the learned spellings this run's query carried (terms + N learned).
+ learned?: { n: number; spellings: string[] };
+ // R6.3: the spans tier 1 heard as a watched name (verbatim, code-checked),
+ // the ones put aside, and what their confirmation kept and dropped (the
+ // job writes the kept ones to the schedule's learned.json).
+ heard?: TriageHeard[];
+ heardDropped?: TriageHeardDropped[];
+ learning?: { kept: LearnedSpelling[]; dropped: LearnedDrop[] };
};
/** seen.json: the ids the owner's last completed triage saw in scope. */
@@ -256,6 +271,8 @@ export type TickTriage = {
capped?: string;
// R6.1: tier 0 was partial — what it did not reach ("not reached: …").
partial?: string;
+ // R6.3: the learned spellings its query carried (terms + N learned).
+ learned?: number;
};
/** A run's slice for its tick line. */
@@ -276,6 +293,7 @@ export function tickTriageOf(f: TriageFile, o: { tier2Usd?: number; capped?: str
usd: { tier1: Math.round((f.cost.tier1 ?? 0) * 10_000) / 10_000, tier2: Math.round((o.tier2Usd ?? 0) * 10_000) / 10_000 },
...(o.capped ? { capped: o.capped } : {}),
...(partialWords(f.tier0) ? { partial: partialWords(f.tier0)! } : {}),
+ ...(f.learned?.n ? { learned: f.learned.n } : {}),
};
}
diff --git a/common/lib/report/schedule/types.ts b/common/lib/report/schedule/types.ts
@@ -105,6 +105,8 @@ export const tickTriageSchema = z.looseObject({
usd: z.looseObject({ tier1: z.number().nonnegative(), tier2: z.number().nonnegative() }),
capped: z.string().optional(),
partial: z.string().optional(),
+ // R6.3: the learned spellings its query carried (terms + N learned).
+ learned: z.number().int().nonnegative().optional(),
});
export const tickSchema = z.looseObject({
@@ -130,6 +132,8 @@ export const tickSchema = z.looseObject({
warnings: z.array(z.string()).optional(),
// Its triage, when it ran one (umtool R6): the tiers in brief, and whether it escalated.
triage: tickTriageSchema.optional(),
+ // R6.3: the proposal pass it ran before tier 0 (a pass was due): what it learned.
+ learn: z.looseObject({ trigger: z.string(), status: z.string(), added: z.number().int().nonnegative().optional(), total: z.number().int().nonnegative().optional(), jobId: z.string().optional() }).optional(),
});
export type Tick = z.infer<typeof tickSchema>;
diff --git a/editor/app/api/ops/_reportSchedule.ts b/editor/app/api/ops/_reportSchedule.ts
@@ -11,6 +11,8 @@ import {
} from "yt-dlp-transcript-common/controller/reportTick";
import type { ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft";
import { armReportSchedule } from "yt-dlp-transcript-common/controller/reportScheduleRunner";
+import { enqueueLearn, learnStep } from "yt-dlp-transcript-common/controller/reportLearn";
+import type { EnqueueLearnFn } from "yt-dlp-transcript-common/controller/reportScheduleOps";
import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
import { SourceRegistry, enumerate } from "yt-dlp-transcript-mcp/research";
import { refreshEditor, researchEditor } from "./_researchEditor";
@@ -35,6 +37,10 @@ import { refreshEditor, researchEditor } from "./_researchEditor";
// triage R6's cheap pass, `report-draft {"task":"triage"}` on
// draft:local (or the extractor's draft:api), awaited; its
// triage.json says whether to escalate (triageStep)
+// learn R6.3's proposal pass (learned spellings), before tier 0
+// when one is due; awaited (learnStep). `enqueueLearn` is
+// the same pass for the ops action and a create or a
+// change of terms (not awaited)
const countWindow: CountWindow = async (q) => {
const paths = getPaths();
@@ -60,7 +66,7 @@ const countWindow: CountWindow = async (q) => {
return { recordings: e.result.total, ...(e.result.truncated ? { partial: true, unreached } : {}) };
};
-export function reportScheduleDeps(): TickDeps {
+export function reportScheduleDeps(): TickDeps & { enqueueLearn: EnqueueLearnFn } {
const paths = getPaths();
const draft: ReportDraftDeps = { paths, corpusTools: (source) => createCorpusTools({ source }), researchEditor, refreshEditor };
return {
@@ -71,6 +77,13 @@ export function reportScheduleDeps(): TickDeps {
...r4Steps(draft),
generateEdition: editionGenerator({ draft, countWindow }),
triage: triageStep(draft),
+ learn: learnStep(draft),
+ },
+ enqueueLearn: async (id, trigger) => {
+ const out = await enqueueLearn(id, trigger, draft);
+ if (!out.ok) return out;
+ void out.result.stream.cancel();
+ return { ok: true, jobId: out.jobId, plan: out.plan };
},
};
}
diff --git a/editor/app/api/ops/report-schedule/route.ts b/editor/app/api/ops/report-schedule/route.ts
@@ -9,7 +9,8 @@ import { reportScheduleDeps } from "../_reportSchedule";
export const dynamic = "force-dynamic";
// POST {"action": "list" | "create" | "update" | "pause" | "resume" |
-// "delete" | "tick-now" | "reset-triage", …}
+// "delete" | "tick-now" | "reset-triage" | "learn" | "unlearn" |
+// "promote-alias", …}
//
// A recurring report (umtool R5): a LIVING report (one article kept current —
// each tick re-fetches the scope and refreshes it), a SERIES (a dated
@@ -32,6 +33,14 @@ export const dynamic = "force-dynamic";
// reset-triage {id, k?, confirm?} -> {plan} | {reset} (R6.1) discard the
// triage runs (from k on), seen.json and the quiet editions they
// covered; the plan unless confirm
+// learn {id, dryRun?} -> {plan, jobId?} (R6.3) the proposal pass now:
+// the names it asks about; a `report-draft` job on the triage
+// model's lane. A create or a change of terms starts one too
+// (the answer's `learn`)
+// unlearn {id, spelling} -> {removed, blocked} never learned again
+// promote-alias {id, spelling, site?, confirm?} -> {plan} | {promoted}
+// a learned spelling as a search alias (global, or a site's),
+// through the alias writer; the plan unless confirm
// AN ADAPTER: every refusal and write is the controller's
// (common/controller/reportScheduleOps.ts).
export async function POST(request: Request) {
diff --git a/mcp/src/callTool.ts b/mcp/src/callTool.ts
@@ -24,7 +24,8 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { FetchClipDeps } from "./fetchClip";
import type { ListArgs, RecordingListing } from "yt-dlp-transcript-common/lib/report/draft/refresh/delta";
-import { listRecordings } from "./enumerate";
+import type { CountPhrasesArgs, PhraseCounts } from "yt-dlp-transcript-common/lib/report/draft/triage/confirm";
+import { countPhrases, listRecordings } from "./enumerate";
import { createServer, TOOLS } from "./server";
import { SourceRegistry } from "./sourceRegistry";
import type { ShardSource } from "./source";
@@ -74,6 +75,9 @@ export type CorpusTools = {
// R6.1: every recording in a scope, uncapped (the build's manifests), as
// data — what a triage's tier 0 lists the scope with. Not an agent tool.
listRecordings(args: ListArgs): Promise<RecordingListing>;
+ // R6.3: phrases counted over a scope, uncapped, in one scan (a learned
+ // spelling's confirmation). Not an agent tool.
+ countPhrases(args: CountPhrasesArgs): Promise<PhraseCounts>;
close(): Promise<void>;
};
@@ -185,6 +189,7 @@ export async function createCorpusTools(opts: CorpusToolsOptions): Promise<Corpu
tools,
call: (name, args) => call(name, args),
listRecordings: async (args) => listRecordings((await registry.resolve()).source, args),
+ countPhrases: async (args) => countPhrases((await registry.resolve()).source, args),
close: async () => {
await client.close();
await server.close();
diff --git a/mcp/src/enumerate.ts b/mcp/src/enumerate.ts
@@ -21,6 +21,8 @@ import {
import type { LayerScope } from "yt-dlp-transcript-common/lib/searchQuery";
import type { TranscriptDetail } from "yt-dlp-transcript-common/lib/transcripts";
import { recordHasText, statHasText, type ListArgs, type ListedRecording, type RecordingListing } from "yt-dlp-transcript-common/lib/report/draft/refresh/delta";
+import type { CountPhrasesArgs, PhraseCount, PhraseCounts } from "yt-dlp-transcript-common/lib/report/draft/triage/confirm";
+import { learnedAlternation, spellingPattern } from "yt-dlp-transcript-common/lib/report/draft/triage/learned";
import type { ChannelRef, ShardSource } from "./source";
import {
parseContentTypes,
@@ -356,3 +358,81 @@ export async function listRecordings(source: ShardSource, args: ListArgs): Promi
}
return { rows, complete: problems.length === 0, unreached: [...unreached], problems };
}
+
+// ─── R6.3: phrases counted over a scope, uncapped ───
+
+// The ids one restricted scan reads: well under the 2,000-recording cap, so a
+// batch can never be cut by it.
+export const COUNT_ID_BATCH = 1000;
+// Snippets kept per recording while counting: every matching line, in practice.
+const COUNT_SNIPPETS = 500;
+
+/**
+ * Each phrase's count in a scope — the recordings it occurs in, its lines, and
+ * a few examples (newest first) — UNCAPPED and in one scan for all of them:
+ * the scope LISTED (listRecordings: every recording the build ships, by id),
+ * then enumerate's own scan restricted to those ids in batches of
+ * COUNT_ID_BATCH, the phrases as one alternation of escaped literals
+ * (learned.ts spellingPattern — what a triage's query matches them with). Each
+ * matching line is attributed to the phrases it holds. A recording listed
+ * with no transcript yet is not counted. A listing that is not complete, or a
+ * batch the scan could not finish, makes the answer `complete: false`, said in
+ * `problems` — a count from it is "at least".
+ */
+export async function countPhrases(source: ShardSource, args: CountPhrasesArgs): Promise<PhraseCounts> {
+ const phrases = [...new Set(args.phrases.filter((p) => typeof p === "string" && p.trim()))];
+ const counts: Record<string, PhraseCount> = Object.fromEntries(phrases.map((p) => [p, { recordings: 0, lines: 0, examples: [] }]));
+ const listing = await listRecordings(source, { ...(args.channels?.length ? { channels: args.channels } : {}), ...(args.date_from ? { date_from: args.date_from } : {}), ...(args.date_to ? { date_to: args.date_to } : {}) });
+ const rows = listing.rows.filter((r) => r.hasTranscript !== false);
+ const problems = [...listing.problems];
+ let complete = listing.complete;
+ const combined = learnedAlternation(phrases);
+ if (!combined || !rows.length) return { counts, complete, problems, listed: rows.length };
+ const res = phrases.map((p) => [p, new RegExp(spellingPattern(p), "i")] as const);
+ const byId = new Map(rows.map((r) => [r.id, r]));
+ const ids = [...byId.keys()];
+ const keep = Math.max(1, args.examples ?? 10);
+ for (let i = 0; i < ids.length; i += COUNT_ID_BATCH) {
+ const batch = ids.slice(i, i + COUNT_ID_BATCH);
+ const e = await enumerate(
+ source,
+ { query: combined, regex: true, ...(args.channels?.length ? { channels: args.channels } : {}), ids: batch, content_types: ["video"] },
+ { includeSnippets: true, snippetsPerVideo: COUNT_SNIPPETS },
+ );
+ if ("error" in e) {
+ complete = false;
+ problems.push(`ids ${i + 1}–${i + batch.length}: ${e.error}`);
+ continue;
+ }
+ if (e.result.truncated) {
+ complete = false;
+ const c = e.result.coverage;
+ problems.push(`ids ${i + 1}–${i + batch.length}: the scan was capped${c.channelStopped ? ` (stopped in ${c.channelStopped.channel} at page ${c.channelStopped.page} of ${c.channelStopped.pages})` : ""}`);
+ }
+ for (const h of e.result.hits) {
+ if (h.contentType === "post") continue;
+ const listed = byId.get(h.videoId);
+ for (const [p, re] of res) {
+ const lines = h.snippets.filter((s) => !s.scope && re.test(s.text));
+ if (!lines.length && !re.test(h.title ?? "")) continue;
+ const c = counts[p]!;
+ c.recordings++;
+ c.lines += lines.length;
+ c.examples.push({
+ id: h.videoId,
+ channel: h.channelName ?? listed?.channel ?? null,
+ channelSlug: h.channelSlug ?? listed?.channelSlug ?? null,
+ date: ymd(h.uploadDate) ?? listed?.date ?? null,
+ title: h.title ?? listed?.title ?? null,
+ start: lines[0]?.seconds ?? null,
+ text: lines[0]?.text ?? null,
+ });
+ }
+ }
+ }
+ for (const c of Object.values(counts)) {
+ c.examples.sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? "")));
+ c.examples = c.examples.slice(0, keep);
+ }
+ return { counts, complete, problems, listed: rows.length };
+}
diff --git a/mcp/src/listRecordings.test.ts b/mcp/src/listRecordings.test.ts
@@ -13,7 +13,7 @@ import os from "node:os";
import path from "node:path";
import { enumerateOf } from "yt-dlp-transcript-common/lib/report/draft/tasks/trace";
import { createCorpusTools, type CorpusTools } from "./callTool";
-import { enumerate, listRecordings, type Enumerated } from "./enumerate";
+import { countPhrases, enumerate, listRecordings, type Enumerated } from "./enumerate";
import { LocalSource } from "./source";
let dir: string;
@@ -136,3 +136,19 @@ test("R6.2 listRecordings says which recordings have transcript text: the stats
await rm(d, { recursive: true, force: true });
}
});
+
+test("countPhrases (R6.3): each phrase counted over the whole listed scope in one restricted scan — recordings, lines, examples newest first; a phrase is literal, whole words", async () => {
+ const src = new LocalSource(dir);
+ const c = await countPhrases(src, { phrases: ["the contest", "co-host", "flour", "contest.*", "nowhere at all"], channels: ["big"] });
+ assert.equal(c.complete, true, c.problems.join("; "));
+ assert.equal(c.listed, 7);
+ assert.deepEqual(
+ Object.fromEntries(Object.entries(c.counts).map(([p, x]) => [p, [x.recordings, x.lines]])),
+ { "the contest": [4, 4], "co-host": [1, 1], flour: [1, 1], "contest.*": [0, 0], "nowhere at all": [0, 0] },
+ );
+ assert.deepEqual(c.counts["the contest"]!.examples.map((x) => x.id), ["new-2", "old-5", "old-3", "old-1"]);
+ assert.deepEqual(c.counts["co-host"]!.examples[0], { id: "new-1", channel: "Big Channel (Mirror)", channelSlug: "big", date: "2026-10-12", title: "Title new-1", start: 0, text: "a co-host joined the show" });
+ // Through the corpus tools, as the editor's jobs call it.
+ const t = await corpus.countPhrases({ phrases: ["the contest"], channels: ["big"], date_from: "2025-01-01" });
+ assert.equal(t.counts["the contest"]!.recordings, 2);
+});
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -119,6 +119,8 @@
// pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait
// pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'
// pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'
+// pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'
+// pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Melanie Mack"}'
//
// --file reads the BODY from a JSON file, which is how a big one gets sent: a
// four-thousand-id tag-videos body is written by a script, not typed by a model
@@ -430,6 +432,8 @@ const ACTIONS = [
// resume | delete | tick-now | reset-triage, …}); tick-now is a
// report-tick job. R6: a watch (no article until a triage finds something),
// and triageFirst. R6.1: reset-triage discards a schedule's triage state.
+ // R6.3: learn (the proposal pass), unlearn and promote-alias (a learned
+ // spelling as a search alias, plan then confirm).
"report-schedule",
];
@@ -1322,7 +1326,8 @@ export function usage() {
"",
'report-schedule keeps a recurring report on a cadence the editor ticks:',
' {"action": "list" | "create" | "update" | "pause" | "resume" | "delete" |',
- ' "tick-now" | "reset-triage", …}. create takes {"shape": "living" | "series", "topic",',
+ ' "tick-now" | "reset-triage" | "learn" | "unlearn" | "promote-alias", …}.',
+ ' create takes {"shape": "living" | "series", "topic",',
' "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence"',
' ({"kind": "daily" | "weekly" | "every", "at": "HH:MM", "dow"?, "days"?}',
' or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"?',
@@ -1348,6 +1353,19 @@ export function usage() {
' (its runs from run k on, default all; seen.json, so the next run counts',
' new from its since; the quiet editions they covered): the plan unless',
' confirm is true; refused while a tick runs.',
+ ' learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned',
+ " spellings): the triage model lists likely mis-hearings of each name in",
+ " the terms; each must occur in scope (an uncapped count) and the judge must",
+ " say, quoting the line, that it means the name, before it joins the",
+ ' candidate query as an escaped literal ("terms + N learned"); the answer is',
+ " the plan (the names it asks about) and the job (a report-draft job on the",
+ " triage model's lane); dryRun answers the plan only. A create of a",
+ " schedule that triages, a change of its terms, and a tick a week after the",
+ ' last pass start one too. unlearn {"id", "spelling"} removes a learned',
+ ' spelling (never learned again). promote-alias {"id", "spelling", "site"?,',
+ ' "confirm"?} writes it as a search alias (global, or the site\'s), a new',
+ " alias or a trigger on the one for that name: the plan unless confirm is",
+ " true.",
"",
"Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,",
" ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").",