commit 6ac8db2142265f1f3ebd84dc0f812a313ee73b7f parent d3c61e05f7b7de993cbd92c28f53a42a9af1431a Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Thu, 15 Oct 2026 10:41:19 -0400 Merge r29/verdicts review fixes (M8/V1) into r29/integration Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
40 files changed, 778 insertions(+), 201 deletions(-)
diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md @@ -38,7 +38,10 @@ each task. Use the archilyzer MCP tools only; run no script for it. `drafts.review.json` yourself. `force: true` re-drafts only what a model drafted; a field the operator wrote is never replaced. Edit an iteration's files by hand only if the operator asks. 4. For each task routed to `code`, do it yourself as usual: `/sweep` for a report (its plan reads the same - policy). + policy). **Except `verdicts`** (proposed verdicts for a fact-check's unruled claims): it runs only on a model in + `settings.generation.verdicts.models` (the verdict bench's bar) — `generate` with task `verdicts`, the article and + that `model`. Never propose or rule a claim's verdict yourself, whatever the route; the proposals are the + operator's to approve or reject in umtool (Inbox → Review verdicts), never written by hand. 5. `via: "api"` or `"local"` on `generate` (or `via=` in a `/sweep` request) overrides one run when the operator asks for it. To move the balance itself, `generation_policy` with `preset` (code, balanced, api, local) or with `task` and `route` — only when the operator asks. diff --git a/COMMANDS.md b/COMMANDS.md @@ -149,7 +149,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `find-copy` | find-copy looks for a copy of every gone recording (deleted or private) a report cites, and fetches the cited windows from it: {"article"} \| {"articles": true} \| {"siteId"}, "dryRun"?. Per recording, one at a time: the Wayback Machine (the newest capture of its page that recorded a 200), then archive.org (a mirror naming its YouTube id, an original video file preferred). Every copy's windows go to ONE fetch-windows job on the archive.org clip queue, the copy's URL as each window's page, so the clips land in the recording's own clips/ with the copy (wayback or archive.org, and its URL) in each window's provenance. A recording with no copy is left: its moments show their words only, marked "Source deleted". -> {recordings: \[{slug, id, gone, watchUrl, youtubeId, windows, tried: \[{from, found, url?, detail?, error?}\], copy?, outcome: fetch \| text-only \| error}\], items, stopped?, jobId?, refused?}. dryRun answers the lookups and starts nothing. | `pnpm ops find-copy --json '{"article":"demo-article","dryRun":true}'`<br>`pnpm ops find-copy --json '{"article":"demo-article"}' --wait` | | `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -> {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). "seed" (a new sweep's, on a Claude model) is cited markdown in the /sweep shape — umtool's research board: kept as the iteration's seed.md, the report starts from it, and the sweep verifies and extends it. "ids" (a sweep's) restricts it to those recordings: an enumeration reads only their pages and answers only their rows, a read of another is refused. A "refresh" re-fetches an iteration's scope and folds in what changed: "iteration" (default: the current report's) — its question, its recorded enumerations and every channel its citations touch. One job on draft:refresh: the editor's own sync / refresh-report / transcribe-bucket (what landed) per video channel and fetch-posts per posts channel (a platform held or cooling down is skipped; transcribe-bucket is skipped, and said, while transcription is paused or no worker is enabled), then a local build of the site holding them (never a deploy); the enumerations again (new and changed recordings) and every cited quote read again (changed words, en vs en-orig, a source gone); nothing changed ends no-change, $0 — or partial, naming what a capped search did not reach. Else, within the caps ("model", "maxUsd", "extractorModel"; past one it ends held-by-cap with the delta and the estimate), a sweep restricted to the new recordings and a revision of the report: a new refresh iteration, refresh.json beside it. "fetch": false skips the fetch and the build; "dryRun": true answers {plan} and writes nothing. Its log ends with @@report-draft {…, refresh: {status, newIds, changed, drifted, deleted, summary}}. "verdicts" proposes a verdict for each UNRULED claim of a fact-check ("article"; "claims"? only those; "model"?, "maxUsd"?): the verdict bench's prompt, one claim per call, on a model in settings.generation.verdicts.models only (refused otherwise; none named: the first of them on the verdicts route). No iteration (iteration 0): the proposals go to the article's verdicts.proposed.json, never report.json; a claim the operator ruled, or whose proposal was reviewed, is not asked. Its log ends with @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}. | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article"}' --wait`<br>`pnpm ops report-draft --json '{"task":"refresh","article":"demo-article","dryRun":true}'`<br>`pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait`<br>`pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait` | | `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -> {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | -| `verdict-review` | verdict-review settles one verdict proposal: {"article", "claim", "decision": "approve" \| "reject", "note"?} -> {proposal}. approve sets the claim's verdict to the proposal's (through the registry; refused when the claim was ruled meanwhile); reject leaves the claim unruled. Synchronous. | `pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve"}'` | +| `verdict-review` | verdict-review settles one verdict proposal: {"article", "claim", "decision": "approve" \| "reject", "verdict", "at", "note"?} -> {proposal}. "verdict" and "at" are the proposal you were shown (its verdicts.proposed.json entry): a compare-and-set, refused (409) when the proposal was replaced or reviewed since, its claim changed (the proposal is stale) or was ruled meanwhile. approve sets the claim's verdict to it (through the registry); reject leaves the claim unruled. Synchronous. | `pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}'` | | `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode or limit with it)} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | | `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` | diff --git a/SETTINGS.md b/SETTINGS.md @@ -1055,6 +1055,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude |---|---|---| | `bar` | object — see below | The bar a model must clear on a bench run (below): each a fraction, 0 to 1. All 0 = no bar set. | | `models` | `[]` | The models the operator ticked as passing the bar — never set automatically. Empty = none: no verdict proposals. | +| `window` | object — see below | The transcript a verdict proposal reads around each cited span (below): set it to the bench run's the bar was set on (its window mode and `--window`). | #### `generation.verdicts.bar` @@ -1064,6 +1065,13 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `contradictedRecall` | `0` | The least share of the claims the operator ruled CONTRADICTED that the model must rule so. | | `notFoundRecall` | `0` | The least share of the claims the operator ruled NOT_FOUND that the model must rule so. | +#### `generation.verdicts.window` + +| Key | Default | Description | +|---|---|---| +| `mode` | `"seconds"` | `seconds` (the cues within `seconds` either side of the cited span) or `turn` (the cited speaker's turn, bounded by `seconds` either side) — the bench's `--window-mode`. | +| `seconds` | `60` | Seconds either side of the cited span, 0 to 600 — the bench's `--window`. | + #### `generation.triage` | Key | Default | Description | @@ -1133,7 +1141,11 @@ Default: "contradictedRecall": 0, "notFoundRecall": 0 }, - "models": [] + "models": [], + "window": { + "mode": "seconds", + "seconds": 60 + } }, "triage": { "model": "local", diff --git a/common/controller/reportVerdicts.ts b/common/controller/reportVerdicts.ts @@ -16,7 +16,7 @@ // iteration: 0, task: "verdicts", status, summary, usd, // verdicts: {proposed, failed, skipped}}`. // reviewProposal `pnpm ops verdict-review {article, claim, decision: -// "approve" | "reject", note?}` (the editor's route and +// "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). @@ -24,7 +24,7 @@ import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; -import { capFor } from "../lib/generationSettings"; +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"; @@ -33,6 +33,7 @@ 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"; @@ -76,7 +77,16 @@ export async function enqueueVerdictProposals(body: ReportDraftBody, deps: Repor let out: VerdictsOutcome | null = null; try { out = await proposeVerdicts( - { article: body.article, model, ...(body.claims?.length ? { claims: body.claims } : {}), ...(maxUsd !== undefined ? { maxUsd } : {}) }, + { + 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), @@ -142,15 +152,19 @@ export async function enqueueVerdictProposals(body: ReportDraftBody, deps: Repor // ─── verdict-review ─── -export const VERDICT_REVIEW_BODY_KEYS = ["article", "claim", "decision", "note"] as const; +// `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<string, unknown>): 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, ...(typeof b.note === "string" && b.note.trim() ? { note: b.note } : {}) }; + 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<string, unknown>, deps: Pick<ReportDraftDeps, "paths" | "now">) { diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -119,10 +119,13 @@ test("cut (release 28 M1): the most entries a drafted cut keeps, 20 by default, }); test("generation settings: the verdict bench's bar (fractions, clamped) and the ticked models; none by default", () => { - assert.deepEqual(DEFAULT_GENERATION_SETTINGS.verdicts, { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] }); + assert.deepEqual(DEFAULT_GENERATION_SETTINGS.verdicts, { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [], window: { mode: "seconds", seconds: 60 } }); assert.deepEqual(sanitizeGeneration({}).verdicts, DEFAULT_GENERATION_SETTINGS.verdicts); const v = sanitizeGeneration({ verdicts: { bar: { agreement: 0.756789, contradictedRecall: 1.5, notFoundRecall: "x" }, models: ["claude-sonnet-5-5", " qwen3:8b ", "bad model", 3, "claude-sonnet-5-5"] }, }).verdicts; - assert.deepEqual(v, { bar: { agreement: 0.7568, contradictedRecall: 1, notFoundRecall: 0 }, models: ["claude-sonnet-5-5", "qwen3:8b"] }); + assert.deepEqual(v, { bar: { agreement: 0.7568, contradictedRecall: 1, notFoundRecall: 0 }, models: ["claude-sonnet-5-5", "qwen3:8b"], window: { mode: "seconds", seconds: 60 } }); + // The window proposals read (release 29): the bench run's the bar was set on. + assert.deepEqual(sanitizeGeneration({ verdicts: { window: { mode: "turn", seconds: 30.4 } } }).verdicts.window, { mode: "turn", seconds: 30 }); + assert.deepEqual(sanitizeGeneration({ verdicts: { window: { mode: "sentence", seconds: 900 } } }).verdicts.window, { mode: "seconds", seconds: 60 }); }); diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -65,7 +65,11 @@ export type GenerationCut = { maxClips: number }; // `models` are the passing models the operator ticked — never set // automatically. M8's verdict proposals run only on these. export type GenerationVerdictBar = { agreement: number; contradictedRecall: number; notFoundRecall: number }; -export type GenerationVerdicts = { bar: GenerationVerdictBar; models: string[] }; +// The transcript window a verdict proposal reads (release 29): set to the +// bench run's the bar was set on, so a proposal reads what the model was +// measured on. +export type GenerationVerdictWindow = { mode: "seconds" | "turn"; seconds: number }; +export type GenerationVerdicts = { bar: GenerationVerdictBar; models: string[]; window: GenerationVerdictWindow }; // Triage first (umtool R6): the cheap pass a recurring report may run before // its sweep — the model it judges on, the threshold it escalates at, and how // many escalations a day may run. @@ -96,7 +100,8 @@ export type GenerationSettings = { triage: GenerationTriage; }; -export const DEFAULT_GENERATION_VERDICTS: GenerationVerdicts = { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] }; +export const DEFAULT_GENERATION_VERDICT_WINDOW: GenerationVerdictWindow = { mode: "seconds", seconds: 60 }; +export const DEFAULT_GENERATION_VERDICTS: GenerationVerdicts = { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [], window: { ...DEFAULT_GENERATION_VERDICT_WINDOW } }; export const DEFAULT_GENERATION_RESEARCH: GenerationResearch = { autonomy: "propose", ...DEFAULT_RESEARCH_LIMITS }; @@ -116,7 +121,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = { citationOrigin: "", research: { ...DEFAULT_GENERATION_RESEARCH }, cut: { maxClips: 20 }, - verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [] }, + verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [], window: { ...DEFAULT_GENERATION_VERDICT_WINDOW } }, triage: { ...DEFAULT_GENERATION_TRIAGE }, }; @@ -155,6 +160,12 @@ export const GENERATION_TRIAGE_FIELD_DOCS: FieldDocs<GenerationTriage> = { export const GENERATION_VERDICTS_FIELD_DOCS: FieldDocs<GenerationVerdicts> = { bar: "The bar a model must clear on a bench run (below): each a fraction, 0 to 1. All 0 = no bar set.", models: "The models the operator ticked as passing the bar — never set automatically. Empty = none: no verdict proposals.", + window: "The transcript a verdict proposal reads around each cited span (below): set it to the bench run's the bar was set on (its window mode and `--window`).", +}; + +export const GENERATION_VERDICT_WINDOW_FIELD_DOCS: FieldDocs<GenerationVerdictWindow> = { + mode: "`seconds` (the cues within `seconds` either side of the cited span) or `turn` (the cited speaker's turn, bounded by `seconds` either side) — the bench's `--window-mode`.", + seconds: "Seconds either side of the cited span, 0 to 600 — the bench's `--window`.", }; export const GENERATION_VERDICT_BAR_FIELD_DOCS: FieldDocs<GenerationVerdictBar> = { @@ -332,7 +343,12 @@ function sanitizeVerdicts(v: unknown): GenerationVerdicts { const models = Array.isArray(o.models) ? [...new Set(o.models.filter((m): m is string => typeof m === "string" && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(m.trim())).map((m) => m.trim()))] : []; - return { bar: { agreement: frac(b.agreement), contradictedRecall: frac(b.contradictedRecall), notFoundRecall: frac(b.notFoundRecall) }, models }; + const w = o.window && typeof o.window === "object" && !Array.isArray(o.window) ? (o.window as Record<string, unknown>) : {}; + const window: GenerationVerdictWindow = { + mode: w.mode === "turn" ? "turn" : "seconds", + seconds: typeof w.seconds === "number" && Number.isFinite(w.seconds) && w.seconds >= 0 && w.seconds <= 600 ? Math.round(w.seconds) : DEFAULT_GENERATION_VERDICT_WINDOW.seconds, + }; + return { bar: { agreement: frac(b.agreement), contradictedRecall: frac(b.contradictedRecall), notFoundRecall: frac(b.notFoundRecall) }, models, window }; } export function presetOf(routes: GenerationRoutes): GenerationPreset | "custom" { diff --git a/common/lib/report/delete.ts b/common/lib/report/delete.ts @@ -68,6 +68,7 @@ import path from "node:path"; import { getPaths, type Paths } from "../paths"; import { getSite, listSiteIds, patchSite } from "../site"; import { isCitedSite, parseSiteReports } from "../siteSchema"; +import { liveVerdictsJob, readVerdictProposals } from "./verdictProposals"; import { ARTICLE_DELETING_PREFIX, ArticleRegistryError, @@ -390,6 +391,11 @@ export async function planArticleDelete(id: string, opts: DeleteOptions): Promis for (const p of read.problems) { kept.push({ what: `${iterationLabel(p.n)}'s iteration.json`, why: `unsound (${p.problems.join("; ")}): its directory goes with the article all the same` }); } + // A verdicts job proposing for it (release 29 M8): it makes no iteration, + // so its mark on the sidecar says so (a mark whose process is gone is not + // a job). A sidecar that does not read goes with the article. + const job = liveVerdictsJob(await readVerdictProposals(id, paths).catch(() => null)); + if (job) refusals.push({ reason: `a verdicts job (job ${job.jobId}) is proposing verdicts for it: cancel it, or wait for it to end`, forceable: false }); } if (published) { diff --git a/common/lib/report/draft/bench/bench.test.ts b/common/lib/report/draft/bench/bench.test.ts @@ -548,6 +548,8 @@ test("V1 run: the injected ask, reason before verdict, a per-call trace; --items await runVerdictBench({ runId: "vb-two", models: ["qwen3:8b"] }, { paths: s.paths, cuesOf, llm: {}, ask }); assert.equal(asked.length, 0); + // A resume with another limit is refused (review fix 5). + await assert.rejects(runVerdictBench({ runId: "vb-two", models: ["qwen3:8b"], limit: 3 }, { paths: s.paths, cuesOf, llm: {}, ask }), /with no limit: drop the limit/); // items-from refuses what would change the items, and a run that does not exist. await assert.rejects(runVerdictBench({ runId: "vb-x", models: ["m"], itemsFrom: "vb-one", limit: 3 }, { paths: s.paths, cuesOf, llm: {}, ask }), /drop the limit/); await assert.rejects(runVerdictBench({ runId: "vb-x", models: ["m"], itemsFrom: "vb-nope" }, { paths: s.paths, cuesOf, llm: {}, ask }), /no run "vb-nope"/); @@ -605,8 +607,9 @@ test("V1 score: not-CORROBORATED precision and recall; two runs compared; the op assert.equal(ms.agreed, 4); assert.deepEqual(ms.notCorroborated, { tp: 4, fp: 1, fn: 2, precision: 0.8, recall: 0.6667 }); // The hash is the items' identity: context lines do not change it. - assert.equal( - benchItemsHash([{ key: "a", verdict: "PARTLY", windows: [] }]), - benchItemsHash([{ key: "a", verdict: "PARTLY", windows: [], title: "t" } as any]), - ); + const one = { key: "a", text: "The article says so.", verdict: "PARTLY" as const, quotes: [{ citation: "q", channel: "c", id: "v", start: 1, end: 2, quote: "so" }], windows: [] }; + assert.equal(benchItemsHash([one]), benchItemsHash([{ ...one, title: "t", section: "s" } as typeof one])); + // The claim's text and its quotes' spans are the items' identity too (review fix 6). + assert.notEqual(benchItemsHash([one]), benchItemsHash([{ ...one, text: "The article says otherwise." }])); + assert.notEqual(benchItemsHash([one]), benchItemsHash([{ ...one, quotes: [{ ...one.quotes[0]!, end: 3 }] }])); }); diff --git a/common/lib/report/draft/bench/items.ts b/common/lib/report/draft/bench/items.ts @@ -441,13 +441,20 @@ export async function benchItemsOf(reports: readonly BenchReport[], o: ItemOptio /** * The identity of a run's items, so two runs can be said to be over the SAME - * items: each item's key, the operator's verdict and its windows (recording, - * from, to, how many cues) — not the context lines, which a run made from an - * earlier run's items may add. 16 hex characters of a sha256. + * items: each item's key, the claim's text, the operator's verdict, its quotes' + * spans and its windows (recording, from, to, how many cues) — not the context + * lines, which a run made from an earlier run's items may add. 16 hex + * characters of a sha256. */ -export function benchItemsHash(items: readonly Pick<BenchItem, "key" | "verdict" | "windows">[]): string { +export function benchItemsHash(items: readonly Pick<BenchItem, "key" | "text" | "verdict" | "quotes" | "windows">[]): string { const canon = items - .map((i) => ({ k: i.key, v: i.verdict, w: i.windows.map((w) => [w.channel, w.id, w.from, w.to, w.cues.length]) })) + .map((i) => ({ + k: i.key, + t: i.text, + v: i.verdict, + q: i.quotes.map((q) => [q.citation, q.channel, q.id, q.start, q.end, q.quote]), + w: i.windows.map((w) => [w.channel, w.id, w.from, w.to, w.cues.length]), + })) .sort((a, b) => (a.k < b.k ? -1 : a.k > b.k ? 1 : 0)); return createHash("sha256").update(JSON.stringify(canon)).digest("hex").slice(0, 16); } diff --git a/common/lib/report/draft/bench/run.ts b/common/lib/report/draft/bench/run.ts @@ -324,6 +324,9 @@ export async function runVerdictBench(o: BenchOptions, deps: BenchDeps): Promise if (o.windowMode !== undefined && o.windowMode !== (s.windowMode ?? "seconds")) { throw new BenchInputError(`run ${id} was made with the ${s.windowMode ?? "seconds"} window mode: drop the mode, or start a new run`); } + if (o.limit !== undefined && o.limit !== s.limit) { + throw new BenchInputError(`run ${id} was made ${s.limit === undefined ? "with no limit" : `with a limit of ${s.limit}`}: drop the limit, or start a new run`); + } if (o.reports?.length && [...o.reports].sort().join(",") !== [...s.reports].sort().join(",")) { throw new BenchInputError(`run ${id} was made over other reports: drop them, or start a new run`); } diff --git a/common/lib/report/draft/tasks/verdicts.test.ts b/common/lib/report/draft/tasks/verdicts.test.ts @@ -7,14 +7,24 @@ import { after, test } from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os, { tmpdir } from "node:os"; import path from "node:path"; import { cuesOf } from "../../../../testing/draft/corpus.mjs"; import { startFakeAnthropic, toolTurn } from "../../../../testing/llm/fakeAnthropic.mjs"; import { articleFile, writeArticle } from "../../registry"; import { createIteration, makeCurrent, updateIteration, writeIterationFile } from "../../iterations"; -import { readVerdictProposals, recordVerdictProposals, reviewVerdictProposal, verdictProposalsFile, waitingProposals } from "../../verdictProposals"; +import { + currentClaims, + markVerdictsJob, + proposalIsCurrent, + readVerdictProposals, + recordVerdictProposals, + reviewVerdictProposal, + verdictProposalsFile, + waitingProposals, +} from "../../verdictProposals"; +import { planArticleDelete } from "../../delete"; import { sanitizeGeneration } from "../../../generationSettings"; import { PROMPT_VERSION, type BenchAsk } from "../bench/index"; import { proposeVerdicts, verdictsModelOf, VerdictsRefusal } from "./verdicts"; @@ -87,11 +97,18 @@ test("proposals: the unruled claims only, the bench's prompt, written to the sid // report.json is untouched: not a byte. assert.equal(readFileSync(s.file, "utf8"), before); const f = (await readVerdictProposals(s.id, s.paths))!; - assert.deepEqual(f.proposals.r02, { verdict: "PARTLY", reason: f.proposals.r02!.reason, model: QWEN, promptVersion: PROMPT_VERSION, at: NOW.toISOString(), status: "proposed" }); + assert.deepEqual(f.proposals.r02, { verdict: "PARTLY", reason: f.proposals.r02!.reason, model: QWEN, promptVersion: PROMPT_VERSION, at: NOW.toISOString(), fingerprint: f.proposals.r02!.fingerprint, status: "proposed" }); + assert.match(f.proposals.r02!.fingerprint, /^[0-9a-f]{16}$/); assert.equal(waitingProposals(f).length, 3); assert.equal(path.basename(verdictProposalsFile(s.paths, s.id)), "verdicts.proposed.json"); }); +// The proposal the operator is shown, for the compare-and-set review. +async function shown(paths: Parameters<typeof readVerdictProposals>[1], id: string, claim: string) { + const p = (await readVerdictProposals(id, paths))!.proposals[claim]!; + return { verdict: p.verdict, at: p.at }; +} + test("the sidecar survives makeCurrent; approve sets the verdict through patchArticle, reject leaves the claim; a reviewed proposal is never asked again", async () => { const s = await store(); const { ask, asked } = stub(() => ({ reason: "shown", verdict: "CONTRADICTED" })); @@ -106,17 +123,17 @@ test("the sidecar survives makeCurrent; approve sets the verdict through patchAr assert.equal(waitingProposals(await readVerdictProposals(s.id, s.paths)).length, 3); // Approve r04: the claim's verdict is set, the proposal approved. - const ok = await reviewVerdictProposal({ article: s.id, claim: "r04", decision: "approve" }, s.paths, NOW); + const ok = await reviewVerdictProposal({ article: s.id, claim: "r04", decision: "approve", ...(await shown(s.paths, s.id, "r04")) }, s.paths, NOW); assert.equal(ok.status, "approved"); - const claimVerdict = (id: string) => JSON.parse(readFileSync(s.file, "utf8")).sections.flatMap((x: any) => x.claims).find((c: any) => c.id === id).verdict; + const claimVerdict = (id: string) => JSON.parse(readFileSync(s.file, "utf8")).sections.flatMap((x: any) => x.claims).find((c: any) => c.id === id)?.verdict; assert.equal(claimVerdict("r04"), "CONTRADICTED"); // Reject r07, with a note: the claim stays unruled. - const no = await reviewVerdictProposal({ article: s.id, claim: "r07", decision: "reject", note: "the window is too short" }, s.paths, NOW); + const no = await reviewVerdictProposal({ article: s.id, claim: "r07", decision: "reject", note: "the window is too short", ...(await shown(s.paths, s.id, "r07")) }, s.paths, NOW); assert.deepEqual([no.status, no.note], ["rejected", "the window is too short"]); assert.equal(claimVerdict("r07"), undefined); // Twice: refused. No proposal: 404. - await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r04", decision: "approve" }, s.paths, NOW), /approved already/); - await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r01", decision: "approve" }, s.paths, NOW), (e: any) => e.status === 404); + await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r04", decision: "approve", verdict: "CONTRADICTED", at: NOW.toISOString() }, s.paths, NOW), /approved already/); + await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r01", decision: "approve", verdict: "CONTRADICTED", at: NOW.toISOString() }, s.paths, NOW), (e: any) => e.status === 404); // A rerun: r04 is ruled now and r07's proposal was rejected — only r02 is asked. asked.length = 0; @@ -124,18 +141,100 @@ test("the sidecar survives makeCurrent; approve sets the verdict through patchAr assert.deepEqual(again.proposed, ["r02"]); assert.equal(asked.length, 1); assert.ok(again.skipped.some((x) => x.claim === "r07" && /rejected by the operator/.test(x.reason))); - // A reviewed proposal is never replaced by a record either. - const rec = await recordVerdictProposals(s.id, { r07: { verdict: "PARTLY", reason: "x", model: QWEN, promptVersion: PROMPT_VERSION, at: NOW.toISOString() } }, s.paths, NOW); - assert.deepEqual(rec, { written: [], kept: ["r07"] }); + // A reviewed proposal on the same claim is never replaced by a record either. + const fp = (await readVerdictProposals(s.id, s.paths))!.proposals.r07!.fingerprint; + const rec = await recordVerdictProposals(s.id, { r07: { verdict: "PARTLY", reason: "x", model: QWEN, promptVersion: PROMPT_VERSION, at: NOW.toISOString(), fingerprint: fp } }, s.paths, NOW); + assert.deepEqual(rec, { written: [], kept: ["r07"], stale: [] }); // A claim ruled by hand after its proposal: approving is refused, the verdict kept. const r = JSON.parse(readFileSync(s.file, "utf8")); for (const sec of r.sections) for (const c of sec.claims) if (c.id === "r02") c.verdict = "CORROBORATED"; await writeArticle(r, { paths: s.paths }); - await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r02", decision: "approve" }, s.paths, NOW), /ruled already/); + await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r02", decision: "approve", ...(await shown(s.paths, s.id, "r02")) }, s.paths, NOW), /ruled already/); assert.equal(claimVerdict("r02"), "CORROBORATED"); }); +test("review fix 1: a revision that drops a claim shifts the ids — the shifted proposal is stale (409, not waiting), and the new claim under the id is asked again", async () => { + const s = await store(); + const { ask, asked } = stub((text) => ({ reason: `on ${text.slice(0, 30)}`, verdict: "CONTRADICTED" })); + await proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [QWEN], ask, now: () => NOW }); + // r02 rejected by the operator. + await reviewVerdictProposal({ article: s.id, claim: "r02", decision: "reject", ...(await shown(s.paths, s.id, "r02")) }, s.paths, NOW); + // A revision drops r02: the old r03's text moves up under r02's id, unruled; r04 gets r05's claim. + const r = JSON.parse(readFileSync(s.file, "utf8")); + const sec = r.sections[0]; + const r03 = sec.claims.find((c: any) => c.id === "r03"); + const r05 = sec.claims.find((c: any) => c.id === "r05"); + sec.claims = sec.claims.filter((c: any) => !["r02", "r03", "r04", "r05"].includes(c.id)); + sec.claims.push({ ...r03, id: "r02", verdict: undefined }, { ...r05, id: "r04", verdict: undefined }); + for (const c of sec.claims) if (c.verdict === undefined) delete c.verdict; + await writeArticle(r, { paths: s.paths }); + const claims = currentClaims(JSON.parse(readFileSync(s.file, "utf8"))); + const f = (await readVerdictProposals(s.id, s.paths))!; + // The r04 proposal judged another claim: stale, and its review refused. + assert.equal(proposalIsCurrent(f.proposals.r04!, claims.get("r04")), false); + await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r04", decision: "approve", ...(await shown(s.paths, s.id, "r04")) }, s.paths, NOW), (e: any) => e.status === 409 && /stale/.test(e.message)); + assert.equal(claims.get("r04")!.ruled, false); + // A rerun asks the new r02 (its old proposal's rejection was another claim's) and the new r04. + asked.length = 0; + const again = await proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [QWEN], ask, now: () => NOW }); + assert.deepEqual(again.proposed.sort(), ["r02", "r04", "r07"]); + const g = (await readVerdictProposals(s.id, s.paths))!; + assert.equal(g.proposals.r02!.status, "proposed"); + assert.equal(g.proposals.r02!.fingerprint, claims.get("r02")!.fingerprint); +}); + +test("review fix 2: the review is a compare-and-set — a proposal rewritten between view and click is refused; concurrent approve and reject: one wins", async () => { + const s = await store(); + const { ask } = stub(() => ({ reason: "shown", verdict: "CORROBORATED" })); + await proposeVerdicts({ article: s.id, model: QWEN }, { paths: s.paths, cuesOf, llm: {}, allowed: [QWEN], ask, now: () => NOW }); + const seen = await shown(s.paths, s.id, "r02"); + // Another run rewrites r02 to PARTLY after the operator saw CORROBORATED. + const later = new Date(NOW.getTime() + 60_000); + const fp = (await readVerdictProposals(s.id, s.paths))!.proposals.r02!.fingerprint; + await recordVerdictProposals(s.id, { r02: { verdict: "PARTLY", reason: "newer", model: "claude-opus-5-5", promptVersion: PROMPT_VERSION, at: later.toISOString(), fingerprint: fp } }, s.paths, later); + await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r02", decision: "approve", ...seen }, s.paths, NOW), (e: any) => e.status === 409 && /changed since it was shown/.test(e.message)); + const claimVerdict = (id: string) => JSON.parse(readFileSync(s.file, "utf8")).sections.flatMap((x: any) => x.claims).find((c: any) => c.id === id)?.verdict; + assert.equal(claimVerdict("r02"), undefined); + // A wrong verdict named: refused too. + await assert.rejects(reviewVerdictProposal({ article: s.id, claim: "r02", decision: "approve", verdict: "CORROBORATED", at: later.toISOString() }, s.paths, NOW), /changed since it was shown/); + // Approve and reject of r04 at once: exactly one wins, and the record agrees with the claim. + const r04 = await shown(s.paths, s.id, "r04"); + const both = await Promise.allSettled([ + reviewVerdictProposal({ article: s.id, claim: "r04", decision: "approve", ...r04 }, s.paths, NOW), + reviewVerdictProposal({ article: s.id, claim: "r04", decision: "reject", ...r04 }, s.paths, NOW), + ]); + assert.equal(both.filter((x) => x.status === "fulfilled").length, 1); + assert.ok(both.some((x) => x.status === "rejected" && (x.reason as any).status === 409)); + const status = (await readVerdictProposals(s.id, s.paths))!.proposals.r04!.status; + assert.equal(claimVerdict("r04") === "CORROBORATED", status === "approved"); + assert.equal(claimVerdict("r04") === undefined, status === "rejected"); +}); + +test("review fix 3: no write without report.json (no orphan directory); deleteArticle refuses while a verdicts job is marked", async () => { + const s = await store(); + const sitesDir = path.join(path.dirname(s.paths.articlesDir), "sites"); + const opts = { projectsRoot: path.join(path.dirname(s.paths.articlesDir), "projects"), paths: { ...s.paths, sitesDir } }; + await markVerdictsJob(s.id, { jobId: "job-1" }, s.paths, NOW); + const plan = await planArticleDelete(s.id, opts); + assert.ok(plan.refusals.some((r) => /a verdicts job \(job job-1\)/.test(r.reason))); + await markVerdictsJob(s.id, null, s.paths, NOW); + assert.ok(!(await planArticleDelete(s.id, opts)).refusals.some((r) => /verdicts job/.test(r.reason))); + // A mark whose process is gone is not a job. + const f = JSON.parse(readFileSync(verdictProposalsFile(s.paths, s.id), "utf8")); + writeFileSync(verdictProposalsFile(s.paths, s.id), JSON.stringify({ ...f, job: { jobId: "old", pid: 2 ** 22 + 7, host: os.hostname(), since: NOW.toISOString() } })); + assert.ok(!(await planArticleDelete(s.id, opts)).refusals.some((r) => /verdicts job/.test(r.reason))); + // The article deleted mid-run: the next record is refused and makes nothing. + rmSync(path.dirname(s.file), { recursive: true, force: true }); + await assert.rejects( + recordVerdictProposals(s.id, { r02: { verdict: "PARTLY", reason: "x", model: QWEN, promptVersion: PROMPT_VERSION, at: NOW.toISOString(), fingerprint: "x" } }, s.paths, NOW), + (e: any) => e.status === 404, + ); + assert.equal(existsSync(path.dirname(s.file)), false); + await assert.rejects(markVerdictsJob(s.id, { jobId: "job-2" }, s.paths, NOW), /no report.json/); + assert.equal(existsSync(path.dirname(s.file)), false); +}); + test("an API model: held to maxUsd before each call; the spend is the Meter's", async () => { const s = await store(); const api = await startFakeAnthropic(); diff --git a/common/lib/report/draft/tasks/verdicts.ts b/common/lib/report/draft/tasks/verdicts.ts @@ -24,10 +24,11 @@ import type { GenerationSettings } from "../../../generationSettings"; import type { Paths } from "../../../paths"; import type { CuesOf } from "../../convertShared"; import { isVerdict } from "../../verdicts"; -import { readVerdictProposals, recordVerdictProposals, type NewProposal } from "../../verdictProposals"; +import { claimFingerprint, markVerdictsJob, proposalIsCurrent, readVerdictProposals, recordVerdictProposals, VerdictProposalsError, type NewProposal } from "../../verdictProposals"; import { benchPrompt, benchReportsOf, + DEFAULT_WINDOW_S, estimateCall, LOCAL_PROMPT_CAP, PROMPT_VERSION, @@ -73,8 +74,13 @@ export type VerdictsInput = { // Only these claims (default: every unruled one). claims?: string[]; maxUsd?: number; + // The window a proposal reads (settings.generation.verdicts.window: the + // bench run the bar was set on). Default the bench's: seconds, ±60. windowS?: number; windowMode?: WindowMode; + // The job proposing (marked on the sidecar while it runs: deleteArticle + // refuses then). + jobId?: string; }; export type VerdictsDeps = { @@ -123,6 +129,10 @@ export async function proposeVerdicts(input: VerdictsInput, deps: VerdictsDeps): const local = providerOf(model) === "local"; const localCap = deps.localCapTokens ?? LOCAL_PROMPT_CAP; const [report] = await benchReportsOf(deps.paths, [article]); + // Each claim as this run reads it (review fix 1: a proposal carries it). + const citations = (report!.report.citations ?? {}) as Record<string, unknown>; + const fingerprints = new Map<string, string>(); + for (const sec of report!.report.sections) for (const c of sec.claims ?? []) fingerprints.set(c.id, claimFingerprint(c, citations)); const { items, skipped, dropped } = await unruledItemsOfReport(report!, { cuesOf: deps.cuesOf, ...(input.windowS !== undefined ? { windowS: input.windowS } : {}), @@ -131,17 +141,19 @@ export async function proposeVerdicts(input: VerdictsInput, deps: VerdictsDeps): ...(deps.dateOf ? { dateOf: deps.dateOf } : {}), ...(input.claims?.length ? { claims: input.claims } : {}), }); - // A proposal the operator has reviewed is not asked again. + // A proposal the operator has reviewed is not asked again — on the same + // claim (a reviewed proposal on a claim since changed is as good as none). const prior = await readVerdictProposals(article, deps.paths); const todo = items.filter((it) => { const p = prior?.proposals[it.claim]; - if (p && p.status !== "proposed") { + if (p && p.status !== "proposed" && proposalIsCurrent(p, { fingerprint: fingerprints.get(it.claim) ?? "" })) { skipped.push({ key: it.key, report: article, claim: it.claim, reason: `its proposal was ${p.status} by the operator` }); return false; } return true; }); - log(`verdicts ${article} on ${model} (prompt version ${PROMPT_VERSION}): ${todo.length} unruled claim${todo.length === 1 ? "" : "s"} to propose for, ${skipped.length} skipped, ${dropped.length} citations dropped`); + const win = `${input.windowMode === "turn" ? "the speaker's turn within " : "±"}${input.windowS ?? DEFAULT_WINDOW_S} s`; + log(`verdicts ${article} on ${model} (prompt version ${PROMPT_VERSION}, window ${win}): ${todo.length} unruled claim${todo.length === 1 ? "" : "s"} to propose for, ${skipped.length} skipped, ${dropped.length} citations dropped`); const meter = new Meter(); const ask: BenchAsk = @@ -153,38 +165,45 @@ export async function proposeVerdicts(input: VerdictsInput, deps: VerdictsDeps): let status: VerdictsOutcome["status"] = "done"; let done = 0; deps.progress?.(0, todo.length); - for (const item of todo) { - if (deps.signal?.aborted) { - status = "cancelled"; - break; - } - if (!local && input.maxUsd !== undefined) { - const next = estimateCall({ ...item, verdict: "CORROBORATED" }, model, localCap).usd; - if (meter.usd + next > input.maxUsd) { - status = "capped"; - log(`stopped at the cap: $${meter.usd.toFixed(4)} spent, the next call (~$${next.toFixed(4)}) would pass $${input.maxUsd}`); - break; - } - } - const prompt = benchPrompt(item, local ? { capTokens: localCap } : {}); - try { - const ans = await ask<{ verdict?: unknown; reason?: unknown }>(prompt.system, prompt.user, VERDICT_ANSWER_SCHEMA, model); - const reason = typeof ans?.reason === "string" ? ans.reason.trim().slice(0, REASON_MAX) : ""; - if (!isVerdict(ans?.verdict) || !reason) throw new StructuredAnswerError(`not a verdict and a reason: ${JSON.stringify(ans ?? null).slice(0, 120)}`); - const p: NewProposal = { verdict: ans.verdict, reason, model, promptVersion: PROMPT_VERSION, at: now().toISOString() }; - const { written } = await recordVerdictProposals(article, { [item.claim]: p }, deps.paths, now()); - if (written.length) proposed.push(item.claim); - log(`${item.claim}: ${ans.verdict} — ${reason}`); - } catch (err) { + if (input.jobId) await markVerdictsJob(article, { jobId: input.jobId }, deps.paths, now()); + try { + for (const item of todo) { if (deps.signal?.aborted) { status = "cancelled"; break; } - const error = (err as Error).message.slice(0, 300); - failed.push({ claim: item.claim, error }); - log(`${item.claim}: no proposal (${error})`); + if (!local && input.maxUsd !== undefined) { + const next = estimateCall({ ...item, verdict: "CORROBORATED" }, model, localCap).usd; + if (meter.usd + next > input.maxUsd) { + status = "capped"; + log(`stopped at the cap: $${meter.usd.toFixed(4)} spent, the next call (~$${next.toFixed(4)}) would pass $${input.maxUsd}`); + break; + } + } + const prompt = benchPrompt(item, local ? { capTokens: localCap } : {}); + try { + const ans = await ask<{ verdict?: unknown; reason?: unknown }>(prompt.system, prompt.user, VERDICT_ANSWER_SCHEMA, model); + const reason = typeof ans?.reason === "string" ? ans.reason.trim().slice(0, REASON_MAX) : ""; + if (!isVerdict(ans?.verdict) || !reason) throw new StructuredAnswerError(`not a verdict and a reason: ${JSON.stringify(ans ?? null).slice(0, 120)}`); + const p: NewProposal = { verdict: ans.verdict, reason, model, promptVersion: PROMPT_VERSION, at: now().toISOString(), fingerprint: fingerprints.get(item.claim) ?? "" }; + const { written, stale } = await recordVerdictProposals(article, { [item.claim]: p }, deps.paths, now()); + if (written.length) proposed.push(item.claim); + log(`${item.claim}: ${ans.verdict} — ${reason}${stale.length ? " (not kept: the claim was ruled or changed meanwhile)" : ""}`); + } catch (err) { + // The article gone (deleted mid-run): nothing more is written for it. + if (err instanceof VerdictProposalsError && err.status === 404) throw err; + if (deps.signal?.aborted) { + status = "cancelled"; + break; + } + const error = (err as Error).message.slice(0, 300); + failed.push({ claim: item.claim, error }); + log(`${item.claim}: no proposal (${error})`); + } + deps.progress?.(++done, todo.length); } - deps.progress?.(++done, todo.length); + } finally { + if (input.jobId) await markVerdictsJob(article, null, deps.paths, now()).catch((e: Error) => log(`the job mark was not cleared: ${e.message}`)); } const usd = Math.round(meter.usd * 1e6) / 1e6; const summary = diff --git a/common/lib/report/registry.ts b/common/lib/report/registry.ts @@ -281,7 +281,7 @@ type LockHolder = { pid: number; host: string; since: number }; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); -function pidAlive(pid: number): boolean { +export function pidAlive(pid: number): boolean { try { process.kill(pid, 0); return true; @@ -497,7 +497,20 @@ export async function patchArticle( paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(), ): Promise<Report | null> { assertId(id); - return withArticleStoreLock(async () => { + return withArticleStoreLock(() => patchArticleHoldingLock(id, patch, paths), paths); +} + +// patchArticle's body, for a caller that already holds withArticleStoreLock +// and checks more than the report before it patches (release 29 M8: a verdict +// proposal's review, ./verdictProposals.ts). The lock is not re-entrant: never +// call patchArticle there. +export async function patchArticleHoldingLock( + id: string, + patch: ArticlePatch | ((current: Report) => ArticlePatch), + paths: Pick<Paths, "articlesDir" | "exportIndexDir"> = getPaths(), +): Promise<Report | null> { + assertId(id); + { const read = await readArticle(paths, id); if (!read.ok) { if (read.reason === "absent") return null; @@ -528,7 +541,7 @@ export async function patchArticle( } await writeJsonAtomic(articleFile(paths, id), next); return after.value; - }, paths); + } } // WRITE A WHOLE ARTICLE — a generator's report.json, created or replaced at diff --git a/common/lib/report/verdictProposals.ts b/common/lib/report/verdictProposals.ts @@ -4,30 +4,48 @@ // transcripts/reports/<id>/verdicts.proposed.json // { format: "archilyzer-verdict-proposals", version: 1, article, // proposals: { "<claim id>": { verdict, reason, model, promptVersion, at, +// fingerprint, // status: "proposed" | "approved" | "rejected", // note?, reviewedAt? } }, +// job?: { jobId, pid, host, since }, // updatedAt } // // NEVER in report.json: the claim schema is strict, and `makeCurrent` // (./iterations.ts) replaces the article's report.json whole, so a proposal // kept there would vanish with the next iteration. The sidecar is written // only here, under the article store's lock (./registry.ts -// withArticleStoreLock), whole and atomic, as the store's other per-article -// files are; reads are lock-free. +// withArticleStoreLock), whole and atomic, and only while the article's +// report.json exists (no write ever makes the directory: a deleted article +// leaves no orphan sidecar). Reads are lock-free. // -// A proposal never sets a verdict. The operator's review does: approve → -// `patchArticle` sets the claim's `verdict` to the proposal's (refused when -// the claim was ruled meanwhile), then the proposal is marked approved; -// reject → the proposal is marked rejected (the claim stays unruled). A -// reviewed proposal is never replaced by a later run, and a ruled claim is -// never proposed (draft/tasks/verdicts.ts reads the unruled claims only). +// THE FINGERPRINT (review fix 1). A claim id is positional (`k1`, `k2`, … — +// a revision that drops a finding shifts them), so each proposal carries +// `claimFingerprint`: a hash of the claim's text and its citations' spans as +// the run read them. A proposal whose claim's fingerprint is not the current +// one's is STALE: never shown as waiting, never reviewable (409), and — when +// it was reviewed — no reason to skip the claim now under that id. +// +// A proposal never sets a verdict. The operator's review does, as a +// COMPARE-AND-SET (review fix 2): the review names the verdict and the `at` +// the operator was shown; under the lock it is refused (409) when the +// proposal is no longer that one, no longer `proposed`, its claim's +// fingerprint changed, or the claim was ruled meanwhile. Approve then sets +// the claim's `verdict` to it (patchArticleHoldingLock) and records the +// checked proposal approved; reject records it rejected (the claim stays +// unruled). +// +// `job` marks a verdicts job proposing for the article (review fix 3): +// deleteArticle refuses while it names a live process on this host. // // SERVER-ONLY (node:fs). +import { createHash } from "node:crypto"; +import os from "node:os"; import path from "node:path"; import { getPaths, type Paths } from "../paths"; import { readJsonFile, writeJsonAtomic } from "../jsonFile-server"; -import { ArticleRegistryError, articleDir, patchArticle, withArticleStoreLock } from "./registry"; +import { isSpanCitation, type Citation } from "../citations/schema"; +import { articleDir, articleFile, patchArticleHoldingLock, pidAlive, withArticleStoreLock } from "./registry"; import type { Section } from "./schema"; import { isVerdict, type Verdict } from "./verdicts"; @@ -45,16 +63,21 @@ export type VerdictProposal = { model: string; promptVersion: string; at: string; + // claimFingerprint of the claim the run read. + fingerprint: string; status: ProposalStatus; note?: string; reviewedAt?: string; }; +export type VerdictsJobMark = { jobId: string; pid: number; host: string; since: string }; + export type VerdictProposalsFile = { format: typeof VERDICT_PROPOSALS_FORMAT; version: typeof VERDICT_PROPOSALS_VERSION; article: string; proposals: Record<string, VerdictProposal>; + job?: VerdictsJobMark; updatedAt: string; }; @@ -79,6 +102,62 @@ export function verdictProposalsFile(paths: StorePaths, article: string): string return path.join(articleDir(paths, article), VERDICT_PROPOSALS_FILE); } +// ─── The fingerprint ─── + +type ClaimLike = { id?: unknown; text?: unknown; citations?: unknown; verdict?: unknown }; + +/** + * A claim as a proposal judged it: its text and each citation's span (kind, + * recording, seconds, quote). 16 hex characters of a sha256. + */ +export function claimFingerprint(claim: ClaimLike, citations: Record<string, unknown> | undefined): string { + const ids = Array.isArray(claim.citations) ? (claim.citations as unknown[]).filter((x): x is string => typeof x === "string") : []; + const cites = ids.map((id) => { + const c = citations?.[id] as Citation | undefined; + if (!c) return [id, null]; + if (isSpanCitation(c)) return [id, c.kind, c.channel, c.id, c.start, c.end, c.quote]; + const o = c as Record<string, unknown>; + return [id, o.kind ?? null, o.channel ?? null, o.id ?? null, o.quote ?? null]; + }); + return createHash("sha256") + .update(JSON.stringify({ t: String(claim.text ?? ""), c: cites })) + .digest("hex") + .slice(0, 16); +} + +export type CurrentClaim = { id: string; text: string; section: string; ruled: boolean; verdict?: Verdict; fingerprint: string }; + +/** Every claim of a report (its raw JSON) with its fingerprint, in order. */ +export function currentClaims(raw: unknown): Map<string, CurrentClaim> { + const r = (raw ?? {}) as { citations?: Record<string, unknown>; sections?: { title?: unknown; claims?: ClaimLike[] }[] }; + const out = new Map<string, CurrentClaim>(); + for (const s of Array.isArray(r.sections) ? r.sections : []) { + for (const c of Array.isArray(s?.claims) ? s.claims : []) { + if (typeof c?.id !== "string") continue; + out.set(c.id, { + id: c.id, + text: String(c.text ?? ""), + section: String(s.title ?? ""), + ruled: isVerdict(c.verdict), + ...(isVerdict(c.verdict) ? { verdict: c.verdict } : {}), + fingerprint: claimFingerprint(c, r.citations), + }); + } + } + return out; +} + +async function readReportRaw(paths: StorePaths, article: string): Promise<unknown | null> { + const read = await readJsonFile(articleFile(paths, article)); + if (!read.ok) { + if (read.reason === "absent") return null; + throw new VerdictProposalsError(`reports/${article}/report.json is ${read.reason}`, 409); + } + return read.value; +} + +// ─── Reading ─── + function clean(raw: unknown, article: string): VerdictProposalsFile { const r = (raw ?? {}) as Record<string, unknown>; const proposals: Record<string, VerdictProposal> = {}; @@ -92,16 +171,24 @@ function clean(raw: unknown, article: string): VerdictProposalsFile { model: typeof p.model === "string" ? p.model : "", promptVersion: typeof p.promptVersion === "string" ? p.promptVersion : "", at: typeof p.at === "string" ? p.at : "", + // A proposal with none matches no claim: stale. + fingerprint: typeof p.fingerprint === "string" ? p.fingerprint : "", status: p.status as ProposalStatus, ...(typeof p.note === "string" && p.note ? { note: p.note.slice(0, PROPOSAL_NOTE_MAX) } : {}), ...(typeof p.reviewedAt === "string" ? { reviewedAt: p.reviewedAt } : {}), }; } + const j = r.job as Record<string, unknown> | undefined; + const job = + j && typeof j.jobId === "string" && typeof j.pid === "number" && typeof j.host === "string" && typeof j.since === "string" + ? { jobId: j.jobId, pid: j.pid, host: j.host, since: j.since } + : null; return { format: VERDICT_PROPOSALS_FORMAT, version: VERDICT_PROPOSALS_VERSION, article, proposals, + ...(job ? { job } : {}), updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : "", }; } @@ -121,98 +208,164 @@ export async function readVerdictProposals(article: string, paths: StorePaths = return clean(read.value, article); } -/** The proposals still waiting on the operator (status `proposed`). */ +/** The proposals still waiting on the operator (status `proposed`), stale or not. */ export function waitingProposals(f: VerdictProposalsFile | null): [string, VerdictProposal][] { return Object.entries(f?.proposals ?? {}).filter(([, p]) => p.status === "proposed"); } +/** Whether a proposal judged the claim now under its id. */ +export const proposalIsCurrent = (p: Pick<VerdictProposal, "fingerprint">, claim: Pick<CurrentClaim, "fingerprint"> | undefined): boolean => + !!claim && !!p.fingerprint && p.fingerprint === claim.fingerprint; + +/** A verdicts job marked on the file that names a live process on this host. */ +export function liveVerdictsJob(f: VerdictProposalsFile | null): VerdictsJobMark | null { + const j = f?.job; + return j && j.host === os.hostname() && pidAlive(j.pid) ? j : null; +} + +// ─── Writing (under the store's lock, only while report.json exists) ─── + +async function writeHoldingLock(paths: StorePaths, f: VerdictProposalsFile): Promise<void> { + // No mkdir: the article's directory exists while its report.json does. + await writeJsonAtomic(verdictProposalsFile(paths, f.article), f); +} + +const noReport = (article: string) => new VerdictProposalsError(`reports/${article} has no report.json: nothing is proposed for it`, 404); + /** - * Record a run's proposals, under the store's lock. A proposal the operator - * has reviewed (approved or rejected) is kept as it is; a waiting one is - * replaced by the newer. Answers which claims were written and which kept. + * Record a run's proposals, under the store's lock, against the report as it + * is NOW: a claim gone, ruled, or changed since the run read it (another + * fingerprint) is not written; a proposal the operator reviewed on the same + * claim is kept; a waiting one, or a reviewed one on a claim since changed, + * is replaced. Refused when the article has no report.json. */ export async function recordVerdictProposals( article: string, made: Record<string, NewProposal>, paths: StorePaths = getPaths(), now: Date = new Date(), -): Promise<{ written: string[]; kept: string[] }> { +): Promise<{ written: string[]; kept: string[]; stale: string[] }> { return withArticleStoreLock(async () => { + const raw = await readReportRaw(paths, article); + if (!raw) throw noReport(article); + const claims = currentClaims(raw); const cur = (await readVerdictProposals(article, paths)) ?? clean(null, article); const written: string[] = []; const kept: string[] = []; + const stale: string[] = []; for (const [claim, p] of Object.entries(made)) { if (!CLAIM_ID_RE.test(claim)) throw new VerdictProposalsError(`"${claim}" is not a claim id`); if (!isVerdict(p.verdict)) throw new VerdictProposalsError(`${claim}: "${String(p.verdict)}" is not a verdict`); + const now_ = claims.get(claim); + if (!now_ || now_.ruled || !proposalIsCurrent(p, now_)) { + stale.push(claim); + continue; + } const was = cur.proposals[claim]; - if (was && was.status !== "proposed") { + if (was && was.status !== "proposed" && proposalIsCurrent(was, now_)) { kept.push(claim); continue; } - cur.proposals[claim] = { verdict: p.verdict, reason: p.reason.slice(0, PROPOSAL_REASON_MAX), model: p.model, promptVersion: p.promptVersion, at: p.at, status: "proposed" }; + cur.proposals[claim] = { + verdict: p.verdict, + reason: p.reason.slice(0, PROPOSAL_REASON_MAX), + model: p.model, + promptVersion: p.promptVersion, + at: p.at, + fingerprint: p.fingerprint, + status: "proposed", + }; written.push(claim); } if (written.length) { cur.updatedAt = now.toISOString(); - await writeJsonAtomic(verdictProposalsFile(paths, article), cur, { mkdir: true }); + await writeHoldingLock(paths, cur); } - return { written, kept }; + return { written, kept, stale }; + }, paths); +} + +/** Mark (or clear, `null`) the verdicts job proposing for the article. Marking is refused with no report.json. */ +export async function markVerdictsJob(article: string, job: Omit<VerdictsJobMark, "pid" | "host" | "since"> | null, paths: StorePaths = getPaths(), now: Date = new Date()): Promise<void> { + await withArticleStoreLock(async () => { + const raw = await readReportRaw(paths, article); + if (!raw) { + if (job) throw noReport(article); + return; + } + const cur = (await readVerdictProposals(article, paths)) ?? clean(null, article); + if (job) cur.job = { jobId: job.jobId, pid: process.pid, host: os.hostname(), since: now.toISOString() }; + else if (!cur.job) return; + else delete cur.job; + cur.updatedAt = now.toISOString(); + await writeHoldingLock(paths, cur); }, paths); } -export type ProposalReview = { article: string; claim: string; decision: "approve" | "reject"; note?: string }; +// ─── The operator's review ─── + +export type ProposalReview = { + article: string; + claim: string; + decision: "approve" | "reject"; + // The proposal the operator was shown: its verdict and its `at`. + verdict: Verdict; + at: string; + note?: string; +}; /** - * The operator's review of one waiting proposal. Approve: the claim's - * `verdict` set to the proposal's through `patchArticle` (refused when the - * claim has been ruled since, or is gone), then the proposal marked approved. - * Reject: the proposal marked rejected; the claim is untouched. Answers the - * proposal as it now is. + * The operator's review of one waiting proposal — a compare-and-set, under + * the store's lock: refused (409) unless the proposal is still the one shown + * (`verdict`, `at`), still `proposed`, its claim unchanged (fingerprint) and + * unruled. Approve sets the claim's `verdict` through patchArticleHoldingLock; + * either way the CHECKED proposal is recorded with its new status. Answers it. */ export async function reviewVerdictProposal(r: ProposalReview, paths: StorePaths = getPaths(), now: Date = new Date()): Promise<VerdictProposal & { claim: string }> { if (r.decision !== "approve" && r.decision !== "reject") throw new VerdictProposalsError('"decision" is "approve" or "reject"'); + if (!isVerdict(r.verdict)) throw new VerdictProposalsError('"verdict" is the proposed verdict the operator was shown'); + if (typeof r.at !== "string" || !r.at) throw new VerdictProposalsError('"at" is the proposal\'s time the operator was shown'); const note = typeof r.note === "string" ? r.note.trim().slice(0, PROPOSAL_NOTE_MAX) : ""; - const f = await readVerdictProposals(r.article, paths); - const p = f?.proposals[r.claim]; - if (!p) throw new VerdictProposalsError(`${r.article} has no proposal for claim ${r.claim}`, 404); - if (p.status !== "proposed") throw new VerdictProposalsError(`${r.article}/${r.claim}'s proposal was ${p.status} already`, 409); - if (r.decision === "approve") { - const patched = await patchArticle( - r.article, - (report) => { - let found = false; - const sections = report.sections.map((s: Section) => ({ - ...s, - ...(s.claims - ? { - claims: s.claims.map((c) => { - if (c.id !== r.claim) return c; - found = true; - if (isVerdict(c.verdict)) throw new ArticleRegistryError(`${r.article}/${r.claim} is ruled already (${c.verdict})`); - return { ...c, verdict: p.verdict }; - }), - } - : {}), - })); - if (!found) throw new ArticleRegistryError(`${r.article} has no claim ${r.claim}`); - return { sections }; - }, - paths, - ); - if (!patched) throw new VerdictProposalsError(`${r.article} has no report.json`, 404); - } return withArticleStoreLock(async () => { - const cur = (await readVerdictProposals(r.article, paths)) ?? clean(null, r.article); - const was = cur.proposals[r.claim] ?? p; + const f = await readVerdictProposals(r.article, paths); + const p = f?.proposals[r.claim]; + if (!f || !p) throw new VerdictProposalsError(`${r.article} has no proposal for claim ${r.claim}`, 404); + if (p.status !== "proposed") throw new VerdictProposalsError(`${r.article}/${r.claim}'s proposal was ${p.status} already`, 409); + if (p.verdict !== r.verdict || p.at !== r.at) { + throw new VerdictProposalsError(`${r.article}/${r.claim}'s proposal changed since it was shown (now ${p.verdict}, ${p.at}): reload it`, 409); + } + const raw = await readReportRaw(paths, r.article); + if (!raw) throw noReport(r.article); + const claim = currentClaims(raw).get(r.claim); + if (!claim) throw new VerdictProposalsError(`${r.article} has no claim ${r.claim} now`, 409); + if (!proposalIsCurrent(p, claim)) throw new VerdictProposalsError(`${r.article}/${r.claim} changed since it was proposed for (another claim, or other citations): the proposal is stale`, 409); + if (claim.ruled) throw new VerdictProposalsError(`${r.article}/${r.claim} is ruled already (${claim.verdict})`, 409); + if (r.decision === "approve") { + const patched = await patchArticleHoldingLock( + r.article, + (report) => ({ + sections: report.sections.map((s: Section) => + s.claims ? { ...s, claims: s.claims.map((c) => (c.id === r.claim ? { ...c, verdict: p.verdict } : c)) } : s, + ), + }), + paths, + ); + if (!patched) throw noReport(r.article); + } const next: VerdictProposal = { - ...was, + verdict: p.verdict, + reason: p.reason, + model: p.model, + promptVersion: p.promptVersion, + at: p.at, + fingerprint: p.fingerprint, status: r.decision === "approve" ? "approved" : "rejected", reviewedAt: now.toISOString(), ...(note ? { note } : {}), }; - cur.proposals[r.claim] = next; - cur.updatedAt = now.toISOString(); - await writeJsonAtomic(verdictProposalsFile(paths, r.article), cur, { mkdir: true }); + f.proposals[r.claim] = next; + f.updatedAt = now.toISOString(); + await writeHoldingLock(paths, f); return { ...next, claim: r.claim }; }, paths); } diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -35,6 +35,7 @@ import { GENERATION_WEB_FIELD_DOCS, GENERATION_VERDICTS_FIELD_DOCS, GENERATION_VERDICT_BAR_FIELD_DOCS, + GENERATION_VERDICT_WINDOW_FIELD_DOCS, SOCIAL_LINK_FIELD_DOCS, SOCIAL_SETTINGS_FIELD_DOCS, X_SOCIAL_SETTINGS_FIELD_DOCS, @@ -302,6 +303,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, { path: "generation.cut", docs: GENERATION_CUT_FIELD_DOCS, defaults: fromObject(d.generation.cut) }, { path: "generation.verdicts", docs: GENERATION_VERDICTS_FIELD_DOCS, defaults: fromObject(d.generation.verdicts) }, { path: "generation.verdicts.bar", docs: GENERATION_VERDICT_BAR_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.bar) }, + { path: "generation.verdicts.window", docs: GENERATION_VERDICT_WINDOW_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.window) }, { path: "generation.triage", docs: GENERATION_TRIAGE_FIELD_DOCS, defaults: fromObject(d.generation.triage) }, ], }; diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -90,6 +90,7 @@ export { GENERATION_WEB_FIELD_DOCS, GENERATION_VERDICTS_FIELD_DOCS, GENERATION_VERDICT_BAR_FIELD_DOCS, + GENERATION_VERDICT_WINDOW_FIELD_DOCS, GENERATION_TRIAGE_FIELD_DOCS, type GenerationSettings, } from "./generationSettings"; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -8,6 +8,7 @@ - **The drive health timing on `/storage` says "Saved." at once** — it could wait about five seconds (the next automatic refresh), as Settings' save did before. Needs a restart of the editor. - **A storage move's Reconcile and resume no longer calls a folder whose date alone differs "changed".** It says "N directories differ only in mtime" apart from what was added, missing or changed, and a reconcile with nothing else to settle says the copy's content already matches. - **`generate`'s answer for a media draft names the video project first**, above the iteration's own files. +- **A model can propose verdicts for a fact-check's unruled claims, for you to approve or reject.** `pnpm ops report-draft --json '{"task":"verdicts","article":"<id>"}'` asks each claim with no verdict, with the verdict bench's own prompt, and keeps each proposed verdict, its reason, the model and the prompt version in `verdicts.proposed.json` beside the article, never in `report.json`. It runs only on a model you ticked on the verdict bench (`settings.generation.verdicts.models`, empty until you do), and never sets a verdict itself. umtool's Inbox shows "N verdicts proposed" under Review; **Review verdicts** opens the article, where each proposal has **Approve** (the claim gets that verdict) and **Reject** (the claim stays unruled), with an optional note. A claim you have ruled, or whose proposal you have reviewed, is not asked again. `pnpm ops verdict-review` does the same from the command line, naming the verdict and time of the proposal you saw: if it was replaced since, or its claim changed (a revision that moved the claim ids), the review is refused instead of ruling the wrong claim. A proposal whose claim changed is counted as stale and not shown; a `verdicts.proposed.json` that does not read is shown on the article and as a Blocking card. Proposals read the transcript window in `settings.generation.verdicts.window`, which saving the bar on the verdict bench sets to that run's window. An article is not deleted while a proposal job runs for it. Needs a restart of the editor and umtool. - **The verdict bench asks to the operator's standard, and says which prompt it asked with.** What each verdict means is written once (`common/lib/report/verdicts.mjs`) and read by the bench's prompt, REPORT.md and umtool's bench page: CORROBORATED when the substance of the claim is shown by the cited words (framing, emphasis or a detail the transcript does not show does not demote it), PARTLY only when a part is shown overstated or wrong, and when in doubt between the two, CORROBORATED. The model now writes its reason before its verdict, and sees the report's title, the claim's section, and each cited line's speaker and recording date. Each run records its prompt version and a hash of its items; a run made before this is version 1, and a run is never resumed under another version. Needs a restart of the editor and umtool. - **`archilyzer reports bench-verdicts` takes `--items-from <run>`, `--window-mode seconds|turn` and a stratified `--limit`.** `--items-from vb-r28` asks the same items again (for example a local model on a new prompt, at no cost). `--window-mode turn` shows the cited speaker's turn instead of a fixed number of seconds either side, bounded by `--window`. `--limit` keeps every verdict the operator ruled, in proportion. A re-run of a run asks only the models it names, so a local-only re-run never asks a paid model again. A citation that gives no transcript is listed with its reason instead of being left out silently. `pnpm ops bench-verdicts` takes the same keys (`itemsFrom`, `windowMode`, `limit`). - **umtool's verdict bench compares runs and takes your marks.** `/tools/bench` shows each run's prompt version and items hash, and **compare with** lists the runs over the same items: each model's agreement in both and every claim whose answer changed. Each disagreement has **Right** and **Wrong** (was the model right?), kept beside the run, and the not-CORROBORATED precision and recall beside the bar are shown as ruled and with your marks, so the bar can be set from what you marked. "What the verdicts mean" lists the definitions. diff --git a/editor/app/api/ops/_verdicts.test.ts b/editor/app/api/ops/_verdicts.test.ts @@ -68,18 +68,20 @@ test("the body: a verdicts job takes claims, never an iteration; claims are a ve assert.throws(() => parseReportDraftBody({ task: "verdicts", article: "a", iteration: 2 }), /takes no iteration/); assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["c"], claims: ["c1"] }), /"claims" is a verdicts job's/); assert.throws(() => parseVerdictReviewBody({ article: "a", claim: "c1", decision: "maybe" }), /"approve" or "reject"/); + assert.throws(() => parseVerdictReviewBody({ article: "a", claim: "c1", decision: "approve" }), /"verdict" is the proposed verdict you were shown/); + assert.throws(() => parseVerdictReviewBody({ article: "a", claim: "c1", decision: "approve", verdict: "PARTLY" }), /"at" is the proposal's `at`/); }); test("refused until a model clears the bar; then a report-draft job on draft:local writes proposals, never a verdict; approve sets it", async () => { const none = await enqueueReportDraft({ task: "verdicts", article: id }, deps()); assert.equal(none.result.ok, false); assert.match((none.result as { error: string }).error, /models is empty/); - const unlisted = await enqueueReportDraft({ task: "verdicts", article: id, model: "qwen3:8b" }, deps({ verdicts: { bar: gen.verdicts.bar, models: ["claude-opus-5-5"] } })); + const unlisted = await enqueueReportDraft({ task: "verdicts", article: id, model: "qwen3:8b" }, deps({ verdicts: { ...gen.verdicts, models: ["claude-opus-5-5"] } })); assert.match((unlisted.result as { error: string }).error, /has not cleared the verdict bench's bar/); const before = await readFile(articleFile(paths, id), "utf8"); for (let i = 0; i < 3; i++) ol.push(jsonReply({ reason: "the window shows the opposite", verdict: "CONTRADICTED" })); - const out = await enqueueReportDraft({ task: "verdicts", article: id }, deps({ verdicts: { bar: gen.verdicts.bar, models: ["qwen3:8b"] } })); + const out = await enqueueReportDraft({ task: "verdicts", article: id }, deps({ verdicts: { ...gen.verdicts, models: ["qwen3:8b"], window: { mode: "turn", seconds: 30 } } })); assert.ok(out.result.ok, (out.result as { error?: string }).error); assert.equal("iteration" in out ? out.iteration : null, 0); const job = getRegistry().get(out.result.jobId)!; @@ -91,12 +93,18 @@ test("refused until a model clears the bar; then a report-draft job on draft:loc assert.equal(done.status, "done", log); assert.match(log, /@@report-draft \{"article":"synth-ruled","iteration":0,"task":"verdicts","status":"done"/); assert.match(log, /unloaded qwen3:8b from ollama/); + // The window is settings.generation.verdicts.window's. + assert.match(log, /window the speaker's turn within 30 s/); assert.deepEqual(ol.unloads.at(-1), "qwen3:8b"); assert.equal(await readFile(articleFile(paths, id), "utf8"), before, "report.json untouched"); const f = (await readVerdictProposals(id, paths))!; assert.deepEqual(Object.keys(f.proposals).sort(), ["r02", "r04", "r07"]); + // The job's mark is cleared when it ends; the window was the settings' (logged by the task). + assert.equal(f.job, undefined); - const p = await reviewProposal({ article: id, claim: "r04", decision: "approve" }, { paths }); + // A compare-and-set: the verdict and `at` the operator was shown. + await assert.rejects(reviewProposal({ article: id, claim: "r04", decision: "approve", verdict: "PARTLY", at: f.proposals.r04!.at }, { paths }), (e: any) => e.status === 409); + const p = await reviewProposal({ article: id, claim: "r04", decision: "approve", verdict: "CONTRADICTED", at: f.proposals.r04!.at }, { paths }); assert.equal(p.status, "approved"); const after = JSON.parse(await readFile(articleFile(paths, id), "utf8")); assert.equal(after.sections.flatMap((s: any) => s.claims).find((c: any) => c.id === "r04").verdict, "CONTRADICTED"); diff --git a/editor/app/api/ops/verdict-review/route.ts b/editor/app/api/ops/verdict-review/route.ts @@ -7,12 +7,15 @@ import { opsFail, ops } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { article, claim, decision: "approve" | "reject", note? } +// POST { article, claim, decision: "approve" | "reject", verdict, at, note? } // -> { ok: true, proposal: {claim, verdict, reason, model, promptVersion, at, status, note?, reviewedAt} } // // The operator's review of one verdict PROPOSAL (release 29 M8): a model's // proposed verdict for an unruled fact-check claim, kept in -// `reports/<article>/verdicts.proposed.json` (never report.json). Approve +// `reports/<article>/verdicts.proposed.json` (never report.json). A +// COMPARE-AND-SET: `verdict` and `at` are the proposal the operator was shown; +// one replaced since, reviewed already, or whose claim changed (its +// fingerprint) or was ruled meanwhile is refused 409. Approve // sets the claim's `verdict` to the proposal's through the registry's // patchArticle, then marks the proposal approved; reject marks it rejected // and leaves the claim unruled. Synchronous. 404 no such proposal; 409 one diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts @@ -36,7 +36,7 @@ type Sent = { url: string; method: string; body?: unknown }; // An editor that serves the policy, the day's usage, a report-draft POST, a // job that runs for `runPolls` polls and then ends `end`, and the iteration. -function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end?: string; iteration?: Record<string, unknown>; marker?: boolean; task?: string } = {}) { +function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end?: string; iteration?: Record<string, unknown>; marker?: boolean; task?: string; markerJson?: Record<string, unknown> } = {}) { let policy = { ...POLICY, ...(opts.policy ?? {}) }; let polls = 0; const runPolls = opts.runPolls ?? 0; @@ -57,7 +57,7 @@ function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end steps: [], ...(opts.iteration ?? {}), }; - const marker = `@@report-draft ${JSON.stringify({ article: "synth-a", iteration: 3, task: opts.task ?? "revise-report", status: opts.end ?? "done", summary: "2 op(s) applied, 1 refused — “A title”", usd: 0.45, minutes: 2.5 })}`; + const marker = `@@report-draft ${JSON.stringify(opts.markerJson ?? { article: "synth-a", iteration: 3, task: opts.task ?? "revise-report", status: opts.end ?? "done", summary: "2 op(s) applied, 1 refused — “A title”", usd: 0.45, minutes: 2.5 })}`; const fake = fakeEditor((s) => { const u = new URL(s.url); if (u.pathname === "/api/ops/settings" && s.method === "GET") return { status: 200, body: { ok: true, key: "generation", value: policy } }; @@ -449,3 +449,22 @@ test("generate: a research run's summary is its phase and proposals, with what i assert.match(a.text, /generate with task "sweep", article "synth-a", iteration: 3, wait: true/); assert.doesNotMatch(a.text, /Review it — you are the reviewer/); }); + +test("generate verdicts: never this session's — a code route with no model refuses; done, the marker's counts and the operator's review", async () => { + const e = editor({ policy: { routes: { ...POLICY.routes, verdicts: "code" } } }); + const a = await generateTool({ task: "verdicts", article: "synth-ruled" }, e.deps as never); + assert.equal(a.isError, true); + assert.match(a.text, /verdict proposals run only on a model that cleared the verdict bench's bar \(settings\.generation\.verdicts\.models\)/); + assert.match(a.text, /never proposes or rules claims' verdicts itself/); + assert.equal(e.sentOf("/api/ops/report-draft").length, 0); + const done = editor({ + markerJson: { article: "synth-ruled", iteration: 0, task: "verdicts", status: "done", summary: "3 verdicts proposed on qwen3:8b", usd: 0, verdicts: { proposed: 3, failed: 0, skipped: 5, promptVersion: "2" } }, + }); + const b = await generateTool({ task: "verdicts", article: "synth-ruled", model: "qwen3:8b", wait: true }, done.deps as never); + assert.equal(b.isError, false, b.text); + assert.match(b.text, /^generate verdicts: job job-1 ended \*\*done\*\* — 3 verdicts proposed on qwen3:8b/); + assert.match(b.text, /Article: synth-ruled · 3 proposed, 0 failed, 5 skipped · prompt v2/); + assert.match(b.text, /Review verdicts/); + assert.match(b.text, /Never set a claim's verdict yourself/); + assert.equal(done.sentOf("/api/ops/iterations").length, 0); +}); diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts @@ -344,7 +344,36 @@ export async function followGeneration( } } -type Marker = { article?: string; iteration?: number; task?: string; status?: string; summary?: string; usd?: number; minutes?: number }; +type Marker = { + article?: string; + iteration?: number; + task?: string; + status?: string; + summary?: string; + usd?: number; + minutes?: number; + // A verdicts job's (release 29 M8): no iteration (0). + verdicts?: { proposed?: number; failed?: number; skipped?: number; promptVersion?: string }; +}; + +// What to do with verdict proposals: they are the operator's to rule. +export const VERDICTS_REVIEW_GUIDANCE = + "**The proposals are the operator's to rule**: they wait in umtool's Inbox (Review → Review verdicts) on the " + + "article's tab, where each is approved or rejected; `pnpm ops verdict-review` does the same when the operator " + + "asks. Never set a claim's verdict yourself, and never rule claims in this session in a proposal's place."; + +function verdictsSummary(f: Extract<Followed, { kind: "ended" }>, m: Marker): ToolAnswer { + const v = m.verdicts ?? {}; + const lines = [ + `generate verdicts: job ${f.job.id} ended **${f.job.status}** — ${m.summary ?? m.status ?? ""}`.trim(), + `Article: ${m.article ?? "?"} · ${v.proposed ?? 0} proposed, ${v.failed ?? 0} failed, ${v.skipped ?? 0} skipped` + + (v.promptVersion ? ` · prompt v${v.promptVersion}` : "") + + (m.usd ? ` · $${m.usd.toFixed(4)}` : ""), + "", + VERDICTS_REVIEW_GUIDANCE, + ]; + return { text: lines.join("\n"), isError: f.job.status !== "done" }; +} export function resultMarkerOf(tail: readonly string[]): Marker | null { for (let i = tail.length - 1; i >= 0; i--) { @@ -457,6 +486,7 @@ async function summarise( hint: { task?: string; article?: string; iteration?: number }, ): Promise<ToolAnswer> { const marker = resultMarkerOf(f.tail); + if (marker?.task === "verdicts") return verdictsSummary(f, marker); const article = marker?.article ?? hint.article; const n = marker?.iteration ?? hint.iteration; const task = marker?.task ?? hint.task ?? "report-draft"; @@ -539,7 +569,16 @@ export async function generateTool( } const p = read.policy; if (req.via) body.model = p.models[req.via]; - else if (p.routes[task] === "code") { + else if (task === "verdicts" && p.routes[task] === "code") { + // Verdicts are not a session's to make: the bench's bar names the models. + return { + text: + `generate: verdicts is routed to Claude Code (preset ${p.preset}), and verdict proposals run only on a model ` + + `that cleared the verdict bench's bar (settings.generation.verdicts.models) — name one as model. ` + + `This session never proposes or rules claims' verdicts itself.`, + isError: true, + }; + } else if (p.routes[task] === "code") { const continuing = task === "sweep" && typeof body.iteration === "number"; return { text: continuing diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9581,3 +9581,12 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri pause/resume actions (`LaneActionButton`) still revalidate. - **`CopyDifferences.mtimeOnly`** (`common/controller/relocateDir.ts`): `classifyDrift` puts a directory whose only difference is its mtime there, not in `changed`; `describeDifferences` names it apart. + +- **Review fixes (2026-10-15):** a proposal's `fingerprint` (`claimFingerprint`: the claim's text and its citations' + kind, recording, seconds, quote) ties it to the claim it judged; a mismatch is STALE (not waiting, review 409, no reason + to skip). `verdict-review` requires `verdict` and `at` (a compare-and-set, all under one lock; + `patchArticleHoldingLock` in `registry.ts` is `patchArticle`'s body for a lock holder). No sidecar write without + `report.json`, no `mkdir`; a running verdicts job is `job {jobId, pid, host, since}` on the sidecar and + `planArticleDelete` refuses while it is live. `settings.generation.verdicts.window {mode, seconds}` (default seconds, + 60) is the window proposals read; umtool's bar form writes the run's. `benchItemsHash` covers the claim's text and its + quotes' spans. diff --git a/plans/release-29.md b/plans/release-29.md @@ -594,6 +594,49 @@ Found and left: re-render late under load as the timing's did; the publish-lane spec now waits on the lane's state instead. Not changed here: the button is shared by every lane. +### M8/V1 review fixes, as shipped (2026-10-15, lane B, `r29/verdicts`) + +The read-only review of `3217bdfb..925bc809` (seven findings) and the orchestrator's rulings, fixed on top of `925bc809`: + +- **Fingerprint (1).** Each proposal carries `fingerprint` = `claimFingerprint(claim, citations)` (sha256, 16 hex, of the + claim's text and each citation's kind, recording, seconds and quote). A proposal whose claim's fingerprint is not the + current one is STALE: never waiting (umtool counts it: "N stale (the claim changed since)"), its review refused 409, + and — reviewed — no reason to skip the claim now under that id (`proposeVerdicts`, `recordVerdictProposals`). Tested on + a revision that drops a claim and shifts the ids. +- **Compare-and-set (2).** `verdict-review` takes `verdict` and `at` (the proposal shown; required). The whole review runs + under ONE lock (`patchArticleHoldingLock`, new in `registry.ts`, `patchArticle`'s body): refused 409 when the proposal + was replaced or reviewed, its claim changed or was ruled; the CHECKED proposal is recorded. umtool's panel sends them + and shows a refusal. Tested: a rewrite between view and click, concurrent approve and reject (one wins, the record and + the claim agree). +- **No orphans (3).** Every sidecar write is under the lock and refused (404) when `report.json` is absent; no `mkdir`. A + verdicts job marks itself on the sidecar (`job {jobId, pid, host, since}`, cleared at its end); `planArticleDelete` + refuses while the mark names a live process on this host. +- **The `code` route (4).** MCP `generate` refuses a verdicts job routed to `code` with no model ("a session never proposes + or rules claims' verdicts itself"); its `@@report-draft` verdicts marker (iteration 0) is rendered with the counts and + the operator's review; `.claude/commands/gen.md` step 4 says verdicts are never a session's. +- **Resume (5):** a changed `--limit` is refused. **Hash (6):** `benchItemsHash` includes the claim's text and its quotes' + spans (context lines still out). **Unreadable sidecar (7):** shown on the article tab (`data-proposals-error`) and as the + Inbox's `unreadable-proposals` (Blocking, "Repair verdicts.proposed.json"). +- **The window (the open question, ruled):** `settings.generation.verdicts.window {mode: seconds | turn, seconds}` + (default the bench's: seconds, 60; SETTINGS.md) is what proposals read. umtool's bar form saves the run's window with + the bar ("proposals read ±60 s (this run's window)"); a save without one keeps the set window. + +| Commit | What | +| --- | --- | +| `58270685` | common, editor, mcp: the fingerprint, the compare-and-set, no orphans + the delete refusal, the MCP/`code` route, the limit, the hash, the window setting; tests; SETTINGS.md, COMMANDS.md, settings.json.example, gen.md | +| `a6c42610` | umtool: the panel (verdict/at, refusal, stale, error), `unreadable-proposals`, the bar's window; both specs | +| `309c2fbe` | umtool: the window line as one string | +| (this commit) | this record, FACTS, CHANGELOG, umtool docs | + +Gates (at `309c2fbe`): repo-wide tsc clean at each commit; common **4205/4205** (+3: the shift, the compare-and-set, no +orphans and the delete refusal; the settings window; the bench limit and hash); editor unit 306/306 (`_verdicts.test.ts`: +the compare-and-set body, the window from settings in the log); mcp **371/371** (+1: the `code` route refused, the +verdicts marker rendered); test:scripts 1016 tests, 1013 pass, 3 skipped, 0 fail (+1 `unreadable-proposals`); umtool +33/33; docs cli/files/env and settings example checks clean; umtool e2e `verdict-proposed.spec` + `verdict-bench.spec`: +run 1 4 passed, 1 failed (the bar's window line rendered without its space — `309c2fbe`), run 2 `verdict-bench.spec` +**4/4**; `verdict-proposed.spec` **1/1** in run 1 (the stale proposal counted, the rewrite between view and click +refused, then rejected on reload). + ## Not in this release Auto-posting to X/Bluesky/YouTube (text only); any umtool restructuring; the "en track → 0 cues" bug (closed in r20). diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -118,7 +118,7 @@ // pnpm ops report-draft --json '{"task":"triage","article":"co-host-watch","question":"Who co-hosts?","channels":["demo-channel"],"terms":"co-host"}' --wait // pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait // pnpm ops report-draft --json '{"task":"verdicts","article":"demo-factcheck"}' --wait -// pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve"}' +// pnpm ops verdict-review --json '{"article":"demo-factcheck","claim":"c04","decision":"approve","verdict":"PARTLY","at":"2026-10-15T10:00:00.000Z"}' // pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}' // pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}' // pnpm ops report-schedule --json '{"action":"list"}' @@ -437,7 +437,8 @@ const ACTIONS = [ // rejected ({article, iteration, ids?, approve?, note?}). Synchronous. "research-approve", // VERDICT PROPOSALS (release 29 M8): the operator's review of one model's - // proposed verdict ({article, claim, decision: approve | reject, note?}): + // proposed verdict ({article, claim, decision: approve | reject, verdict, + // at, note?} — a compare-and-set on the proposal shown): // approve sets the claim's verdict through the registry. Synchronous. "verdict-review", // THE VERDICT BENCH (release 28 M7): ruled fact-check claims asked of each @@ -1354,9 +1355,12 @@ export function usage() { " @@report-draft {…, verdicts: {proposed, failed, skipped, promptVersion}}.", "", 'verdict-review settles one verdict proposal: {"article", "claim",', - ' "decision": "approve" | "reject", "note"?} -> {proposal}. approve sets the', - " claim's verdict to the proposal's (through the registry; refused when the", - " claim was ruled meanwhile); reject leaves the claim unruled. Synchronous.", + ' "decision": "approve" | "reject", "verdict", "at", "note"?} -> {proposal}.', + ' "verdict" and "at" are the proposal you were shown (its', + " verdicts.proposed.json entry): a compare-and-set, refused (409) when the", + " proposal was replaced or reviewed since, its claim changed (the proposal is", + " stale) or was ruled meanwhile. approve sets the claim's verdict to it", + " (through the registry); reject leaves the claim unruled. Synchronous.", "", 'research-approve settles a research run\'s acquisitions: {"article",', ' "iteration", "ids"?: ["p01", …], "approve"?: true | false, "note"?} ->', diff --git a/settings.json.example b/settings.json.example @@ -296,7 +296,11 @@ "contradictedRecall": 0, "notFoundRecall": 0 }, - "models": [] + "models": [], + "window": { + "mode": "seconds", + "seconds": 60 + } }, "triage": { "model": "local", diff --git a/umtool/app/tools/bench/page.tsx b/umtool/app/tools/bench/page.tsx @@ -141,7 +141,7 @@ function RunView({ <div className="flex flex-wrap items-start gap-3"> <section aria-label="the bar" className="min-w-[24rem] flex-1 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3"> {policy ? ( - <BarForm initial={policy} models={score.models} /> + <BarForm initial={policy} models={score.models} window={{ mode: s.windowMode ?? "seconds", seconds: s.windowS }} /> ) : ( <p role="alert" className="text-[var(--color-bad)]"> the bar cannot be read: {policyError} diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx @@ -471,7 +471,7 @@ async function ArticleTab({ proposals ? ( <> {line} - <VerdictProposals article={reportId} waiting={proposals.waiting} /> + <VerdictProposals article={reportId} waiting={proposals.waiting} stale={proposals.stale} {...(proposals.error ? { error: proposals.error } : {})} /> </> ) : ( line diff --git a/umtool/components/articles/VerdictProposals.tsx b/umtool/components/articles/VerdictProposals.tsx @@ -10,9 +10,24 @@ import type { WaitingProposal } from "@/lib/articles/verdicts"; // model and its prompt version — and Approve (the claim's verdict is set, by // the editor's verdict-review through the registry) or Reject (the claim // stays unruled), each with an optional note. Proposed verdicts are plain -// text: a verdict's colour is a ruling's, and these are not rulings yet. +// text: a verdict's colour is a ruling's, and these are not rulings yet. The +// review sends the verdict and `at` shown (a compare-and-set: a proposal that +// changed since is refused, and the refusal shown). Stale proposals are +// counted, an unreadable sidecar said. -export default function VerdictProposals({ article, waiting }: { article: string; waiting: WaitingProposal[] }) { +export default function VerdictProposals({ + article, + waiting, + stale = 0, + error, +}: { + article: string; + waiting: WaitingProposal[]; + // Proposals on claims changed since they were made: not shown, not reviewable. + stale?: number; + // The sidecar did not read: nothing in it is shown until it is repaired. + error?: string; +}) { const router = useRouter(); const [left, setLeft] = useState(waiting); const [notes, setNotes] = useState<Record<string, string>>({}); @@ -24,7 +39,11 @@ export default function VerdictProposals({ article, waiting }: { article: string setStatus(null); try { const note = notes[p.claim]?.trim(); - const r = await fetch("/api/articles/verdicts", { method: "POST", body: JSON.stringify({ article, claim: p.claim, decision, ...(note ? { note } : {}) }) }); + // The proposal shown: the review is refused (409) if it changed since. + const r = await fetch("/api/articles/verdicts", { + method: "POST", + body: JSON.stringify({ article, claim: p.claim, decision, verdict: p.verdict, at: p.at, ...(note ? { note } : {}) }), + }); const body = await r.json(); if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`); setLeft((xs) => xs.filter((x) => x.claim !== p.claim)); @@ -37,12 +56,17 @@ export default function VerdictProposals({ article, waiting }: { article: string } } - if (!left.length && !status) return null; + if (!left.length && !status && !error && !stale) return null; return ( <section aria-label="verdict proposals" id="verdict-proposals" className="w-full rounded-[3px] border border-seam bg-panel px-3 py-2 text-[12px] text-text"> <div className="micro"> - verdict proposals · {left.length} waiting + verdict proposals · {left.length} waiting{stale ? ` · ${stale} stale (the claim changed since)` : ""} </div> + {error && ( + <p role="alert" data-proposals-error="" className="mt-1 text-[var(--color-bad)]"> + verdicts.proposed.json does not read: {error} + </p> + )} {status && ( <p role="status" className={status.ok ? "mt-1 text-text-2" : "mt-1 text-[var(--color-bad)]"}> {status.text} diff --git a/umtool/components/bench/BarForm.tsx b/umtool/components/bench/BarForm.tsx @@ -20,7 +20,11 @@ const KEYS: { key: keyof VerdictBar; label: string }[] = [ const field = "w-16 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]"; const toPct = (v: number) => String(Math.round(v * 1000) / 10); -export default function BarForm({ initial, models }: { initial: GenerationVerdicts; models: ModelScore[] }) { +// The window proposals read is the run's the bar is set on: saved with it +// (settings.generation.verdicts.window, release 29). +const windowWords = (w: { mode: string; seconds: number }) => (w.mode === "turn" ? `the speaker's turn within ${w.seconds} s` : `±${w.seconds} s`); + +export default function BarForm({ initial, models, window }: { initial: GenerationVerdicts; models: ModelScore[]; window: GenerationVerdicts["window"] }) { const [typed, setTyped] = useState(() => Object.fromEntries(KEYS.map((k) => [k.key, toPct(initial.bar[k.key])])) as Record<keyof VerdictBar, string>); const [ticked, setTicked] = useState<string[]>(initial.models); const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null); @@ -35,7 +39,7 @@ export default function BarForm({ initial, models }: { initial: GenerationVerdic setStatus(null); const keep = ticked.filter((m) => !here.has(m) || passesBar(models.find((x) => x.model === m)!, bar).pass); try { - const r = await fetch("/api/bench/bar", { method: "POST", body: JSON.stringify({ bar, models: keep }) }); + const r = await fetch("/api/bench/bar", { method: "POST", body: JSON.stringify({ bar, models: keep, window }) }); const body = await r.json(); if (!r.ok) throw new Error(body.error ?? `HTTP ${r.status}`); const v = body.verdicts as GenerationVerdicts; @@ -89,6 +93,10 @@ export default function BarForm({ initial, models }: { initial: GenerationVerdic </label> ); })} + <span className="text-[var(--color-dim)]" data-window={`${window.mode}:${window.seconds}`}> + {`proposals read ${windowWords(window)} (this run's window)`} + {initial.window && (initial.window.mode !== window.mode || initial.window.seconds !== window.seconds) ? ` · now ${windowWords(initial.window)}` : ""} + </span> <Button type="submit" size="sm" disabled={busy}> Save the bar </Button> diff --git a/umtool/docs/inbox.md b/umtool/docs/inbox.md @@ -91,11 +91,12 @@ Cover); a cut's opens the cut's page, at the song's full path. | `refresh-held` ([refresh.md](refresh.md)) | Your call | Refresh | | `iteration-ready` — done, not current, newer than current | Review | Make i<n> current | | `drafts-unreviewed` — drafted fields awaiting review (unreviewed, or edited since approved) | Review | Review drafts | -| `verdict-proposed` — a model's proposed verdict for a fact-check's unruled claim (the article's `verdicts.proposed.json`), one row per proposal; gone once approved or rejected on the article's tab, or the claim is ruled by hand | Review | Review verdicts | +| `verdict-proposed` — a model's proposed verdict for a fact-check's unruled claim (the article's `verdicts.proposed.json`), one row per proposal; gone once approved or rejected on the article's tab, the claim is ruled by hand, or the claim changes under its id (a stale proposal: counted on the tab, never shown) | Review | Review verdicts | | `edition-ready` | Review | Review edition | | `refresh-available` — a partial check says so ("the check was partial — not reached: …; a Refresh reads the rest"), never "nothing new" | Review | Refresh | | `open-note` — an operator note (its href ends `note=<id>`) | Notes | Answer note | | `unreadable-notes` | Blocking | Repair notes.json | +| `unreadable-proposals` — an article's `verdicts.proposed.json` does not read: no proposal is shown or written until it is fixed | Blocking | Repair verdicts.proposed.json | | `link-ambiguous` — a slug match no iteration or manifest settles | Open | Link the video | | `looks-done` | Ready to finish | Mark done | diff --git a/umtool/docs/tools.md b/umtool/docs/tools.md @@ -13,7 +13,7 @@ a tool the rail opens Tools into its tools: find · mix · **song ▸** (the fou | Faces | `/tools/faces` | every cover corner on record, deduped by episode and moment, the ones that ship first: judge the crop (`face-verdicts.json`, which `make-thumb.mjs` reads; the page never touches the thumb manifests). The dashed box is what `facecrop.py` would cut, the solid one yours. `?cover=` / `?key=` open one | | Sources | `/tools/sources` | where the song palette comes from: placements (the finished runtime an episode supplies) and clips (the palette) per episode — different units, both shown, never summed — the top episode, the top five, how many cover half | | Trim | `/tools/trim/<set>` | a hook set's trims against the waveform, then **run the chain** (apply-hook-trims → pick-take → mix-hooks) | -| Verdict bench | `/tools/bench` | could a model propose a fact-check verdict well enough to review: runs of `archilyzer reports bench-verdicts`, each with its prompt version and items hash, each model's agreement and recalls against the bar (**passes the bar** / **fails the bar**), confusion matrices, the items; **compare with** another run over the same items (each model's agreement in both, the claims whose answers changed); **Right** / **Wrong** on each disagreement (was the model right? kept in the run's `marks.json`), and not-CORROBORATED precision and recall as ruled and as marked beside the bar; what the verdicts mean. The bar is set here (`settings.generation.verdicts`); a ticked model is the only kind verdict proposals run on (the Inbox's `verdict-proposed`, [inbox.md](inbox.md)) | +| Verdict bench | `/tools/bench` | could a model propose a fact-check verdict well enough to review: runs of `archilyzer reports bench-verdicts`, each with its prompt version and items hash, each model's agreement and recalls against the bar (**passes the bar** / **fails the bar**), confusion matrices, the items; **compare with** another run over the same items (each model's agreement in both, the claims whose answers changed); **Right** / **Wrong** on each disagreement (was the model right? kept in the run's `marks.json`), and not-CORROBORATED precision and recall as ruled and as marked beside the bar; what the verdicts mean. The bar is set here (`settings.generation.verdicts`), and with it the window proposals read (`verdicts.window`: the run's window mode and seconds); a ticked model is the only kind verdict proposals run on (the Inbox's `verdict-proposed`, [inbox.md](inbox.md)) | A song's own page links its piles, find, mix and sources (its Overview's Song tools; [piece.md](piece.md#a-song-projectspath)). The old addresses (`/sort`, `/salvage`, `/verify`, `/keeps`, `/mix`, `/bench`, `/browse/find`, `/browse/faces`, diff --git a/umtool/e2e/verdict-bench.spec.ts b/umtool/e2e/verdict-bench.spec.ts @@ -83,10 +83,12 @@ test("the bar: saved through the editor's settings action; a passing model ticke const use = form.getByRole("checkbox", { name: `use ${SONNET}` }); await expect(use).toBeEnabled(); await use.check(); + await expect(form.locator("[data-window]")).toHaveText(/^proposals read ±60 s \(this run's window\)/); await form.getByRole("button", { name: "Save the bar" }).click(); await expect(form.getByRole("status")).toHaveText("Saved."); expect(stubAsked("settings").at(-1)).toMatchObject({ - patch: { generation: { verdicts: { bar: { agreement: 0.5, contradictedRecall: 0.5, notFoundRecall: 0.5 }, models: [SONNET] } } }, + // The window proposals read is the run's the bar was set on (release 29). + patch: { generation: { verdicts: { bar: { agreement: 0.5, contradictedRecall: 0.5, notFoundRecall: 0.5 }, models: [SONNET], window: { mode: "seconds", seconds: 60 } } } }, authorization: "Bearer umtool-e2e-token", }); // Read back: the tiles say who passes the saved bar. diff --git a/umtool/e2e/verdict-proposed.spec.ts b/umtool/e2e/verdict-proposed.spec.ts @@ -3,6 +3,7 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { WARM_TIMEOUT, warm } from "./warm"; +import { claimFingerprint } from "yt-dlp-transcript-common/lib/report/verdictProposals"; // --------------------------------------------------------------------------- // Verdict proposals (release 29 M8): a synthetic fact-check in the fixture's @@ -10,7 +11,9 @@ import { WARM_TIMEOUT, warm } from "./warm"; // (`verdicts.proposed.json` beside it). The Inbox's `verdict-proposed` card // (Review) → the article's tab → Approve sets the claim's verdict (the stub // editor runs the REAL verdict-review over the fixture's store), Reject -// leaves the claim unruled; the card goes once nothing waits. +// leaves the claim unruled; the card goes once nothing waits. Release 29's +// review fixes: a stale proposal (its claim changed) is counted, not shown; a +// proposal rewritten between view and click is refused. // --------------------------------------------------------------------------- const HERE = path.dirname(fileURLToPath(import.meta.url)); @@ -37,18 +40,23 @@ const report = { { id: "c1", text: "The article says she opened the shop in spring.", verdict: "CORROBORATED", citations: ["q1"] }, { id: "c2", text: "The article says the oven was broken for a month.", citations: ["q1"] }, { id: "c3", text: "The article says she sold the van.", citations: ["q1"] }, + { id: "c4", text: "The article says she moved the shop.", citations: ["q1"] }, ], }, ], }; +// Each proposal carries the fingerprint of the claim it judged; c4's judged +// another claim (a revision moved the ids): stale, never shown. +const fp = (id: string) => claimFingerprint(report.sections[0]!.claims.find((c) => c.id === id)!, report.citations); const proposals = { format: "archilyzer-verdict-proposals", version: 1, article: ID, proposals: { - c2: { verdict: "PARTLY", reason: "She says the oven ran hot, not that it was broken.", model: MODEL, promptVersion: "2", at: AT, status: "proposed" }, - c3: { verdict: "CONTRADICTED", reason: "She says she kept the van.", model: MODEL, promptVersion: "2", at: AT, status: "proposed" }, + c2: { verdict: "PARTLY", reason: "She says the oven ran hot, not that it was broken.", model: MODEL, promptVersion: "2", at: AT, fingerprint: fp("c2"), status: "proposed" }, + c3: { verdict: "CONTRADICTED", reason: "She says she kept the van.", model: MODEL, promptVersion: "2", at: AT, fingerprint: fp("c3"), status: "proposed" }, + c4: { verdict: "CORROBORATED", reason: "Another claim's.", model: MODEL, promptVersion: "2", at: AT, fingerprint: "0000000000000000", status: "proposed" }, }, updatedAt: AT, }; @@ -88,6 +96,7 @@ test("an Inbox row → the article's proposals → Approve sets the verdict, Rej const panel = page.getByRole("region", { name: "verdict proposals" }); await expect(panel.locator("[data-proposal]")).toHaveCount(2); + await expect(panel).toContainText("2 waiting · 1 stale (the claim changed since)"); const c2 = panel.locator('[data-proposal="c2"]'); await expect(c2.locator("[data-proposed]")).toHaveText("PARTLY"); await expect(c2).toContainText("She says the oven ran hot"); @@ -97,10 +106,19 @@ test("an Inbox row → the article's proposals → Approve sets the verdict, Rej expect(claims().find((c) => c.id === "c2")!.verdict).toBe("PARTLY"); expect(sidecar().proposals.c2.status).toBe("approved"); - const c3 = panel.locator('[data-proposal="c3"]'); + // Another run rewrites c3's proposal after the page showed it: the review is refused. + const doc = sidecar(); + writeFileSync(path.join(DIR, "verdicts.proposed.json"), JSON.stringify({ ...doc, proposals: { ...doc.proposals, c3: { ...doc.proposals.c3, verdict: "PARTLY", at: "2026-10-15T11:00:00.000Z" } } }, null, 2) + "\n"); + await panel.locator('[data-proposal="c3"]').getByRole("button", { name: "Reject" }).click(); + await expect(panel.getByRole("status")).toContainText("changed since it was shown"); + expect(sidecar().proposals.c3.status).toBe("proposed"); + // Read again, it is the new one; reject that. + await page.reload(); + const c3 = page.getByRole("region", { name: "verdict proposals" }).locator('[data-proposal="c3"]'); + await expect(c3.locator("[data-proposed]")).toHaveText("PARTLY"); await c3.getByRole("textbox", { name: "note on c3" }).fill("the window is too short"); await c3.getByRole("button", { name: "Reject" }).click(); - await expect(panel.getByRole("status")).toHaveText("Rejected: c3 stays unruled."); + await expect(page.getByRole("region", { name: "verdict proposals" }).getByRole("status")).toHaveText("Rejected: c3 stays unruled."); expect(claims().find((c) => c.id === "c3")!.verdict).toBeUndefined(); expect(sidecar().proposals.c3).toMatchObject({ status: "rejected", note: "the window is too short" }); // The operator's ruling stayed as it was. diff --git a/umtool/lib/articles/verdicts.ts b/umtool/lib/articles/verdicts.ts @@ -1,4 +1,4 @@ -import { readVerdictProposals, waitingProposals, type VerdictProposal } from "yt-dlp-transcript-common/lib/report/verdictProposals"; +import { currentClaims, proposalIsCurrent, readVerdictProposals, waitingProposals, type CurrentClaim, type VerdictProposal } from "yt-dlp-transcript-common/lib/report/verdictProposals"; import { articleFile } from "yt-dlp-transcript-common/lib/report/registry"; import { readJsonFile } from "yt-dlp-transcript-common/lib/jsonFile-server"; import { isVerdict, type Verdict } from "yt-dlp-transcript-common/lib/report/verdicts"; @@ -14,6 +14,10 @@ import { sitesPaths } from "./sites"; // reject goes to the editor's `verdict-review` (the one writer: approve sets // the claim's verdict through the registry). // +// A waiting proposal whose claim changed under its id (a revision) is STALE: +// counted, never shown (review fix 1). A sidecar that does not read is an +// error the tab shows and the Inbox raises (review fix 7). +// // SERVER-ONLY. export type WaitingProposal = { @@ -31,51 +35,46 @@ export type ArticleProposals = { waiting: WaitingProposal[]; approved: number; rejected: number; + // Waiting proposals whose claim is not the one they judged now (a revision + // moved the ids, or changed the claim or its citations): never shown, never + // reviewable (review fix 1). + stale: number; // The sidecar did not read (it is never taken for empty). error?: string; }; -type ClaimRow = { id: string; text: string; section: string; verdict?: unknown }; - -async function claimsOf(article: string): Promise<Map<string, ClaimRow> | null> { - const read = await readJsonFile(articleFile(sitesPaths(), article)); - if (!read.ok) return null; - const r = read.value as { kind?: unknown; sections?: { title?: string; claims?: { id?: string; text?: string; verdict?: unknown }[] }[] }; - if (r.kind !== "factcheck") return null; - const out = new Map<string, ClaimRow>(); - for (const s of r.sections ?? []) { - for (const c of s.claims ?? []) if (typeof c.id === "string") out.set(c.id, { id: c.id, text: String(c.text ?? ""), section: String(s.title ?? ""), verdict: c.verdict }); - } - return out; -} - -/** An article's proposals: the waiting ones on still-unruled claims, in the report's order. */ +/** An article's proposals: the waiting ones on still-unruled, unchanged claims, in the report's order. */ export async function readArticleProposals(article: string): Promise<ArticleProposals | null> { if (!isReportId(article)) return null; let f; try { f = await readVerdictProposals(article, sitesPaths()); } catch (e) { - return { waiting: [], approved: 0, rejected: 0, error: (e as Error).message }; + return { waiting: [], approved: 0, rejected: 0, stale: 0, error: (e as Error).message }; } if (!f) return null; - const claims = await claimsOf(article); + const read = await readJsonFile(articleFile(sitesPaths(), article)); + const raw = read.ok ? (read.value as { kind?: unknown }) : null; + const claims = raw && raw.kind === "factcheck" ? currentClaims(raw) : new Map<string, CurrentClaim>(); + const order = [...claims.keys()]; const all = Object.values(f.proposals) as VerdictProposal[]; - const order = claims ? [...claims.keys()] : []; - const waiting = waitingProposals(f) - .filter(([id]) => { - const c = claims?.get(id); - return !!c && !isVerdict(c.verdict); - }) - .map(([id, p]) => { - const c = claims!.get(id)!; - return { claim: id, text: c.text, section: c.section, verdict: p.verdict, reason: p.reason, model: p.model, promptVersion: p.promptVersion, at: p.at }; - }) - .sort((a, b) => order.indexOf(a.claim) - order.indexOf(b.claim)); + let stale = 0; + const waiting: WaitingProposal[] = []; + for (const [id, p] of waitingProposals(f)) { + const c = claims.get(id); + if (c?.ruled) continue; + if (!c || !proposalIsCurrent(p, c)) { + stale++; + continue; + } + waiting.push({ claim: id, text: c.text, section: c.section, verdict: p.verdict, reason: p.reason, model: p.model, promptVersion: p.promptVersion, at: p.at }); + } + waiting.sort((a, b) => order.indexOf(a.claim) - order.indexOf(b.claim)); return { waiting, approved: all.filter((p) => p.status === "approved").length, rejected: all.filter((p) => p.status === "rejected").length, + stale, }; } @@ -85,7 +84,9 @@ export async function reviewArticleProposal(body: unknown): Promise<{ proposal: if (typeof b.article !== "string" || typeof b.claim !== "string") throw new EditorError('send {"article", "claim", "decision": "approve" | "reject", "note"?}', 400); if (b.decision !== "approve" && b.decision !== "reject") throw new EditorError('"decision" is "approve" or "reject"', 400); if (b.note !== undefined && typeof b.note !== "string") throw new EditorError('"note" is text', 400); - const sent = { article: b.article, claim: b.claim, decision: b.decision, ...(typeof b.note === "string" && b.note.trim() ? { note: b.note.trim() } : {}) }; + // The proposal the operator was shown: the editor's review is a compare-and-set on it. + if (!isVerdict(b.verdict) || typeof b.at !== "string" || !b.at) throw new EditorError('send the "verdict" and "at" of the proposal shown', 400); + const sent = { article: b.article, claim: b.claim, decision: b.decision, verdict: b.verdict, at: b.at, ...(typeof b.note === "string" && b.note.trim() ? { note: b.note.trim() } : {}) }; const answer = await askEditor<{ proposal?: unknown }>("/api/ops/verdict-review", { method: "POST", body: sent }); return { proposal: answer.proposal ?? null }; } diff --git a/umtool/lib/bench.ts b/umtool/lib/bench.ts @@ -207,7 +207,15 @@ export async function writeVerdictsPolicy(v: unknown): Promise<GenerationVerdict if (typeof x !== "number" || !Number.isFinite(x) || x < 0 || x > 1) throw new EditorError(`bar.${k} is a fraction from 0 to 1`, 400); } if (!Array.isArray(o.models) || !o.models.every((m) => typeof m === "string")) throw new EditorError("models is a list of model names", 400); - const verdicts = sanitizeGeneration({ verdicts: { bar: b, models: o.models } }).verdicts; + // The window proposals read (release 29): the run's the bar is set on, when + // the form sends it; else the one in settings is kept (the block is written whole). + let window = o.window as Record<string, unknown> | undefined; + if (window !== undefined) { + if (!window || typeof window !== "object" || (window.mode !== "seconds" && window.mode !== "turn") || typeof window.seconds !== "number" || window.seconds < 0 || window.seconds > 600) { + throw new EditorError('window is {mode: "seconds" | "turn", seconds: 0–600}', 400); + } + } else window = (await readVerdictsPolicy()).window; + const verdicts = sanitizeGeneration({ verdicts: { bar: b, models: o.models, window } }).verdicts; await askEditor("/api/ops/settings", { method: "POST", body: { patch: { generation: { verdicts } } } }); return readVerdictsPolicy(); } diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts @@ -10,7 +10,7 @@ import { readManifest, reportSignature } from "./projects/report.mjs"; import { draftsView } from "./report/drafts.mjs"; import { articleHref, generationPolicyHref, reviewHref, triageHref } from "./hrefs"; import { awaitingReview, draftsDecisions } from "./inbox/drafts.mjs"; -import { verdictsDecisions } from "./inbox/verdicts.mjs"; +import { unreadableProposalsDecision, verdictsDecisions } from "./inbox/verdicts.mjs"; import { readArticleProposals } from "./articles/verdicts"; import { readFieldProvenance } from "./report/draft-provenance.mjs"; import { pieceOfDecision, readPieceGraph, type Piece, type PieceGraph } from "./pieces"; @@ -63,7 +63,8 @@ import { refreshDecisions } from "./inbox/refresh"; // claim (release 29 M8; the article's // verdicts.proposed.json, lib/inbox/verdicts.mjs), one row // per proposal, gone once approved or rejected (or the -// claim ruled by hand) +// claim ruled by hand, or changed: a stale proposal) +// unreadable-proposals that file does not read: one Blocking row // // -- each row given its piece, category, group, one action, lifecycle and // `hidden` (lib/inbox/groups.mjs), ranked. One row per decision, never dropped: @@ -356,12 +357,10 @@ async function proposalDecisions(graph: PieceGraph): Promise<Decision[]> { const per = await Promise.all( storeArticles(graph).map(async (p) => { const got = await readArticleProposals(p.report as string).catch(() => null); + const href = articleHref({ site: ARTICLES_KEY, id: p.report as string }, { tab: "article" }); + if (got?.error) return [unreadableProposalsDecision({ base: articleRow(p), href, error: got.error, at: p.newestMs })] as Decision[]; if (!got?.waiting.length) return [] as Decision[]; - return verdictsDecisions({ - base: articleRow(p), - href: articleHref({ site: ARTICLES_KEY, id: p.report as string }, { tab: "article" }), - waiting: got.waiting, - }) as Decision[]; + return verdictsDecisions({ base: articleRow(p), href, waiting: got.waiting }) as Decision[]; }), ); return per.flat(); diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -67,6 +67,7 @@ const KIND_CATEGORY = { // Release 29 M8: a model's proposed verdicts for a fact-check's unruled // claims, each waiting on the operator's approve or reject. "verdict-proposed": "review", + "unreadable-proposals": "fix", }; const CATEGORY_GROUP = { @@ -95,7 +96,7 @@ export function groupOf(d) { // Within a group: the brief's order first (proposals before failed runs), then // everything else as equals. -const KIND_RANK = { "worth-researching": 0, "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "tick-partial": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "verdict-proposed": 1, "unreadable-notes": 0, "refresh-held": 2, "refresh-available": 2 }; +const KIND_RANK = { "worth-researching": 0, "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "tick-partial": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "verdict-proposed": 1, "unreadable-notes": 0, "unreadable-proposals": 0, "refresh-held": 2, "refresh-available": 2 }; const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 }; // ONE primary action per decision, its button copy naming the result. @@ -105,6 +106,7 @@ const ACTION_LABEL = { "iteration-ready": (d) => `Make ${d.target} current`, "drafts-unreviewed": "Review drafts", "verdict-proposed": "Review verdicts", + "unreadable-proposals": "Repair verdicts.proposed.json", "open-note": "Answer note", "unreadable-notes": "Repair notes.json", "link-ambiguous": "Link the video", diff --git a/umtool/lib/inbox/verdicts.mjs b/umtool/lib/inbox/verdicts.mjs @@ -36,3 +36,22 @@ export function verdictsDecisions({ base, href, waiting }) { const at = Math.max(0, ...waiting.map((w) => Date.parse(w.at) || 0)); return waiting.map((w) => ({ ...base, kind: "verdict-proposed", target: w.claim, what, why, href, severity: "open", at })); } + +/** + * An article whose `verdicts.proposed.json` does not read (review fix 7): one + * blocking row, as an unreadable notes.json is — nothing is shown from it, + * and nothing writes it, until it is repaired. + * + * @param {{ base: { project: string, projectKind?: string, projectTitle: string, piece?: string }, href: string, error: string, at?: number }} o + */ +export function unreadableProposalsDecision({ base, href, error, at = Date.now() }) { + return { + ...base, + kind: "unreadable-proposals", + target: "verdicts.proposed.json", + why: `verdicts.proposed.json does not read (${error}); no proposal is shown or written until it is fixed`, + href, + severity: "blocking", + at, + }; +} diff --git a/umtool/lib/inbox/verdicts.test.mjs b/umtool/lib/inbox/verdicts.test.mjs @@ -2,7 +2,7 @@ // card's words, in the Review group with its one action. import { test } from "node:test"; import assert from "node:assert/strict"; -import { verdictsDecisions, verdictsWhy } from "./verdicts.mjs"; +import { unreadableProposalsDecision, verdictsDecisions, verdictsWhy } from "./verdicts.mjs"; import { annotate, groupOf, summarizeGroups } from "./groups.mjs"; import { whatOf } from "./what.mjs"; @@ -27,3 +27,13 @@ test("verdict-proposed: a row per proposal, the card's words, the Review group, assert.equal(review.cards[0].what, "2 verdicts proposed"); assert.deepEqual(verdictsDecisions({ base: { project: "x", projectTitle: "x" }, href: "/", waiting: [] }), []); }); + +test("unreadable-proposals: one Blocking row, its action the repair", () => { + const d = unreadableProposalsDecision({ base: { project: "sites/articles/fc", projectTitle: "A check", piece: "a:articles/fc" }, href: "/articles/fc?tab=article", error: "unparseable", at: 5 }); + assert.equal(d.kind, "unreadable-proposals"); + assert.equal(groupOf(d), "blocking"); + assert.match(d.why, /does not read \(unparseable\)/); + const [a] = annotate([d], { pieceOf: () => "a:articles/fc", lifecycleOf: () => "active", isMuted: () => false }); + assert.equal(a.action.label, "Repair verdicts.proposed.json"); + assert.equal(whatOf("unreadable-proposals"), "verdicts.proposed.json does not read"); +}); diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -9,6 +9,7 @@ export const WHAT = { "iteration-ready": "iteration ready", "drafts-unreviewed": "drafts to review", "verdict-proposed": "verdicts proposed", + "unreadable-proposals": "verdicts.proposed.json does not read", "open-note": "open notes", "unreadable-notes": "notes.json does not read", "link-ambiguous": "video not linked",