Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit b4b6b08420c1f1ce9d08c1fe8c4fef460891b73b
parent d032e211723f8e3a325e58f9a90dea40614e4a4e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 16 Oct 2026 16:43:57 -0400

umtool: by hand on an article's Iterations tab — Fix a mishearing (respell: preview every change per file as word hunks, Apply with the CLI's backups, the report's respellings listed, the video's Build tab offered) and Add a claim (a section or a new one, a verdict, citations picked or added from a pasted moment's cues, each new quote checked against the record before saving); Create's article form starts blank with no model; by-hand.spec.ts

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/articles/by-hand/route.ts | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/app/api/articles/respell/route.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/articles/HandTools.tsx | 602+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/articles/IterationsTab.tsx | 7+++++++
Mumtool/components/articles/IterationsView.tsx | 16++++++++++++++--
Mumtool/components/articles/NewArticleForm.tsx | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Aumtool/e2e/by-hand.spec.ts | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/articles/hand-types.ts | 29+++++++++++++++++++++++++++++
Mumtool/lib/inbox.ts | 2+-
9 files changed, 1153 insertions(+), 34 deletions(-)

diff --git a/umtool/app/api/articles/by-hand/route.ts b/umtool/app/api/articles/by-hand/route.ts @@ -0,0 +1,135 @@ +import { + addClaimByHand, + cuesAround, + defaultHandBase, + HandEditError, + parseMoment, + startBlankArticle, + type HandClaimInput, +} from "yt-dlp-transcript-common/controller/handEdits"; +import { readIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; +import { ArticleRegistryError } from "yt-dlp-transcript-common/lib/report/registry"; +import { isReportId, type Report } from "yt-dlp-transcript-common/lib/report/schema"; +import { errorResponse } from "@/lib/articles/generation"; +import { sitesPaths } from "@/lib/articles/sites"; +import { clearPiecesCache } from "@/lib/pieces"; +import { clearRailCounts } from "@/lib/rail"; +import type { HandBaseView } from "@/lib/articles/hand-types"; + +export const dynamic = "force-dynamic"; + +// AN ARTICLE BY HAND (release 32 R2): no model, the iterations store's +// writers (common's controller/handEdits.ts). +// +// GET ?article=<id>[&n=<iteration>] the report a claim would join: its +// sections, citations and respellings (n +// absent: the default base) +// GET ?moment=<text> a pasted moment (an archive link, the +// house citation, <channel>/<id>@<m:ss>) +// and the record's cues around it +// GET ?channel=&id=&at= the cues around a second +// POST {action: "blank", article, title, kind?} an article in the +// making: i1 (hand), a titled empty report +// POST {action: "claim", article, base?, section, claim, cite?, add?} +// a claim by hand; each new quote checked +// against the record first + +const NO_STORE = { "cache-control": "no-store" }; +const bad = (error: string, problems: string[] = []) => Response.json({ error, problems }, { status: 400, headers: NO_STORE }); + +// The cues shown around a moment: 20 s before it, 60 after. +const BEFORE = 20; +const AFTER = 60; + +async function baseView(article: string, n: number | null): Promise<HandBaseView> { + const paths = sitesPaths(); + const at = n ?? (await defaultHandBase(article, paths)); + const empty: HandBaseView = { article, n: at, reportKind: null, title: null, sections: [], citations: [], respellings: [] }; + if (at === null) return empty; + const text = await readIterationFile(article, at, "report.json", paths); + if (text === null) return empty; + let r: Report; + try { + r = JSON.parse(text) as Report; + } catch { + return empty; + } + return { + article, + n: at, + reportKind: r.kind, + title: r.title ?? null, + sections: (r.sections ?? []).map((s) => ({ id: s.id, title: s.title, claims: (s.claims ?? []).length })), + citations: Object.entries(r.citations ?? {}).map(([id, c]) => ({ + id, + kind: c.kind, + where: + c.kind === "video" || c.kind === "audio" + ? `${c.channel}/${c.id} ${c.start}–${c.end} s` + : c.kind === "post" + ? `${c.channel}/${c.id}` + : c.kind === "page" + ? c.url + : c.source, + quote: c.quote, + })), + respellings: r.respellings ?? [], + }; +} + +export async function GET(request: Request) { + const q = new URL(request.url).searchParams; + try { + const moment = q.get("moment"); + if (moment !== null || q.get("channel")) { + const m = moment !== null ? parseMoment(moment) : { channel: q.get("channel") ?? "", id: q.get("id") ?? "", kind: "span" as const, at: Number(q.get("at") ?? 0), quote: null }; + if (!m || !m.channel || !m.id) return bad("not a moment: paste an archive link, a citation, or <channel>/<id>@<m:ss>"); + const at = m.at ?? 0; + const cues = m.kind === "span" ? await cuesAround(m.channel, m.id, Math.max(0, at - BEFORE), at + AFTER, sitesPaths()) : null; + return Response.json({ ...m, at, title: cues?.title ?? null, cues: cues?.cues ?? [], found: !!cues }, { headers: NO_STORE }); + } + const article = q.get("article") ?? ""; + if (!isReportId(article)) return bad(`"${article}" is not an article id`); + const nRaw = q.get("n"); + const n = nRaw ? Number(nRaw) : null; + if (n !== null && !(Number.isInteger(n) && n > 0)) return bad("n is an iteration number"); + return Response.json(await baseView(article, n), { headers: NO_STORE }); + } catch (err) { + if (err instanceof ArticleRegistryError || err instanceof HandEditError) return bad(err.message, err.problems ?? []); + return errorResponse(err); + } +} + +export async function POST(request: Request) { + const body = (await request.json().catch(() => ({}))) as Record<string, unknown>; + const article = String(body.article ?? ""); + if (!isReportId(article)) return bad(`"${article}" is not an article id`); + try { + if (body.action === "blank") { + const kind = body.kind === "sweep" ? "sweep" : "factcheck"; + const out = await startBlankArticle(article, { title: String(body.title ?? ""), kind }, sitesPaths()); + clearPiecesCache(); + clearRailCounts(); + return Response.json({ ok: true, iteration: out.iteration.n }, { headers: NO_STORE }); + } + if (body.action === "claim") { + const base = body.base === undefined || body.base === null || body.base === "" ? null : Number(body.base); + if (base !== null && !(Number.isInteger(base) && base > 0)) return bad("base is an iteration number"); + const input: HandClaimInput = { + base, + section: (body.section ?? {}) as HandClaimInput["section"], + claim: (body.claim ?? {}) as HandClaimInput["claim"], + cite: Array.isArray(body.cite) ? body.cite.map(String) : [], + add: Array.isArray(body.add) ? (body.add as HandClaimInput["add"]) : [], + }; + const out = await addClaimByHand(article, input, sitesPaths()); + clearPiecesCache(); + clearRailCounts(); + return Response.json({ ok: true, ...out }, { headers: NO_STORE }); + } + return bad('action is "blank" or "claim"'); + } catch (err) { + if (err instanceof ArticleRegistryError || err instanceof HandEditError) return bad(err.message, err.problems ?? []); + return errorResponse(err); + } +} diff --git a/umtool/app/api/articles/respell/route.ts b/umtool/app/api/articles/respell/route.ts @@ -0,0 +1,87 @@ +import path from "node:path"; +import { applyRespell, planRespell, wordHunks } from "yt-dlp-transcript-common/lib/report/respellArticle"; +import { ArticleRegistryError } from "yt-dlp-transcript-common/lib/report/registry"; +import { isReportId } from "yt-dlp-transcript-common/lib/report/schema"; +import { errorResponse, projectsRootOf, readArticleIterations, readPolicy } from "@/lib/articles/generation"; +import { sitesPaths } from "@/lib/articles/sites"; +import { configuredProjectsRoot } from "@/lib/report/chain.mjs"; +import { clearPiecesCache } from "@/lib/pieces"; +import type { RespellView } from "@/lib/articles/hand-types"; + +export const dynamic = "force-dynamic"; + +// FIX A MISHEARING (release 32 R2): `archilyzer reports respell` from the +// article page, through the same two functions (common's respellArticle.ts). +// +// POST {article, heard: string[] | "a, b", reads, bracket?, note?, iteration?, apply?} +// apply absent/false -> { plan } the preview: every change per file, +// as word hunks («before» → «after») +// apply: true -> { plan, backups } applied (the plan is computed +// again), each changed file backed up +// first, as the CLI does +// Each answer names the iteration's video project (`projectId`) when it has +// one: a respelled video shows the new words once it is rebuilt. + +const NO_STORE = { "cache-control": "no-store" }; + +async function projectsRoot(): Promise<string> { + try { + return projectsRootOf((await readPolicy()).generation); + } catch { + return configuredProjectsRoot(); // the editor unreachable: settings.json, as the chain reads it + } +} + +const heardOf = (v: unknown): string[] => + (Array.isArray(v) ? v : typeof v === "string" ? v.split(",") : []).map((s) => String(s).trim()).filter(Boolean); + +// A file as the operator reads it: under the article's folder, or under the projects root. +function shown(file: string, article: string, root: string): string { + const a = path.relative(path.join(sitesPaths().articlesDir, article), file); + if (!a.startsWith("..") && !path.isAbsolute(a)) return a; + const p = path.relative(root, file); + return !p.startsWith("..") && !path.isAbsolute(p) ? p : file; +} + +export async function POST(request: Request) { + const body = (await request.json().catch(() => ({}))) as Record<string, unknown>; + const article = String(body.article ?? ""); + if (!isReportId(article)) return Response.json({ error: `"${article}" is not an article id` }, { status: 400, headers: NO_STORE }); + const reads = typeof body.reads === "string" ? body.reads.trim() : ""; + const heard = heardOf(body.heard); + if (!heard.length || !reads) return Response.json({ error: "give the heard forms and what was said" }, { status: 400, headers: NO_STORE }); + const iteration = body.iteration === undefined || body.iteration === null || body.iteration === "" ? undefined : Number(body.iteration); + if (iteration !== undefined && !(Number.isInteger(iteration) && iteration > 0)) return Response.json({ error: "iteration is an iteration number" }, { status: 400, headers: NO_STORE }); + const respelling = { + heard, + reads, + ...(body.bracket === true ? { bracket: true } : {}), + ...(typeof body.note === "string" && body.note.trim() ? { note: body.note.trim() } : {}), + }; + const root = await projectsRoot(); + const opts = { projectsRoot: root, paths: sitesPaths(), ...(iteration !== undefined ? { iteration } : {}) }; + try { + const out = body.apply === true ? await applyRespell(article, [respelling], opts) : { plan: await planRespell(article, [respelling], opts), backups: undefined }; + const its = await readArticleIterations(article).catch(() => null); + const projectId = out.plan.iteration !== null ? (its?.iterations.find((r) => r.n === out.plan.iteration)?.projectId ?? null) : null; + const view: RespellView = { + article, + iteration: out.plan.iteration, + respellings: out.plan.respellings, + total: out.plan.total, + notes: out.plan.notes, + targets: out.plan.targets.map((t) => ({ + kind: t.kind, + file: shown(t.file, article, root), + changes: t.changes.map((c) => ({ at: c.at, hunks: wordHunks(c.before, c.after) })), + })), + projectId, + ...(out.backups ? { backups: out.backups.map((b) => shown(b, article, root)) } : {}), + }; + if (body.apply === true) clearPiecesCache(); + return Response.json(view, { headers: NO_STORE }); + } catch (err) { + if (err instanceof ArticleRegistryError) return Response.json({ error: err.message, problems: err.problems ?? [] }, { status: 400, headers: NO_STORE }); + return errorResponse(err); + } +} diff --git a/umtool/components/articles/HandTools.tsx b/umtool/components/articles/HandTools.tsx @@ -0,0 +1,602 @@ +"use client"; + +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { badgeVariants } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Field, Input, Select, Textarea } from "@/components/ui/field"; +import { useHydrated } from "@/components/ui/use-hydrated"; +import { projectHref } from "@/lib/hrefs"; +import type { HandBaseView, RespellView } from "@/lib/articles/hand-types"; + +// --------------------------------------------------------------------------- +// BY HAND (release 32 R2): what a model does to an article, done by a person, +// with no model -- on the Iterations tab, above the iterations. +// +// Fix a mishearing `archilyzer reports respell`: the heard forms, what was +// said, bracketed or not, a note -> Preview (every change +// per file, as word hunks) -> Apply (each file backed up +// first) -> the backups, and the video's Build tab when its +// manifest changed. The respellings the report has are +// listed with their heard forms. +// Add a claim a claim in a section (or a new one), its citations picked +// from the report's or added from a moment -- an archive +// link, a citation, <channel>/<id>@<m:ss> -- whose cues are +// shown to pick the quote from; every new quote is checked +// against the record before it is saved (the server's). +// A fact-check's claim may carry your verdict. +// +// Both work on ONE iteration (the select): the article's by default. A claim is +// written as a new `hand` iteration, or into a hand draft nobody uses yet; +// nothing here makes an iteration the article's ("Use this iteration" does). +// After a write the Iterations list re-reads (ITERATIONS_CHANGED). +// --------------------------------------------------------------------------- + +export const ITERATIONS_CHANGED = "umtool:iterations-changed"; + +export type HandBase = { n: number; label: string; kind: string; current: boolean }; + +const VERDICT_WORDS: Record<string, string> = { + CORROBORATED: "corroborated", + PARTLY: "partly", + CONTRADICTED: "contradicted", + NOT_FOUND: "not found", + UNTESTABLE: "untestable", +}; + +const mmss = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`; + +async function call<T>(url: string, init?: RequestInit): Promise<T> { + const r = await fetch(url, { cache: "no-store", ...init, ...(init?.body ? { headers: { "content-type": "application/json" } } : {}) }); + const b = (await r.json().catch(() => ({}))) as T & { error?: string; problems?: string[] }; + if (!r.ok) { + const e = new Error(b.error ?? `HTTP ${r.status}`) as Error & { problems?: string[] }; + e.problems = b.problems ?? []; + throw e; + } + return b; +} + +function Problems({ error }: { error: { message: string; problems: string[] } | null }) { + if (!error) return null; + return ( + <div role="alert" data-hand-error="" className="text-[12px] text-reject-text"> + <p className="m-0">{error.message}</p> + {error.problems.length > 0 && ( + <ul className="m-0 mt-0.5 list-disc pl-5"> + {error.problems.map((p, i) => ( + <li key={i}>{p}</li> + ))} + </ul> + )} + </div> + ); +} + +const errorOf = (e: unknown) => ({ message: (e as Error).message, problems: (e as { problems?: string[] }).problems ?? [] }); + +/** «before» → «after» with the changed words marked. */ +function Hunk({ text }: { text: string }) { + const parts = text.split(/(«[^»]*»)/g); + return ( + <span className="font-serif"> + {parts.map((p, i) => + p.startsWith("«") ? ( + <mark key={i} className="rounded-[2px] bg-panel-2 px-0.5 text-text"> + {p.slice(1, -1) || "∅"} + </mark> + ) : ( + <span key={i}>{p}</span> + ), + )} + </span> + ); +} + +// ─── Fix a mishearing ─── + +function RespellForm({ article, n, view, onDone }: { article: string; n: number | null; view: HandBaseView | null; onDone: () => void }) { + const hydrated = useHydrated(); + const [heard, setHeard] = useState(""); + const [reads, setReads] = useState(""); + const [bracket, setBracket] = useState(false); + const [note, setNote] = useState(""); + const [plan, setPlan] = useState<RespellView | null>(null); + const [applied, setApplied] = useState<RespellView | null>(null); + const [busy, setBusy] = useState<"preview" | "apply" | null>(null); + const [error, setError] = useState<{ message: string; problems: string[] } | null>(null); + const asked = JSON.stringify({ heard, reads, bracket, note, n }); + const [planned, setPlanned] = useState(""); + + const run = async (apply: boolean) => { + setBusy(apply ? "apply" : "preview"); + setError(null); + try { + const out = await call<RespellView>("/api/articles/respell", { + method: "POST", + body: JSON.stringify({ article, heard, reads, bracket, note, ...(n !== null ? { iteration: n } : {}), apply }), + }); + if (apply) { + setApplied(out); + setPlan(null); + onDone(); + } else { + setPlan(out); + setApplied(null); + setPlanned(asked); + } + } catch (e) { + setError(errorOf(e)); + } finally { + setBusy(null); + } + }; + + const videoChanged = (v: RespellView) => v.targets.some((t) => t.kind === "video-manifest" && t.changes.length > 0); + const shownPlan = plan ?? applied; + + return ( + <section aria-label="fix a mishearing" data-hand-respell="" className="grid gap-2.5"> + {view && view.respellings.length > 0 && ( + <ul aria-label="respellings" className="m-0 grid list-none gap-0.5 p-0 text-[12px] text-text-2"> + {view.respellings.map((r, i) => ( + <li key={i} data-respelling={r.reads}> + {r.heard.map((h) => `“${h}”`).join(", ")} <span className="text-muted-2">→</span> <span className="text-text">{r.reads}</span> + {r.bracket ? <span className="text-muted"> (bracketed)</span> : null} + {r.note ? <span className="text-muted"> · {r.note}</span> : null} + </li> + ))} + </ul> + )} + <form + className="flex flex-wrap items-end gap-x-3 gap-y-2" + onSubmit={(e) => { + e.preventDefault(); + void run(false); + }} + > + <Field label="Heard" hint="what the transcript says; several forms, comma-separated"> + <Input aria-label="heard forms" value={heard} onChange={(e) => setHeard(e.target.value)} placeholder="cake cup, cakeup" className="w-56" /> + </Field> + <Field label="Reads"> + <Input aria-label="reads as" value={reads} onChange={(e) => setReads(e.target.value)} placeholder="K-Cup" className="w-40" /> + </Field> + <Field label="Note"> + <Input aria-label="respelling note" value={note} onChange={(e) => setNote(e.target.value)} placeholder="optional" className="w-48" /> + </Field> + <label className="flex items-center gap-1.5 pb-1.5 text-[12px] text-text-2"> + <input type="checkbox" checked={bracket} onChange={(e) => setBracket(e.target.checked)} aria-label="bracket the reading" /> + bracket it, <span className="font-mono">[{reads || "reading"}]</span> + </label> + <Button type="submit" variant="outline" disabled={!hydrated || busy !== null || !heard.trim() || !reads.trim()}> + {busy === "preview" ? "Previewing…" : "Preview"} + </Button> + </form> + <Problems error={error} /> + {shownPlan && ( + <div data-respell-plan={shownPlan.total} data-respell-applied={applied ? "" : undefined} className="grid gap-2 rounded-[3px] border border-seam p-2.5 text-[12px]"> + <p className="m-0 text-text" role="status"> + {applied ? "Applied: " : ""} + {shownPlan.total} change{shownPlan.total === 1 ? "" : "s"} in {shownPlan.targets.filter((t) => t.changes.length).length} file + {shownPlan.targets.filter((t) => t.changes.length).length === 1 ? "" : "s"} + {shownPlan.iteration !== null ? ` (i${shownPlan.iteration})` : ""} + </p> + {shownPlan.targets.map((t) => ( + <div key={`${t.kind}:${t.file}`} data-respell-target={t.kind} className="grid gap-1"> + <div className="font-mono text-[11px] text-muted"> + {t.kind} · {t.file} · {t.changes.length ? `${t.changes.length} change${t.changes.length === 1 ? "" : "s"}` : "gains the respellings only"} + </div> + {t.changes.map((c, i) => ( + <div key={i} className="pl-3"> + <div className="font-mono text-[10.5px] text-muted-2">{c.at}</div> + {c.hunks.map((h, j) => ( + <div key={j} data-respell-hunk="" className="pl-2 text-[12.5px] text-text-2"> + <Hunk text={h} /> + </div> + ))} + </div> + ))} + </div> + ))} + {shownPlan.notes.map((x, i) => ( + <p key={i} className="m-0 text-muted"> + note: {x} + </p> + ))} + {plan && ( + <div> + <Button variant="go" size="sm" disabled={!hydrated || busy !== null || planned !== asked} onClick={() => void run(true)}> + {busy === "apply" ? "Applying…" : "Apply"} + </Button> + {planned !== asked && <span className="ml-2 text-muted">the fields changed since the preview: preview again</span>} + </div> + )} + {applied && ( + <> + {applied.backups && applied.backups.length > 0 && ( + <div data-respell-backups={applied.backups.length}> + <div className="text-muted">backups (copy one back to undo):</div> + <ul className="m-0 list-none p-0 font-mono text-[11px] text-text-2"> + {applied.backups.map((b) => ( + <li key={b}>{b}</li> + ))} + </ul> + </div> + )} + {videoChanged(applied) && applied.projectId && ( + <Link href={projectHref(applied.projectId, { tab: "build" })} prefetch={false} className="ink-link" data-respell-rebuild=""> + Rebuild the video → + </Link> + )} + </> + )} + </div> + )} + </section> + ); +} + +// ─── Add a claim ─── + +type Cue = { start: number; end: number; text: string }; +type MomentView = { channel: string; id: string; kind: "span" | "post"; at: number; quote: string | null; title: string | null; cues: Cue[]; found: boolean }; +type Pending = { kind: "video" | "audio" | "post"; channel: string; id: string; start: number; end: number; quote: string }; + +function CitationAdder({ onAdd }: { onAdd: (c: Pending) => void }) { + const hydrated = useHydrated(); + const [moment, setMoment] = useState(""); + const [found, setFound] = useState<MomentView | null>(null); + const [pick, setPick] = useState<[number, number] | null>(null); + const [kind, setKind] = useState<Pending["kind"]>("video"); + const [channel, setChannel] = useState(""); + const [id, setId] = useState(""); + const [start, setStart] = useState(""); + const [end, setEnd] = useState(""); + const [quote, setQuote] = useState(""); + const [error, setError] = useState<{ message: string; problems: string[] } | null>(null); + + const find = async () => { + setError(null); + try { + const m = await call<MomentView>(`/api/articles/by-hand?moment=${encodeURIComponent(moment)}`); + setFound(m); + setPick(null); + setChannel(m.channel); + setId(m.id); + setKind(m.kind === "post" ? "post" : "video"); + if (m.quote) setQuote(m.quote); + if (m.kind === "span") { + setStart(String(m.at)); + setEnd(""); + } + } catch (e) { + setError(errorOf(e)); + } + }; + + // A click picks a cue; a second click on another extends the pick to it. + const choose = (i: number) => { + if (!found) return; + const next: [number, number] = pick && pick[0] === pick[1] && i !== pick[0] ? [Math.min(pick[0], i), Math.max(pick[0], i)] : [i, i]; + setPick(next); + const cs = found.cues.slice(next[0], next[1] + 1); + setQuote(cs.map((c) => c.text.trim()).join(" ")); + setStart(String(cs[0]!.start)); + setEnd(String(cs[cs.length - 1]!.end)); + }; + + const add = () => { + setError(null); + const s = Number(start); + const e = Number(end); + if (!channel.trim() || !id.trim() || !quote.trim()) return setError({ message: "a citation needs its channel, its id and the quote", problems: [] }); + if (kind !== "post" && !(Number.isFinite(s) && Number.isFinite(e) && e > s)) return setError({ message: "a span needs a start and a later end, in seconds", problems: [] }); + onAdd({ kind, channel: channel.trim(), id: id.trim(), start: s, end: e, quote: quote.trim() }); + setFound(null); + setPick(null); + setMoment(""); + setQuote(""); + setStart(""); + setEnd(""); + }; + + return ( + <div data-hand-adder="" className="grid gap-2 rounded-[3px] border border-dashed border-seam-2 p-2.5"> + <div className="flex flex-wrap items-end gap-2"> + <Field label="Moment" hint="an archive link, a copied citation, or channel/id@m:ss" className="min-w-0 flex-1"> + <Input aria-label="moment" value={moment} onChange={(e) => setMoment(e.target.value)} placeholder="https://…/?v=channel/id&t=123" className="font-mono" /> + </Field> + <Button type="button" variant="outline" disabled={!hydrated || !moment.trim()} onClick={() => void find()}> + Find + </Button> + </div> + {found && ( + <div data-hand-cues={found.cues.length} className="grid gap-1"> + <div className="text-[12px] text-muted"> + {found.found ? (found.title ?? `${found.channel}/${found.id}`) : `${found.channel}/${found.id}: no record in this archive`} + {found.cues.length ? " · click a line, then another to take the lines between" : ""} + </div> + {found.cues.length > 0 && ( + <ol className="m-0 grid max-h-56 list-none gap-px overflow-y-auto rounded-[2px] bg-reader p-1.5 text-reader-ink"> + {found.cues.map((c, i) => { + const on = !!pick && i >= pick[0] && i <= pick[1]; + return ( + <li key={i}> + <button + type="button" + data-cue={c.start} + aria-pressed={on} + onClick={() => choose(i)} + className={`w-full rounded-[2px] px-1.5 py-0.5 text-left font-serif text-[13px] ${on ? "bg-[color-mix(in_srgb,var(--signal)_22%,transparent)]" : "hover:bg-[color-mix(in_srgb,var(--text)_8%,transparent)]"}`} + > + <span className="mr-2 font-mono text-[10.5px] opacity-60">{mmss(c.start)}</span> + {c.text} + </button> + </li> + ); + })} + </ol> + )} + </div> + )} + <div className="flex flex-wrap items-end gap-2"> + <Field label="Kind"> + <Select aria-label="citation kind" value={kind} onChange={(e) => setKind(e.target.value as Pending["kind"])}> + <option value="video">video</option> + <option value="audio">audio</option> + <option value="post">post</option> + </Select> + </Field> + <Field label="Channel"> + <Input aria-label="citation channel" value={channel} onChange={(e) => setChannel(e.target.value)} className="w-36 font-mono" /> + </Field> + <Field label="Id"> + <Input aria-label="citation id" value={id} onChange={(e) => setId(e.target.value)} className="w-32 font-mono" /> + </Field> + {kind !== "post" && ( + <> + <Field label="Start s"> + <Input aria-label="citation start" inputMode="decimal" value={start} onChange={(e) => setStart(e.target.value)} className="num w-20" /> + </Field> + <Field label="End s"> + <Input aria-label="citation end" inputMode="decimal" value={end} onChange={(e) => setEnd(e.target.value)} className="num w-20" /> + </Field> + </> + )} + </div> + <Field label="Quote" hint="verbatim: it is checked against the record when the claim is saved"> + <Textarea aria-label="citation quote" rows={2} value={quote} onChange={(e) => setQuote(e.target.value)} /> + </Field> + <div> + <Button type="button" size="sm" variant="outline" disabled={!hydrated} onClick={add}> + Add this citation + </Button> + </div> + <Problems error={error} /> + </div> + ); +} + +function ClaimForm({ article, view, onDone }: { article: string; view: HandBaseView; onDone: (said: string, n: number) => void }) { + const hydrated = useHydrated(); + const [section, setSection] = useState(view.sections[0]?.id ?? ""); + const [newSection, setNewSection] = useState(""); + const [title, setTitle] = useState(""); + const [text, setText] = useState(""); + const [verdict, setVerdict] = useState(""); + const [cite, setCite] = useState<string[]>([]); + const [added, setAdded] = useState<Pending[]>([]); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<{ message: string; problems: string[] } | null>(null); + useEffect(() => setSection((s) => (view.sections.some((x) => x.id === s) ? s : (view.sections[0]?.id ?? ""))), [view.sections]); + const factcheck = view.reportKind === "factcheck"; + + const save = async () => { + setBusy(true); + setError(null); + try { + const out = await call<{ n: number; amended: boolean; claim: string; warnings: string[] }>("/api/articles/by-hand", { + method: "POST", + body: JSON.stringify({ + action: "claim", + article, + base: view.n, + section: section ? { id: section } : { title: newSection }, + claim: { text, ...(title.trim() ? { title } : {}), ...(factcheck && verdict ? { verdict } : {}) }, + cite, + add: added.map((a) => (a.kind === "post" ? { kind: a.kind, channel: a.channel, id: a.id, quote: a.quote } : a)), + }), + }); + setText(""); + setTitle(""); + setVerdict(""); + setCite([]); + setAdded([]); + setNewSection(""); + onDone(`${out.claim} saved in i${out.n}${out.amended ? "" : " (a new iteration)"}${out.warnings.length ? ` — ${out.warnings.join("; ")}` : ""}`, out.n); + } catch (e) { + setError(errorOf(e)); + } finally { + setBusy(false); + } + }; + + return ( + <form + aria-label="add a claim" + data-hand-claim="" + className="grid gap-2.5" + onSubmit={(e) => { + e.preventDefault(); + void save(); + }} + > + <div className="flex flex-wrap items-end gap-3"> + <Field label="Section"> + <Select aria-label="claim section" value={section} onChange={(e) => setSection(e.target.value)}> + {view.sections.map((s) => ( + <option key={s.id} value={s.id}> + {s.title} ({s.claims}) + </option> + ))} + <option value="">a new section…</option> + </Select> + </Field> + {!section && ( + <Field label="New section's title"> + <Input aria-label="new section title" value={newSection} onChange={(e) => setNewSection(e.target.value)} className="w-64" /> + </Field> + )} + <Field label="Title"> + <Input aria-label="claim title" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="optional" className="w-56" /> + </Field> + {factcheck && ( + <Field label="Verdict"> + <Select aria-label="claim verdict" value={verdict} onChange={(e) => setVerdict(e.target.value)}> + <option value="">not ruled</option> + {Object.entries(VERDICT_WORDS).map(([v, w]) => ( + <option key={v} value={v}> + {w} + </option> + ))} + </Select> + </Field> + )} + </div> + <Field label="Claim" hint="as the document under review states it"> + <Textarea aria-label="claim text" rows={2} value={text} onChange={(e) => setText(e.target.value)} /> + </Field> + {view.citations.length > 0 && ( + <fieldset className="grid gap-0.5" aria-label="the report's citations"> + <legend className="micro mb-1">its citations</legend> + {view.citations.map((c) => ( + <label key={c.id} className="flex min-w-0 items-baseline gap-2 text-[12px]"> + <input + type="checkbox" + aria-label={`cite ${c.id}`} + checked={cite.includes(c.id)} + onChange={(e) => setCite(e.target.checked ? [...cite, c.id] : cite.filter((x) => x !== c.id))} + /> + <span className="shrink-0 font-mono text-[11px] text-muted">{c.id}</span> + <span className="shrink-0 font-mono text-[11px] text-muted-2">{c.where}</span> + <span className="truncate text-text-2">“{c.quote}”</span> + </label> + ))} + </fieldset> + )} + {added.length > 0 && ( + <ul aria-label="new citations" className="m-0 grid list-none gap-0.5 p-0 text-[12px]"> + {added.map((a, i) => ( + <li key={i} data-hand-new-citation={i} className="flex min-w-0 items-baseline gap-2"> + <span className={badgeVariants({ variant: "info", size: "sm" })}>new</span> + <span className="shrink-0 font-mono text-[11px] text-muted-2"> + {a.channel}/{a.id} + {a.kind !== "post" ? ` ${a.start}–${a.end} s` : ""} + </span> + <span className="truncate text-text-2">“{a.quote}”</span> + <Button type="button" size="sm" variant="quiet" onClick={() => setAdded(added.filter((_, j) => j !== i))}> + Remove + </Button> + </li> + ))} + </ul> + )} + <CitationAdder onAdd={(c) => setAdded([...added, c])} /> + <div className="flex items-center gap-2"> + <Button type="submit" variant="go" disabled={!hydrated || busy || !text.trim() || (!section && !newSection.trim())}> + {busy ? "Checking…" : "Save claim"} + </Button> + <span className="text-[12px] text-muted">new quotes are checked against the record first</span> + </div> + <Problems error={error} /> + </form> + ); +} + +// ─── the tools ─── + +export default function HandTools({ article, bases, initialBase }: { article: string; bases: HandBase[]; initialBase: number | null }) { + const router = useRouter(); + const [n, setN] = useState<number | null>(initialBase); + const [open, setOpen] = useState<"respell" | "claim" | null>(null); + const [view, setView] = useState<HandBaseView | null>(null); + const [said, setSaid] = useState(""); + const load = useCallback(async () => { + try { + setView(await call<HandBaseView>(`/api/articles/by-hand?article=${encodeURIComponent(article)}${n !== null ? `&n=${n}` : ""}`)); + } catch { + setView(null); + } + }, [article, n]); + useEffect(() => { + if (open) void load(); + }, [open, load]); + const changed = useCallback(() => { + window.dispatchEvent(new CustomEvent(ITERATIONS_CHANGED, { detail: { article } })); + router.refresh(); + }, [article, router]); + const known = useMemo(() => bases.slice().sort((a, b) => b.n - a.n), [bases]); + if (!known.length) return null; + return ( + <section aria-label="by hand" data-hand-tools={article} className="rounded-[3px] border border-seam bg-panel px-4 py-3"> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="micro mr-1">by hand</h2> + <Button size="sm" variant={open === "respell" ? "pressed" : "outline"} aria-expanded={open === "respell"} onClick={() => setOpen(open === "respell" ? null : "respell")}> + Fix a mishearing + </Button> + <Button size="sm" variant={open === "claim" ? "pressed" : "outline"} aria-expanded={open === "claim"} onClick={() => setOpen(open === "claim" ? null : "claim")}> + Add a claim + </Button> + <label className="ml-auto flex items-center gap-1.5 text-[12px] text-muted"> + on + <Select aria-label="iteration to work on" value={n ?? ""} onChange={(e) => setN(e.target.value ? Number(e.target.value) : null)} className="py-[2px] text-[12px]"> + {known.map((b) => ( + <option key={b.n} value={b.n}> + {b.label} · {b.kind} + {b.current ? " · the article's" : ""} + </option> + ))} + </Select> + </label> + </div> + {said && ( + <p role="status" data-hand-said="" className="mb-0 mt-2 text-[12px] text-text-2"> + {said} + </p> + )} + {open === "respell" && ( + <div className="mt-3"> + <RespellForm + article={article} + n={n} + view={view} + onDone={() => { + setSaid(""); + void load(); + changed(); + }} + /> + </div> + )} + {open === "claim" && + (view ? ( + <div className="mt-3"> + <ClaimForm + article={article} + view={view} + onDone={(s, at) => { + setSaid(s); + // The next claim joins the iteration this one went into. + if (at !== n) setN(at); + else void load(); + changed(); + }} + /> + </div> + ) : ( + <p className="mb-0 mt-2 text-[12px] text-muted">reading i{n}…</p> + ))} + </section> + ); +} diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx @@ -7,6 +7,7 @@ import { hasRunPage, runHref } from "@/lib/research/runs-hrefs"; import { projectHref } from "@/lib/hrefs"; import { badgeVariants } from "@/components/ui/badge"; import ChainPanel from "@/components/articles/ChainPanel"; +import { ITERATIONS_CHANGED } from "@/components/articles/HandTools"; import { EditorJobProgress } from "@/components/ui/job-progress"; import ResearchSlot from "@/components/articles/ResearchSlot"; import { RefreshButton } from "@/components/articles/RefreshDialog"; @@ -380,6 +381,12 @@ export default function IterationsTab({ if (p?.ok) setToday((await p.json()).today ?? null); }, [article]); const refreshNow = useCallback(() => void refresh(), [refresh]); + // A write by hand (HandTools, release 32): the list re-reads. + useEffect(() => { + const on = () => void refresh(); + window.addEventListener(ITERATIONS_CHANGED, on); + return () => window.removeEventListener(ITERATIONS_CHANGED, on); + }, [refresh]); const stepRunning = data.iterations.some((it) => it.steps.some((s) => s.status === "running" && !s.task.startsWith("chain:"))); useEffect(() => { diff --git a/umtool/components/articles/IterationsView.tsx b/umtool/components/articles/IterationsView.tsx @@ -1,9 +1,12 @@ +import HandTools from "@/components/articles/HandTools"; import IterationsTab from "@/components/articles/IterationsTab"; import { readArticleIterations, readPolicy, readToday, type PolicyView } from "@/lib/articles/generation"; // The Iterations tab's server half (release 27 S8): the article's iterations // as the store has them, the policy and the day's spend as the editor has -// them (null when the editor does not answer: the list still reads). +// them (null when the editor does not answer: the list still reads). Above +// them, what a person does by hand (release 32 R2, HandTools): it needs +// neither the editor nor a model. export default async function IterationsView({ article }: { article: string }) { const initial = await readArticleIterations(article); let policy: PolicyView | null = null; @@ -13,5 +16,14 @@ export default async function IterationsView({ article }: { article: string }) { policy = null; } const today = policy ? await readToday(policy.generation.caps.daily).catch(() => null) : null; - return <IterationsTab initial={initial} policy={policy} today={today} />; + const bases = initial.iterations + .filter((r) => r.status === "done" && r.hasReport) + .map((r) => ({ n: r.n, label: r.label, kind: r.kind, current: r.currentReport || initial.current.reportFrom === r.n })); + const initialBase = initial.current.reportFrom ?? bases[0]?.n ?? null; + return ( + <> + <HandTools article={article} bases={bases} initialBase={initialBase} /> + <IterationsTab initial={initial} policy={policy} today={today} /> + </> + ); } diff --git a/umtool/components/articles/NewArticleForm.tsx b/umtool/components/articles/NewArticleForm.tsx @@ -18,6 +18,10 @@ import type { EditorChannel, PolicyView } from "@/lib/articles/generation"; // autonomy chosen here (propose, limits, auto); its queue is on the article's // Iterations tab, and a sweep continues it from there. // +// Or it starts BLANK, by hand (release 32 R2): no model and no editor -- an +// article in the making whose first iteration (kind `hand`) is a titled report +// with no sections, filled on its Iterations tab ("Add a claim"). +// // It lives on Create (/create?make=article, P5) as "Article from a question": // there the policy is a chip linking /settings/generation (`showPolicy` // false), Escape is Cancel, and the ESTIMATE is said before Start -- what such @@ -29,7 +33,7 @@ const field = const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; type Task = "agent" | "pipeline"; -type Start = "sweep" | "research"; +type Start = "sweep" | "research" | "blank"; type Autonomy = "propose" | "limits" | "auto"; const AUTONOMY_SAYS: Record<Autonomy, string> = { @@ -147,7 +151,7 @@ export default function NewArticleForm({ const [model, setModel] = useState(routeModel ?? ""); const [extractor, setExtractor] = useState(policy?.generation.models.extractor ?? ""); // A cap is a Claude run's: the agent, or research on a Claude model. - const capped = begin === "research" ? model.startsWith("claude-") : task === "agent"; + const capped = begin === "blank" ? false : begin === "research" ? model.startsWith("claude-") : task === "agent"; const capDefault = policy?.generation.caps.sweep ?? 5; const [cap, setCap] = useState(String(capDefault)); const [id, setId] = useState(""); @@ -155,6 +159,8 @@ export default function NewArticleForm({ const [channels, setChannels] = useState<string[]>([]); const [from, setFrom] = useState(""); const [to, setTo] = useState(""); + const [title, setTitle] = useState(""); + const [reportKind, setReportKind] = useState<"factcheck" | "sweep">("factcheck"); const [error, setError] = useState(""); const [sending, setSending] = useState(false); @@ -173,6 +179,20 @@ export default function NewArticleForm({ e.preventDefault(); setError(""); if (idProblem) return setError(`article id: ${idProblem}`); + if (begin === "blank") { + if (!title.trim()) return setError("give the article a title"); + setSending(true); + try { + const r = await fetch("/api/articles/by-hand", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ action: "blank", article: id, title, kind: reportKind }) }); + const b = await r.json(); + if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`); + router.push(`/articles/${id}?tab=iterations`); + } catch (err) { + setError((err as Error).message); + setSending(false); + } + return; + } if (begin === "sweep" && !channels.length) return setError("pick at least one channel"); const maxUsd = Number(cap); if (capped && !(maxUsd > 0 && maxUsd <= capDefault)) return setError(`the cap is above $0 and at most the policy's $${capDefault}`); @@ -223,10 +243,17 @@ export default function NewArticleForm({ } }} > - <label className="flex flex-col gap-1"> - <span className="micro">question</span> - <textarea className={field} rows={2} required value={question} onChange={(e) => setQuestion(e.target.value)} aria-label="question" /> - </label> + {begin === "blank" ? ( + <label className="flex flex-col gap-1"> + <span className="micro">title</span> + <input className={field} required value={title} onChange={(e) => setTitle(e.target.value)} aria-label="article title" /> + </label> + ) : ( + <label className="flex flex-col gap-1"> + <span className="micro">question</span> + <textarea className={field} rows={2} required value={question} onChange={(e) => setQuestion(e.target.value)} aria-label="question" /> + </label> + )} <fieldset className="flex flex-col gap-1" aria-label="start with"> <legend className="micro mb-1">start with</legend> @@ -239,13 +266,33 @@ export default function NewArticleForm({ <input type="radio" name="start" checked={begin === "research"} onChange={() => setBegin("research")} /> research <span className="text-[var(--color-dim)]">(find what the archive lacks first)</span> </label> + <label className="flex items-center gap-1"> + <input type="radio" name="start" checked={begin === "blank"} onChange={() => setBegin("blank")} aria-label="start blank (no model)" /> + blank <span className="text-[var(--color-dim)]">(no model: write it by hand)</span> + </label> </div> </fieldset> - <div className="flex flex-col gap-1"> - <span className="micro">channels{begin === "research" ? " (optional)" : ""}</span> - <ChannelPicker value={channels} onChange={setChannels} /> - </div> + {begin === "blank" ? ( + <fieldset className="flex flex-col gap-1" aria-label="kind of article"> + <legend className="micro mb-1">kind</legend> + <div className="flex gap-3 text-[12px]"> + <label className="flex items-center gap-1"> + <input type="radio" name="report-kind" checked={reportKind === "factcheck"} onChange={() => setReportKind("factcheck")} /> + fact-check <span className="text-[var(--color-dim)]">(claims with verdicts)</span> + </label> + <label className="flex items-center gap-1"> + <input type="radio" name="report-kind" checked={reportKind === "sweep"} onChange={() => setReportKind("sweep")} /> + sweep <span className="text-[var(--color-dim)]">(sections, no verdicts)</span> + </label> + </div> + </fieldset> + ) : ( + <div className="flex flex-col gap-1"> + <span className="micro">channels{begin === "research" ? " (optional)" : ""}</span> + <ChannelPicker value={channels} onChange={setChannels} /> + </div> + )} <div className="flex flex-wrap items-end gap-4"> <label className="flex flex-col gap-1"> @@ -259,14 +306,18 @@ export default function NewArticleForm({ onChange={(e) => setId(e.target.value.trim())} /> </label> - <label className="flex flex-col gap-1"> - <span className="micro">from</span> - <input className={field} type="date" aria-label="from" value={from} onChange={(e) => setFrom(e.target.value)} /> - </label> - <label className="flex flex-col gap-1"> - <span className="micro">to</span> - <input className={field} type="date" aria-label="to" value={to} onChange={(e) => setTo(e.target.value)} /> - </label> + {begin !== "blank" && ( + <> + <label className="flex flex-col gap-1"> + <span className="micro">from</span> + <input className={field} type="date" aria-label="from" value={from} onChange={(e) => setFrom(e.target.value)} /> + </label> + <label className="flex flex-col gap-1"> + <span className="micro">to</span> + <input className={field} type="date" aria-label="to" value={to} onChange={(e) => setTo(e.target.value)} /> + </label> + </> + )} </div> {idProblem && <p className="text-[12px] text-[var(--color-dirty)]">article id: {idProblem}</p>} @@ -298,16 +349,18 @@ export default function NewArticleForm({ </div> </fieldset> )} - <label className="flex flex-col gap-1"> - <span className="micro">model</span> - <select className={`${field} font-mono`} aria-label="model" value={model} onChange={(e) => setModel(e.target.value)}> - {[...new Set([model, ...models].filter(Boolean))].map((m) => ( - <option key={m} value={m}> - {m} - </option> - ))} - </select> - </label> + {begin !== "blank" && ( + <label className="flex flex-col gap-1"> + <span className="micro">model</span> + <select className={`${field} font-mono`} aria-label="model" value={model} onChange={(e) => setModel(e.target.value)}> + {[...new Set([model, ...models].filter(Boolean))].map((m) => ( + <option key={m} value={m}> + {m} + </option> + ))} + </select> + </label> + )} {begin === "sweep" && model.startsWith("claude-") && ( <ExtractorSelect label="extractor for this sweep" value={extractor} onChange={setExtractor} models={policy?.models.api ?? []} /> )} @@ -324,8 +377,8 @@ export default function NewArticleForm({ /> </label> )} - <Button type="submit" variant="go" size="lg" disabled={sending || !policy}> - {sending ? "Starting…" : begin === "research" ? "Start research" : "Start sweep"} + <Button type="submit" variant="go" size="lg" disabled={sending || (!policy && begin !== "blank")}> + {sending ? "Starting…" : begin === "research" ? "Start research" : begin === "blank" ? "Start blank" : "Start sweep"} </Button> {onCancel && ( <Button type="button" variant="quiet" size="lg" onClick={onCancel}> @@ -333,7 +386,7 @@ export default function NewArticleForm({ </Button> )} </div> - {policy && ( + {policy && begin !== "blank" && ( <p className="text-[12px] text-[var(--color-dim)]" data-estimate={begin}> <span className="micro mr-2">estimate</span> {estimate} diff --git a/umtool/e2e/by-hand.spec.ts b/umtool/e2e/by-hand.spec.ts @@ -0,0 +1,194 @@ +import { test, expect } from "@playwright/test"; +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { WARM_TIMEOUT, warm } from "./warm"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// BY HAND (release 32 R2): what a model does to an article, done with no model. +// +// hand-respell a fact-check in the fixture's article store, current on its +// i1, quoting sitechan/sv1 ("The vote was rigged and +// everybody knew."): Fix a mishearing -> the preview's word +// hunks per file -> Apply -> both reports respelled, the +// backups listed, the quote still checks +// hand-blank started BLANK on Create (no model, no editor job), then a +// claim added by hand: a new section, a verdict, a citation +// picked from the record's cues after pasting a moment; a quote +// that is not in the record is refused and nothing is written. +// The record is hand-chan/hv1, written here as the corpus has +// one (metadata + an English VTT), which the quote check reads. +// +// WRITES articles/hand-respell/, articles/hand-blank/, channels/hand-chan/ +// (removed after) +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const ARTICLES = path.join(FIXTURE, "articles"); +const RESPELL = "hand-respell"; +const BLANK = "hand-blank"; +const AT = "2026-10-16T10:00:00.000Z"; +const CHANNEL = path.join(FIXTURE, "channels", "hand-chan"); + +const ts = (s: number) => new Date(s * 1000).toISOString().slice(11, 23); +const VTT = + "WEBVTT\nKind: captions\nLanguage: en\n\n" + + ([ + [0, 3, "Opening line of the hand source."], + [3, 6, "The vote was rigged and everybody knew."], + [6, 9, "Nobody checked it at the time."], + ] as const) + .map(([a, b, t]) => `${ts(a)} --> ${ts(b)}\n${t}\n`) + .join("\n"); + +const report = { + format: "archilyzer-report", + version: 1, + id: RESPELL, + kind: "factcheck", + title: "The Vote Check", + citations: { + q1: { kind: "video", channel: "sitechan", id: "sv1", start: 3, end: 6, quote: "The vote was rigged and everybody knew." }, + }, + sections: [{ id: "s1", title: "The vote", claims: [{ id: "c1", text: "The article says the vote was rigged.", citations: ["q1"] }] }], +}; + +const json = (file: string) => JSON.parse(readFileSync(file, "utf8")); +const put = (file: string, v: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(v, null, 2) + "\n"); +}; + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + for (const id of [RESPELL, BLANK]) rmSync(path.join(ARTICLES, id), { recursive: true, force: true }); + put(path.join(CHANNEL, "config.json"), { handling: "youtube", name: "Hand Channel", url: "https://www.youtube.com/@handchan/videos" }); + put(path.join(CHANNEL, "data", "hv1", "metadata.info.json"), { + id: "hv1", + title: "Hand source", + channel: "hand-chan", + upload_date: "20240315", + duration: 9, + webpage_url: "https://www.youtube.com/watch?v=hv1", + extractor_key: "Youtube", + }); + writeFileSync(path.join(CHANNEL, "data", "hv1", "transcript.en.vtt"), VTT); + const dir = path.join(ARTICLES, RESPELL); + put(path.join(dir, "report.json"), report); + put(path.join(dir, "iterations", "1", "iteration.json"), { + format: "archilyzer-iteration", + version: 1, + article: RESPELL, + n: 1, + kind: "sweep", + model: "qwen3:8b", + parent: null, + copyOf: null, + question: "What was said about the vote?", + status: "done", + usage: {}, + steps: [], + createdAt: AT, + updatedAt: AT, + endedAt: AT, + }); + put(path.join(dir, "iterations", "1", "report.json"), report); + put(path.join(dir, "iterations", "current.json"), { format: "archilyzer-iterations-current", version: 1, report: 1, reportFrom: 1, video: null, reportAt: AT }); + await warm(playwright, [urls.articleHref({ site: "articles", id: RESPELL }, { tab: "iterations" }), `/api/articles/by-hand?article=${RESPELL}`, urls.newArticleHref()]); +}); +test.afterAll(() => { + for (const id of [RESPELL, BLANK]) rmSync(path.join(ARTICLES, id), { recursive: true, force: true }); + rmSync(CHANNEL, { recursive: true, force: true }); +}); + +test("Fix a mishearing: the preview's word hunks per file, then Apply writes both reports and lists the backups", async ({ page }) => { + await page.goto(urls.articleHref({ site: "articles", id: RESPELL }, { tab: "iterations" })); + const tools = page.getByRole("region", { name: "by hand" }); + await expect(tools.getByRole("combobox", { name: "iteration to work on" })).toHaveValue("1"); + await tools.getByRole("button", { name: "Fix a mishearing" }).click(); + const form = tools.getByRole("region", { name: "fix a mishearing" }); + await form.getByRole("textbox", { name: "heard forms" }).fill("vote"); + await form.getByRole("textbox", { name: "reads as" }).fill("ballot"); + await form.getByRole("button", { name: "Preview" }).click(); + + // Two files (the iteration's report and the article's), each its quote's hunk. + const plan = form.locator("[data-respell-plan]"); + await expect(plan).toHaveAttribute("data-respell-plan", "2"); + await expect(plan.locator("[data-respell-target='iteration-report']")).toContainText("iterations/1/report.json"); + await expect(plan.locator("[data-respell-target='article-report']")).toBeVisible(); + await expect(plan.locator("[data-respell-hunk]").first()).toContainText("ballot"); + // Nothing written by the preview. + expect(json(path.join(ARTICLES, RESPELL, "report.json")).citations.q1.quote).toBe("The vote was rigged and everybody knew."); + + // A field changed since the preview: Apply waits for a new one. + await form.getByRole("textbox", { name: "respelling note" }).fill("a synthetic note"); + await expect(plan.getByRole("button", { name: "Apply" })).toBeDisabled(); + await form.getByRole("button", { name: "Preview" }).click(); + await plan.getByRole("button", { name: "Apply" }).click(); + await expect(form.locator("[data-respell-applied]")).toContainText("Applied: 2 changes in 2 files"); + await expect(form.locator("[data-respell-backups]")).toHaveAttribute("data-respell-backups", "2"); + + for (const file of [path.join(ARTICLES, RESPELL, "report.json"), path.join(ARTICLES, RESPELL, "iterations", "1", "report.json")]) { + const doc = json(file); + expect(doc.citations.q1.quote).toBe("The ballot was rigged and everybody knew."); + expect(doc.respellings).toEqual([{ heard: ["vote"], reads: "ballot", note: "a synthetic note" }]); + } + // The report's respellings are listed with their heard forms. + await expect(form.getByRole("list", { name: "respellings" })).toContainText("“vote” → ballot"); +}); + +test("start blank on Create, then add a claim by hand: a new section, a verdict, a citation from the record's cues", async ({ page }) => { + await page.goto(urls.newArticleHref()); + const form = page.getByRole("form", { name: "new article" }); + await form.getByRole("radio", { name: "start blank (no model)" }).check(); + await form.getByRole("textbox", { name: "article title" }).fill("A Blank Check"); + await form.getByRole("textbox", { name: "article id" }).fill(BLANK); + await form.getByRole("button", { name: "Start blank" }).click(); + await expect(page).toHaveURL(new RegExp(`/articles/${BLANK}\\?tab=iterations$`)); + const card = page.locator("[data-iteration='1']"); + await expect(card).toHaveAttribute("data-kind", "hand"); + await expect(card).toHaveAttribute("data-status", "done"); + + const tools = page.getByRole("region", { name: "by hand" }); + await tools.getByRole("button", { name: "Add a claim" }).click(); + const claim = tools.getByRole("form", { name: "add a claim" }); + await claim.getByRole("combobox", { name: "claim section" }).selectOption(""); + await claim.getByRole("textbox", { name: "new section title" }).fill("The Vote"); + await claim.getByRole("textbox", { name: "claim text" }).fill("The article says the vote was rigged."); + await claim.getByRole("combobox", { name: "claim verdict" }).selectOption("CORROBORATED"); + + // A quote that is not in the record: refused, nothing written. + await claim.getByRole("textbox", { name: "citation channel" }).fill("hand-chan"); + await claim.getByRole("textbox", { name: "citation id" }).fill("hv1"); + await claim.getByRole("textbox", { name: "citation start" }).fill("3"); + await claim.getByRole("textbox", { name: "citation end" }).fill("6"); + await claim.getByRole("textbox", { name: "citation quote" }).fill("The vote was never rigged at all."); + await claim.getByRole("button", { name: "Add this citation" }).click(); + await claim.getByRole("button", { name: "Save claim" }).click(); + await expect(claim.locator("[data-hand-error]").last()).toContainText("does not check against the record"); + expect(json(path.join(ARTICLES, BLANK, "iterations", "1", "report.json")).sections).toEqual([]); + await claim.locator("[data-hand-new-citation='0']").getByRole("button", { name: "Remove" }).click(); + + // The moment pasted, its cues shown; a click takes the line as the quote. + await claim.getByRole("textbox", { name: "moment" }).fill("hand-chan/hv1@0:03"); + await claim.getByRole("button", { name: "Find" }).click(); + await claim.locator("[data-cue='3']").click(); + await expect(claim.getByRole("textbox", { name: "citation quote" })).toHaveValue("The vote was rigged and everybody knew."); + await expect(claim.getByRole("textbox", { name: "citation end" })).toHaveValue("6"); + await claim.getByRole("button", { name: "Add this citation" }).click(); + await claim.getByRole("button", { name: "Save claim" }).click(); + await expect(tools.locator("[data-hand-said]")).toContainText("c1 saved in i1"); + + const doc = json(path.join(ARTICLES, BLANK, "iterations", "1", "report.json")); + expect(doc.sections).toEqual([{ id: "the-vote", title: "The Vote", claims: [{ id: "c1", text: "The article says the vote was rigged.", verdict: "CORROBORATED", citations: ["h1"] }] }]); + expect(doc.citations.h1).toEqual({ kind: "video", channel: "hand-chan", id: "hv1", start: 3, end: 6, quote: "The vote was rigged and everybody knew." }); + // Still one iteration, nothing made current: "Use this iteration" is the person's. + expect(readdirSync(path.join(ARTICLES, BLANK, "iterations")).filter((n) => /^\d+$/.test(n))).toEqual(["1"]); + expect(existsSync(path.join(ARTICLES, BLANK, "report.json"))).toBe(false); + await expect(card.getByRole("button", { name: "Use this iteration" })).toBeVisible(); + await card.getByRole("button", { name: "Use this iteration" }).click(); + await expect(page.locator("[data-current-report='1']")).toBeVisible(); + expect(json(path.join(ARTICLES, BLANK, "report.json")).sections[0].claims[0].verdict).toBe("CORROBORATED"); +}); diff --git a/umtool/lib/articles/hand-types.ts b/umtool/lib/articles/hand-types.ts @@ -0,0 +1,29 @@ +import type { RespellPlan } from "yt-dlp-transcript-common/lib/report/respellArticle"; +import type { Report } from "yt-dlp-transcript-common/lib/report/schema"; + +// The shapes umtool's by-hand routes answer (release 32 R2): what +// components/articles/HandTools.tsx reads. Types only. + +/** POST /api/articles/respell: the plan (or the plan applied, with its backups). */ +export type RespellView = { + article: string; + iteration: number | null; + respellings: RespellPlan["respellings"]; + total: number; + notes: string[]; + targets: { kind: string; file: string; changes: { at: string; hunks: string[] }[] }[]; + /** The iteration's video project, when it has one under the reports root. */ + projectId: string | null; + backups?: string[]; +}; + +/** GET /api/articles/by-hand?article=: the report a claim would join. */ +export type HandBaseView = { + article: string; + n: number | null; + reportKind: Report["kind"] | null; + title: string | null; + sections: { id: string; title: string; claims: number }[]; + citations: { id: string; kind: string; where: string; quote: string }[]; + respellings: NonNullable<Report["respellings"]>; +}; diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts @@ -163,7 +163,7 @@ async function iterationDecisions(piece: Piece, spendOfJob: Map<string, number>) kind: "iteration-ready", target: r.label, why: - `${r.label} (${r.kind} on ${r.model}) is done and newer than the current ${video ? "video" : "report"}` + + `${r.label} (${r.kind === "hand" ? "by hand" : `${r.kind} on ${r.model}`}) is done and newer than the current ${video ? "video" : "report"}` + `${against === null ? " (none yet)" : ` (i${against})`}${spent(r) ? ` · ${usd(spent(r))}` : ""}`, href, severity: "open",