// AN ARTICLE WRITTEN BY HAND (release 32, lane R2: "every step a model can do, a // person can do in the UI"). Two writes, both through the iterations store // (lib/report/iterations.ts), neither calling a model: // // startBlankArticle an article in the making with ONE iteration of kind // `hand`: a report with a title and no sections, which a // person fills (sections and claims by addClaimByHand) // addClaimByHand a claim — in an existing section or a new one — with // its citations: picked from the report's own, or added // (a span: channel, id, start, end, quote; a post: // channel, id, quote), each new quote checked STRICTLY // against the record before anything is written (the // verify-quotes check, bin/reports-check.ts: `ok` or the // `fragment` warning pass; drift, inexact, a missing // record or no cues refuse). A fact-check's claim may // carry the person's verdict: a ruling needs no sweep and // no proposal. // // WHERE A CLAIM GOES. The base is an iteration with a report (default: the one // the article's report came from, else the newest done one with a report); an // article older than iterations (a report.json, no iteration) is its own base, // and the claim's iteration is its first (no parent). A // base of kind `hand` that is no one's current (report or video) and has no // video project is AMENDED in place — a person filling a blank article adds to // one draft, not one iteration per claim; its `feedback` gains a line. Any // other base is left alone: a NEW `hand` iteration (parent = the base) holds // the report with the claim. Neither makes anything current: "Use this // iteration" does, as for any other. // // SERVER-ONLY. import { pageCitationAsPost } from "../lib/citations/pageAsPost"; import type { Paths } from "../lib/paths"; import { getPaths } from "../lib/paths"; import { createIteration, currentIteration, hasArticleReport, iterationLabel, readIteration, readIterationFile, readIterations, updateIteration, writeIterationFile, type Iteration, } from "../lib/report/iterations"; import { readFile } from "node:fs/promises"; import { ArticleRegistryError, articleFile, assertArticleId } from "../lib/report/registry"; import { REPORT_FORMAT, REPORT_VERSION, REPORT_KINDS, type Claim, type Report, type ReportKind } from "../lib/report/schema"; import { RESERVED_ANCHOR_IDS } from "../lib/report/slideRules"; import { isVerdict, type Verdict } from "../lib/report/verdicts"; import { parseReport } from "../lib/report/validate"; import { MAX_CITATION_SPAN_SECONDS, REF_ID_RE, type Citation } from "../lib/citations/schema"; import { parseCitationHref, slugOf } from "../lib/report/convertShared"; import { QUOTE_WARNING_STATUSES, verifyReportQuotes, type QuoteResult } from "../bin/reports-check"; export const HAND_MODEL = "hand"; type HandPaths = Pick; export class HandEditError extends Error { constructor( message: string, readonly problems: string[] = [], ) { super(message); } } const fail = (msg: string, problems: string[] = []): never => { throw new HandEditError(msg, problems); }; const str = (v: unknown): string => (typeof v === "string" ? v.trim() : ""); const oneLine = (v: unknown, what: string, max?: number): string | undefined => { const s = str(v); if (!s) return undefined; if (/[\r\n]/.test(s)) fail(`${what} is one line`); if (max !== undefined && s.length > max) fail(`${what} is at most ${max} characters`); return s; }; // ─── a blank start ─── export type BlankInput = { title: string; kind?: ReportKind }; /** * START AN ARTICLE BY HAND: `id` must be new (no report.json, no iterations). * Answers the iteration (i1, kind `hand`, done) holding the blank report. */ export async function startBlankArticle(id: string, input: BlankInput, paths: HandPaths = getPaths(), now: Date = new Date()): Promise<{ iteration: Iteration; report: Report }> { assertArticleId(id); const title = oneLine(input.title, "the title") ?? fail("give the article a title"); const kind: ReportKind = input.kind ?? "factcheck"; if (!(REPORT_KINDS as readonly string[]).includes(kind)) fail(`kind is one of ${REPORT_KINDS.join(", ")}`); if (await hasArticleReport(id, paths)) fail(`an article "${id}" exists: add to it on its page`); if ((await readIterations(id, paths)).iterations.length) fail(`"${id}" has iterations already: add to it on its page`); const report: Report = { format: REPORT_FORMAT, version: REPORT_VERSION, id, kind, title: title!, sections: [] }; const it = await createIteration(id, { kind: "hand", model: HAND_MODEL, feedback: "started blank", status: "running" }, paths, now); return { iteration: await finishHand(id, it.n, report, paths, now), report }; } // Write the report into iteration n and mark it done; a write that is refused // marks it failed (with the refusal) and throws. async function finishHand(id: string, n: number, report: Report, paths: HandPaths, now: Date): Promise { try { await writeIterationFile(id, n, "report.json", report, paths); } catch (e) { await updateIteration(id, n, { status: "failed", error: (e as Error).message }, paths, now).catch(() => {}); throw e; } return updateIteration(id, n, { status: "done" }, paths, now); } // ─── a claim by hand ─── export type AddedSpan = { kind: "video" | "audio"; channel: string; id: string; start: number; end: number; quote: string; speaker?: string; date?: string; label?: string; note?: string }; export type AddedPost = { kind: "post"; channel: string; id: string; quote: string; speaker?: string; date?: string; label?: string; note?: string }; export type AddedCitation = AddedSpan | AddedPost; export type HandClaimInput = { // The iteration whose report the claim joins (default: see the header). base?: number | null; // An existing section's id, or a new section's title. section: { id?: string; title?: string }; claim: { title?: string; text: string; verdict?: Verdict | null; gist?: string; flag?: string; findings?: string }; // Citations the report has, by id; and new ones (each checked before saving). cite?: string[]; add?: AddedCitation[]; }; export type HandClaimResult = { // The iteration written: the base amended, or a new one. n: number; amended: boolean; claim: string; section: string; // The new citations' ids and their checks (a `fragment` is a warning). added: { id: string; check: QuoteResult }[]; warnings: string[]; }; /** The iteration a claim joins when none is named: the article's report's, else the newest done one with a report. */ export async function defaultHandBase(id: string, paths: HandPaths = getPaths()): Promise { const cur = await currentIteration(id, paths); if (cur.reportFrom !== null) return cur.reportFrom; const its = (await readIterations(id, paths)).iterations.filter((it) => it.status === "done").sort((a, b) => b.n - a.n); for (const it of its) if ((await readIterationFile(id, it.n, "report.json", paths)) !== null) return it.n; return null; } const SPAN_KINDS = new Set(["video", "audio"]); /** A citation as a person typed it, checked for shape (not yet against the record). */ export function cleanAddedCitation(raw: unknown, at: string): AddedCitation { const o = (raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}) as Record; const kind = str(o.kind) || "video"; const channel = str(o.channel); const id = str(o.id); const quote = str(o.quote).replace(/\s+/g, " "); if (!channel || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(channel)) fail(`${at}: the channel is a channel's slug`); if (!id) fail(`${at}: name the recording (or post) id`); if (!quote) fail(`${at}: the quote is the words, verbatim`); const extra = { ...(oneLine(o.speaker, `${at}: the speaker`) ? { speaker: oneLine(o.speaker, `${at}: the speaker`)! } : {}), ...(oneLine(o.date, `${at}: the date`) ? { date: oneLine(o.date, `${at}: the date`)! } : {}), ...(oneLine(o.label, `${at}: the label`) ? { label: oneLine(o.label, `${at}: the label`)! } : {}), ...(str(o.note) ? { note: str(o.note) } : {}), }; if (kind === "post") return { kind: "post", channel, id, quote, ...extra }; if (!SPAN_KINDS.has(kind)) fail(`${at}: a citation added here is a video, an audio or a post`); const start = Number(o.start); const end = Number(o.end); if (!Number.isFinite(start) || start < 0) fail(`${at}: start is the second the quote starts`); if (!Number.isFinite(end) || end <= start) fail(`${at}: end is after start`); if (end - start > MAX_CITATION_SPAN_SECONDS) fail(`${at}: a span is at most ${MAX_CITATION_SPAN_SECONDS} s`); return { kind: kind as "video" | "audio", channel, id, start, end, quote, ...extra }; } /** * Each new citation checked as verify-quotes checks a report's: the strict * check (verbatim within ±90 s of the cited second; a post: in its text), * with the report's respellings. `ok` and `fragment` pass; anything else is * the refusal. */ export async function checkAddedCitations( cites: readonly AddedCitation[], o: { respellings?: Report["respellings"]; paths: HandPaths; now?: string }, ): Promise { if (!cites.length) return []; const citations = Object.fromEntries(cites.map((c, i) => [`h${i + 1}`, c])); const probe = { format: REPORT_FORMAT, version: REPORT_VERSION, id: "hand-check", kind: "sweep", title: "check", citations, sections: [], ...(o.respellings?.length ? { respellings: o.respellings } : {}), } as unknown as Report; const full = { ...getPaths(), ...o.paths } as Paths; return verifyReportQuotes(probe, { paths: full, ...(o.now ? { now: o.now } : {}) }); } // `fragment` is the one warning that passes: the strict check found it verbatim. const passes = (r: QuoteResult) => r.status === "ok" || (r.status === "fragment" && QUOTE_WARNING_STATUSES.has(r.status)); function idsOf(r: Report): Set { const ids = new Set(); for (const s of r.sections) { ids.add(s.id); for (const c of s.claims ?? []) ids.add(c.id); } for (const e of r.entries ?? []) ids.add(e.id); for (const a of RESERVED_ANCHOR_IDS) ids.add(a); return ids; } function freshId(taken: Set, base: string, fallback: string): string { const b = REF_ID_RE.test(base) ? base : fallback; if (!taken.has(b)) return b; for (let i = 2; ; i++) { const id = `${b}-${i}`.slice(0, 64); if (!taken.has(id)) return id; } } function nextNumbered(taken: Set, prefix: string): string { for (let i = 1; ; i++) if (!taken.has(`${prefix}${i}`)) return `${prefix}${i}`; } async function readReportOf(id: string, n: number, paths: HandPaths): Promise { const text = await readIterationFile(id, n, "report.json", paths); if (text === null) fail(`${iterationLabel(n)} has no report of its own to add to`); let raw: unknown; try { raw = JSON.parse(text!); } catch { fail(`${iterationLabel(n)}'s report.json is not JSON`); } const parsed = parseReport(raw, { id }); if (!parsed.ok) fail(`${iterationLabel(n)}'s report does not read`, parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`)); // The raw document: the file keeps its own key order. return raw as Report; } /** The article's own report.json, parsed (raw, its key order kept). */ export async function readArticleReport(id: string, paths: HandPaths = getPaths()): Promise { const file = articleFile(paths, id); let raw: unknown; try { raw = JSON.parse(await readFile(file, "utf8")); } catch { fail(`"${id}"'s report.json does not read`); } const parsed = parseReport(raw, { id }); if (!parsed.ok) fail(`"${id}"'s report does not read`, parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`)); return raw as Report; } /** ADD A CLAIM BY HAND (see the header). Throws HandEditError (input) or ArticleRegistryError (the store). */ export async function addClaimByHand(id: string, input: HandClaimInput, paths: HandPaths = getPaths(), now: Date = new Date()): Promise { assertArticleId(id); const text = str(input.claim?.text); if (!text) fail("the claim's text is the claim, as stated"); const base = input.base ?? (await defaultHandBase(id, paths)); let baseIt: Iteration | null = null; let report: Report; if (base === null || base === undefined) { // An article older than iterations: its report.json is the base. if (!(await hasArticleReport(id, paths)) || (await readIterations(id, paths)).iterations.length) fail(`"${id}" has no report to add to: start it blank first`); report = await readArticleReport(id, paths); } else { baseIt = await readIteration(id, base, paths); if (!baseIt) fail(`"${id}" has no iteration ${iterationLabel(base)}`); if (baseIt!.status !== "done") fail(`${iterationLabel(base)} is ${baseIt!.status}: add to a done iteration`); report = await readReportOf(id, base, paths); } const verdict = input.claim.verdict ?? null; if (verdict !== null && !isVerdict(verdict)) fail(`"${String(verdict)}" is not a verdict`); if (verdict !== null && report.kind !== "factcheck") fail("a sweep's claims carry no verdict"); // The citations: the report's own, and the new ones (checked first). const cite = [...new Set((input.cite ?? []).map(str).filter(Boolean))]; const known = report.citations ?? {}; for (const c of cite) if (!known[c]) fail(`the report has no citation "${c}"`); const add = (input.add ?? []).map((c, i) => cleanAddedCitation(c, `new citation ${i + 1}`)); const checks = await checkAddedCitations(add, { respellings: report.respellings, paths, now: now.toISOString() }); const refused = checks.filter((r) => !passes(r)); if (refused.length) { fail( `${refused.length === 1 ? "a new quote does" : `${refused.length} new quotes do`} not check against the record`, refused.map((r) => `${r.channel}/${r.id}${r.start !== undefined ? ` ${r.start}–${r.end} s` : ""}: ${r.status}${r.message ? ` — ${r.message}` : ""}`), ); } const citations: Record = { ...known }; const taken = new Set(Object.keys(citations)); const added: HandClaimResult["added"] = []; add.forEach((c, i) => { const cid = nextNumbered(taken, "h"); taken.add(cid); citations[cid] = c as Citation; added.push({ id: cid, check: { ...checks[i]!, citation: cid } }); }); // The section: an existing one, or a new one by title. const ids = idsOf(report); const sections = report.sections.map((s) => ({ ...s, claims: [...(s.claims ?? [])] })); let si = -1; const sid = str(input.section?.id); if (sid) { si = sections.findIndex((s) => s.id === sid); if (si < 0) fail(`the report has no section "${sid}"`); } else { const title = oneLine(input.section?.title, "the section's title") ?? fail("pick a section, or give a new one's title"); const nid = freshId(ids, slugOf(title!, 40), nextNumbered(ids, "s")); ids.add(nid); sections.push({ id: nid, title: title!, claims: [] }); si = sections.length - 1; } const cidClaim = nextNumbered(ids, "c"); const claim: Claim = { id: cidClaim, ...(oneLine(input.claim.title, "the claim's title") ? { title: oneLine(input.claim.title, "the claim's title")! } : {}), text, ...(verdict ? { verdict } : {}), ...(oneLine(input.claim.gist, "the gist", 240) ? { gist: oneLine(input.claim.gist, "the gist", 240)! } : {}), ...(oneLine(input.claim.flag, "the flag", 60) ? { flag: oneLine(input.claim.flag, "the flag", 60)! } : {}), ...(str(input.claim.findings) ? { findings: str(input.claim.findings) } : {}), ...(cite.length + added.length ? { citations: [...cite, ...added.map((a) => a.id)] } : {}), }; sections[si]!.claims.push(claim); const next: Report = { ...report, ...(Object.keys(citations).length ? { citations } : {}), sections: sections.map((s) => { const { claims, ...rest } = s; return claims.length ? { ...rest, claims } : rest; }), }; const parsed = parseReport(next, { id }); if (!parsed.ok) fail("the report with the claim does not read", parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`)); const line = `added ${cidClaim} to “${sections[si]!.title}”${added.length ? ` (${added.length} new citation${added.length === 1 ? "" : "s"})` : ""}`; const cur = await currentIteration(id, paths); const amend = !!baseIt && baseIt.kind === "hand" && cur.report !== base && cur.reportFrom !== base && cur.video !== base && !baseIt.projectDir; let n: number; if (amend) { n = base!; await writeIterationFile(id, n, "report.json", next, paths); await updateIteration(id, n, (it) => ({ feedback: it.feedback ? `${it.feedback}\n${line}` : line }), paths, now); } else { const it = await createIteration( id, { kind: "hand", model: HAND_MODEL, parent: baseIt ? base! : null, feedback: baseIt ? line : `from the article's report.json: ${line}`, status: "running" }, paths, now, ); n = it.n; await finishHand(id, n, next, paths, now); } const warnings = added.filter((a) => a.check.status !== "ok").map((a) => `${a.id}: ${a.check.message ?? a.check.status}`); return { n, amended: amend, claim: cidClaim, section: sections[si]!.id, added, warnings }; } // ─── a page citation turned into its page record (release 37 S4) ─── export type ImportedCaptureInput = { // The page citation's id in the report. cite: string; // The page record the capture became: its Wayback pages channel and id. channel: string; id: string; // Or the rewritten citation itself, as find-copy's page mode names it per // item (`as`, built by the same pageCitationAsPost): its channel and id are // the record's. as?: Extract; base?: number | null; }; export type ImportedCaptureResult = { n: number; amended: boolean; citation: Citation; check: QuoteResult; }; /** * IMPORT THIS CAPTURE, the report's half: the `page` citation `cite` becomes * a `post` citation of the page record its archived copy was imported as * (`channel`/`id`), its quote and common fields kept and the page facts kept * as its `fallback`. The quote is checked against the record's text first, as * a hand-added post's is; a quote the record does not hold is refused. Written * as a hand edit (the base hand iteration amended, else a new one). */ export async function replacePageCitationWithRecord( id: string, input: ImportedCaptureInput, paths: HandPaths = getPaths(), now: Date = new Date(), ): Promise { assertArticleId(id); const base = input.base ?? (await defaultHandBase(id, paths)); let baseIt: Iteration | null = null; let report: Report; if (base === null || base === undefined) { if (!(await hasArticleReport(id, paths)) || (await readIterations(id, paths)).iterations.length) fail(`"${id}" has no report to change`); report = await readArticleReport(id, paths); } else { baseIt = await readIteration(id, base, paths); if (!baseIt) fail(`"${id}" has no iteration ${iterationLabel(base)}`); if (baseIt!.status !== "done") fail(`${iterationLabel(base)} is ${baseIt!.status}: change a done iteration`); report = await readReportOf(id, base, paths); } const old = report.citations?.[input.cite]; if (!old) fail(`the report has no citation "${input.cite}"`); if (old!.kind !== "page") fail(`citation "${input.cite}" is a ${old!.kind}, not a page`); const page = old as Extract; if (input.as && input.as.kind !== "post") fail("`as` is a post citation"); const channel = str(input.as?.channel ?? input.channel); const rid = str(input.as?.id ?? input.id); if (!channel || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(channel)) fail("the channel is a channel's slug"); if (!rid) fail("name the page record's id"); // One builder for both paths: find-copy's `as` is this same citation. const citation = pageCitationAsPost(page, { channel, id: rid }) as Citation; const [check] = await checkAddedCitations([{ kind: "post", channel, id: rid, quote: page.quote }], { respellings: report.respellings, paths, now: now.toISOString(), }); if (!passes(check!)) { fail("the quote does not check against the page record", [`${channel}/${rid}: ${check!.status}${check!.message ? ` — ${check!.message}` : ""}`]); } const next: Report = { ...report, citations: { ...report.citations, [input.cite]: citation } }; const parsed = parseReport(next, { id }); if (!parsed.ok) fail("the report with the citation does not read", parsed.problems.map((p) => `${p.path || "(root)"}: ${p.message}`)); const line = `${input.cite}: the page citation is now the page record ${channel}/${rid} (Import this capture)`; const cur = await currentIteration(id, paths); const amend = !!baseIt && baseIt.kind === "hand" && cur.report !== base && cur.reportFrom !== base && cur.video !== base && !baseIt.projectDir; let n: number; if (amend) { n = base!; await writeIterationFile(id, n, "report.json", next, paths); await updateIteration(id, n, (it) => ({ feedback: it.feedback ? `${it.feedback}\n${line}` : line }), paths, now); } else { const it = await createIteration( id, { kind: "hand", model: HAND_MODEL, parent: baseIt ? base! : null, feedback: baseIt ? line : `from the article's report.json: ${line}`, status: "running" }, paths, now, ); n = it.n; await finishHand(id, n, next, paths, now); } return { n, amended: amend, citation, check: { ...check!, citation: input.cite } }; } // ─── reading a moment, for the form ─── export type MomentRead = { channel: string; id: string; kind: "span" | "post"; at: number | null; // A house citation's quote (`"…" [title @ m:ss](url)`), when one was pasted. quote: string | null; }; /** * What a person pasted, as a moment: an archive moment link (`?v=/&t=`), * a moment page, the house citation that carries one, or `/@` * (`m:ss` too). Null when it is none of these. */ export function parseMoment(text: string): MomentRead | null { const s = text.trim(); if (!s) return null; const house = /^"([\s\S]*?)"\s*\[[^\]]*\]\(([^)\s]+)\)\s*$/.exec(s); const url = house ? house[2]! : /^https?:\/\//.test(s) ? s : null; if (url) { const p = parseCitationHref(url); if (!p || (p.kind !== "span" && p.kind !== "post")) return null; return { channel: p.channel, id: p.id, kind: p.kind, at: p.kind === "span" ? p.seconds : null, quote: house ? house[1]!.trim() : null }; } const m = /^([A-Za-z0-9][A-Za-z0-9._-]*)\/([^\s@/]+)(?:\s*[@ ]\s*(\d+(?::\d{1,2}){0,2}(?:\.\d+)?))?$/.exec(s); if (!m) return null; const at = m[3] ? m[3].split(":").reduce((t, part) => t * 60 + Number(part), 0) : null; return { channel: m[1]!, id: m[2]!, kind: "span", at, quote: null }; } export { ArticleRegistryError };