// `report-draft {"task": "triage", …}` — the triage step as an editor job // (umtool R6; plans/umtool-redesign.md "R6 — Triage first"). The step is // lib/report/draft/triage/; this is the editor's side of it: // // enqueueTriage the run (reports/.triage///triage.json, queued, // under the article store's lock), then ONE `report-draft` // job on the model's lane: `draft:local` (the default — every // ollama call through the GPU arbiter, yielding to // transcription; ollama unloaded when the job ends) or // `draft:api` (`models.extractor`: metered, held to its cap // and the daily cap, its usage in the ledger as task // `triage`) // the job runTriage over the MCP's corpus tools (the newest build // holding the channels, as a sweep reads), the cue reader // the quote checks use. Its log ends `@@report-draft {…, // task: "triage", triage: {k, status, candidates, flagged, // dismissed, escalate, why, usd}}` // // The body: `article` is the OWNER (the schedule — or article — the run is // for), `question`, `channels` (`from`/`to`), `terms` (`regex`), `topics`, // `threshold` {strong, weak}, `since` (YYYY-MM-DD: "new" with no last run), // `ids` (the candidates, named: no scan), `windows` ({id: [{start, end}]}), // `maxCandidates`, `model`, `maxUsd`, `source`/`build`. import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { JobProgress } from "../jobs/registry"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; import { capFor, triageModelOf } from "../lib/generationSettings"; import { providerOf, unloadOllama } from "../lib/llm"; import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues"; import type { CorpusToolsLike } from "../lib/report/draft/tasks/types"; import { createTriageRun, readTriageFile, writeTriageFile } from "../lib/report/draft/triage/store"; 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"; export const TRIAGE_TASK = "triage" as const; /** The `triage` slice of the job's result marker. */ export type TriageMarker = { k: number; status: string; candidates: number; flagged: number; dismissed: number; escalate: boolean; why: string; usd: number; partial?: string }; export async function enqueueTriage(body: ReportDraftBody, deps: ReportDraftDeps): Promise { const refuse = (error: string) => ({ result: { ok: false as const, error } }); const paths = deps.paths; const gen = (deps.settings ?? getSettings)().generation; const model = triageModelOf(gen, body.model); const provider = providerOf(model) === "local" ? "local" : "api"; let maxUsd: number | undefined; if (provider === "api") { try { maxUsd = capFor(gen.caps, "sweep", body.maxUsd); } catch (e) { return refuse((e as Error).message); } const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) return refuse(refusal); } const now = (deps.now?.() ?? new Date()).toISOString(); const threshold = cleanThreshold(body.threshold, { strong: gen.triage.strong ?? DEFAULT_TRIAGE_THRESHOLD.strong, weak: gen.triage.weak ?? DEFAULT_TRIAGE_THRESHOLD.weak }); let run: TriageFile; try { run = await createTriageRun( (k) => ({ format: TRIAGE_FORMAT, version: TRIAGE_VERSION, owner: body.article, k, status: "queued", model, provider, question: body.question!, scope: { channels: body.channels ?? [], ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) }, terms: body.terms ?? null, regex: body.regex === true, topics: body.topics ?? [], threshold, since: body.since ?? null, knownCount: null, createdAt: now, cost: { tier0: 0, tier1: 0 }, summary: "queued", warnings: [], }), paths, body.article, ); } catch (e) { return refuse((e as Error).message); } const k = run.k; const result = await runManagedFunction({ kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, fn: modelLogged({ paths, task: "triage" }, (onLog, signal, setProgress, ctx) => runTriageJob({ body, k, model, provider, maxUsd, jobId: ctx.jobId, onLog, signal, setProgress }, deps)), }); const mark = async (patch: Partial) => { const cur = await readTriageFile(body.article, k, paths).catch(() => null); if (cur) await writeTriageFile({ ...cur, ...patch }, paths).catch(() => {}); }; if (!result.ok) { await mark({ status: "failed", error: result.error, summary: `failed: ${result.error}` }); return { result }; } await mark({ jobId: result.jobId }); // A job cancelled (or refused) before it ran leaves its run queued: end it. void result.done.then(async (d) => { const cur = await readTriageFile(body.article, k, paths).catch(() => null); if (cur?.status === "queued") await mark({ status: d.status === "cancelled" ? "cancelled" : "failed", error: `the job ended ${d.status} before it ran`, summary: `the job ended ${d.status} before it ran` }); }); return { result, iteration: k, triage: { owner: body.article, k } }; } async function runTriageJob( o: { body: ReportDraftBody; k: number; model: string; provider: "api" | "local"; maxUsd?: number; jobId: string; onLog: (l: string) => void; signal: AbortSignal; setProgress?: (snap: JobProgress) => void; }, deps: ReportDraftDeps, ): Promise { const { body, k, model, provider, onLog, signal } = o; const paths = deps.paths; const gen = (deps.settings ?? getSettings)().generation; onLog(`triage ${body.article}/${k} on ${model} (${provider === "api" ? `the Claude API, cap $${o.maxUsd}` : "the local model, through the GPU arbiter"})`); if (provider === "api") { const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) throw new Error(refusal); } let corpus: (CorpusToolsLike & { close(): Promise }) | null = null; let ran: Awaited> | 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 | 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}`); corpus = await deps.corpusTools(where.source); ran = await runTriage( { owner: body.article, k, ...(body.ids?.length ? { ids: body.ids } : {}), ...(body.windows ? { windows: body.windows } : {}), 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), corpus, paths, cuesOf: corpusCuesOf(corpus), log: onLog, progress: (done, total) => o.setProgress?.({ metric: "entries", initial: 0, target: Math.max(total, done), current: done }), signal, ...(deps.now ? { now: deps.now } : {}), }, ); } catch (e) { // A run that never started (no build holds the channels, …) says why. const cur = await readTriageFile(body.article, k, paths).catch(() => null); if (cur && (cur.status === "queued" || cur.status === "running")) { const msg = (e as Error).message; await writeTriageFile({ ...cur, status: signal.aborted ? "cancelled" : "failed", error: msg, summary: signal.aborted ? "cancelled" : `failed: ${msg}`, endedAt: new Date().toISOString() }, paths).catch(() => {}); } throw e; } finally { await corpus?.close().catch(() => {}); if (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}`), ); } } if (provider === "api" && ran) { const at = deps.now?.() ?? new Date(); const rows: GenerationUsageRow[] = Object.entries(ran.byModel) .filter(([, t]) => t.calls > 0) .map(([m, t]) => { const u = usageOf(t); return { at: at.toISOString(), day: utcDay(at), jobId: o.jobId, article: body.article, iteration: k, task: TRIAGE_TASK, model: m, inputTokens: u.inputTokens, outputTokens: u.outputTokens, cacheReadTokens: u.cacheReadTokens ?? 0, cacheWriteTokens: u.cacheWriteTokens ?? 0, usd: Math.round(u.usd * 10_000) / 10_000, }; }); 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, candidates: f.tier0?.candidates.length ?? 0, flagged: f.tier1?.flags.length ?? 0, dismissed: f.tier1?.dismissed.length ?? 0, escalate: !!f.escalation?.escalate, why: f.escalation?.why ?? f.summary, usd: f.cost.tier1, ...(partialWords(f.tier0) ? { partial: partialWords(f.tier0)! } : {}), }; onLog(`${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: body.article, iteration: k, task: TRIAGE_TASK, status: f.status, summary: f.summary, usd: f.cost.tier1, triage: marker })}`); if (f.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (f.status === "failed") throw new Error(f.summary); }