"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`). // "Add spelling" (release 32 R2) is the same by hand, with no model: the // spelling and the watched name it means; the editor counts it in scope and // finds its proving line by code (`report-schedule add-spelling`), and keeps it // as "added by hand" only when it occurs. // 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", "Add spelling" // (its fields "spelling to add" and "the name it means"), the regions // "remove " and "promote ", the select "Alias list". // --------------------------------------------------------------------------- const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 10) : ""); async function ask(body: Record): Promise> { 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 & { 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 (
{children}
); } const DROP_WORDS: Record = { "no-hits": "no hits", "not-the-name": "not the name", "not-verbatim": "not verbatim", "too-few": "too few", 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(view.rows[0]?.spelling ?? null); const [busy, setBusy] = useState(null); const [status, setStatus] = useState<{ text: string; tone: "ok" | "error" } | null>(null); const [removing, setRemoving] = useState(false); const [plan, setPlan] = useState(null); const [target, setTarget] = useState("global"); const [adding, setAdding] = useState(false); const [newSpelling, setNewSpelling] = useState(""); const [means, setMeans] = useState(view.names[0] ?? ""); 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(null); const confirmPromoteRef = useRef(null); useEffect(() => { if (removing) confirmRemoveRef.current?.focus(); }, [removing]); useEffect(() => { if (plan && !plan.refused) confirmPromoteRef.current?.focus(); }, [plan]); const act = async (what: string, body: Record, done?: (b: Record) => 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 (
{view.rows.length === 0 ? (

{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."}

) : (
{view.rows.map((r) => ( “{r.spelling}” → {r.means} {r.hits} recording{r.hits === 1 ? "" : "s"} {r.partial ? " at least" : ""} · {r.source} {r.source === "heard" && r.k ? ` (triage ${r.k})` : ""} {r.source === "hand" ? " (by hand)" : ""} {r.suggestRemoving && suggest removing} {r.idle && idle} {r.promoted && alias} ))} {lit && (

“{lit.quote}”

{lit.url ? ( {lit.cite} ) : ( {lit.cite} )} {lit.title ? · {lit.title} : null}

“{lit.spelling}” means {lit.means} · in {lit.hits} 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}` : ""}` : lit.source === "hand" ? "added by hand" : "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})` : ""}

{lit.windows?.length ? (
    {lit.windows.map((w) => (
  • {w.means ? (w.verbatim ? "the name" : "not verbatim") : "not the name"} {w.recording} {w.means && w.quote ? `“${w.quote}”` : w.reason}
  • ))}
) : null} {lit.suggestRemoving && (

Its candidates were dismissed in each of its last runs with none flagged: suggested for removal.

)} {!removing && !plan && (
)} {removing && (
{ if (e.key === "Escape") { e.preventDefault(); setRemoving(false); } }} >

Remove “{lit.spelling}” from this watch. It is never learned again{lit.promoted ? "; the alias it was promoted to stays" : ""}.

)} {plan && (
{ if (e.key === "Escape") { e.preventDefault(); setPlan(null); } }} >

{plan.action === "none" ? "Nothing to write: " : ""} {plan.action === "none" ? plan.why : `${plan.why.charAt(0).toUpperCase()}${plan.why.slice(1)}`}.

Label
{plan.alias.label}
Triggers
{plan.alias.triggers.join(", ")}
Suggestion
{plan.alias.suggestion}
Note
{plan.alias.note ?? ""}
{plan.refused && (

{plan.refused}

)}
)}
)}
)}
{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"} {status && ( {status.text} )}
{adding && (
{ e.preventDefault(); const sp = newSpelling.trim(); if (!sp || !means) return; void act("add", { action: "add-spelling", spelling: sp, means }, (b) => { const a = b.added as { spelling?: string; hits?: number; partial?: boolean } | undefined; setAdding(false); setNewSpelling(""); setLitId(a?.spelling ?? sp); setStatus({ tone: "ok", text: `Added “${a?.spelling ?? sp}” → ${means}: in ${a?.hits ?? 0}${a?.partial ? " or more" : ""} recording${a?.hits === 1 ? "" : "s"}${b.unblocked ? " (no longer removed)" : ""}` }); router.refresh(); }); }} > counted in the watch's scope; kept only when it occurs there
)} {view.dropped.length > 0 && (
Dropped, newest first ({view.dropped.length})
    {view.dropped.map((d, i) => (
  • “{d.spelling}” → {d.means} {DROP_WORDS[d.reason] ?? d.reason} {d.why}
  • ))}
)}
); }