commit d032e211723f8e3a325e58f9a90dea40614e4a4e
parent 05348da09cf3062fe9d66e749c4fef9dc90ca003
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 16 Oct 2026 16:35:08 -0400
common: an article written by hand — the `hand` iteration kind; startBlankArticle (an article in the making with a titled, empty report) and addClaimByHand (a claim in a section or a new one, citations picked or added, each new quote checked strictly against the record before anything is written; a hand draft no one uses is amended in place, any other base gets a new hand iteration; nothing made current); parseMoment and cuesAround for the form
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
3 files changed, 578 insertions(+), 1 deletion(-)
diff --git a/common/controller/handEdits.test.ts b/common/controller/handEdits.test.ts
@@ -0,0 +1,184 @@
+// An article written by hand (release 32 R2): a blank start, and a claim added by
+// hand — new quotes checked strictly against a synthetic record before anything
+// is written. Temp stores and a synthetic channel only.
+//
+// Run with: node_modules/.bin/tsx --test controller/handEdits.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { createIteration, currentIteration, makeCurrent, readIteration, readIterations, updateIteration, writeIterationFile } from "../lib/report/iterations";
+import { addClaimByHand, cuesAround, defaultHandBase, HandEditError, parseMoment, startBlankArticle } from "./handEdits";
+
+const ROOTS: string[] = [];
+after(() => {
+ for (const r of ROOTS) rmSync(r, { recursive: true, force: true });
+});
+
+const NOW = new Date("2026-10-16T12:00:00.000Z");
+const CHAN = "synth-hand";
+
+const ts = (s: number) => new Date(s * 1000).toISOString().slice(11, 23);
+const vtt = (cues: [number, number, string][]) =>
+ "WEBVTT\nKind: captions\nLanguage: en\n\n" + cues.map(([a, b, text]) => `${ts(a)} --> ${ts(b)}\n${text}\n`).join("\n");
+
+function store() {
+ const root = mkdtempSync(path.join(tmpdir(), "hand-edits-"));
+ ROOTS.push(root);
+ const channelsDir = path.join(root, "channels");
+ const put = (file: string, text: string) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, text);
+ };
+ put(path.join(channelsDir, CHAN, "config.json"), JSON.stringify({ handling: "youtube", name: "Synth Hand", url: "https://www.youtube.com/@synthhand/videos" }));
+ const dir = path.join(channelsDir, CHAN, "data", "rec1");
+ put(
+ path.join(dir, "metadata.info.json"),
+ JSON.stringify({ id: "rec1", title: "Synthetic stream", channel: CHAN, upload_date: "20260110", duration: 600, webpage_url: "https://www.youtube.com/watch?v=rec1", extractor_key: "Youtube" }),
+ );
+ put(
+ path.join(dir, "transcript.en.vtt"),
+ vtt([
+ [10, 14, "The bakery opened in the spring of that year."],
+ [14, 18, "I was there for the first loaf, honestly."],
+ [18, 22, "Nobody believed the oven would hold up."],
+ ]),
+ );
+ return { articlesDir: path.join(root, "reports"), exportIndexDir: path.join(root, ".export-index"), channelsDir };
+}
+
+const reportOf = (paths: ReturnType<typeof store>, id: string, n: number) =>
+ JSON.parse(readFileSync(path.join(paths.articlesDir, id, "iterations", String(n), "report.json"), "utf8"));
+
+test("a blank start: i1 of kind hand, done, a titled report with no sections; an existing id is refused", async () => {
+ const paths = store();
+ const { iteration, report } = await startBlankArticle("bakery", { title: "The Bakery", kind: "factcheck" }, paths, NOW);
+ assert.equal(iteration.n, 1);
+ assert.equal(iteration.kind, "hand");
+ assert.equal(iteration.model, "hand");
+ assert.equal(iteration.status, "done");
+ assert.deepEqual(report.sections, []);
+ assert.equal(reportOf(paths, "bakery", 1).title, "The Bakery");
+ // Nothing made current: an article in the making.
+ assert.equal((await currentIteration("bakery", paths)).report, null);
+ await assert.rejects(startBlankArticle("bakery", { title: "Again" }, paths, NOW), /has iterations already/);
+ await assert.rejects(startBlankArticle("other", { title: " " }, paths, NOW), HandEditError);
+});
+
+test("a claim by hand on a blank start: amends the hand draft in place, a new section, a new quote checked", async () => {
+ const paths = store();
+ await startBlankArticle("bakery", { title: "The Bakery" }, paths, NOW);
+ const r = await addClaimByHand(
+ "bakery",
+ {
+ section: { title: "The Opening" },
+ claim: { text: "The article says the bakery opened in spring.", verdict: "CORROBORATED" },
+ add: [{ kind: "video", channel: CHAN, id: "rec1", start: 10, end: 14, quote: "The bakery opened in the spring of that year." }],
+ },
+ paths,
+ NOW,
+ );
+ assert.equal(r.n, 1);
+ assert.equal(r.amended, true);
+ assert.equal(r.section, "the-opening");
+ assert.equal(r.claim, "c1");
+ assert.deepEqual(r.added.map((a) => [a.id, a.check.status]), [["h1", "ok"]]);
+ const doc = reportOf(paths, "bakery", 1);
+ assert.deepEqual(doc.sections[0].claims[0], { id: "c1", text: "The article says the bakery opened in spring.", verdict: "CORROBORATED", citations: ["h1"] });
+ assert.equal(doc.citations.h1.quote, "The bakery opened in the spring of that year.");
+ assert.match((await readIteration("bakery", 1, paths))!.feedback ?? "", /added c1 to “The Opening” \(1 new citation\)/);
+
+ // A second claim, in the same section, citing the report's h1: c2, still i1.
+ const r2 = await addClaimByHand("bakery", { section: { id: "the-opening" }, claim: { text: "The article says she was there." }, cite: ["h1"] }, paths, NOW);
+ assert.deepEqual([r2.n, r2.claim, r2.amended], [1, "c2", true]);
+ assert.equal(reportOf(paths, "bakery", 1).sections[0].claims.length, 2);
+});
+
+test("a quote that is not verbatim in the record is refused, and nothing is written", async () => {
+ const paths = store();
+ await startBlankArticle("bakery", { title: "The Bakery" }, paths, NOW);
+ const before = readFileSync(path.join(paths.articlesDir, "bakery", "iterations", "1", "report.json"), "utf8");
+ await assert.rejects(
+ addClaimByHand(
+ "bakery",
+ {
+ section: { title: "Wrong" },
+ claim: { text: "A paraphrase." },
+ add: [{ kind: "video", channel: CHAN, id: "rec1", start: 10, end: 14, quote: "The bakery never opened in the spring." }],
+ },
+ paths,
+ NOW,
+ ),
+ (e: unknown) => e instanceof HandEditError && /does not check against the record/.test(e.message) && /inexact|drift/.test(e.problems.join(" ")),
+ );
+ await assert.rejects(
+ addClaimByHand("bakery", { section: { title: "Gone" }, claim: { text: "x" }, add: [{ kind: "video", channel: CHAN, id: "nope", start: 1, end: 2, quote: "a b c" }] }, paths, NOW),
+ (e: unknown) => e instanceof HandEditError && /missing-record/.test(e.problems.join(" ")),
+ );
+ assert.equal(readFileSync(path.join(paths.articlesDir, "bakery", "iterations", "1", "report.json"), "utf8"), before);
+});
+
+test("a claim on a model's iteration is a NEW hand iteration, its parent the base; nothing made current", async () => {
+ const paths = store();
+ const it = await createIteration("swept", { kind: "sweep", model: "qwen3:8b", question: "What was said?" }, paths, NOW);
+ await writeIterationFile(
+ "swept",
+ it.n,
+ "report.json",
+ { format: "archilyzer-report", version: 1, id: "swept", kind: "factcheck", title: "Swept", sections: [{ id: "s1", title: "One", claims: [{ id: "c1", text: "First." }] }] },
+ paths,
+ );
+ await updateIteration("swept", it.n, { status: "done" }, paths, NOW);
+ await makeCurrent("swept", it.n, paths, NOW);
+ assert.equal(await defaultHandBase("swept", paths), 1);
+ const r = await addClaimByHand("swept", { section: { id: "s1" }, claim: { text: "Second.", verdict: "NOT_FOUND" } }, paths, NOW);
+ assert.deepEqual([r.n, r.amended, r.claim], [2, false, "c2"]);
+ const i2 = (await readIterations("swept", paths)).iterations.find((x) => x.n === 2)!;
+ assert.deepEqual([i2.kind, i2.parent, i2.status, i2.model], ["hand", 1, "done", "hand"]);
+ assert.equal(reportOf(paths, "swept", 2).sections[0].claims[1].verdict, "NOT_FOUND");
+ assert.equal((await currentIteration("swept", paths)).report, 1);
+ // The base (i1) is current: a claim on it again is another new iteration, i3.
+ const r3 = await addClaimByHand("swept", { base: 1, section: { id: "s1" }, claim: { text: "Third." } }, paths, NOW);
+ assert.equal(r3.n, 3);
+ // i2 is hand and not current: amended.
+ const r4 = await addClaimByHand("swept", { base: 2, section: { title: "More" }, claim: { text: "Fourth." } }, paths, NOW);
+ assert.deepEqual([r4.n, r4.amended], [2, true]);
+});
+
+test("refusals: a verdict on a sweep, an unknown citation or section, no report to add to", async () => {
+ const paths = store();
+ await startBlankArticle("plain", { title: "Plain", kind: "sweep" }, paths, NOW);
+ await assert.rejects(addClaimByHand("plain", { section: { title: "S" }, claim: { text: "x", verdict: "PARTLY" } }, paths, NOW), /carry no verdict/);
+ await assert.rejects(addClaimByHand("plain", { section: { title: "S" }, claim: { text: "x" }, cite: ["q9"] }, paths, NOW), /no citation "q9"/);
+ await assert.rejects(addClaimByHand("plain", { section: { id: "zz" }, claim: { text: "x" } }, paths, NOW), /no section "zz"/);
+ await assert.rejects(addClaimByHand("nothing", { section: { title: "S" }, claim: { text: "x" } }, paths, NOW), /no report to add to/);
+ await assert.rejects(
+ addClaimByHand("plain", { section: { title: "S" }, claim: { text: "x" }, add: [{ kind: "video", channel: CHAN, id: "rec1", start: 10, end: 300, quote: "a" }] }, paths, NOW),
+ /at most 120 s/,
+ );
+});
+
+test("parseMoment: an archive link, the house citation, channel/id@time", () => {
+ assert.deepEqual(parseMoment("https://archive.example/?v=synth-hand%2Frec1&t=12"), { channel: "synth-hand", id: "rec1", kind: "span", at: 12, quote: null });
+ assert.deepEqual(parseMoment('"The bakery opened" [Synthetic stream @ 0:12](https://archive.example/?v=synth-hand/rec1&t=12)'), {
+ channel: "synth-hand",
+ id: "rec1",
+ kind: "span",
+ at: 12,
+ quote: "The bakery opened",
+ });
+ assert.deepEqual(parseMoment("synth-hand/rec1@1:05"), { channel: "synth-hand", id: "rec1", kind: "span", at: 65, quote: null });
+ assert.deepEqual(parseMoment("synth-hand/rec1"), { channel: "synth-hand", id: "rec1", kind: "span", at: null, quote: null });
+ assert.equal(parseMoment("not a moment"), null);
+});
+
+test("cuesAround: the record's cues in a window, and its title", async () => {
+ const paths = store();
+ const got = await cuesAround(CHAN, "rec1", 13, 19, paths);
+ assert.equal(got?.title, "Synthetic stream");
+ assert.deepEqual(got?.cues.map((c) => c.start), [10, 14, 18]);
+ assert.equal(await cuesAround(CHAN, "../x", 0, 10, paths), null);
+ assert.equal(await cuesAround(CHAN, "nope", 0, 10, paths), null);
+});
diff --git a/common/controller/handEdits.ts b/common/controller/handEdits.ts
@@ -0,0 +1,390 @@
+// 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). 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 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 { ArticleRegistryError, 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 { readCitedRecord } from "../publish/composeReports";
+import { QUOTE_WARNING_STATUSES, verifyReportQuotes, type QuoteResult } from "../bin/reports-check";
+
+export const HAND_MODEL = "hand";
+
+type HandPaths = Pick<Paths, "articlesDir" | "exportIndexDir" | "channelsDir">;
+
+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<Iteration> {
+ 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<number | null> {
+ 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<string, unknown>;
+ 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<QuoteResult[]> {
+ 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<string> {
+ const ids = new Set<string>();
+ 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<string>, 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<string>, 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<Report> {
+ 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;
+}
+
+/** 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<HandClaimResult> {
+ 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));
+ if (base === null || base === undefined) fail(`"${id}" has no report to add to: start it blank first`);
+ const 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`);
+ const 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<string, Citation> = { ...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!.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: base!, feedback: 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 };
+}
+
+// ─── 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=<channel>/<id>&t=`),
+ * a moment page, the house citation that carries one, or `<channel>/<id>@<seconds>`
+ * (`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 type CueLine = { start: number; end: number; text: string };
+
+/** The record's cues from `from` to `to` seconds (its best track: the one compose reads), and its title. */
+export async function cuesAround(
+ channel: string,
+ id: string,
+ from: number,
+ to: number,
+ paths: Pick<Paths, "channelsDir"> = getPaths(),
+): Promise<{ title: string | null; cues: CueLine[] } | null> {
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(channel) || !id || /[/\\]|^\.\.?$/.test(id)) return null;
+ const rec = await readCitedRecord(paths.channelsDir, channel, id).catch(() => null);
+ if (!rec) return null;
+ return {
+ title: rec.summary.title ?? null,
+ cues: rec.cues.filter((c) => c.end > from && c.start < to).map((c) => ({ start: c.start, end: c.end, text: c.text })),
+ };
+}
+
+export { ArticleRegistryError };
diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts
@@ -62,7 +62,10 @@ export const ITERATIONS_CURRENT_FORMAT = "archilyzer-iterations-current";
// `refresh` (umtool R4, draft/refresh): fetch what is new, say what changed
// against its parent, and fold it in — a revision of its parent that names no
// feedback of its own.
-export const ITERATION_KINDS = ["sweep", "revise-report", "revise-video", "research", "refresh"] as const;
+// `hand` (release 32): written by a person in umtool, no model — a blank start
+// (no parent), or a claim added by hand to the report of its parent
+// (controller/handEdits.ts). Its model is "hand"; it costs nothing.
+export const ITERATION_KINDS = ["sweep", "revise-report", "revise-video", "research", "refresh", "hand"] as const;
export type IterationKind = (typeof ITERATION_KINDS)[number];
// `queued`: created for a job that has not started; the rest as a job ends.
export const ITERATION_STATUSES = ["queued", "running", "done", "failed", "cancelled"] as const;