commit 73a36bf5b9cda281b47cd82a9432c1f07984e276 parent 84aa4735e28129dfaec28395d96e1da5304c3b35 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Thu, 15 Oct 2026 08:26:16 -0400 common, editor, mcp: M8/V1 review fixes — each proposal carries its claim's fingerprint (text + citation spans; a stale proposal is never reviewable, never waiting, and no reason to skip the claim now under its id); the review is a compare-and-set under one lock (the verdict and `at` shown; 409 if replaced, reviewed, the claim changed or ruled; the checked proposal recorded; patchArticleHoldingLock); no sidecar write without report.json (no mkdir) and deleteArticle refuses while a verdicts job is marked on the sidecar; the MCP refuses a code-routed verdicts job with no model and renders its marker, /gen says verdicts are never a session's; a resumed bench refuses another --limit; benchItemsHash includes the claim's text and quote spans; settings.generation.verdicts.window (the bench run's window) read by proposals; SETTINGS.md, COMMANDS.md, settings.json.example Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
22 files changed, 575 insertions(+), 144 deletions(-)
diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md @@ -36,7 +36,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 @@ -147,7 +147,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/<handle>/status/<id>) or a Bluesky post (bsky.app/profile/<handle>/post/<id>, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --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 @@ -1054,6 +1054,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` @@ -1063,6 +1064,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 | @@ -1131,7 +1139,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 @@ -112,10 +112,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> = { @@ -331,7 +342,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/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 @@ -35,7 +35,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; @@ -56,7 +56,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 } }; @@ -427,3 +427,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--) { @@ -453,6 +482,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"; @@ -535,7 +565,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/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -114,7 +114,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"}' @@ -426,7 +426,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 @@ -1313,9 +1314,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 @@ -295,7 +295,11 @@ "contradictedRecall": 0, "notFoundRecall": 0 }, - "models": [] + "models": [], + "window": { + "mode": "seconds", + "seconds": 60 + } }, "triage": { "model": "local",