// `report-draft {"task": "verdicts", "article", "model"?, "claims"?, "maxUsd"?}` // — verdict proposals (release 29 M8) as an editor job, and the operator's // review of one (`verdict-review`). // // enqueueVerdictProposals refused unless the model is in // settings.generation.verdicts.models (verdictsModelOf), // the article is a fact-check, and (an API model) the // caps allow; then ONE `report-draft` job on the model's // lane: `draft:local` (every ollama call through the GPU // arbiter; ollama unloaded when the job ends) or // `draft:api` (metered, held to the revision cap and the // daily cap, its usage in the ledger as task `verdicts`). // The cues are the local corpus's (`diskCuesOf`), as the // bench reads them. No iteration is made: the answer's // `iteration` is 0. The log ends `@@report-draft {article, // iteration: 0, task: "verdicts", status, summary, usd, // verdicts: {proposed, failed, skipped}}`. // reviewProposal `pnpm ops verdict-review {article, claim, decision: // "approve" | "reject", verdict, at, note?}` (the editor's route and // umtool's article tab): approve sets the claim's verdict // through patchArticle, reject marks the proposal only // (lib/report/verdictProposals.ts). import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; import { capFor, DEFAULT_GENERATION_VERDICT_WINDOW } from "../lib/generationSettings"; import { providerOf, unloadOllama } from "../lib/llm"; import { diskCuesOf } from "../lib/report/convert-server"; import { diskDateOf, diskTurnsOf } from "../lib/report/draft/bench/disk"; import { benchReportsOf } from "../lib/report/draft/bench/index"; import { usageOf } from "../lib/report/draft/tasks/run"; import { proposeVerdicts, verdictsModelOf, VERDICTS_TASK, type VerdictsOutcome } from "../lib/report/draft/tasks/verdicts"; import { reviewVerdictProposal, VerdictProposalsError, type ProposalReview } from "../lib/report/verdictProposals"; import { isReportId } from "../lib/report/schema"; import { isVerdict } from "../lib/report/verdicts"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft"; export { VERDICTS_TASK }; export async function enqueueVerdictProposals(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; let model: string; try { model = verdictsModelOf(gen, body.model); // A fact-check with report.json (benchReportsOf refuses anything else). await benchReportsOf(paths, [body.article]); } catch (e) { return refuse((e as Error).message); } const provider = providerOf(model); let maxUsd: number | undefined; if (provider === "api") { try { maxUsd = capFor(gen.caps, "revision", 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 result = await runManagedFunction({ kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, fn: modelLogged({ paths, task: "verdicts" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { // Again at the job's turn: jobs ahead in the queue may have spent the day. const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); if (late) throw new Error(late); } onLog(`verdicts ${body.article} on ${model} (${provider === "api" ? `the Claude API, cap $${maxUsd}` : "the local model, through the GPU arbiter"})`); let out: VerdictsOutcome | null = null; try { out = await proposeVerdicts( { article: body.article, model, ...(body.claims?.length ? { claims: body.claims } : {}), ...(maxUsd !== undefined ? { maxUsd } : {}), // The window of the bench run the bar was set on (settings.generation.verdicts.window). windowS: (g.verdicts.window ?? DEFAULT_GENERATION_VERDICT_WINDOW).seconds, windowMode: (g.verdicts.window ?? DEFAULT_GENERATION_VERDICT_WINDOW).mode, jobId: ctx.jobId, }, { paths, cuesOf: diskCuesOf(paths.channelsDir), turnsOf: diskTurnsOf(paths.channelsDir), dateOf: diskDateOf(paths.channelsDir), llm: llmConfigOf(g, paths, provider === "local" ? { onLog, signal } : undefined), // Read again at the job's turn: a model unticked meanwhile is refused. allowed: g.verdicts.models, log: onLog, progress: (done, total) => setProgress?.({ metric: "entries", initial: 0, target: Math.max(total, done), current: done }), signal, ...(deps.now ? { now: deps.now } : {}), }, ); } finally { if (provider === "local") { await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, model).then( () => onLog(`unloaded ${model} from ollama`), (e) => onLog(`ollama unload failed: ${(e as Error).message}`), ); } } if (provider === "api") { const at = deps.now?.() ?? new Date(); const rows: GenerationUsageRow[] = Object.entries(out.byModel) .filter(([, t]) => t.calls > 0) .map(([m, t]) => { const u = usageOf(t); return { at: at.toISOString(), day: utcDay(at), jobId: ctx.jobId, article: body.article, iteration: 0, task: VERDICTS_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}`)); } onLog( `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: body.article, iteration: 0, task: VERDICTS_TASK, status: out.status, summary: out.summary, usd: out.usd, verdicts: { proposed: out.proposed.length, failed: out.failed.length, skipped: out.skipped.length, promptVersion: out.promptVersion }, })}`, ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; } // ─── verdict-review ─── // `verdict` and `at` are the proposal the operator was shown (a compare-and-set: // a proposal replaced since is refused, 409). export const VERDICT_REVIEW_BODY_KEYS = ["article", "claim", "decision", "verdict", "at", "note"] as const; /** The body, judged without touching the disk. */ export function parseVerdictReviewBody(b: Record): ProposalReview { if (!isReportId(b.article)) throw new VerdictProposalsError('"article" is an article id'); if (typeof b.claim !== "string" || !/^[A-Za-z0-9._:-]{1,64}$/.test(b.claim)) throw new VerdictProposalsError('"claim" is a claim id'); if (b.decision !== "approve" && b.decision !== "reject") throw new VerdictProposalsError('"decision" is "approve" or "reject"'); if (!isVerdict(b.verdict)) throw new VerdictProposalsError('"verdict" is the proposed verdict you were shown (verdicts.proposed.json)'); if (typeof b.at !== "string" || !b.at) throw new VerdictProposalsError('"at" is the proposal\'s `at` you were shown (verdicts.proposed.json)'); if (b.note !== undefined && b.note !== null && typeof b.note !== "string") throw new VerdictProposalsError('"note" is text'); return { article: b.article as string, claim: b.claim, decision: b.decision, verdict: b.verdict, at: b.at, ...(typeof b.note === "string" && b.note.trim() ? { note: b.note } : {}) }; } export async function reviewProposal(raw: Record, deps: Pick) { const r = parseVerdictReviewBody(raw); return reviewVerdictProposal(r, deps.paths, deps.now?.() ?? new Date()); }