Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 37f5cbae1c34fcacaf7898c490e25f3fff736902
parent 8936b76260e7decd323d81b5b6781628a0e3123f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 14 Oct 2026 21:42:17 -0400

umtool: Learned spellings on the series/watch page (R6.3) — the lit list (spelling → name, hits, source; suggest removing, idle, promoted), the proving line on the reader with its cite, Remove and Promote to search alias (each plan, then confirm; the list chosen, the alias as written), Propose spellings; the triage page names a candidate a learned spelling brought (terms + N learned); /api/schedules forwards learn / unlearn / promote-alias; the stub's proposal pass; learned-spellings.spec, lib/research/learned.test.ts

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/testing/schedule/opsStub.ts | 82++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/app/api/schedules/route.ts | 13+++++++++----
Mumtool/app/series/[id]/page.tsx | 17++++++++++++++++-
Aumtool/components/series/LearnedSpellings.tsx | 349+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/series/TriageView.tsx | 11++++++++++-
Aumtool/e2e/learned-spellings.spec.ts | 181+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/learned-types.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/learned.test.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/research/learned.ts | 31+++++++++++++++++++++++++++++++
9 files changed, 795 insertions(+), 11 deletions(-)

diff --git a/common/testing/schedule/opsStub.ts b/common/testing/schedule/opsStub.ts @@ -26,7 +26,19 @@ // R6.1); a quiet run also lists two recordings without // a transcript yet (R6.2); else a strong flag and a weak one // on sitechan/sv1 and sv2, an invented line dismissed as -// not verbatim, a window not relevant; $0 (local) +// not verbatim, a window not relevant; $0 (local). With +// learned spellings (R6.3), sv3 is a candidate a learned +// spelling alone brought, and the run says "terms + N +// learned" +// learn (R6.3, a create of a watch whose terms name someone, a +// change of terms, `learn`) the pass runs here at once: two +// spellings of the first name kept — "Vote Rigg" (proposed, +// sv1) and "Vote Rick" (heard in triage 1, sv2; its +// candidates dismissed four runs running: suggest removing) +// — and "Boat Rig" dropped (no hits), through the real +// writer (a blocked spelling stays out). promote-alias and +// unlearn are the real ones: the alias file is +// <root>/search-aliases.json, the sites <root>/sites import { mkdir } from "node:fs/promises"; import path from "node:path"; @@ -35,11 +47,16 @@ import { sanitizeGeneration } from "../../lib/generationSettings"; import { createIteration, updateIteration, writeIterationFile } from "../../lib/report/iterations"; import { claimTick } from "../../controller/reportSchedule"; import { createTriageRun, writeTriageFile } from "../../lib/report/draft/triage/store"; -import { DEFAULT_TRIAGE_THRESHOLD, TRIAGE_FORMAT, TRIAGE_VERSION, escalationOf, partialWords, triageLine, type TriageFile, type TriageFlag } from "../../lib/report/draft/triage/types"; +import { DEFAULT_TRIAGE_THRESHOLD, TRIAGE_FORMAT, TRIAGE_VERSION, escalationOf, partialWords, triageLine, type TriageCandidate, type TriageFile, type TriageFlag } from "../../lib/report/draft/triage/types"; import { writeFile } from "node:fs/promises"; import { iterationFile } from "../../lib/report/iterations"; import { runTick, type TickDeps, type TickSteps } from "../../controller/reportTick"; -import { reportScheduleAction } from "../../controller/reportScheduleOps"; +import { reportScheduleAction, type EnqueueLearnFn } from "../../controller/reportScheduleOps"; +import { recordLearnPass } from "../../controller/learnedSpellings"; +import { planLearn } from "../../controller/reportLearn"; +import { readLearned } from "../../lib/report/draft/triage/learnedStore"; +import { activeLearned, namesOf, type LearnedSpelling } from "../../lib/report/draft/triage/learned"; +import { readSchedule } from "../../lib/report/schedule/store"; const argv = process.argv.slice(2); const flag = (name: string) => { @@ -62,6 +79,8 @@ const paths = { exportIndexDir: path.join(root, ".export-index-schedule"), generationUsageFile: path.join(root, ".generation-usage.jsonl"), jobsDir: path.join(root, ".jobs-schedule"), + globalAliasesFile: path.join(root, "search-aliases.json"), + sitesDir: path.join(root, "sites"), } as unknown as Paths; await mkdir(articlesDir, { recursive: true }); @@ -155,6 +174,9 @@ const steps: TickSteps = { }, triage: async (input, ctx) => { const s = input.schedule; + // R6.3: the learned spellings its query carries. + const lf = await readLearned(paths, s).catch(() => null); + const learnt = activeLearned(lf, namesOf(s.scope.terms ?? null, s.scope.regex === true)).map((l) => l.spelling); // "partial" (R6.1): tier 0 hit a cap — a channel not reached — and nothing flagged. const partial = /partial/.test(words(s)); const quiet = partial || /quiet/.test(words(s)); @@ -182,7 +204,16 @@ const steps: TickSteps = { startedAt: at, endedAt: at, tier0: { - candidates: ["sv1", "sv2", "sv3", "sv4"].map((id, i) => ({ id, channel: "Site Channel", title: `Site video ${["one", "two", "three", "four"][i]}`, date: "2024-03-15", matches: 2 - (i % 2), by: i === 3 ? ["topics"] : ["terms"], ...(i === 3 ? { tags: ["elections"] } : {}) })), + candidates: ["sv1", "sv2", "sv3", "sv4"].map((id, i) => ({ + id, + channel: "Site Channel", + title: `Site video ${["one", "two", "three", "four"][i]}`, + date: "2024-03-15", + matches: 2 - (i % 2), + by: i === 3 ? ["topics"] : i === 2 && learnt.length ? ["learned"] : ["terms"], + ...(i === 3 ? { tags: ["elections"] } : {}), + ...(i === 2 && learnt.length ? { learned: [learnt[0]!] } : {}), + })) as TriageCandidate[], scanned: 16, newCount: 4, cut: [], @@ -193,7 +224,9 @@ const steps: TickSteps = { listedBy: "manifests", // R6.2: a quiet run lists two recordings whose transcripts have not landed (not seen). ...(quiet && !partial ? { untranscribed: 2, untranscribedIds: ["sv5", "sv6"] } : {}), + ...(learnt.length ? { learned: { spellings: learnt, matched: 1 } } : {}), }, + ...(learnt.length ? { learned: { n: learnt.length, spellings: learnt } } : {}), tier1: { model: generation.models.local, flags: quiet ? [] : FLAGS, @@ -223,6 +256,45 @@ const steps: TickSteps = { }, }; +// R6.3: the proposal pass, at once (no model): two spellings of the first name kept, one dropped. +const enqueueLearn: EnqueueLearnFn = async (id, trigger) => { + const plan = await planLearn(id, { paths, settings: () => ({ generation }), ...(nowIso ? { now: () => new Date(nowIso) } : {}) }); + if (plan.refused) return { ok: false, error: plan.refused, plan }; + const s = (await readSchedule(id, paths))!; + const at = (nowIso ? new Date(nowIso) : new Date()).toISOString(); + const name = plan.names[0]!; + const kept: LearnedSpelling[] = [ + { spelling: "Vote Rigg", means: name, quote: "The vote was rigged and everybody knew.", recording: "sv1", channel: "sitechan", title: "Site video one", start: 3, url: `${ORIGIN}/?v=sitechan%2Fsv1&t=3`, hits: 2, lines: 3, source: "proposed", at }, + { + spelling: "Vote Rick", + means: name, + quote: "Then she said the opposite.", + recording: "sv2", + channel: "sitechan", + title: "Site video two", + start: 8, + url: `${ORIGIN}/?v=sitechan%2Fsv2&t=8`, + hits: 1, + source: "heard", + k: 1, + at, + uses: [1, 2, 3, 4].map((k) => ({ k, at, candidates: 1, flagged: 0 })), + }, + ]; + await recordLearnPass( + s, + { + pass: { at, trigger, status: "done", model: generation.models.local, names: plan.names, notAsked: plan.notAsked, proposed: 3, kept: 0, dropped: 0, usd: 0, jobId: `${jobId}-learn` }, + kept, + dropped: [{ spelling: "Boat Rig", means: name, source: "proposed", reason: "no-hits", why: "does not occur in scope (16 recordings counted)", at }], + termsKey: s.scope.terms ? `${s.scope.regex ? "re" : "lit"}:${s.scope.terms}` : null, + }, + paths, + new Date(at), + ); + return { ok: true, jobId: `${jobId}-learn`, plan }; +}; + const deps: TickDeps = { paths, ...(nowIso ? { now: () => new Date(nowIso) } : {}), @@ -248,6 +320,6 @@ if (body.action === "tick-now") { console.log(JSON.stringify({ ok: true, jobId, tick, log })); } } else { - const out = await reportScheduleAction(body, { ...deps, lane: () => ({ held: false, armed: true }) }); + const out = await reportScheduleAction(body, { ...deps, lane: () => ({ held: false, armed: true }), enqueueLearn }); console.log(JSON.stringify(out)); } diff --git a/umtool/app/api/schedules/route.ts b/umtool/app/api/schedules/route.ts @@ -6,16 +6,19 @@ import { readSchedules, scheduleAsk } from "@/lib/schedules"; export const dynamic = "force-dynamic"; const NO_STORE = { "cache-control": "no-store" }; -const ACTIONS = ["create", "update", "pause", "resume", "delete", "tick-now"]; +const ACTIONS = ["create", "update", "pause", "resume", "delete", "tick-now", "learn", "unlearn", "promote-alias"]; // RECURRING REPORTS (plans/umtool-redesign.md, R5). // // GET every schedule, read from the article store (no editor call) -// POST { action: create | update | pause | resume | delete | tick-now, … } +// POST { action: create | update | pause | resume | delete | tick-now | +// learn | unlearn | promote-alias, … } // -- the editor's `report-schedule` ops action, forwarded as sent: the // editor keeps the schedules and is their one writer (a create with // `dryRun: true` is its plan; a delete without `confirm: true` is its -// plan). Answers the editor's JSON, or its refusal in its words. +// plan; R6.3: a learn with `dryRun: true` and a promote-alias without +// `confirm: true` are plans). Answers the editor's JSON, or its +// refusal in its words. export async function GET() { try { return Response.json(await readSchedules(), { headers: NO_STORE }); @@ -33,7 +36,9 @@ export async function POST(request: Request) { try { const out = await scheduleAsk(body); // A write changes what Work, the Inbox and the rail show. - if (!(body.action === "create" && body.dryRun === true) && !(body.action === "delete" && body.confirm !== true)) { + const planOnly = + ((body.action === "create" || body.action === "learn") && body.dryRun === true) || ((body.action === "delete" || body.action === "promote-alias") && body.confirm !== true); + if (!planOnly) { clearPiecesCache(); clearRailCounts(); } diff --git a/umtool/app/series/[id]/page.tsx b/umtool/app/series/[id]/page.tsx @@ -1,6 +1,7 @@ import Link from "next/link"; import { redirect } from "next/navigation"; import LifecycleChip from "@/components/piece/LifecycleChip"; +import LearnedSpellings from "@/components/series/LearnedSpellings"; import ScheduleControls from "@/components/series/ScheduleControls"; import TickProgress from "@/components/series/TickProgress"; import AppShell from "@/components/shell/AppShell"; @@ -10,6 +11,7 @@ import { Panel } from "@/components/ui/panel"; import { Table, TD, TH } from "@/components/ui/table"; import { ARTICLES_KEY } from "@/lib/articles/key.mjs"; import { articleHref, triageHref, workHref } from "@/lib/hrefs"; +import { readScheduleLearned } from "@/lib/research/learned"; import { readScheduleTriage, triageBoardId } from "@/lib/research/triage"; import { researchCaseHref } from "@/lib/research/hrefs"; import type { ScheduleTriage } from "@/lib/research/triage-types"; @@ -35,7 +37,8 @@ export const dynamic = "force-dynamic"; // A WATCH (R6) has no editions: its page lists what its escalations FOUND // (each tick's article and board), and every schedule that triages shows its // triage runs (the tiers, each run's page), the precision of the flags the -// operator marked and the threshold the marks suggest. +// operator marked and the threshold the marks suggest. R6.3: a schedule that +// triages lists its LEARNED SPELLINGS (components/series/LearnedSpellings.tsx). // // A living report's schedule is its article's: /series/<article> goes there. // A static segment (`series`), so nothing else's catch-all takes it. @@ -96,6 +99,8 @@ export default async function SeriesPage({ params }: { params: Promise<{ id: str const watch = v.shape === "watch"; const triage = triagesFirst(v) ? await readScheduleTriage(v).catch(() => null) : null; const found = watch ? ticks.filter((t) => t.article && t.triage?.escalated) : []; + // R6.3: what the watch learned of how the transcripts mishear its names. + const learned = triagesFirst(v) ? await readScheduleLearned(v).catch(() => null) : null; return ( <div className="flex h-full flex-col"> <AppShell @@ -182,6 +187,16 @@ export default async function SeriesPage({ params }: { params: Promise<{ id: str </Panel> )} {triage && <TriagePanel id={v.id} t={triage} />} + {learned && ( + <Panel + title="Learned spellings" + aside={<span className="text-muted">{learned.rows.length ? `terms + ${learned.rows.filter((r) => !r.idle).length} learned` : "how the transcripts mishear its names"}</span>} + className="w-full max-w-[1100px]" + data-series-learned="" + > + <LearnedSpellings view={learned} /> + </Panel> + )} <Panel title="Ticks" aside={<span className="text-muted">{ticks.length} recorded</span>} className="w-full max-w-[1100px]" data-series-ticks=""> {ticks.length === 0 ? ( <p className="m-0 text-[12.5px] text-muted">Nothing has ticked yet.</p> diff --git a/umtool/components/series/LearnedSpellings.tsx b/umtool/components/series/LearnedSpellings.tsx @@ -0,0 +1,349 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useRef, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { LitList, type LitDetail } from "@/components/ui/lit-list"; +import { LitLine } from "@/components/ui/lit-line"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import type { LearnedRow, LearnedView, PromotePlanView } from "@/lib/research/learned-types"; +import { cn } from "@/lib/utils"; + +// --------------------------------------------------------------------------- +// LEARNED SPELLINGS (plans/umtool-redesign.md, R6.3): how the transcripts +// mishear the names a watch watches, as the watch learned them -- proposed by +// the triage model or heard by its judge, kept only once the code found the +// spelling in scope and the judge, quoting the line, said it means the name. +// +// ONE lit list (spelling -> name, its hits, where it came from; "suggest +// removing" when its candidates were dismissed run after run; "idle" when its +// name left the terms). Beside it the lit spelling's PROVING LINE on the +// reader surface with its cite, and its two actions, each plan-then-confirm: +// Remove never learned again (`report-schedule unlearn`) +// Promote to search alias the corpus-wide aliases are the operator's: the +// plan names the list (global or a site's), the +// alias as it would be written, then Confirm +// promote (`report-schedule promote-alias`) +// "Propose spellings" runs the proposal pass now (`report-schedule learn`). +// Every write is the editor's, through POST /api/schedules; the page re-reads. +// +// Labels are contracts (e2e/learned-spellings.spec.ts): the list "Learned +// spellings", the buttons "Remove", "Confirm remove", "Promote to search +// alias", "Confirm promote", "Keep it", "Propose spellings", the regions +// "remove <spelling>" and "promote <spelling>", the select "Alias list". +// --------------------------------------------------------------------------- + +const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 10) : ""); + +async function ask(body: Record<string, unknown>): Promise<Record<string, unknown>> { + const r = await fetch("/api/schedules", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const b = (await r.json().catch(() => ({}))) as Record<string, unknown> & { error?: string }; + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + return b; +} + +/** Source words: the reader surface. */ +function Paper({ children, className, ...props }: React.ComponentProps<"div">) { + return ( + <div className={cn("rounded-[2px] bg-reader px-3.5 py-2.5 text-reader-ink shadow-[inset_0_0_0_1px_var(--reader-edge)]", className)} {...props}> + {children} + </div> + ); +} + +const DROP_WORDS: Record<string, string> = { + "no-hits": "no hits", + "not-the-name": "not the name", + "not-verbatim": "not verbatim", + known: "known", + blocked: "removed", + cap: "past the cap", + invalid: "not a spelling", + unread: "not read", +}; + +export default function LearnedSpellings({ view }: { view: LearnedView }) { + const router = useRouter(); + const hydrated = useHydrated(); + const [litId, setLitId] = useState<string | null>(view.rows[0]?.spelling ?? null); + const [busy, setBusy] = useState<string | null>(null); + const [status, setStatus] = useState<{ text: string; tone: "ok" | "error" } | null>(null); + const [removing, setRemoving] = useState(false); + const [plan, setPlan] = useState<PromotePlanView | null>(null); + const [target, setTarget] = useState("global"); + const lit: LearnedRow | null = view.rows.find((r) => r.spelling === litId) ?? view.rows[0] ?? null; + const onLight = useCallback((d: LitDetail) => { + setLitId(d.id); + setRemoving(false); + setPlan(null); + }, []); + const confirmRemoveRef = useRef<HTMLButtonElement>(null); + const confirmPromoteRef = useRef<HTMLButtonElement>(null); + useEffect(() => { + if (removing) confirmRemoveRef.current?.focus(); + }, [removing]); + useEffect(() => { + if (plan && !plan.refused) confirmPromoteRef.current?.focus(); + }, [plan]); + + const act = async (what: string, body: Record<string, unknown>, done?: (b: Record<string, unknown>) => void) => { + setBusy(what); + setStatus(null); + try { + const b = await ask({ id: view.schedule, ...body }); + done?.(b); + } catch (e) { + setStatus({ tone: "error", text: (e as Error).message }); + } finally { + setBusy(null); + } + }; + + const askPlan = (to: string) => { + if (!lit) return; + setTarget(to); + void act("plan", { action: "promote-alias", spelling: lit.spelling, ...(to === "global" ? {} : { site: to }) }, (b) => setPlan((b.plan as PromotePlanView) ?? null)); + }; + + return ( + <div className="grid gap-3" data-learned={view.schedule}> + {view.rows.length === 0 ? ( + <p className="m-0 text-[12.5px] text-muted" data-learned-empty=""> + {view.names.length + ? `Nothing learned yet. ${view.lastPass ? `The last proposal pass (${day(view.lastPass.at)}) kept nothing.` : "No proposal pass has run."} It asks about ${view.names.slice(0, 6).join(", ")}${view.names.length > 6 ? ` and ${view.names.length - 6} more` : ""}.` + : "No name in the terms to learn spellings of: a literal alternative with a capital letter, or a phrase."} + </p> + ) : ( + <div className="grid grid-cols-[minmax(260px,380px)_minmax(0,1fr)] gap-x-5"> + <LitList label="Learned spellings" onLight={onLight} className="min-w-0"> + {view.rows.map((r) => ( + <LitLine + key={r.spelling} + id={r.spelling} + data-learned-spelling={r.spelling} + data-learned-source={r.source} + {...(r.suggestRemoving ? { "data-suggest-removing": "" } : {})} + {...(r.promoted ? { "data-promoted": r.promoted.to } : {})} + className={cn("grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-x-2 py-[7px]", r.idle && "opacity-60")} + > + <span className="min-w-0"> + <span className="block truncate text-[13px] text-text"> + <span className="font-serif">“{r.spelling}”</span> <span className="text-muted-2">→</span> {r.means} + </span> + <small className="block truncate text-[11px] text-muted-2"> + <span className="font-mono text-meter">{r.hits}</span> recording{r.hits === 1 ? "" : "s"} + {r.partial ? " at least" : ""} · {r.source} + {r.source === "heard" && r.k ? ` (triage ${r.k})` : ""} + </small> + </span> + <span className="flex items-center gap-1"> + {r.suggestRemoving && <span className={badgeVariants({ variant: "state", size: "sm" })}>suggest removing</span>} + {r.idle && <span className={badgeVariants({ variant: "info", size: "sm" })}>idle</span>} + {r.promoted && <span className={badgeVariants({ variant: "on", size: "sm" })}>alias</span>} + </span> + </LitLine> + ))} + </LitList> + {lit && ( + <section className="grid min-w-0 content-start gap-2.5" aria-label={`learned spelling ${lit.spelling}`} data-learned-detail={lit.spelling}> + <Paper data-learned-quote=""> + <p className="m-0 font-serif text-[14px] leading-snug">“{lit.quote}”</p> + </Paper> + <p className="m-0 text-[12px] text-text-2" data-learned-cite={lit.cite}> + {lit.url ? ( + <a href={lit.url} target="_blank" rel="noreferrer" className="ink-link font-mono text-[11.5px]"> + {lit.cite} + </a> + ) : ( + <span className="font-mono text-[11.5px]">{lit.cite}</span> + )} + {lit.title ? <span className="text-muted"> · {lit.title}</span> : null} + </p> + <p className="m-0 text-[12px] text-muted"> + “{lit.spelling}” means {lit.means} · in <span className="font-mono text-meter">{lit.hits}</span> recording{lit.hits === 1 ? "" : "s"} + {lit.lines ? ` (${lit.lines} line${lit.lines === 1 ? "" : "s"})` : ""} + {lit.partial ? ", at least" : ""} · {lit.source === "heard" ? `heard by the judge${lit.k ? ` in triage ${lit.k}` : ""}` : "proposed by the model"} · learned {day(lit.at)} + {lit.uses?.length ? ` · last ${lit.uses.length} run${lit.uses.length === 1 ? "" : "s"}: ${lit.uses.map((u) => `${u.flagged}/${u.candidates}`).join(", ")} flagged` : ""} + {lit.idle ? " · idle: its name is no longer in the terms" : ""} + {lit.promoted ? ` · promoted to ${lit.promoted.to === "global" ? "the global aliases" : `${lit.promoted.to}'s aliases`} (${lit.promoted.alias})` : ""} + </p> + {lit.suggestRemoving && ( + <p className="m-0 text-[12px] text-text-2" data-learned-suggestion=""> + Its candidates were dismissed in each of its last runs with none flagged: suggested for removal. + </p> + )} + {!removing && !plan && ( + <div className="flex flex-wrap items-center gap-2"> + <Button size="sm" variant="outline" disabled={!hydrated || busy !== null} data-learned-remove="" onClick={() => setRemoving(true)}> + Remove + </Button> + <Button size="sm" variant="outline" disabled={!hydrated || busy !== null} data-learned-promote="" onClick={() => askPlan("global")}> + {busy === "plan" ? "Planning…" : "Promote to search alias"} + </Button> + </div> + )} + {removing && ( + <section + role="region" + aria-label={`remove ${lit.spelling}`} + className="rounded-[3px] border border-seam-2 bg-ink p-3 text-[12px]" + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + setRemoving(false); + } + }} + > + <p className="m-0 font-medium"> + Remove “{lit.spelling}” from this watch. It is never learned again{lit.promoted ? "; the alias it was promoted to stays" : ""}. + </p> + <div className="mt-2 flex gap-2"> + <Button + ref={confirmRemoveRef} + size="sm" + variant="outline" + disabled={busy !== null} + onClick={() => + void act("remove", { action: "unlearn", spelling: lit.spelling }, () => { + setRemoving(false); + setStatus({ tone: "ok", text: `Removed “${lit.spelling}”` }); + router.refresh(); + }) + } + > + {busy === "remove" ? "Removing…" : "Confirm remove"} + </Button> + <Button size="sm" variant="quiet" onClick={() => setRemoving(false)}> + Keep it + </Button> + </div> + </section> + )} + {plan && ( + <section + role="region" + aria-label={`promote ${lit.spelling}`} + data-promote-action={plan.action} + data-promote-to={busy === "plan" ? "" : plan.to} + className="grid gap-2 rounded-[3px] border border-seam-2 bg-ink p-3 text-[12px]" + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + setPlan(null); + } + }} + > + <label className="flex items-center gap-2"> + <span className="text-muted">Alias list</span> + <select + aria-label="Alias list" + value={target} + disabled={busy !== null} + onChange={(e) => askPlan(e.target.value)} + className="rounded-[3px] border border-seam-2 bg-panel px-2 py-1 text-[12px]" + > + <option value="global">Global (every site)</option> + {plan.sites.map((s) => ( + <option key={s} value={s}> + {s} + </option> + ))} + </select> + <span className="font-mono text-[11px] text-muted-2" data-promote-file=""> + {plan.file} + </span> + </label> + <p className="m-0 font-medium" data-promote-why=""> + {plan.action === "none" ? "Nothing to write: " : ""} + {plan.action === "none" ? plan.why : `${plan.why.charAt(0).toUpperCase()}${plan.why.slice(1)}`}. + </p> + <dl className="m-0 grid grid-cols-[90px_minmax(0,1fr)] gap-x-3 gap-y-1" data-promote-alias={plan.alias.id}> + <dt className="text-muted">Label</dt> + <dd className="m-0">{plan.alias.label}</dd> + <dt className="text-muted">Triggers</dt> + <dd className="m-0 font-mono text-[11.5px]">{plan.alias.triggers.join(", ")}</dd> + <dt className="text-muted">Suggestion</dt> + <dd className="m-0 break-all font-mono text-[11.5px]">{plan.alias.suggestion}</dd> + <dt className="text-muted">Note</dt> + <dd className="m-0 text-text-2">{plan.alias.note ?? ""}</dd> + </dl> + {plan.refused && ( + <p role="alert" className="m-0 text-reject-text"> + {plan.refused} + </p> + )} + <div className="flex gap-2"> + <Button + ref={confirmPromoteRef} + size="sm" + variant="outline" + disabled={!!plan.refused || busy !== null} + onClick={() => + void act("promote", { action: "promote-alias", spelling: lit.spelling, confirm: true, ...(target === "global" ? {} : { site: target }) }, () => { + setPlan(null); + setStatus({ tone: "ok", text: `“${lit.spelling}” is a search alias in ${target === "global" ? "the global list" : `${target}'s list`}` }); + router.refresh(); + }) + } + > + {busy === "promote" ? "Promoting…" : "Confirm promote"} + </Button> + <Button size="sm" variant="quiet" onClick={() => setPlan(null)}> + Keep it + </Button> + </div> + </section> + )} + </section> + )} + </div> + )} + <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 text-[12px] text-muted" data-learned-pass=""> + <Button + size="sm" + variant="outline" + disabled={!hydrated || busy !== null || !view.names.length} + data-learned-propose="" + onClick={() => + void act("learn", { action: "learn" }, (b) => { + const p = b.plan as { names?: string[] } | undefined; + setStatus({ tone: "ok", text: `Proposal pass queued — job ${String(b.jobId ?? "")}: asks about ${(p?.names ?? []).join(", ")}` }); + router.refresh(); + }) + } + > + {busy === "learn" ? "Proposing…" : "Propose spellings"} + </Button> + <span> + {view.rows.length} of {view.cap} kept + {view.blocked.length ? ` · ${view.blocked.length} removed` : ""} + {view.lastPass + ? ` · last pass ${day(view.lastPass.at)} (${view.lastPass.trigger}): ${view.lastPass.status === "done" ? `${view.lastPass.proposed} proposed, ${view.lastPass.kept} kept, ${view.lastPass.dropped} dropped` : view.lastPass.status}` + : " · no proposal pass yet"} + </span> + {status && ( + <span role={status.tone === "error" ? "alert" : "status"} className={cn("basis-full", status.tone === "error" ? "text-reject-text" : "text-text-2")} data-learned-status=""> + {status.text} + </span> + )} + </div> + {view.dropped.length > 0 && ( + <details className="text-[12px]" data-learned-dropped=""> + <summary className="cursor-pointer text-muted">Dropped, newest first ({view.dropped.length})</summary> + <ul className="m-0 mt-1 grid list-none gap-0.5 p-0 text-text-2"> + {view.dropped.map((d, i) => ( + <li key={`${d.spelling}-${i}`} className="flex min-w-0 items-baseline gap-2"> + <span className="truncate"> + “{d.spelling}” → {d.means} + </span> + <span className={badgeVariants({ variant: "info", size: "sm" })}>{DROP_WORDS[d.reason] ?? d.reason}</span> + <small className="truncate text-muted-2">{d.why}</small> + </li> + ))} + </ul> + </details> + )} + </div> + ); +} diff --git a/umtool/components/series/TriageView.tsx b/umtool/components/series/TriageView.tsx @@ -274,6 +274,12 @@ export default function TriageView({ initial }: { initial: TriageRunView }) { · {t0.untranscribed} without a transcript yet </span> ) : null} + {t0.learned?.spellings.length ? ( + <span data-tier0-learned={t0.learned.spellings.length} title={t0.learned.spellings.map((x) => `“${x}”`).join(", ")}> + {" "} + · terms + {t0.learned.spellings.length} learned ({t0.learned.matched} by a learned spelling alone) + </span> + ) : null} {t0.cut.length ? <span className="text-doubt-text"> · {t0.cut.length} past the cap</span> : null} {t0.partial ? ( <span className="text-doubt-text" data-tier0-partial=""> @@ -405,7 +411,10 @@ export default function TriageView({ initial }: { initial: TriageRunView }) { <code className="font-mono text-[11px] text-muted-2">{c.id}</code> <span className="truncate">{c.title ?? ""}</span> <span className="shrink-0 text-muted-2"> - {c.date ?? ""} · {c.by.join(" + ")} + {c.date ?? ""} ·{" "} + <span {...(c.learned?.length ? { "data-candidate-learned": c.learned.join("|") } : {})}> + {c.by.map((x) => (x === "learned" && c.learned?.length ? `learned ${c.learned.map((l) => `“${l}”`).join(", ")}` : x)).join(" + ")} + </span> {c.tags?.length ? ` (${c.tags.join(", ")})` : ""} {c.matches ? ` · ${c.matches} line${c.matches === 1 ? "" : "s"}` : ""} </span> diff --git a/umtool/e2e/learned-spellings.spec.ts b/umtool/e2e/learned-spellings.spec.ts @@ -0,0 +1,181 @@ +import { test, expect, type Page } from "@playwright/test"; +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// LEARNED SPELLINGS (plans/umtool-redesign.md, R6.3) over the editor stub, +// which runs the REAL report-schedule action and learned.json writer over the +// fixture's article store (common/testing/schedule/opsStub.ts). A create of a +// watch whose terms name someone runs the stub's proposal pass at once: "Vote +// Rigg" kept (proposed, its proving line sitechan/sv1), "Vote Rick" kept +// (heard; its candidates dismissed four runs running — suggest removing), +// "Boat Rig" dropped (no hits). +// +// the series page's Learned spellings: the lit list, the proving line on the +// reader with its cite, suggest removing · Promote to search alias: the plan +// (the list chosen, the alias as it would be written), Confirm promote — +// written through the editor's alias writer · Remove: plan, then confirm — +// gone, and a new pass does not learn it again · the triage page names the +// candidate a learned spelling brought +// +// WRITES articles/.series/r63-*, articles/.triage/r63-*, <fixture>/search-aliases.json +// (removed after) +// +// R63_SHOTS=<dir> also saves the screenshots (1366×768, both themes). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const ARTICLES = path.join(FIXTURE, "articles"); +const ALIASES = path.join(FIXTURE, "search-aliases.json"); +const SHOTS = process.env.R63_SHOTS ?? ""; +const learned = (id: string) => JSON.parse(readFileSync(path.join(ARTICLES, ".series", id, "learned.json"), "utf8")); + +function clean() { + for (const dir of [path.join(ARTICLES, ".series"), path.join(ARTICLES, ".triage")]) { + if (!existsSync(dir)) continue; + for (const n of readdirSync(dir).filter((x) => x.startsWith("r63-"))) rmSync(path.join(dir, n), { recursive: true, force: true }); + } + rmSync(ALIASES, { force: true }); +} + +async function shoot(page: Page, name: string) { + if (!SHOTS) return; + mkdirSync(SHOTS, { recursive: true }); + const was = await page.evaluate(() => document.documentElement.getAttribute("data-theme")); + await page.setViewportSize({ width: 1366, height: 768 }); + for (const theme of ["dark", "light"] as const) { + await page.evaluate((t) => document.documentElement.setAttribute("data-theme", t), theme); + await page.waitForTimeout(150); + await page.screenshot({ path: path.join(SHOTS, `${name}-1366x768-${theme}.png`) }); + } + await page.evaluate((t) => (t ? document.documentElement.setAttribute("data-theme", t) : document.documentElement.removeAttribute("data-theme")), was); + await page.setViewportSize({ width: 1280, height: 720 }); +} + +async function api(page: Page, body: Record<string, unknown>) { + const r = await page.request.post("/api/schedules", { data: body }); + const b = (await r.json()) as Record<string, unknown>; + expect(r.ok(), JSON.stringify(b)).toBe(true); + return b; +} + +test.describe.configure({ mode: "serial" }); + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + clean(); + await warm(playwright, [urls.seriesHref("r63-none"), urls.triageHref("r63-none", 1), "/"]); +}); +test.afterAll(() => clean()); + +test("a watch's Learned spellings: made by its first proposal pass; the lit list, the proving line with its cite, suggest removing", async ({ page }) => { + test.setTimeout(90_000); + await page.goto("/"); + const made = await api(page, { action: "create", shape: "watch", id: "r63-watch", topic: "R63 watch", question: "Who says the vote was rigged?", channels: ["sitechan"], cadence: "weekly mon 06:00", terms: "Ada Ballot|rigged", regex: true }); + expect(made.learn).toMatchObject({ names: ["Ada Ballot"] }); + expect(learned("r63-watch")).toMatchObject({ owner: "r63-watch", termsKey: "re:Ada Ballot|rigged", learned: [{ spelling: "Vote Rigg" }, { spelling: "Vote Rick" }], dropped: [{ spelling: "Boat Rig", reason: "no-hits" }] }); + await page.goto(urls.seriesHref("r63-watch")); + const panel = page.locator("[data-series-learned]"); + await expect(panel).toContainText("terms + 2 learned"); + const list = panel.getByRole("group", { name: "Learned spellings" }); + await expect(list.locator("[data-learned-spelling]")).toHaveCount(2); + const rigg = list.locator("[data-learned-spelling='Vote Rigg']"); + await expect(rigg).toContainText("“Vote Rigg” → Ada Ballot"); + await expect(rigg).toContainText("2 recordings · proposed"); + const rick = list.locator("[data-learned-spelling='Vote Rick']"); + await expect(rick).toHaveAttribute("data-suggest-removing", ""); + await expect(rick).toContainText("suggest removing"); + // The lit one's proving line on the reader, its cite. + await expect(rigg).toHaveAttribute("data-lit", ""); + const detail = panel.locator("[data-learned-detail='Vote Rigg']"); + await expect(detail.locator("[data-learned-quote]")).toHaveText("“The vote was rigged and everybody knew.”"); + await expect(detail.locator("[data-learned-cite]")).toHaveAttribute("data-learned-cite", "sitechan/sv1 at 0:03"); + await expect(detail.getByRole("link", { name: "sitechan/sv1 at 0:03" })).toHaveAttribute("href", "https://priv.example/?v=sitechan%2Fsv1&t=3"); + // j moves the light (focus in the list): the heard one, with why it is suggested for removal. + await rigg.focus(); + await page.keyboard.press("j"); + await expect(rick).toHaveAttribute("data-lit", ""); + await expect(panel.locator("[data-learned-detail='Vote Rick']")).toContainText("heard by the judge in triage 1"); + await expect(panel.locator("[data-learned-suggestion]")).toContainText("suggested for removal"); + await expect(panel.locator("[data-learned-pass]")).toContainText("2 of 20 kept · last pass"); + await panel.locator("[data-learned-dropped] summary").click(); + await expect(panel.locator("[data-learned-dropped]")).toContainText("“Boat Rig” → Ada Ballot"); + await expect(panel.locator("[data-learned-dropped]")).toContainText("no hits"); + await page.keyboard.press("Escape"); + await rigg.click(); + await shoot(page, "learned-spellings"); +}); + +test("Promote to search alias: the plan (the list, the alias as written), then Confirm promote — through the editor's alias writer", async ({ page }) => { + test.setTimeout(90_000); + await page.goto(urls.seriesHref("r63-watch")); + const panel = page.locator("[data-series-learned]"); + await panel.locator("[data-learned-spelling='Vote Rigg']").click(); + await panel.getByRole("button", { name: "Promote to search alias" }).click(); + const plan = panel.getByRole("region", { name: "promote Vote Rigg" }); + await expect(plan).toHaveAttribute("data-promote-action", "new"); + await expect(plan).toHaveAttribute("data-promote-to", "global"); + await expect(plan.locator("[data-promote-why]")).toHaveText('A new alias "Ada Ballot" firing on "Ada Ballot" and "Vote Rigg".'); + await expect(plan).toContainText("ada ballot, vote rigg"); + await expect(plan).toContainText("\\bAda Ballot\\b|\\bVote Rigg\\b"); + await expect(plan).toContainText("learned by watch r63-watch from sitechan/sv1 at 0:03"); + // The sites are offered; choosing one asks for its plan (nothing written). + const select = plan.getByRole("combobox", { name: "Alias list" }); + await expect(select.locator("option")).toHaveText(["Global (every site)", "priv", "pub"]); + await select.selectOption("priv"); + await expect(plan).toHaveAttribute("data-promote-to", "priv"); + await expect(plan).toContainText("sites/priv/search-aliases.json"); + await select.selectOption("global"); + await expect(plan).toHaveAttribute("data-promote-to", "global"); + await expect(plan.locator("[data-promote-file]")).toHaveText("search-aliases.json"); + expect(existsSync(ALIASES)).toBe(false); + await shoot(page, "learned-promote-plan"); + await expect(plan.getByRole("button", { name: "Confirm promote" })).toBeFocused(); + await plan.getByRole("button", { name: "Confirm promote" }).click(); + await expect(panel.locator("[data-learned-status]")).toContainText("“Vote Rigg” is a search alias in the global list"); + await expect(panel.locator("[data-learned-spelling='Vote Rigg']")).toHaveAttribute("data-promoted", "global"); + const written = JSON.parse(readFileSync(ALIASES, "utf8")); + expect(written.aliases.at(-1)).toEqual({ id: "ada-ballot", label: "Ada Ballot", triggers: ["ada ballot", "vote rigg"], suggestion: "\\bAda Ballot\\b|\\bVote Rigg\\b", useRegex: true, enabled: true, note: "learned by watch r63-watch from sitechan/sv1 at 0:03" }); + // Keep it closes a plan, nothing written. + await panel.locator("[data-learned-spelling='Vote Rick']").click(); + await panel.getByRole("button", { name: "Promote to search alias" }).click(); + await panel.getByRole("region", { name: "promote Vote Rick" }).getByRole("button", { name: "Keep it" }).click(); + await expect(panel.getByRole("region", { name: "promote Vote Rick" })).toHaveCount(0); +}); + +test("Remove: plan, then confirm — gone, blocked, and a new proposal pass does not learn it again", async ({ page }) => { + test.setTimeout(90_000); + await page.goto(urls.seriesHref("r63-watch")); + const panel = page.locator("[data-series-learned]"); + await panel.locator("[data-learned-spelling='Vote Rick']").click(); + await panel.getByRole("button", { name: "Remove" }).click(); + const region = panel.getByRole("region", { name: "remove Vote Rick" }); + await expect(region).toContainText("It is never learned again"); + await expect(region.getByRole("button", { name: "Confirm remove" })).toBeFocused(); + await region.getByRole("button", { name: "Confirm remove" }).click(); + await expect(panel.locator("[data-learned-spelling]")).toHaveCount(1); + expect(learned("r63-watch").blocked).toMatchObject([{ spelling: "Vote Rick", means: "Ada Ballot" }]); + await panel.getByRole("button", { name: "Propose spellings" }).click(); + await expect(panel.locator("[data-learned-status]")).toContainText("Proposal pass queued"); + await expect(panel.locator("[data-learned-status]")).toContainText("asks about Ada Ballot"); + await page.reload(); + await expect(page.locator("[data-series-learned] [data-learned-spelling]")).toHaveCount(1); + const f = learned("r63-watch"); + expect(f.learned.map((l: { spelling: string }) => l.spelling)).toEqual(["Vote Rigg"]); + expect(f.dropped.at(-1)).toMatchObject({ spelling: "Vote Rick", reason: "blocked" }); + expect(f.passes.map((p: { trigger: string }) => p.trigger)).toEqual(["create", "ops"]); +}); + +test("the triage page names the candidate a learned spelling brought (terms + N learned)", async ({ page }) => { + test.setTimeout(90_000); + await page.goto("/"); + await api(page, { action: "tick-now", id: "r63-watch" }); + await page.goto(urls.triageHref("r63-watch", 1)); + await expect(page.locator("[data-tier0-learned]")).toContainText("terms + 1 learned (1 by a learned spelling alone)"); + await expect(page.locator("[data-candidate-learned='Vote Rigg']")).toHaveText("learned “Vote Rigg”"); + await shoot(page, "learned-triage"); +}); diff --git a/umtool/lib/research/learned-types.ts b/umtool/lib/research/learned-types.ts @@ -0,0 +1,47 @@ +// A WATCH'S LEARNED SPELLINGS, as umtool's series page reads them +// (plans/umtool-redesign.md, R6.3). The editor writes learned.json (its one +// writer, common/controller/learnedSpellings.ts); umtool reads it and acts +// through `report-schedule` (learn, unlearn, promote-alias). Types only: safe +// for a client component. + +import type { LearnedDrop, LearnedPass, LearnedSpelling } from "yt-dlp-transcript-common/lib/report/draft/triage/learned"; + +export type { LearnedDrop, LearnedPass, LearnedSpelling }; + +export type LearnedRow = LearnedSpelling & { + // Its candidates were dismissed run after run: suggested for removal (never removed on its own). + suggestRemoving: boolean; + // Its name is no longer in the terms: kept, not used. + idle: boolean; + // "<channel>/<recording> at mm:ss". + cite: string; +}; + +export type LearnedView = { + schedule: string; + rows: LearnedRow[]; + blocked: { spelling: string; means?: string; at: string }[]; + // The newest drops first (at most 12). + dropped: LearnedDrop[]; + lastPass: LearnedPass | null; + proposedAt: string | null; + // The names the terms watch (what a pass asks about). + names: string[]; + cap: number; +}; + +/** What promote-alias answers as its plan (common/controller/learnedSpellings.ts PromotePlan). */ +export type PromotePlanView = { + id: string; + spelling: string; + means: string; + to: string; + file: string; + action: "new" | "trigger" | "none"; + alias: { id: string; label: string; triggers: string[]; suggestion: string; useRegex: boolean; note?: string }; + before: { id: string; label: string; triggers: string[]; suggestion: string } | null; + why: string; + cite: string; + sites: string[]; + refused: string | null; +}; diff --git a/umtool/lib/research/learned.test.ts b/umtool/lib/research/learned.test.ts @@ -0,0 +1,75 @@ +// Learned spellings, umtool's read (plans/umtool-redesign.md, R6.3): a watch's +// learned.json as the series page lists it — each spelling with its cite, the +// one whose candidates were dismissed run after run marked "suggest removing", +// one whose name left the terms idle; the drops newest first. Temp stores only. + +import { after, before, 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 { Paths } from "yt-dlp-transcript-common/lib/paths"; +import { createSchedule, parseCreate } from "yt-dlp-transcript-common/controller/reportSchedule"; +import { recordLearnPass } from "yt-dlp-transcript-common/controller/learnedSpellings"; +import { readSchedule } from "yt-dlp-transcript-common/lib/report/schedule/store"; +import type { LearnedSpelling } from "yt-dlp-transcript-common/lib/report/draft/triage/learned"; + +let tmp: string; +let paths: Paths; +let lib: typeof import("./learned"); + +const at = "2026-10-14T10:00:00.000Z"; +const spelling = (s: string, means: string, over: Partial<LearnedSpelling> = {}): LearnedSpelling => ({ spelling: s, means, quote: `then ${s} said so`, recording: "v1", channel: "chan-a", start: 65, hits: 2, source: "proposed", at, ...over }); + +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-learned-")); + process.env.ARTICLES_DIR = path.join(tmp, "articles"); + process.env.REPORTS_DIR = path.join(tmp, "reports"); + process.env.SITES_DIR = path.join(tmp, "sites"); + process.env.CHANNELS_DIR = path.join(tmp, "channels"); + process.env.SETTINGS_FILE = path.join(tmp, "settings.json"); + paths = { articlesDir: path.join(tmp, "articles"), exportIndexDir: path.join(tmp, "idx") } as unknown as Paths; + await createSchedule(parseCreate({ shape: "watch", id: "guest-watch", topic: "Guest watch", channels: ["chan-a"], cadence: "weekly mon 06:00", tz: "UTC", terms: "Pia Tartlet|Ross Crumb", regex: true }), { paths }); + const s = (await readSchedule("guest-watch", paths))!; + await recordLearnPass( + s, + { + pass: { at, trigger: "create", status: "done", model: "qwen3:8b", names: ["Pia Tartlet", "Ross Crumb"], notAsked: [], proposed: 4, kept: 0, dropped: 0, usd: 0 }, + kept: [ + spelling("pia tart lit", "Pia Tartlet", { url: "https://x.example/?v=chan-a%2Fv1&t=65" }), + spelling("ross crum", "Ross Crumb", { source: "heard", k: 2, uses: [1, 2, 3, 4].map((k) => ({ k, at, candidates: 1, flagged: 0 })) }), + spelling("old name", "Gone Person"), + ], + dropped: [ + { spelling: "pea tartlet", means: "Pia Tartlet", source: "proposed", reason: "no-hits", why: "does not occur in scope", at }, + { spelling: "ross", means: "Ross Crumb", source: "proposed", reason: "not-the-name", why: "another Ross", at }, + ], + termsKey: "re:Pia Tartlet|Ross Crumb", + }, + paths, + new Date(at), + ); + lib = await import("./learned"); +}); +after(() => rm(tmp, { recursive: true, force: true })); + +test("readScheduleLearned: each spelling with its cite and state; drops newest first; the names a pass asks about", async () => { + const s = (await readSchedule("guest-watch", paths))!; + const v = await lib.readScheduleLearned(s); + assert.deepEqual( + v.rows.map((r) => [r.spelling, r.means, r.cite, r.suggestRemoving, r.idle]), + [ + ["pia tart lit", "Pia Tartlet", "chan-a/v1 at 1:05", false, false], + ["ross crum", "Ross Crumb", "chan-a/v1 at 1:05", true, false], + ["old name", "Gone Person", "chan-a/v1 at 1:05", false, true], + ], + ); + assert.deepEqual(v.names, ["Pia Tartlet", "Ross Crumb"]); + assert.deepEqual(v.dropped.map((d) => d.spelling), ["ross", "pea tartlet"]); + assert.equal(v.lastPass?.trigger, "create"); + assert.equal(v.lastPass?.kept, 3); + assert.equal(v.cap, 20); + // A schedule with nothing learned reads as an empty list. + const none = await lib.readScheduleLearned({ ...s, id: "no-such" }); + assert.deepEqual([none.rows.length, none.lastPass], [0, null]); +}); diff --git a/umtool/lib/research/learned.ts b/umtool/lib/research/learned.ts @@ -0,0 +1,31 @@ +import { LEARNED_CAP, activeLearned, learnedCite, namesOf, suggestRemoving } from "yt-dlp-transcript-common/lib/report/draft/triage/learned"; +import { readLearned } from "yt-dlp-transcript-common/lib/report/draft/triage/learnedStore"; +import type { Schedule } from "yt-dlp-transcript-common/lib/report/schedule/types"; +import { sitesPaths } from "../articles/sites"; +import type { LearnedView } from "./learned-types"; + +// --------------------------------------------------------------------------- +// LEARNED SPELLINGS, umtool's side (plans/umtool-redesign.md, R6.3). The +// editor proposes, confirms and keeps a watch's spellings in learned.json +// beside the schedule (its one writer). umtool READS it here for the series +// page; Remove and Promote go through `report-schedule` (POST /api/schedules). +// +// SERVER ONLY. +// --------------------------------------------------------------------------- + +/** A schedule's learned spellings for its page: each with its state (suggest removing, idle) and cite. */ +export async function readScheduleLearned(s: Pick<Schedule, "id" | "shape" | "scope">): Promise<LearnedView> { + const f = await readLearned(sitesPaths(), s).catch(() => null); + const names = namesOf(s.scope.terms ?? null, s.scope.regex === true); + const active = new Set(activeLearned(f, names).map((l) => l.spelling)); + return { + schedule: s.id, + rows: (f?.learned ?? []).map((l) => ({ ...l, suggestRemoving: suggestRemoving(l), idle: !active.has(l.spelling), cite: learnedCite(l) })), + blocked: f?.blocked ?? [], + dropped: [...(f?.dropped ?? [])].reverse().slice(0, 12), + lastPass: f?.passes.at(-1) ?? null, + proposedAt: f?.proposedAt ?? null, + names, + cap: LEARNED_CAP, + }; +}