// VERDICT PROPOSALS (release 29 M8) — a model's proposed verdicts for a // fact-check's unruled claims, kept in a SIDECAR beside the article: // // transcripts/reports//verdicts.proposed.json // { format: "archilyzer-verdict-proposals", version: 1, article, // proposals: { "": { 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, 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. // // 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 { 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"; export const VERDICT_PROPOSALS_FILE = "verdicts.proposed.json"; export const VERDICT_PROPOSALS_FORMAT = "archilyzer-verdict-proposals"; export const VERDICT_PROPOSALS_VERSION = 1; export const PROPOSAL_STATUSES = ["proposed", "approved", "rejected"] as const; export type ProposalStatus = (typeof PROPOSAL_STATUSES)[number]; export const PROPOSAL_NOTE_MAX = 500; export const PROPOSAL_REASON_MAX = 300; export type VerdictProposal = { verdict: Verdict; reason: string; 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; job?: VerdictsJobMark; updatedAt: string; }; // A proposal as a run makes it: everything but its status. export type NewProposal = Omit; type StorePaths = Pick; export class VerdictProposalsError extends Error { constructor( message: string, readonly status = 400, ) { super(message); this.name = "VerdictProposalsError"; } } const CLAIM_ID_RE = /^[A-Za-z0-9._:-]{1,64}$/; 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 | 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; 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 { const r = (raw ?? {}) as { citations?: Record; sections?: { title?: unknown; claims?: ClaimLike[] }[] }; const out = new Map(); 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 { 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; const proposals: Record = {}; const given = r.proposals && typeof r.proposals === "object" && !Array.isArray(r.proposals) ? (r.proposals as Record) : {}; for (const [claim, v] of Object.entries(given)) { const p = v as Record | null; if (!CLAIM_ID_RE.test(claim) || !p || !isVerdict(p.verdict) || !(PROPOSAL_STATUSES as readonly unknown[]).includes(p.status)) continue; proposals[claim] = { verdict: p.verdict, reason: typeof p.reason === "string" ? p.reason.slice(0, PROPOSAL_REASON_MAX) : "", 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 | 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 : "", }; } /** * An article's proposals: null when it has none; a file that does not read as * one is an error (409) — never taken for empty, so no write replaces it. */ export async function readVerdictProposals(article: string, paths: StorePaths = getPaths()): Promise { const read = await readJsonFile(verdictProposalsFile(paths, article)); if (!read.ok) { if (read.reason === "absent") return null; throw new VerdictProposalsError(`reports/${article}/${VERDICT_PROPOSALS_FILE} is ${read.reason}`, 409); } const v = read.value as { format?: unknown }; if (!v || v.format !== VERDICT_PROPOSALS_FORMAT) throw new VerdictProposalsError(`reports/${article}/${VERDICT_PROPOSALS_FILE} is not an ${VERDICT_PROPOSALS_FORMAT} file`, 409); return clean(read.value, article); } /** 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, claim: Pick | 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 { // 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, 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, paths: StorePaths = getPaths(), now: Date = new Date(), ): 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" && 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, fingerprint: p.fingerprint, status: "proposed", }; written.push(claim); } if (written.length) { cur.updatedAt = now.toISOString(); await writeHoldingLock(paths, cur); } 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 | null, paths: StorePaths = getPaths(), now: Date = new Date()): Promise { 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); } // ─── 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 — 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 { 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) : ""; return withArticleStoreLock(async () => { 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 = { 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 } : {}), }; f.proposals[r.claim] = next; f.updatedAt = now.toISOString(); await writeHoldingLock(paths, f); return { ...next, claim: r.claim }; }, paths); }