// 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 { modelLogged } from "./jobModelLog"; 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, proveByHand, runLearnPass } from "../lib/report/draft/triage/confirm"; import { CONFIRM_WINDOWS, LEARNED_CAP, NAMES_PER_PASS, PROPOSALS_PER_NAME, coveredByTerms, 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, type HandProver } 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 { 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 { 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)` : 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 } | { 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 { 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: modelLogged({ paths, task: "learn" }, (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 }; } async function runLearnJob( o: { id: string; trigger: LearnTrigger; plan: LearnPlan; maxUsd?: number; jobId: string; onLog: (l: string) => void; signal: AbortSignal }, deps: ReportDraftDeps, ): Promise { 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>["kept"] = []; let dropped: Awaited>["dropped"] = []; let proposed = 0; let corpus: Awaited> | 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 = (system: string, user: string, schema: object) => structuredAnswer({ 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>[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, covered: coveredByTerms(s.scope.terms, s.scope.regex === true) }, { 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}` } : {}), }; }; } /** * A spelling added by hand, proved over the corpus a sweep of the scope would * read (release 32 R2): the count and the proving line, code only — no model, * no job (a count is one scan). The editor binds this into `report-schedule * {"action":"add-spelling"}` (controller/learnedSpellings.ts addSpellingByHand). */ export function handProver(deps: Pick): HandProver { return async (i) => { const gen = (deps.settings ?? getSettings)().generation; const where = await resolveCorpus({}, i.scope.channels, deps.paths, gen); const c = await deps.corpusTools(where.source); try { const count = c.countPhrases ? (a: Parameters>[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)"); return await proveByHand(i, { corpus: c, count }); } finally { await c.close().catch(() => {}); } }; }