commit 7abfdc60ec2362a3d2dec1af1c521f65cf7c15b5
parent 7c8a54c2658d8f90c1dfb4df43b6c1cda72e9bb8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 16 Oct 2026 18:38:35 -0400
Merge branch 'main' into r32/review-player
# Conflicts:
# plans/FACTS.md
Diffstat:
41 files changed, 3027 insertions(+), 67 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -155,7 +155,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode or limit with it)} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
| `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?, "rederive"?} -> {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.<profile>.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once; {"rederive": true} works the derived timeline out again from the readings the sidecar holds (no model, no frame; refused while a scan of the video runs) and answers {rederived: {before, after, tournaments, eventsByKind}}. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}'` |
| `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -> {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/<slug>.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` |
-| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` |
+| `report-schedule` | report-schedule keeps a recurring report on a cadence the editor ticks: {"action": "list" \| "create" \| "update" \| "pause" \| "resume" \| "delete" \| "tick-now" \| "reset-triage" \| "learn" \| "unlearn" \| "promote-alias" \| "add-spelling", …}. create takes {"shape": "living" \| "series", "topic", "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence" ({"kind": "daily" \| "weekly" \| "every", "at": "HH:MM", "dow"?, "days"?} or "weekly mon 06:00"), "tz"?, "article"? (living), "autoMakeCurrent"? (living), "model"?, "maxUsd"?, "dryRun"?} -> {plan, schedule?}: the plan names the first tick, the model and its cap. A living report is one article kept current: each tick fetches the scope (R4's stage 1) and refreshes it, the new iteration left ready (or made current with autoMakeCurrent); its first tick is its first sweep. A series makes an edition each tick: a new article <series>-<date> over the window since the last edition ("<topic> · week of <date>"); a window the terms (or, with none, any recording) do not match is a quiet edition: recorded, no article, $0. Ticks run as report-tick jobs, one at a time, never on an idle boot, held by the lane's gate (lane report-schedule); a window missed while the editor was down is ONE catch-up tick. A cap refusal ends a tick held-by-cap. update {"id", …} (a new cadence re-plans from now); pause / resume {"id"}; delete {"id", "confirm"?} answers the plan unless confirm is true; tick-now {"id"} -> {jobId} (refused while a tick of it is queued or running); --wait prints the tick's @@report-tick {json}. list {"id"?} answers the schedules with their chip, call and spend, and the lane. A tick whose scan hit a cap (or did not reach a channel) and found nothing ends partial, naming what it did not reach — never quiet. reset-triage {"id", "k"?, "confirm"?} discards a schedule's triage state (its runs from run k on, default all; seen.json, so the next run counts new from its since; the quiet editions they covered): the plan unless confirm is true; refused while a tick runs. learn {"id", "dryRun"?} runs the proposal pass now (R6.3: learned spellings): the triage model lists likely mis-hearings of each name in the terms; each must occur in scope (an uncapped count) and the judge must say, quoting the line, that it means the name, before it joins the candidate query as an escaped literal ("terms + N learned"); the answer is the plan (the names it asks about) and the job (a report-draft job on the triage model's lane); dryRun answers the plan only. A create of a schedule that triages, a change of its terms, and a tick a week after the last pass start one too. unlearn {"id", "spelling"} removes a learned spelling (never learned again). promote-alias {"id", "spelling", "site"?, "confirm"?} writes it as a search alias (global, or the site's), a new alias or a trigger on the one for that name: the plan unless confirm is true. add-spelling {"id", "spelling", "means"} adds a spelling by hand (no model): "means" is one of the names the terms watch; it is counted in scope and its proving line found by code, and kept (source hand) only when it occurs; a removed spelling added by hand is no longer blocked. | `pnpm ops report-schedule --json '{"action":"create","shape":"series","topic":"Co-host updates","channels":["demo-channel"],"cadence":"weekly mon 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"create","shape":"watch","topic":"Co-host watch","channels":["demo-channel"],"terms":"co-host","cadence":"daily 06:00","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"list"}'`<br>`pnpm ops report-schedule --json '{"action":"tick-now","id":"co-host-updates"}' --wait`<br>`pnpm ops report-schedule --json '{"action":"delete","id":"co-host-updates","confirm":true}'`<br>`pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}'`<br>`pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}'`<br>`pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}'` |
| `audio-audit` | audio-audit decodes every audio file a channel holds, with error tolerance, and writes the verdict beside it in audio-integrity.json: {"slug" \| "platform" (every channel on it, e.g. "odysee"), "scope"? ("untranscribed", the default: videos with no transcript yet; "all": every video holding audio), "max"? (files decoded across the run), "force"? (decode again a file whose record is still its own)} -> {jobIds, channels, refused}. One audio-audit job per channel on the audio-audit queue: one file at a time machine-wide, at idle I/O priority and nice 19. The verdict is clean, damaged (a gap, or under 98% of the container's duration decodes) or undecodable, with the decoded seconds, the gaps, the file's size and mtime and ffmpeg's version. The same body again resumes (a file whose record matches is skipped). A channel whose media is unreachable is refused; a drive that stops answering mid-run ends that channel's job with the sentence (failed), as do two decodes in a row past their deadline (a minute plus a tenth of the audio's length). Corrupt full sources are left to their retry. Damaged untranscribed files (and their salvage transcripts) are the report's corruptHeldAudio bucket, held out of the transcription lane: retry-bucket {"bucket": "corruptHeldAudio"} refetches them; a transcription of one salvages automatically. Each log ends with @@audio-audit {slug, scope, held, fresh, planned, checked, clean, damaged, undecodable, unmeasured, timedOut, corruptFullSource, stopped?}. | `pnpm ops audio-audit --json '{"platform":"odysee","scope":"untranscribed"}' --wait`<br>`pnpm ops audio-audit --json '{"slug":"demo-odysee","scope":"all","max":50}'` |
### Usage, flags and environment
diff --git a/common/controller/handEdits.test.ts b/common/controller/handEdits.test.ts
@@ -0,0 +1,188 @@
+// 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, 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("an article older than iterations: its report.json is the base; the claim's iteration is i1, no parent", async () => {
+ const paths = store();
+ const { writeArticle } = await import("../lib/report/registry");
+ await writeArticle({ format: "archilyzer-report", version: 1, id: "older", kind: "factcheck", title: "Older", sections: [{ id: "s1", title: "One", claims: [{ id: "c1", text: "First." }] }] }, { paths });
+ assert.equal(await defaultHandBase("older", paths), null);
+ const r = await addClaimByHand("older", { section: { id: "s1" }, claim: { text: "Second." } }, paths, NOW);
+ assert.deepEqual([r.n, r.amended, r.claim], [1, false, "c2"]);
+ const i1 = (await readIterations("older", paths)).iterations[0]!;
+ assert.deepEqual([i1.kind, i1.parent, i1.status], ["hand", null, "done"]);
+ assert.match(i1.feedback ?? "", /^from the article's report\.json: added c2/);
+ assert.equal(reportOf(paths, "older", 1).sections[0].claims.length, 2);
+});
diff --git a/common/controller/handEdits.ts b/common/controller/handEdits.ts
@@ -0,0 +1,399 @@
+// 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 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<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;
+}
+
+/** The article's own report.json, parsed (raw, its key order kept). */
+export async function readArticleReport(id: string, paths: HandPaths = getPaths()): Promise<Report> {
+ 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<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));
+ 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<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 && 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 };
+}
+
+// ─── 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 { ArticleRegistryError };
diff --git a/common/controller/learnedSpellings.test.ts b/common/controller/learnedSpellings.test.ts
@@ -260,3 +260,37 @@ test("applyTriageLearning: a heard spelling the run confirmed is kept; a blocked
assert.deepEqual(f?.dropped.map((d) => d.reason), ["no-hits"]);
assert.equal(await applyTriageLearning({ ...base, owner: "no-such" }, paths, NOW), null);
});
+
+test("add-spelling (release 32): a spelling by hand — a watched name, proved by code, kept as hand; refusals; a removed one unblocked", async () => {
+ const paths = store();
+ await createSchedule(parseCreate(WATCH), depsOf(paths));
+ const proved: string[] = [];
+ const proveSpelling = async (i: { spelling: string; means: string; at: string }) => {
+ proved.push(i.spelling);
+ if (i.spelling === "Pya Tortlet") return { ok: false as const, reason: "no-hits" as const, why: "does not occur in scope (4 recordings counted)" };
+ return { ok: true as const, spelling: learnedOf(i.spelling, { means: i.means, source: "hand" as const, at: i.at }) };
+ };
+ const d = { ...depsOf(paths), proveSpelling };
+ // No prover: refused as not wired.
+ assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "pia tart lit", means: "Pia Tartlet" }, depsOf(paths))).error, /not wired/);
+ const out = await ask({ action: "add-spelling", id: "pia-watch", spelling: "pia tart lit", means: "Pia Tartlet" }, d);
+ assert.equal(out.ok, true, out.error);
+ assert.deepEqual([out.added.spelling, out.added.source, out.unblocked], ["pia tart lit", "hand", false]);
+ const f = await readLearned(paths, { shape: "watch", id: "pia-watch" });
+ assert.deepEqual(f?.learned.map((l) => [l.spelling, l.source]), [["pia tart lit", "hand"]]);
+ // Refusals, each before any count: not a watched name, the name itself, the terms find it, learned already.
+ assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "pie tart", means: "Someone" }, d)).error, /one of the watched names: "Pia Tartlet"/);
+ assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "pia tartlet", means: "Pia Tartlet" }, d)).error, /the name itself/);
+ assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "the contest", means: "Pia Tartlet" }, d)).error, /terms already find/);
+ assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "Pia Tart Lit", means: "Pia Tartlet" }, d)).error, /learned "Pia Tart Lit" already/);
+ assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "a b c d e", means: "Pia Tartlet" }, d)).error, /too long/);
+ assert.deepEqual(proved, ["pia tart lit"]);
+ // Not in scope: refused with the count's words; nothing written.
+ assert.match((await ask({ action: "add-spelling", id: "pia-watch", spelling: "Pya Tortlet", means: "Pia Tartlet" }, d)).error, /not kept: does not occur in scope/);
+ // A removed spelling added back by hand: the block lifted.
+ await ask({ action: "unlearn", id: "pia-watch", spelling: "pia tart lit" }, depsOf(paths));
+ const back = await ask({ action: "add-spelling", id: "pia-watch", spelling: "pia tart lit", means: "Pia Tartlet" }, d);
+ assert.deepEqual([back.ok, back.unblocked], [true, true]);
+ const g = await readLearned(paths, { shape: "watch", id: "pia-watch" });
+ assert.deepEqual([g?.learned.length, g?.blocked.length], [1, 0]);
+});
diff --git a/common/controller/learnedSpellings.ts b/common/controller/learnedSpellings.ts
@@ -16,6 +16,11 @@
// plan, unless confirm — then the alias written
// through the editor's alias writer (aliasesStore:
// global, or one site's) and the spelling marked
+// addSpellingByHand `report-schedule {"action":"add-spelling"}` (release
+// 32 R2): a person's spelling of a watched name, counted
+// in scope and its proving line found by code
+// (triage/confirm.ts proveByHand), kept with source
+// "hand" — no model, no judge
//
// Nothing here runs a model; the pass is controller/reportLearn.ts's job.
@@ -29,6 +34,12 @@ import { coerceAliasConfig, type SearchAlias } from "../lib/searchAliases";
import { isValidSiteId, listSiteIds } from "../lib/site";
import {
LEARNED_CAP,
+ SPELLING_MAX_CHARS,
+ SPELLING_MAX_WORDS,
+ coveredByTerms,
+ namesOf,
+ normSpelling,
+ termKeys,
PASSES_KEPT,
emptyLearned,
learnedCite,
@@ -44,6 +55,7 @@ import {
} from "../lib/report/draft/triage/learned";
import { learnedFilePath, readLearned } from "../lib/report/draft/triage/learnedStore";
import type { TriageFile } from "../lib/report/draft/triage/types";
+import type { HandProof } from "../lib/report/draft/triage/confirm";
export class LearnedInputError extends Error {}
@@ -239,3 +251,58 @@ export async function promoteAlias(id: string, spelling: string, site: string |
);
return plan;
}
+
+// ─── a spelling added by hand (release 32 R2) ───
+
+/** Proves a hand spelling over the watch's scope (the editor binds it to its corpus: reportLearn.ts handProver). */
+export type HandProver = (i: { spelling: string; means: string; scope: { channels: string[]; from?: string; to?: string }; at: string }) => Promise<HandProof>;
+
+/**
+ * ADD A SPELLING BY HAND: `spelling` is how the transcripts write `means`, one of
+ * the names the watch's terms watch. Refused when it is not a spelling (words,
+ * at most SPELLING_MAX_WORDS), is the name itself, the terms already find it, it
+ * is learned already, or the watch is at its cap; then counted in scope and its
+ * proving line found (`prove`, code only) — refused when it does not occur. A
+ * spelling the operator removed is the operator's to add back: adding it by hand
+ * lifts the block. Answers what was kept.
+ */
+export async function addSpellingByHand(
+ id: string,
+ input: { spelling?: unknown; means?: unknown },
+ deps: { paths: LearnedPathsFull; prove: HandProver; now?: () => Date },
+): Promise<{ added: LearnedSpelling; unblocked: boolean }> {
+ const spelling = normSpelling(input.spelling);
+ const means = typeof input.means === "string" ? input.means.trim() : "";
+ if (!spelling) fail('"spelling" is how the transcripts write the name');
+ const s = await scheduleOf(id, deps.paths);
+ const names = namesOf(s.scope.terms ?? null, s.scope.regex === true);
+ if (!names.length) fail(`"${id}" watches no name: its terms have no capitalised literal alternative`);
+ if (!names.includes(means)) fail(`"means" is one of the watched names: ${names.map((n) => `"${n}"`).join(", ")}`);
+ const key = spellingKey(spelling);
+ const words = key.split(" ").filter(Boolean).length;
+ if (!key || !/^[\p{L}\p{N}][\p{L}\p{N}' .&-]*$/u.test(spelling)) fail(`"${spelling}" is not a spelling (words only)`);
+ if (spelling.length > SPELLING_MAX_CHARS || words > SPELLING_MAX_WORDS) fail(`"${spelling}" is too long (at most ${SPELLING_MAX_WORDS} words, ${SPELLING_MAX_CHARS} characters)`);
+ if (key === spellingKey(means)) fail(`"${spelling}" is the name itself`);
+ if (termKeys(s).includes(key) || coveredByTerms(s.scope.terms, s.scope.regex === true)(spelling)) fail(`the terms already find "${spelling}"`);
+ const cur = await readLearned(deps.paths, s);
+ if (cur?.learned.some((l) => spellingKey(l.spelling) === key)) fail(`"${id}" has learned "${spelling}" already`);
+ if ((cur?.learned.length ?? 0) >= LEARNED_CAP) fail(`the watch keeps at most ${LEARNED_CAP} spellings: remove one first`);
+ const now = deps.now?.() ?? new Date();
+ const proof = await deps.prove({ spelling, means, scope: { channels: s.scope.channels, ...(s.scope.from ? { from: s.scope.from } : {}) }, at: now.toISOString() });
+ if (!proof.ok) fail(`"${spelling}" is not kept: ${proof.why}`);
+ const added = (proof as Extract<HandProof, { ok: true }>).spelling;
+ let unblocked = false;
+ await mutateLearned(
+ s,
+ deps.paths,
+ (f) => {
+ const blocked = f.blocked.filter((b) => spellingKey(b.spelling) !== key);
+ unblocked = blocked.length !== f.blocked.length;
+ const m = mergeLearned({ ...f, blocked }, { kept: [added], dropped: [], at: now.toISOString(), cap: LEARNED_CAP });
+ if (!m.added.length) fail(`"${spelling}" is not kept: ${m.dropped.at(-1)?.why ?? "the watch refused it"}`);
+ return m.file;
+ },
+ now,
+ );
+ return { added, unblocked };
+}
diff --git a/common/controller/reportLearn.ts b/common/controller/reportLearn.ts
@@ -28,7 +28,7 @@ import { Meter, providerOf, structuredAnswer, unloadOllama } from "../lib/llm";
import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues";
import { usageOf } from "../lib/report/draft/tasks/run";
import { enumerateViaTools } from "../lib/report/draft/refresh/delta";
-import { countViaEnumerate, runLearnPass } from "../lib/report/draft/triage/confirm";
+import { countViaEnumerate, proveByHand, runLearnPass } from "../lib/report/draft/triage/confirm";
import {
CONFIRM_WINDOWS,
LEARNED_CAP,
@@ -46,7 +46,7 @@ import { readLearned } from "../lib/report/draft/triage/learnedStore";
import { readScheduleById } from "../lib/report/schedule/store";
import { triagesFirst, type Schedule } from "../lib/report/schedule/types";
import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage";
-import { recordLearnPass } from "./learnedSpellings";
+import { recordLearnPass, type HandProver } from "./learnedSpellings";
import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, resolveCorpus, type ReportDraftDeps } from "./reportDraft";
export const LEARN_TASK = "learn" as const;
@@ -246,3 +246,24 @@ export function learnStep(draft: ReportDraftDeps, calls: { enqueueLearn?: typeof
};
};
}
+
+/**
+ * A spelling added by hand, proved over the corpus a sweep of the scope would
+ * read (release 32 R2): the count and the proving line, code only — no model,
+ * no job (a count is one scan). The editor binds this into `report-schedule
+ * {"action":"add-spelling"}` (controller/learnedSpellings.ts addSpellingByHand).
+ */
+export function handProver(deps: Pick<ReportDraftDeps, "paths" | "corpusTools" | "settings">): HandProver {
+ return async (i) => {
+ const gen = (deps.settings ?? getSettings)().generation;
+ const where = await resolveCorpus({}, i.scope.channels, deps.paths, gen);
+ const c = await deps.corpusTools(where.source);
+ try {
+ const count = c.countPhrases ? (a: Parameters<NonNullable<typeof c.countPhrases>>[0]) => c.countPhrases!(a) : c.listRecordings ? countViaEnumerate((a) => c.listRecordings!(a), enumerateViaTools(c)) : null;
+ if (!count) throw new Error("this corpus cannot count a spelling in scope (no listing)");
+ return await proveByHand(i, { corpus: c, count });
+ } finally {
+ await c.close().catch(() => {});
+ }
+ };
+}
diff --git a/common/controller/reportScheduleOps.ts b/common/controller/reportScheduleOps.ts
@@ -32,6 +32,9 @@
// change of terms start one too
// {"action": "unlearn", "id", "spelling"} (R6.3) remove a learned spelling;
// it is never learned again
+// {"action": "add-spelling", "id", (release 32 R2) a spelling added by
+// "spelling", "means"} hand: counted in scope, its proving
+// line found by code, kept as "hand"
// {"action": "promote-alias", "id", (R6.3) a learned spelling as a
// "spelling", "site"?, "confirm"?} search alias (global, or a
// site's) through the alias
@@ -58,12 +61,12 @@ import {
} from "./reportSchedule";
import { enqueueTick, type TickDeps } from "./reportTick";
import { isReportScheduleArmed } from "./reportScheduleRunner";
-import { LearnedInputError, planPromoteAlias, promoteAlias, unlearnSpelling } from "./learnedSpellings";
+import { LearnedInputError, addSpellingByHand, planPromoteAlias, promoteAlias, unlearnSpelling, type HandProver } from "./learnedSpellings";
import { planLearn, type LearnPlan, type LearnTrigger } from "./reportLearn";
import { triagesFirst } from "../lib/report/schedule/types";
import { namesForPass } from "../lib/report/draft/triage/learned";
-export const REPORT_SCHEDULE_ACTIONS = ["list", "create", "update", "pause", "resume", "delete", "tick-now", "reset-triage", "learn", "unlearn", "promote-alias"] as const;
+export const REPORT_SCHEDULE_ACTIONS = ["list", "create", "update", "pause", "resume", "delete", "tick-now", "reset-triage", "learn", "unlearn", "promote-alias", "add-spelling"] as const;
export type ReportScheduleActionName = (typeof REPORT_SCHEDULE_ACTIONS)[number];
export const REPORT_SCHEDULE_BODY_KEYS = [
@@ -91,6 +94,7 @@ export const REPORT_SCHEDULE_BODY_KEYS = [
"threshold",
"k",
"spelling",
+ "means",
"site",
] as const;
@@ -136,7 +140,7 @@ async function learnAfter(id: string, trigger: LearnTrigger, s: { shape: string;
/** One `report-schedule` ask. Input errors answer `{ok: false, error}` (a 400); nothing throws for them. */
export async function reportScheduleAction(
body: Record<string, unknown>,
- deps: TickDeps & { lane?: () => LaneView; enqueueLearn?: EnqueueLearnFn },
+ deps: TickDeps & { lane?: () => LaneView; enqueueLearn?: EnqueueLearnFn; proveSpelling?: HandProver },
): Promise<Ok | Refused> {
const action = body.action;
if (typeof action !== "string" || !(REPORT_SCHEDULE_ACTIONS as readonly string[]).includes(action)) {
@@ -193,6 +197,12 @@ export async function reportScheduleAction(
const out = await unlearnSpelling(id, String(body.spelling ?? ""), deps);
return { ok: true, removed: out.removed, blocked: out.blocked };
}
+ case "add-spelling": {
+ const id = idOf(body);
+ if (!deps.proveSpelling) return { ok: false, error: "not wired: no corpus to count a spelling in (release 32) in this process" };
+ const out = await addSpellingByHand(id, { spelling: body.spelling, means: body.means }, { paths: deps.paths, prove: deps.proveSpelling, ...(deps.now ? { now: deps.now } : {}) });
+ return { ok: true, added: out.added, unblocked: out.unblocked };
+ }
case "promote-alias": {
const id = idOf(body);
const site = body.site === undefined || body.site === null || body.site === "" || body.site === "global" ? null : typeof body.site === "string" ? body.site.trim() : "";
diff --git a/common/lib/report/draft/triage/confirm.ts b/common/lib/report/draft/triage/confirm.ts
@@ -349,3 +349,55 @@ export async function runLearnPass(
const c = await confirmSpellings({ pending: p.proposed, question: i.question, scope: i.scope, at: i.at, ...(i.windows ? { windows: i.windows } : {}) }, d);
return { proposed: p.proposed, kept: c.kept, dropped: [...p.dropped, ...c.dropped], counted: c.counted, judged: c.judged };
}
+
+// ─── a spelling added by hand (release 32 R2) ───
+
+export type HandProof = { ok: true; spelling: LearnedSpelling } | { ok: false; reason: LearnedDropReason; why: string };
+
+/**
+ * A spelling a PERSON says means a watched name: counted in scope (uncapped, the
+ * same count a proposal gets) and its proving line found by code — the first
+ * line holding it, in the newest recordings that do (up to `windows`). No judge:
+ * the person's word is the judge's. Not kept when it does not occur in scope, or
+ * when no line holding it could be read.
+ */
+export async function proveByHand(
+ i: { spelling: string; means: string; scope: { channels: string[]; from?: string; to?: string }; at: string; windows?: number },
+ d: { corpus: Pick<CorpusToolsLike, "call">; count: CountPhrasesFn },
+): Promise<HandProof> {
+ const spelling = normSpelling(i.spelling);
+ const counted = await d.count({ phrases: [spelling], channels: i.scope.channels, ...(i.scope.from ? { date_from: i.scope.from } : {}), ...(i.scope.to ? { date_to: i.scope.to } : {}), examples: 10 });
+ const c = counted.counts[spelling] ?? { recordings: 0, lines: 0, examples: [] };
+ if (!c.recordings) {
+ return counted.complete
+ ? { ok: false, reason: "no-hits", why: `does not occur in scope (${counted.listed.toLocaleString("en-US")} recordings counted)` }
+ : { ok: false, reason: "unread", why: `not found in what the count read (partial: ${counted.problems.join("; ")})` };
+ }
+ const ids = [...c.examples].sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? ""))).slice(0, i.windows ?? CONFIRM_WINDOWS);
+ const parsed = parseTranscripts(await d.corpus.call("get_transcripts", { video_ids: ids.map((x) => x.id), query: spellingPattern(spelling), regex: true, link_style: "base", channels: i.scope.channels }));
+ for (const x of ids) {
+ const t = parsed.get(x.id);
+ const line = t?.lines.find((l) => l && holdsSpelling(l[1], spelling));
+ if (!t || !line) continue;
+ const at = line[0];
+ return {
+ ok: true,
+ spelling: {
+ spelling,
+ means: i.means,
+ quote: clean(line[1]),
+ recording: x.id,
+ channel: x.channelSlug ?? slugOfBase(t.momentBase),
+ title: t.title ?? x.title ?? x.id,
+ start: at,
+ ...(t.momentBase ? { url: `${t.momentBase}${Math.floor(at)}` } : {}),
+ hits: c.recordings,
+ lines: c.lines,
+ ...(counted.complete ? {} : { partial: true }),
+ source: "hand",
+ at: i.at,
+ },
+ };
+ }
+ return { ok: false, reason: "unread", why: `counted in ${c.recordings} recording(s), but no line holding it could be read` };
+}
diff --git a/common/lib/report/draft/triage/learned.test.ts b/common/lib/report/draft/triage/learned.test.ts
@@ -16,7 +16,7 @@ import path from "node:path";
import type { EnumeratedAnswer, EnumerateFn, ListFn } from "../refresh/delta";
import type { CorpusToolsLike } from "../tasks/types";
import { EXTRACT_SYSTEM } from "../tasks/sweep-pipeline";
-import { confirmSpellings, countViaEnumerate, keptByWindows, runLearnPass, type CountPhrasesFn } from "./confirm";
+import { confirmSpellings, countViaEnumerate, keptByWindows, proveByHand, runLearnPass, type CountPhrasesFn } from "./confirm";
import { checkHeard, judgeCandidates } from "./judge";
import {
CONFIRM_SYSTEM,
@@ -460,3 +460,17 @@ test("runTriage with learned spellings and names: terms + N learned, the heard s
const back = await readTriageFile("pia-watch", f0.k, paths);
assert.equal(back?.learning?.kept.length, 1);
});
+
+test("proveByHand (release 32): counted in scope, the proving line found by code, no model; no hits is refused", async () => {
+ const count = countViaEnumerate(listOver(RECS), enumerateOver(RECS));
+ const corpus = corpusOver(RECS);
+ const at = "2026-10-16T12:00:00.000Z";
+ const got = await proveByHand({ spelling: "Pia Tart Lit", means: "Pia Tartlet", scope: { channels: [CHAN] }, at }, { corpus, count });
+ assert.equal(got.ok, true);
+ const l = (got as { spelling: LearnedSpelling }).spelling;
+ // The newest recording holding it first: d-04, its first line.
+ assert.deepEqual([l.spelling, l.means, l.recording, l.channel, l.start, l.quote, l.hits, l.source], ["Pia Tart Lit", "Pia Tartlet", "d-04", CHAN, 0, "pia tart lit could not make it tonight", 2, "hand"]);
+ assert.equal(l.url, `https://synth.example/?v=${CHAN}%2Fd-04&t=0`);
+ const none = await proveByHand({ spelling: "Pya Tortlet", means: "Pia Tartlet", scope: { channels: [CHAN] }, at }, { corpus, count });
+ assert.deepEqual(none.ok ? null : none.reason, "no-hits");
+});
diff --git a/common/lib/report/draft/triage/learned.ts b/common/lib/report/draft/triage/learned.ts
@@ -50,7 +50,9 @@ export const PASSES_KEPT = 10;
export const SPELLING_MAX_WORDS = 4;
export const SPELLING_MAX_CHARS = 48;
-export type SpellingSource = "proposed" | "heard";
+// "hand" (release 32 R2): added by a person in umtool ("Add spelling"): counted in
+// scope and its proving line found by code, no model; the person's word is the judge's.
+export type SpellingSource = "proposed" | "heard" | "hand";
/** One tick's use of a spelling: the candidates it matched in triage run `k`, and how many were flagged. */
export type LearnedUse = { k: number; at: string; candidates: number; flagged: number };
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;
diff --git a/common/publish/citedCues.test.ts b/common/publish/citedCues.test.ts
@@ -0,0 +1,43 @@
+// The cues around a cited second (release 32 R2): the record's cues as compose
+// reads them, in a window, and its title. A synthetic record in a temp dir.
+//
+// Run with: node_modules/.bin/tsx --test publish/citedCues.test.ts
+
+import { after, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { cuesAround } from "./citedCues";
+
+const root = mkdtempSync(path.join(tmpdir(), "cited-cues-"));
+after(() => rmSync(root, { recursive: true, force: true }));
+
+const ts = (s: number) => new Date(s * 1000).toISOString().slice(11, 23);
+const put = (file: string, text: string) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, text);
+};
+const channelsDir = path.join(root, "channels");
+const dir = path.join(channelsDir, "synth-hand", "data", "rec1");
+put(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "rec1", title: "Synthetic stream", channel: "synth-hand", upload_date: "20260110", duration: 600, webpage_url: "https://www.youtube.com/watch?v=rec1", extractor_key: "Youtube" }));
+put(
+ path.join(dir, "transcript.en.vtt"),
+ "WEBVTT\nKind: captions\nLanguage: en\n\n" +
+ ([
+ [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."],
+ [40, 44, "Much later."],
+ ] as const)
+ .map(([a, b, t]) => `${ts(a)} --> ${ts(b)}\n${t}\n`)
+ .join("\n"),
+);
+
+test("cuesAround: the record's cues in a window, and its title; a bad id or no record is null", async () => {
+ const got = await cuesAround("synth-hand", "rec1", 13, 19, { channelsDir });
+ assert.equal(got?.title, "Synthetic stream");
+ assert.deepEqual(got?.cues.map((c) => c.start), [10, 14, 18]);
+ assert.equal(await cuesAround("synth-hand", "../x", 0, 10, { channelsDir }), null);
+ assert.equal(await cuesAround("synth-hand", "nope", 0, 10, { channelsDir }), null);
+});
diff --git a/common/publish/citedCues.ts b/common/publish/citedCues.ts
@@ -0,0 +1,29 @@
+// THE CUES AROUND A CITED SECOND (release 32 R2): what umtool's "Add a claim"
+// lists to pick a quote from — the record's cues as compose reads them
+// (readCitedRecord: the normalized cues, else whisper, else the English VTTs,
+// en-orig first). Here, in publish/, because the reader is; the claim's writer
+// (controller/handEdits.ts) may not import this layer.
+//
+// SERVER-ONLY.
+
+import { getPaths, type Paths } from "../lib/paths";
+import { readCitedRecord } from "./composeReports";
+
+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 })),
+ };
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -10,6 +10,11 @@
- **A video's media operations are buttons on its page.** Under **Media tools**: attach the video's file from a local archive (a folder, a .zip or a .7z; preview, then attach), make a playable copy of its saved video, and for a Wayback or archive.org record bring the channel's records up to their rules (preview, then refresh; a Wayback record's title and date can be given with it). Needs a restart of the editor.
- **More ops-only operations have buttons.** Each article on the Articles tab has **Attach video** (a video file, a poster and a caption: what `archilyzer reports attach-video --article` did). The Download stage's **More ways in** imports an archive.org item, completes a podcast channel's records from its feed, and reads an Odysee or BitChute channel's remote listing; a posts channel imports one post by its URL and captures posts by id; the Cleanup stage has **Keep videos matching** (preview the matches, then keep them). Needs a restart of the editor.
- **An Odysee channel's Configure form shows the audio check on.** The check is on by default for Odysee, but the box showed unticked; it now shows ticked with "on by default for Odysee", and unticking it turns the check off for the channel (`pnpm ops channel-config` with `"audioCheckEnabled": false` too). Needs a restart of the editor.
+- **An article can be written by hand in umtool, with no model.** Create's article form starts **blank** (no model, no editor job): an article in the making whose first iteration is a titled report with no sections. On an article's Iterations tab, **Add a claim** puts a claim in a section (or a new one) with your verdict, citing the report's citations or new ones — paste an archive link, a copied citation or `channel/id@m:ss`, click the transcript lines you mean, and the quote is checked word for word against the record before anything is saved (a paraphrase is refused). A claim goes into a hand draft nobody uses yet, or into a new iteration; **Use this iteration** makes it the article's, as for any other.
+- **Fix a mishearing from the article page.** The Iterations tab's **Fix a mishearing** is `archilyzer reports respell` in the UI: the heard forms, what was said, bracketed or not, a note → **Preview** shows every change per file as before → after → **Apply** writes them with the same backups the CLI makes, lists the backups, and offers the video's Build tab when its manifest changed. The report's respellings are listed with their heard forms. The drafts review's "fix this mishearing" opens it with the heard words filled.
+- **A learned spelling can be added by hand.** On a watch's series page, **Add spelling** (beside **Propose spellings**) takes how the transcripts write a watched name and which name it means; the editor counts it in the watch's scope and finds the line that shows it, with no model, and keeps it (marked "added by hand") only when it occurs. `pnpm ops report-schedule --json '{"action":"add-spelling","id":"<watch>","spelling":"<spelling>","means":"<name>"}'` does the same. A spelling you removed and then add by hand is no longer blocked. Needs a restart of the editor.
+- **A new video project can be seeded from a frame scan.** The new-project form's seed is now a choice — an empty timeline, the digest's chapters, or the frame scan's events — each offered when the video has it, with the frame cut's target length in seconds (what `umtool new --seed frames --target` does).
+- **Fill empty fields by hand on a cut's Media tab.** Beside the drafts, **Fill empty fields by hand** lists every media field the cut leaves empty — each clip's on-screen title, a teaser's lines, the YouTube title and description, the X and Bluesky posts — and the flips or threads (which had no editor of their own) as blanks you fill. What you write is saved as yours ("written by hand"): no draft replaces it, so a cut can reach a buildable manifest with no model at all.
- **Odysee downloads always get the audio check, clip windows included.** A video from Odysee — which intermittently serves corrupt audio — is downloaded with the audio check on unless its channel turns it off (`audioCheck: {"enabled": false}`); before, a channel had to opt in. A clip window from such a source now gets the check's final probe too: a malformed window is deleted and fetched once more, and if it is malformed again the fetch fails and nothing is kept, so a clip is never cut from corrupt audio. The verdict is recorded in the window's provenance.
- **An article can correct what the transcripts mishear in its quotes.** `archilyzer reports respell <article> --heard "cake cup,cakeup" --reads K-Cup` previews every change — the article's quotes and citations, its report's own words, and its video's burned-in quotes and flip cards — as before → after, and writes nothing; `--apply` writes it, each file backed up first. `--bracket` shows the correction as an altered quote, `[K-Cup]`. The article records the respelling, and every quote check applies it to the transcript before comparing, so a corrected quote still verifies exactly; the transcript itself is untouched. A video shows the new words once it is rebuilt.
- **`pnpm ops audio-audit` checks the audio already on disk, file by file.** `pnpm ops audio-audit --json '{"platform":"odysee"}'` (or `{"slug":"<channel>"}`; `"scope":"all"` for transcribed videos too, `"max"` to cap the files) decodes each audio file a channel holds with error tolerance — one file at a time, at the lowest CPU and disk priority — and writes what it found beside the file in `audio-integrity.json`: clean, damaged (part of it will not decode) or undecodable, with how much decodes and where the gaps are. Audio downloaded before the audio check existed, or on a channel without it, was never checked. The same command again skips the files already checked. A drive that stops answering ends that channel's run with a sentence that says so instead of hanging.
diff --git a/editor/app/api/ops/_reportSchedule.ts b/editor/app/api/ops/_reportSchedule.ts
@@ -11,8 +11,9 @@ import {
} from "yt-dlp-transcript-common/controller/reportTick";
import type { ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft";
import { armReportSchedule } from "yt-dlp-transcript-common/controller/reportScheduleRunner";
-import { enqueueLearn, learnStep } from "yt-dlp-transcript-common/controller/reportLearn";
+import { enqueueLearn, handProver, learnStep } from "yt-dlp-transcript-common/controller/reportLearn";
import type { EnqueueLearnFn } from "yt-dlp-transcript-common/controller/reportScheduleOps";
+import type { HandProver } from "yt-dlp-transcript-common/controller/learnedSpellings";
import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool";
import { SourceRegistry, enumerate } from "yt-dlp-transcript-mcp/research";
import { refreshEditor, researchEditor } from "./_researchEditor";
@@ -41,6 +42,9 @@ import { refreshEditor, researchEditor } from "./_researchEditor";
// when one is due; awaited (learnStep). `enqueueLearn` is
// the same pass for the ops action and a create or a
// change of terms (not awaited)
+// proveSpelling release 32 R2: a spelling added by hand, counted over the
+// corpus a sweep would read and its proving line found —
+// code only (handProver), for `add-spelling`
const countWindow: CountWindow = async (q) => {
const paths = getPaths();
@@ -66,7 +70,7 @@ const countWindow: CountWindow = async (q) => {
return { recordings: e.result.total, ...(e.result.truncated ? { partial: true, unreached } : {}) };
};
-export function reportScheduleDeps(): TickDeps & { enqueueLearn: EnqueueLearnFn } {
+export function reportScheduleDeps(): TickDeps & { enqueueLearn: EnqueueLearnFn; proveSpelling: HandProver } {
const paths = getPaths();
const draft: ReportDraftDeps = { paths, corpusTools: (source) => createCorpusTools({ source }), researchEditor, refreshEditor };
return {
@@ -79,6 +83,7 @@ export function reportScheduleDeps(): TickDeps & { enqueueLearn: EnqueueLearnFn
triage: triageStep(draft),
learn: learnStep(draft),
},
+ proveSpelling: handProver(draft),
enqueueLearn: async (id, trigger) => {
const out = await enqueueLearn(id, trigger, draft);
if (!out.ok) return out;
diff --git a/editor/app/api/ops/report-schedule/route.ts b/editor/app/api/ops/report-schedule/route.ts
@@ -10,7 +10,7 @@ export const dynamic = "force-dynamic";
// POST {"action": "list" | "create" | "update" | "pause" | "resume" |
// "delete" | "tick-now" | "reset-triage" | "learn" | "unlearn" |
-// "promote-alias", …}
+// "promote-alias" | "add-spelling", …}
//
// A recurring report (umtool R5): a LIVING report (one article kept current —
// each tick re-fetches the scope and refreshes it), a SERIES (a dated
@@ -38,6 +38,9 @@ export const dynamic = "force-dynamic";
// model's lane. A create or a change of terms starts one too
// (the answer's `learn`)
// unlearn {id, spelling} -> {removed, blocked} never learned again
+// add-spelling {id, spelling, means} -> {added, unblocked} (release 32)
+// a spelling added by hand: counted in scope, its proving line
+// found by code — no model; refused when it does not occur
// promote-alias {id, spelling, site?, confirm?} -> {plan} | {promoted}
// a learned spelling as a search alias (global, or a site's),
// through the alias writer; the plan unless confirm
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -9985,3 +9985,38 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
umtool's `lib/articles/checks.ts` runs it and `verifyReportQuotes` in-process over `sitesPaths()` (the store's
article: `--article`; a site's report: `siteId` + `reports: [id]`); `POST /api/articles/checks {site, report, what:
"quotes" | "check", allowMissingMedia?}`.
+
+## Release 32 lane R2: by hand, no model (verified 2026-10-16, branch `r32/by-hand`)
+
+- **Iteration kind `hand`** (`lib/report/iterations.ts` ITERATION_KINDS): written by a person, model `"hand"`, usage
+ `{}`; no parent required. Writers in `controller/handEdits.ts`: `startBlankArticle(id, {title, kind})` (refuses an
+ id with a report.json or any iteration; i1 done, report `{…, sections: []}`) and `addClaimByHand(id, {base?,
+ section: {id} | {title}, claim: {text, title?, verdict?, gist?, flag?, findings?}, cite?, add?})`. Base default
+ (`defaultHandBase`): current `reportFrom`, else the newest done iteration with a report.json; an article with a
+ report.json and no iteration is its own base (the claim's iteration is i1, no parent). A base of kind `hand`
+ that is not current (report, reportFrom, video) and has no `projectDir` is AMENDED (report rewritten, `feedback`
+ gains a line); any other base → a NEW hand iteration, `parent` = base. Nothing is made current.
+- **A new citation's check** is `verifyReportQuotes` (bin/reports-check.ts) over a probe report holding only the new
+ citations and the report's `respellings`: `ok` and `fragment` pass; everything else (`drift`, `inexact`,
+ `en-orig-drift`, `missing-record`, `no-cues`, `missing-post`, `unreadable`) refuses with the per-citation lines in
+ `HandEditError.problems`. New ids: citations `h1, h2, …`, claims `c1, c2, …`, a new section the title's slug.
+ `readCitedRecord` needs a record a corpus has (metadata.info.json + a transcript, or a fresh cues.json); umtool's
+ e2e `sitechan` records (a bare `transcript.cues.json`) read as `missing-record`.
+- **umtool routes**: `POST /api/articles/respell` (planRespell / applyRespell; hunks = `wordHunks`; files shown
+ relative to the article's folder or the projects root), `GET|POST /api/articles/by-hand` (the base view; `?moment=`
+ → `parseMoment` + `cuesAround` (publish/citedCues.ts: controller/ may not import publish/) −20/+60 s; `action: blank | claim`), `GET|POST /api/report/hand-fill`,
+ `GET /api/projects/new?from=` (`seedsFor` → `{video, chapters, frames}`: ai-digest.json, frame-scan.poker.json).
+ The Iterations list re-reads on the window event `umtool:iterations-changed` (HandTools.tsx `ITERATIONS_CHANGED`).
+- **Learned spellings, source `"hand"`** (`SpellingSource`): `report-schedule {"action":"add-spelling", id,
+ spelling, means}` → `addSpellingByHand` (controller/learnedSpellings.ts): `means` must be one of `namesOf(terms)`;
+ refused when not words / > 4 words or 48 chars / the name itself / found by the terms / learned already / at
+ LEARNED_CAP; proved by `proveByHand` (triage/confirm.ts: the uncapped count, then the first line holding it in the
+ newest ≤3 recordings, via `get_transcripts`); no hits or no readable line → refused, nothing written. A blocked
+ spelling added by hand is unblocked. The editor binds the prover (`handProver`, reportLearn.ts) as
+ `proveSpelling` in `_reportSchedule.ts`; without it the action answers "not wired".
+- **Fill by hand** (`umtool/lib/report/hand-fill.mjs`): `handFillView(manifest)` → empty fields (clip `onscreen`,
+ teaser `lines`, `publish.youtube|x|bluesky`, by `isEmptyField`), the clips, `deck` (render.chrome present), the
+ flips / threads as they stand; `applyHandFill(dir, fills, {token})` writes each through `writeDraftedField` in
+ HAND_FIELDS order, token chained, stopping at the first refusal (earlier writes kept and named). Written unmarked =
+ the operator's. A blank is never written as a placeholder.
+
diff --git a/plans/release-32/by-hand.md b/plans/release-32/by-hand.md
@@ -0,0 +1,89 @@
+# Release 32 lane R2 — by hand, no model (as shipped)
+
+Operator rule (2026-10-16): every step a model can do, a person can do in the UI, with no model. An audit found six
+gaps in umtool; this lane closes them. Nothing here calls a model.
+
+## What
+
+1. **Fix a mishearing** (respell had no UI). On an article's Iterations tab (`HandTools`, "by hand" region): heard
+ forms, reads, bracket, note → **Preview** (every change per file as word hunks, `wordHunks`) → **Apply** (the
+ CLI's `applyRespell`, its backups listed) → **Rebuild the video →** (the iteration's project's Build tab) when the
+ manifest changed. The report's respellings are listed with their heard forms. Apply waits for a fresh preview when
+ a field changed since. `?tab=iterations&heard=<words>` (R1's drafts-review link) opens it with Heard filled,
+ scrolled into view.
+2. **Add a claim by hand.** Same region: section (existing or new), title, text, verdict (fact-check only), the
+ report's citations as checkboxes, and new ones from a pasted moment (archive link, the house citation,
+ `channel/id@m:ss`) whose cues are listed to click — the quote, start and end come from the lines picked. Saved
+ through the iterations store as a `hand` iteration (or into a hand draft no one uses); every new quote is checked
+ strictly against the record first (verify-quotes' check: `ok`/`fragment` pass), else refused with nothing written.
+ Nothing is made current.
+3. **A blank start.** Create's article form: "blank (no model: write it by hand)" — title, kind (fact-check | sweep),
+ id → an article in the making, i1 a `hand` iteration with a titled empty report; the page opens on its
+ Iterations tab, where Add a claim fills it.
+4. **Learned spellings by hand.** Series page: **Add spelling** (spelling + the watched name it means) →
+ `report-schedule add-spelling`: counted in scope and its proving line found by code (`proveByHand`), kept with
+ source `"hand"` ("added by hand") only when it occurs.
+5. **A "frames" seed** in the new-project form: the seed is a select (empty, digest chapters, frame scan events),
+ each offered when the video has it (`GET /api/projects/new?from=`), with the frames cut's target seconds.
+6. **Fill empty fields by hand** on the Media tab (under the drafts): every empty clip on-screen title, teaser lines,
+ YouTube title/description, X and Bluesky post as blanks; the flips or the threads whole when the deck is on.
+ Written through `writeDraftedField` with no drafted mark — the operator's, "written by hand", never replaced.
+ Found missing and added: hand editors for YouTube, X/Bluesky, flips and threads (teaser lines already had
+ StructureEditors; on-screen titles OnscreenSection).
+
+## Files
+
+common: `lib/report/iterations.ts` (kind `hand`), `controller/handEdits.ts` (+ test), `controller/learnedSpellings.ts`
+(`addSpellingByHand`, + test), `controller/reportLearn.ts` (`handProver`), `controller/reportScheduleOps.ts`
+(`add-spelling`, body key `means`), `lib/report/draft/triage/confirm.ts` (`proveByHand`, + test in learned.test.ts),
+`lib/report/draft/triage/learned.ts` (`SpellingSource` + `"hand"`). editor: `app/api/ops/_reportSchedule.ts`
+(`proveSpelling`), `app/api/ops/report-schedule/route.ts` (comment). scripts: `archilyzer-ops.mjs` (help). umtool:
+`app/api/articles/{respell,by-hand}/route.ts`, `app/api/report/hand-fill/route.ts`, `app/api/projects/new/route.ts`
+(GET), `app/api/schedules/route.ts`, `components/articles/{HandTools,IterationsView,IterationsTab,NewArticleForm}.tsx`,
+`components/series/LearnedSpellings.tsx`, `components/NewProjectMenu.tsx`, `components/projects/HandFill.tsx`,
+`components/projects/report/MediaTab.tsx`, `lib/articles/hand-types.ts`, `lib/report/hand-fill.mjs` (+ test),
+`lib/projects/{scaffold.mjs,scaffold.ts}`, `lib/scaffold-frames.test.mjs`, `lib/inbox.ts` ("by hand"),
+`e2e/by-hand.spec.ts`. COMMANDS.md, FACTS.md, CHANGELOG.
+
+## Interfaces
+
+- `startBlankArticle(id, {title, kind?}, paths?, now?)`, `addClaimByHand(id, HandClaimInput, paths?, now?)` →
+ `{n, amended, claim, section, added: [{id, check}], warnings}`, `defaultHandBase`, `checkAddedCitations`,
+ `parseMoment(text)`, `cuesAround(channel, id, from, to, paths?)`, `HandEditError {problems}`, `HAND_MODEL`.
+- `addSpellingByHand(id, {spelling, means}, {paths, prove, now?})` → `{added, unblocked}`; `HandProver`;
+ `proveByHand(i, {corpus, count})` → `HandProof`; `handProver(draftDeps)`.
+- `pnpm ops report-schedule --json '{"action":"add-spelling","id","spelling","means"}'`.
+- umtool: `POST /api/articles/respell`, `GET|POST /api/articles/by-hand`, `GET|POST /api/report/hand-fill`,
+ `GET /api/projects/new?from=`; `handFillView`, `applyHandFill`, `seedsFor`.
+
+## Rulings followed / decisions
+
+- A hand claim on a hand draft no one uses amends it (one draft, not one iteration per claim); any other base gets a
+ new `hand` iteration. Model name `"hand"`.
+- New quotes: `ok` and the `fragment` warning pass; every other status refuses.
+- A spelling a person removed and then adds by hand lifts its block (the person's word, again).
+- Fill by hand writes only what is filled; a blank is a form field, never a manifest placeholder. Flips/threads:
+ the one the cut has, else both offered and the last edited saved (a cut has one or the other).
+- Fill by hand is its own section under the drafts on the Media tab, not inside the Draft everything row.
+
+## Gates
+
+Final, on `3f4e20c0` + `6132db61` (main `45c5a583` merged), all through the shared lock:
+
+- tsc (all packages) clean, before every commit.
+- common 4465 (4464 pass, 1 skipped, 0 fail; baseline 4448 on `977917c7`, +17: handEdits 8, citedCues 1, add-spelling
+ 1, proveByHand 1, the rest from main's merge). An earlier run caught a new layer back-edge (controller/ →
+ publish/): `cuesAround` moved to `publish/citedCues.ts`.
+- umtool 33 (unchanged); scripts 1048 (1044 pass, 4 skipped, 0 fail; baseline 1042 + 3 skipped: +3 tests —
+ hand-fill 2, seedsFor 1; one more environment skip than the baseline, not from this lane); editor 327 (main's
+ 322 + R3's); mcp 377.
+- docs env, files, cli and settings example `--check` clean (COMMANDS.md regenerated for `add-spelling`).
+- e2e umtool (single specs, foreground/detached under the lock): by-hand.spec.ts 3/3 (11.9 s); final run
+ by-hand.spec.ts + article-iterations.spec.ts 7/7 (41.4 s). Earlier runs: 1 passed 1 failed (the respell
+ fixture's word occurred in the title and claim too — the spec now respells a word only the quote holds), then 2/2.
+
+## Not done
+
+- No e2e for "Add spelling" (the editor stub runs report-schedule without a corpus to count in: `add-spelling`
+ answers "not wired" there); covered by unit tests over the corpus fakes.
+- The flips/threads hand editors are form editors only (no preview of the panel).
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -476,7 +476,8 @@ const ACTIONS = [
// report-tick job. R6: a watch (no article until a triage finds something),
// and triageFirst. R6.1: reset-triage discards a schedule's triage state.
// R6.3: learn (the proposal pass), unlearn and promote-alias (a learned
- // spelling as a search alias, plan then confirm).
+ // spelling as a search alias, plan then confirm). Release 32: add-spelling
+ // (a spelling added by hand, counted in scope by code).
"report-schedule",
// THE AUDIO AUDIT (release 31): every audio file a channel (or a platform's
// channels) holds decoded with error tolerance, one at a time at idle
@@ -1536,7 +1537,8 @@ export function usage() {
"",
'report-schedule keeps a recurring report on a cadence the editor ticks:',
' {"action": "list" | "create" | "update" | "pause" | "resume" | "delete" |',
- ' "tick-now" | "reset-triage" | "learn" | "unlearn" | "promote-alias", …}.',
+ ' "tick-now" | "reset-triage" | "learn" | "unlearn" | "promote-alias" |',
+ ' "add-spelling", …}.',
' create takes {"shape": "living" | "series", "topic",',
' "question"?, "channels", "case"?, "from"?, "terms"?, "regex"?, "cadence"',
' ({"kind": "daily" | "weekly" | "every", "at": "HH:MM", "dow"?, "days"?}',
@@ -1575,7 +1577,10 @@ export function usage() {
' spelling (never learned again). promote-alias {"id", "spelling", "site"?,',
' "confirm"?} writes it as a search alias (global, or the site\'s), a new',
" alias or a trigger on the one for that name: the plan unless confirm is",
- " true.",
+ ' true. add-spelling {"id", "spelling", "means"} adds a spelling by hand',
+ ' (no model): "means" is one of the names the terms watch; it is counted in',
+ " scope and its proving line found by code, and kept (source hand) only",
+ " when it occurs; a removed spelling added by hand is no longer blocked.",
"",
"Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,",
" ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").",
diff --git a/umtool/app/api/articles/by-hand/route.ts b/umtool/app/api/articles/by-hand/route.ts
@@ -0,0 +1,142 @@
+import {
+ addClaimByHand,
+ defaultHandBase,
+ HandEditError,
+ parseMoment,
+ readArticleReport,
+ startBlankArticle,
+ type HandClaimInput,
+} from "yt-dlp-transcript-common/controller/handEdits";
+import { cuesAround } from "yt-dlp-transcript-common/publish/citedCues";
+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 (common publish/citedCues.ts) (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: [] };
+ let r: Report;
+ if (at === null) {
+ // An article older than iterations: its own report.json.
+ const own = await readArticleReport(article, paths).catch(() => null);
+ if (!own) return empty;
+ r = own;
+ } else {
+ const text = await readIterationFile(article, at, "report.json", paths);
+ if (text === null) return empty;
+ 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/app/api/projects/new/route.ts b/umtool/app/api/projects/new/route.ts
@@ -1,5 +1,6 @@
import { invalidateProjects } from "@/lib/projects";
import { ScaffoldError, scaffoldProject } from "@/lib/projects/scaffold";
+import { seedsFor } from "@/lib/projects/scaffold.mjs";
export const dynamic = "force-dynamic";
@@ -23,3 +24,10 @@ export async function POST(request: Request) {
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
}
}
+
+// GET ?from=<ref> -> { video, chapters, frames }: what the form may seed a
+// video ref from (release 32 R2) -- its digest's chapters, its frame scan.
+export async function GET(request: Request) {
+ const from = new URL(request.url).searchParams.get("from");
+ return Response.json(await seedsFor({ from }), { headers: { "cache-control": "no-store" } });
+}
diff --git a/umtool/app/api/report/hand-fill/route.ts b/umtool/app/api/report/hand-fill/route.ts
@@ -0,0 +1,50 @@
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { invalidateProjects } from "@/lib/projects";
+import { withEditNotes } from "@/lib/report/guard";
+import { MANIFEST_NAME, StaleToken, manifestToken } from "@/lib/report/manifest.mjs";
+import { applyHandFill, handFillView } from "@/lib/report/hand-fill.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+
+export const dynamic = "force-dynamic";
+
+// FILL BY HAND (release 32 R2; lib/report/hand-fill.mjs): the Media tab's blanks
+// for every empty media field, written as the operator's -- no model, no mark.
+//
+// GET ?project=<id> the view: the empty fields, the clips,
+// the deck, the flips and threads as they
+// stand, and the write token
+// POST {project, token?, fills: [{field, entry?, value}]}
+// each fill through the manifest writer;
+// -> {written, refused, token}
+
+const noStore = { "cache-control": "no-store" };
+
+async function rawManifest(dir: string): Promise<unknown> {
+ return JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, MANIFEST_NAME), "utf8"));
+}
+
+export async function GET(request: Request) {
+ const r = await resolveReport(new URL(request.url).searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers: noStore });
+ return Response.json({ ...handFillView(await rawManifest(r.project.dir)), token: await manifestToken(r.project.dir) }, { headers: noStore });
+}
+
+export async function POST(request: Request) {
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body) return Response.json({ error: "expected JSON" }, { status: 400, headers: noStore });
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers: noStore });
+ try {
+ const token = typeof body.token === "string" ? body.token : null;
+ const { result, editNotes } = await withEditNotes(r.project, () => applyHandFill(r.project.dir, body.fills as unknown[], { token }));
+ if (result.written.length) invalidateProjects();
+ return Response.json(
+ { ok: !result.refused, ...result, editNotes, ...handFillView(await rawManifest(r.project.dir)), token: await manifestToken(r.project.dir) },
+ { status: result.refused && !result.written.length ? 400 : 200, headers: noStore },
+ );
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers: noStore });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400, headers: noStore });
+ }
+}
diff --git a/umtool/app/api/schedules/route.ts b/umtool/app/api/schedules/route.ts
@@ -6,18 +6,19 @@ import { readSchedules, scheduleAsk } from "@/lib/schedules";
export const dynamic = "force-dynamic";
const NO_STORE = { "cache-control": "no-store" };
-const ACTIONS = ["create", "update", "pause", "resume", "delete", "tick-now", "learn", "unlearn", "promote-alias"];
+const ACTIONS = ["create", "update", "pause", "resume", "delete", "tick-now", "learn", "unlearn", "promote-alias", "add-spelling"];
// RECURRING REPORTS (plans/umtool-redesign.md, R5).
//
// GET every schedule, read from the article store (no editor call)
// POST { action: create | update | pause | resume | delete | tick-now |
-// learn | unlearn | promote-alias, … }
+// learn | unlearn | promote-alias | add-spelling, … }
// -- the editor's `report-schedule` ops action, forwarded as sent: the
// editor keeps the schedules and is their one writer (a create with
// `dryRun: true` is its plan; a delete without `confirm: true` is its
// plan; R6.3: a learn with `dryRun: true` and a promote-alias without
-// `confirm: true` are plans). Answers the editor's JSON, or its
+// `confirm: true` are plans; release 32: add-spelling, a spelling
+// added by hand). Answers the editor's JSON, or its
// refusal in its words.
export async function GET() {
try {
diff --git a/umtool/components/NewProjectMenu.tsx b/umtool/components/NewProjectMenu.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Field, Input, Select } from "@/components/ui/field";
@@ -27,6 +27,9 @@ import { useHydrated } from "@/components/ui/use-hydrated";
// [data-new-project]; the form [data-new-project-form] with [data-new-kind],
// [data-new-slug], [data-new-title], [data-new-from], [data-new-origin],
// [data-new-seed], [data-new-brand], [data-new-create] and [data-new-error].
+// Release 32 R2: [data-new-seed] is a select (none, the digest's chapters, the
+// frame scan), each offered when the video has it (GET /api/projects/new?from=);
+// the frames seed's length budget is [data-new-target], seconds.
type Brand = { id: string; label: string };
type Kind = { id: string; label: string; scaffold?: { fields: string[]; brands?: Brand[] } | null };
@@ -35,7 +38,8 @@ type Report = { project: string; path: string; title: string };
const FIELD_HINT: Record<string, string> = {
from: "a sweep-report .md, a viewer share URL, or <channel>/<videoId>",
siteOrigin: "the archive every QR resolves to (e.g. https://jeralyzer.pages.dev)",
- seed: "seed the timeline from the video's digest chapters (review each)",
+ seed: "seed the timeline from the video's digest chapters, or from its frame scan's events (review each)",
+ target: "the frame-scan cut's length budget: the events ranked into this many seconds (10 to 3600)",
brand: "a report-to-video preset: its palette and faces, the title lockup, the header mark, an end card",
};
@@ -77,7 +81,10 @@ export default function NewProjectMenu({
const [src, setSrc] = useState(from ?? reports?.[0]?.path ?? "");
const [byHand, setByHand] = useState(!reports?.length);
const [origin, setOrigin] = useState("");
- const [seed, setSeed] = useState(false);
+ const [seed, setSeed] = useState<"" | "chapters" | "frames">("");
+ const [target, setTarget] = useState("240");
+ // What the video can be seeded from (null: not asked yet, or not a video).
+ const [seeds, setSeeds] = useState<{ chapters: boolean; frames: boolean } | null>(null);
const [brand, setBrand] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -87,6 +94,25 @@ export default function NewProjectMenu({
// Seeding only means something for a video ref, and the server refuses it
// otherwise -- so the box is offered only when the source looks like one.
const looksLikeVideo = /[?&]v=/.test(src) || /^[\w.-]+\/[\w.-]+$/.test(src.trim());
+ const asksSeed = fields.includes("seed") && looksLikeVideo;
+ useEffect(() => {
+ if (!asksSeed) return setSeeds(null);
+ let gone = false;
+ const t = setTimeout(() => {
+ fetch(`/api/projects/new?from=${encodeURIComponent(src.trim())}`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j) => {
+ if (gone || !j?.video) return;
+ setSeeds({ chapters: !!j.chapters, frames: !!j.frames });
+ setSeed((v) => (v && !j[v] ? "" : v));
+ })
+ .catch(() => {});
+ }, 250);
+ return () => {
+ gone = true;
+ clearTimeout(t);
+ };
+ }, [asksSeed, src]);
const create = async () => {
if (!slug.trim()) return;
@@ -96,7 +122,10 @@ export default function NewProjectMenu({
const body: Record<string, unknown> = { kind, slug, title };
if (fields.includes("from") && src.trim()) body.from = src.trim();
if (fields.includes("siteOrigin") && origin.trim()) body.siteOrigin = origin.trim();
- if (fields.includes("seed") && seed && looksLikeVideo) body.seed = "chapters";
+ if (fields.includes("seed") && seed && looksLikeVideo) {
+ body.seed = seed;
+ if (seed === "frames") body.target = Number(target);
+ }
if (fields.includes("brand") && brand) body.brand = brand;
const res = await fetch("/api/projects/new", {
method: "POST",
@@ -234,11 +263,31 @@ export default function NewProjectMenu({
</Select>
</Field>
)}
- {fields.includes("seed") && looksLikeVideo && (
- <label className="flex items-center gap-1.5 pb-1.5 text-[12px] text-text-2" title={FIELD_HINT.seed}>
- <input type="checkbox" checked={seed} onChange={(e) => setSeed(e.target.checked)} data-new-seed />
- Seed from the digest's chapters
- </label>
+ {asksSeed && (
+ <Field label="Seed">
+ <Select value={seed} onChange={(e) => setSeed(e.target.value as typeof seed)} aria-label={`seed — ${FIELD_HINT.seed}`} title={FIELD_HINT.seed} data-new-seed>
+ <option value="">an empty timeline</option>
+ <option value="chapters" disabled={seeds !== null && !seeds.chapters}>
+ the digest's chapters{seeds !== null && !seeds.chapters ? " (none)" : ""}
+ </option>
+ <option value="frames" disabled={seeds !== null && !seeds.frames}>
+ the frame scan's events{seeds !== null && !seeds.frames ? " (no scan)" : ""}
+ </option>
+ </Select>
+ </Field>
+ )}
+ {asksSeed && seed === "frames" && (
+ <Field label="Target s">
+ <Input
+ value={target}
+ onChange={(e) => setTarget(e.target.value)}
+ inputMode="numeric"
+ aria-label={`target seconds — ${FIELD_HINT.target}`}
+ title={FIELD_HINT.target}
+ data-new-target
+ className="num w-20"
+ />
+ </Field>
)}
<div className="flex items-center gap-2 pb-px">
<Button type="submit" variant="go" disabled={!hydrated || busy || !slug.trim()} data-new-create>
diff --git a/umtool/components/articles/ArticlePage.tsx b/umtool/components/articles/ArticlePage.tsx
@@ -65,6 +65,8 @@ import type { NotesRead } from "@/lib/annotations/types";
// ?ws=&rel= a workspace file open on the source view
// ?project=<id> another video project the article owns
// ?all=1 the cut's every quote
+// ?heard=<words> (with tab=iterations) Fix a mishearing open,
+// its heard field filled (release 32 R2)
// ?refresh=1 the Refresh plan open (R4: the suggestion
// card's action)
@@ -78,6 +80,7 @@ export type ArticleSearch = {
all?: string;
project?: string;
refresh?: string;
+ heard?: string;
};
type TabHref = (t: string, q?: { all?: boolean; project?: string }) => string;
@@ -245,7 +248,7 @@ export default async function ArticlePage({
<main className="deck-main flex-1 p-4" data-piece-tab="iterations">
<div className="mx-auto max-w-5xl space-y-4">
{store ? (
- <IterationsView article={reportId} />
+ <IterationsView article={reportId} heard={sp.heard ?? null} />
) : (
<EmptyState title="A site's report has no iterations here">Iterations are the article store's.</EmptyState>
)}
diff --git a/umtool/components/articles/HandTools.tsx b/umtool/components/articles/HandTools.tsx
@@ -0,0 +1,623 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, 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 (`?tab=iterations&heard=<words>` opens it, filled)
+// `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, initialHeard = "" }: { article: string; n: number | null; view: HandBaseView | null; onDone: () => void; initialHeard?: string }) {
+ const hydrated = useHydrated();
+ const [heard, setHeard] = useState(initialHeard);
+ 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,
+ ownReport = false,
+ heard = null,
+}: {
+ article: string;
+ bases: HandBase[];
+ initialBase: number | null;
+ /** An article older than iterations: its report.json is what both tools work on. */
+ ownReport?: boolean;
+ /** `?heard=` (the drafts review's "fix this mishearing"): Fix a mishearing opens with it filled. */
+ heard?: string | null;
+}) {
+ const router = useRouter();
+ const [n, setN] = useState<number | null>(initialBase);
+ const [open, setOpen] = useState<"respell" | "claim" | null>(heard ? "respell" : null);
+ const box = useRef<HTMLElement>(null);
+ useEffect(() => {
+ if (heard) box.current?.scrollIntoView({ block: "start" });
+ }, [heard]);
+ 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 && !ownReport) return null;
+ return (
+ <section ref={box} 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.length && <option value="">the article's report</option>}
+ {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}
+ initialHeard={heard ?? ""}
+ 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 {n !== null ? `i${n}` : "the report"}…</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,10 +1,13 @@
+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).
-export default async function IterationsView({ article }: { article: string }) {
+// 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, heard = null }: { article: string; heard?: string | null }) {
const initial = await readArticleIterations(article);
let policy: PolicyView | null = null;
try {
@@ -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} ownReport={!initial.pending && !initial.iterations.length} heard={heard} />
+ <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/components/projects/HandFill.tsx b/umtool/components/projects/HandFill.tsx
@@ -0,0 +1,370 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Field, Input, Select, Textarea } from "@/components/ui/field";
+import { useHydrated } from "@/components/ui/use-hydrated";
+import { announceManifestChanged } from "./timelineApi";
+
+// ---------------------------------------------------------------------------
+// FILL BY HAND (release 32 R2): beside Draft everything, the cut's EMPTY media
+// fields as blanks a person fills -- each clip's on-screen title, a teaser's
+// lines, the YouTube title and description, the X and Bluesky posts -- and the
+// flips or the threads (no other editor has them), so a cut reaches a buildable
+// manifest with no model. Saved through the manifest writer as the operator's
+// edit (lib/report/hand-fill.mjs): no drafted mark, "written by hand", never
+// replaced by a draft. Only what is filled is written; a blank stays empty.
+//
+// Labels are contracts: the toggle "Fill empty fields by hand", the region
+// "fill by hand", "Save what is filled"; each field's box is named for it
+// ("on-screen title of <clip>", "teaser lines of <id>", "YouTube title", …).
+// ---------------------------------------------------------------------------
+
+type EmptyField = { address: string; entry: string | null; field: string; label: string; context: string };
+type Clip = { id: string; label: string; thread: string | null };
+type Side = { entry: string; when: string; words: string };
+type Pair = { id: string; topic: string; then: Side; now: Side };
+type Thread = { id: string; label: string; outcome?: { verdict: string; label?: string } };
+export type HandFillView = {
+ empty: EmptyField[];
+ clips: Clip[];
+ deck: boolean;
+ flips: { pairs: Pair[] } | null;
+ threads: { list: Thread[]; clips: Record<string, string> } | null;
+ token: string | null;
+};
+
+const VERDICTS = ["CORROBORATED", "PARTLY", "CONTRADICTED", "NOT_FOUND", "UNTESTABLE"];
+const slug = (s: string, at: number, prefix: string) => {
+ const v = s
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 40);
+ return v || `${prefix}${at + 1}`;
+};
+const blankSide = (entry = ""): Side => ({ entry, when: "", words: "" });
+
+function FlipsEditor({ clips, pairs, setPairs }: { clips: Clip[]; pairs: Pair[]; setPairs: (p: Pair[]) => void }) {
+ const set = (i: number, p: Pair) => setPairs(pairs.map((x, j) => (j === i ? p : x)));
+ const side = (i: number, which: "then" | "now", key: keyof Side, v: string) => set(i, { ...pairs[i]!, [which]: { ...pairs[i]![which], [key]: v } });
+ return (
+ <div className="grid gap-2" data-hand-flips={pairs.length}>
+ {pairs.map((p, i) => (
+ <div key={i} className="grid gap-1.5 rounded-[3px] border border-seam-2 p-2">
+ <div className="flex flex-wrap items-end gap-2">
+ <Field label="Topic">
+ <Input aria-label={`flip ${i + 1} topic`} value={p.topic} maxLength={32} onChange={(e) => set(i, { ...p, topic: e.target.value })} className="w-48" />
+ </Field>
+ <Button type="button" size="sm" variant="quiet" onClick={() => setPairs(pairs.filter((_, j) => j !== i))}>
+ Remove pair
+ </Button>
+ </div>
+ {(["then", "now"] as const).map((w) => (
+ <div key={w} className="flex flex-wrap items-end gap-2">
+ <span className="micro w-10 pb-1.5">{w}</span>
+ <Field label="Clip">
+ <Select aria-label={`flip ${i + 1} ${w} clip`} value={p[w].entry} onChange={(e) => side(i, w, "entry", e.target.value)}>
+ <option value="">pick a clip</option>
+ {clips.map((c) => (
+ <option key={c.id} value={c.id}>
+ {c.id} — {c.label}
+ </option>
+ ))}
+ </Select>
+ </Field>
+ <Field label="When">
+ <Input aria-label={`flip ${i + 1} ${w} when`} value={p[w].when} maxLength={18} onChange={(e) => side(i, w, "when", e.target.value)} className="w-28" placeholder="2019" />
+ </Field>
+ <Field label="Words" className="min-w-0 flex-1">
+ <Input aria-label={`flip ${i + 1} ${w} words`} value={p[w].words} maxLength={110} onChange={(e) => side(i, w, "words", e.target.value)} />
+ </Field>
+ </div>
+ ))}
+ </div>
+ ))}
+ <div>
+ <Button type="button" size="sm" variant="outline" onClick={() => setPairs([...pairs, { id: "", topic: "", then: blankSide(), now: blankSide() }])}>
+ Add a pair
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function ThreadsEditor({
+ clips,
+ list,
+ setList,
+ assign,
+ setAssign,
+}: {
+ clips: Clip[];
+ list: Thread[];
+ setList: (l: Thread[]) => void;
+ assign: Record<string, string>;
+ setAssign: (a: Record<string, string>) => void;
+}) {
+ return (
+ <div className="grid gap-2" data-hand-threads={list.length}>
+ {list.map((t, i) => (
+ <div key={i} className="flex flex-wrap items-end gap-2">
+ <Field label="Thread">
+ <Input aria-label={`thread ${i + 1} label`} value={t.label} maxLength={32} onChange={(e) => setList(list.map((x, j) => (j === i ? { ...x, label: e.target.value } : x)))} className="w-56" />
+ </Field>
+ <Field label="Outcome">
+ <Select
+ aria-label={`thread ${i + 1} outcome`}
+ value={t.outcome?.verdict ?? ""}
+ onChange={(e) => setList(list.map((x, j) => (j === i ? { ...x, outcome: e.target.value ? { ...(x.outcome ?? {}), verdict: e.target.value } : undefined } : x)))}
+ >
+ <option value="">none</option>
+ {VERDICTS.map((v) => (
+ <option key={v} value={v}>
+ {v.toLowerCase().replace("_", " ")}
+ </option>
+ ))}
+ </Select>
+ </Field>
+ <Button type="button" size="sm" variant="quiet" onClick={() => setList(list.filter((_, j) => j !== i))}>
+ Remove thread
+ </Button>
+ </div>
+ ))}
+ <div>
+ <Button type="button" size="sm" variant="outline" onClick={() => setList([...list, { id: "", label: "" }])}>
+ Add a thread
+ </Button>
+ </div>
+ {list.length > 0 && (
+ <div className="grid gap-0.5">
+ <span className="micro">each clip's thread</span>
+ {clips.map((c) => (
+ <label key={c.id} className="flex min-w-0 items-center gap-2 text-[12px]">
+ <span className="w-16 shrink-0 font-mono text-[11px] text-muted">{c.id}</span>
+ <select
+ aria-label={`thread of ${c.id}`}
+ value={assign[c.id] ?? ""}
+ onChange={(e) => {
+ const next = { ...assign };
+ if (e.target.value) next[c.id] = e.target.value;
+ else delete next[c.id];
+ setAssign(next);
+ }}
+ className="rounded-[3px] border border-seam-2 bg-panel px-1.5 py-0.5 text-[12px]"
+ >
+ <option value="">none</option>
+ {list.map((t, i) => (
+ <option key={i} value={t.id || slug(t.label, i, "t")}>
+ {t.label || `thread ${i + 1}`}
+ </option>
+ ))}
+ </select>
+ <span className="truncate text-text-2">{c.label}</span>
+ </label>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default function HandFill({ project, initial }: { project: string; initial: HandFillView }) {
+ const router = useRouter();
+ const hydrated = useHydrated();
+ const [view, setView] = useState(initial);
+ const [open, setOpen] = useState(false);
+ const [text, setText] = useState<Record<string, string>>({});
+ const [pairs, setPairs] = useState<Pair[]>(initial.flips?.pairs ?? []);
+ const [list, setList] = useState<Thread[]>(initial.threads?.list ?? []);
+ const [assign, setAssign] = useState<Record<string, string>>(initial.threads?.clips ?? {});
+ const [panelDirty, setPanelDirty] = useState<"flips" | "threads" | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [status, setStatus] = useState<{ ok: boolean; text: string; errors: string[] } | null>(null);
+ const val = (k: string) => text[k] ?? "";
+ const put = (k: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => setText({ ...text, [k]: e.target.value });
+ // A cut has flips or threads, never both: the one it has, else either.
+ const panel: "flips" | "threads" | "either" = view.flips ? "flips" : view.threads ? "threads" : "either";
+ const empties = view.empty.length;
+
+ const fills = () => {
+ const out: { field: string; entry?: string; value: unknown }[] = [];
+ for (const f of view.empty) {
+ if (f.field === "onscreen") {
+ const title = val(`${f.address}:title`).trim();
+ const subtitle = val(`${f.address}:subtitle`).trim();
+ if (title || subtitle) out.push({ field: "onscreen", entry: f.entry!, value: { ...(title ? { title } : {}), ...(subtitle ? { subtitle } : {}) } });
+ } else if (f.field === "lines") {
+ const lines = val(f.address).split("\n").map((l) => l.trim()).filter(Boolean);
+ if (lines.length) out.push({ field: "lines", entry: f.entry!, value: lines });
+ } else if (f.field === "publish.youtube") {
+ const title = val("youtube:title").trim();
+ const description = val("youtube:description").trim();
+ if (title || description) out.push({ field: f.field, value: { title, description } });
+ } else if (f.field === "publish.x" || f.field === "publish.bluesky") {
+ const post = val(f.field).trim();
+ if (post) out.push({ field: f.field, value: { post } });
+ }
+ }
+ if (panelDirty === "flips" && pairs.length) {
+ out.push({
+ field: "render.chrome.flips",
+ value: { pairs: pairs.map((p, i) => ({ id: p.id || slug(p.topic, i, "p"), topic: p.topic.trim(), then: { ...p.then, when: p.then.when.trim(), words: p.then.words.trim() }, now: { ...p.now, when: p.now.when.trim(), words: p.now.words.trim() } })) },
+ });
+ }
+ if (panelDirty === "threads" && list.length) {
+ out.push({
+ field: "render.chrome.threads",
+ value: { list: list.map((t, i) => ({ id: t.id || slug(t.label, i, "t"), label: t.label.trim(), ...(t.outcome?.verdict ? { outcome: t.outcome } : {}) })), clips: assign },
+ });
+ }
+ return out;
+ };
+
+ const save = async () => {
+ const f = fills();
+ if (!f.length) return setStatus({ ok: false, text: "nothing filled yet", errors: [] });
+ setBusy(true);
+ setStatus(null);
+ try {
+ const r = await fetch("/api/report/hand-fill", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, token: view.token, fills: f }), cache: "no-store" });
+ const b = (await r.json().catch(() => ({}))) as Partial<HandFillView> & { written?: string[]; refused?: { field: string; error: string; errors: string[] } | null; error?: string };
+ if (b.written?.length) {
+ announceManifestChanged(project);
+ router.refresh();
+ }
+ if (b.empty) {
+ setView(b as HandFillView);
+ setText({});
+ setPanelDirty(null);
+ }
+ if (!r.ok && !b.refused) throw new Error(b.error ?? `HTTP ${r.status}`);
+ setStatus(
+ b.refused
+ ? { ok: false, text: `${b.written?.length ? `wrote ${b.written.join(", ")}; ` : ""}${b.refused.field} was refused: ${b.refused.error}`, errors: b.refused.errors }
+ : { ok: true, text: `written by hand: ${(b.written ?? []).join(", ")}`, errors: [] },
+ );
+ } catch (e) {
+ setStatus({ ok: false, text: (e as Error).message, errors: [] });
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const onscreen = view.empty.filter((f) => f.field === "onscreen");
+ const teasers = view.empty.filter((f) => f.field === "lines");
+ const has = (field: string) => view.empty.some((f) => f.field === field);
+
+ return (
+ <section aria-label="fill by hand" data-hand-fill={empties} 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 ? "pressed" : "outline"} aria-expanded={open} disabled={!hydrated} onClick={() => setOpen(!open)} data-hand-fill-toggle="">
+ Fill empty fields by hand
+ </Button>
+ <span className="font-mono text-[11.5px] text-muted-2">
+ {empties} empty field{empties === 1 ? "" : "s"}
+ </span>
+ </div>
+ {open && (
+ <form
+ className="mt-3 grid gap-4"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void save();
+ }}
+ >
+ {onscreen.length > 0 && (
+ <fieldset className="grid gap-1.5" aria-label="on-screen titles">
+ <legend className="micro mb-1">on-screen titles</legend>
+ {onscreen.map((f) => (
+ <div key={f.address} className="flex min-w-0 flex-wrap items-center gap-2" data-hand-field={f.address}>
+ <span className="w-16 shrink-0 font-mono text-[11px] text-muted">{f.entry}</span>
+ <Input aria-label={`on-screen title of ${f.entry}`} placeholder="title" value={val(`${f.address}:title`)} onChange={put(`${f.address}:title`)} className="w-60" />
+ <Input aria-label={`on-screen subtitle of ${f.entry}`} placeholder="subtitle (optional)" value={val(`${f.address}:subtitle`)} onChange={put(`${f.address}:subtitle`)} className="w-60" />
+ {f.context && <span className="min-w-0 flex-1 truncate font-serif text-[12px] text-text-2">“{f.context}”</span>}
+ </div>
+ ))}
+ </fieldset>
+ )}
+ {teasers.map((f) => (
+ <Field key={f.address} label={`Teaser ${f.entry}: its lines, one a row`}>
+ <Textarea aria-label={`teaser lines of ${f.entry}`} rows={3} value={val(f.address)} onChange={put(f.address)} />
+ </Field>
+ ))}
+ {has("publish.youtube") && (
+ <fieldset className="grid gap-1.5" aria-label="YouTube">
+ <legend className="micro mb-1">youtube</legend>
+ <Input aria-label="YouTube title" placeholder="title (at most 100)" maxLength={100} value={val("youtube:title")} onChange={put("youtube:title")} />
+ <Textarea aria-label="YouTube description" rows={3} placeholder="description" value={val("youtube:description")} onChange={put("youtube:description")} />
+ </fieldset>
+ )}
+ {(has("publish.x") || has("publish.bluesky")) && (
+ <fieldset className="grid gap-1.5 md:grid-cols-2" aria-label="social posts">
+ <legend className="micro mb-1">social posts</legend>
+ {has("publish.x") && <Textarea aria-label="X post" rows={3} placeholder="X post" value={val("publish.x")} onChange={put("publish.x")} />}
+ {has("publish.bluesky") && <Textarea aria-label="Bluesky post" rows={3} placeholder="Bluesky post" value={val("publish.bluesky")} onChange={put("publish.bluesky")} />}
+ </fieldset>
+ )}
+ {view.deck ? (
+ <>
+ {panel !== "threads" && (
+ <fieldset className="grid gap-1.5" aria-label="flips" onChange={() => setPanelDirty("flips")}>
+ <legend className="micro mb-1">flips{view.flips ? " (as they stand)" : ""}</legend>
+ <FlipsEditor
+ clips={view.clips}
+ pairs={pairs}
+ setPairs={(p) => {
+ setPairs(p);
+ setPanelDirty("flips");
+ }}
+ />
+ </fieldset>
+ )}
+ {panel !== "flips" && (
+ <fieldset className="grid gap-1.5" aria-label="threads" onChange={() => setPanelDirty("threads")}>
+ <legend className="micro mb-1">threads{view.threads ? " (as they stand)" : ""}</legend>
+ <ThreadsEditor
+ clips={view.clips}
+ list={list}
+ setList={(l) => {
+ setList(l);
+ setPanelDirty("threads");
+ }}
+ assign={assign}
+ setAssign={(a) => {
+ setAssign(a);
+ setPanelDirty("threads");
+ }}
+ />
+ </fieldset>
+ )}
+ {panel === "either" && <p className="m-0 text-[12px] text-muted">a cut has flips or threads, not both: the one you edit last is saved</p>}
+ </>
+ ) : (
+ <p className="m-0 text-[12px] text-muted">Flips and threads are drawn by the on-screen deck: turn it on under On-screen to write them.</p>
+ )}
+ <div className="flex items-center gap-2">
+ <Button type="submit" variant="go" disabled={!hydrated || busy}>
+ {busy ? "Saving…" : "Save what is filled"}
+ </Button>
+ <span className="text-[12px] text-muted">saved as yours: no draft replaces it</span>
+ </div>
+ {status && (
+ <div role={status.ok ? "status" : "alert"} data-hand-fill-status={status.ok ? "ok" : "refused"} className={`text-[12px] ${status.ok ? "text-text-2" : "text-reject-text"}`}>
+ {status.text}
+ {status.errors.length > 0 && (
+ <ul className="m-0 mt-0.5 list-disc pl-5">
+ {status.errors.map((x, i) => (
+ <li key={i}>{x}</li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ </form>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/report/MediaTab.tsx b/umtool/components/projects/report/MediaTab.tsx
@@ -7,6 +7,8 @@ import MediaDrafts, { type FieldProvenance } from "../MediaDrafts";
import OnscreenSection from "../OnscreenSection";
import YoutubeSection from "../YoutubeSection";
import SocialPostSection from "../SocialPostSection";
+import HandFill, { type HandFillView } from "../HandFill";
+import { handFillView } from "@/lib/report/hand-fill.mjs";
import type { DraftsView } from "../drafts";
import type { ReportTabProps } from "./shared";
@@ -17,7 +19,9 @@ import type { ReportTabProps } from "./shared";
// (moved out of Build), the upload's text and the promotion posts. Release 28's review page,
// Draft panel and the Iterations tab's media drafts are this now; the
// narration's words are edited and played on its bench (…/narration), the
-// fields walked one at a time on the review bench (…/review).
+// fields walked one at a time on the review bench (…/review). Under the drafts,
+// Fill by hand (release 32 R2): the empty fields as blanks a person fills, no
+// model (components/projects/HandFill.tsx).
export default async function MediaTab({ project, detail }: ReportTabProps) {
const { manifest: m, build, entries } = detail;
@@ -40,6 +44,8 @@ export default async function MediaTab({ project, detail }: ReportTabProps) {
narrated={narrationsOf(m).length}
/>
+ <HandFill project={project.id} initial={{ ...(handFillView(m) as Omit<HandFillView, "token">), token }} />
+
{/* --- what is drawn over it --------------------------------------- */}
{/* The on-screen panel: its settings, its words and a live preview of
both, whole (P4a-1 parked it on Build; its words are media). "Re-render
diff --git a/umtool/components/series/LearnedSpellings.tsx b/umtool/components/series/LearnedSpellings.tsx
@@ -26,11 +26,16 @@ import { cn } from "@/lib/utils";
// alias as it would be written, then Confirm
// promote (`report-schedule promote-alias`)
// "Propose spellings" runs the proposal pass now (`report-schedule learn`).
+// "Add spelling" (release 32 R2) is the same by hand, with no model: the
+// spelling and the watched name it means; the editor counts it in scope and
+// finds its proving line by code (`report-schedule add-spelling`), and keeps it
+// as "added by hand" only when it occurs.
// Every write is the editor's, through POST /api/schedules; the page re-reads.
//
// Labels are contracts (e2e/learned-spellings.spec.ts): the list "Learned
// spellings", the buttons "Remove", "Confirm remove", "Promote to search
-// alias", "Confirm promote", "Keep it", "Propose spellings", the regions
+// alias", "Confirm promote", "Keep it", "Propose spellings", "Add spelling"
+// (its fields "spelling to add" and "the name it means"), the regions
// "remove <spelling>" and "promote <spelling>", the select "Alias list".
// ---------------------------------------------------------------------------
@@ -73,6 +78,9 @@ export default function LearnedSpellings({ view }: { view: LearnedView }) {
const [removing, setRemoving] = useState(false);
const [plan, setPlan] = useState<PromotePlanView | null>(null);
const [target, setTarget] = useState("global");
+ const [adding, setAdding] = useState(false);
+ const [newSpelling, setNewSpelling] = useState("");
+ const [means, setMeans] = useState(view.names[0] ?? "");
const lit: LearnedRow | null = view.rows.find((r) => r.spelling === litId) ?? view.rows[0] ?? null;
const onLight = useCallback((d: LitDetail) => {
setLitId(d.id);
@@ -136,6 +144,7 @@ export default function LearnedSpellings({ view }: { view: LearnedView }) {
<span className="font-mono text-meter">{r.hits}</span> recording{r.hits === 1 ? "" : "s"}
{r.partial ? " at least" : ""} · {r.source}
{r.source === "heard" && r.k ? ` (triage ${r.k})` : ""}
+ {r.source === "hand" ? " (by hand)" : ""}
</small>
</span>
<span className="flex items-center gap-1">
@@ -164,7 +173,7 @@ export default function LearnedSpellings({ view }: { view: LearnedView }) {
<p className="m-0 text-[12px] text-muted">
“{lit.spelling}” means {lit.means} · in <span className="font-mono text-meter">{lit.hits}</span> recording{lit.hits === 1 ? "" : "s"}
{lit.lines ? ` (${lit.lines} line${lit.lines === 1 ? "" : "s"})` : ""}
- {lit.partial ? ", at least" : ""} · {lit.source === "heard" ? `heard by the judge${lit.k ? ` in triage ${lit.k}` : ""}` : "proposed by the model"} · learned {day(lit.at)}
+ {lit.partial ? ", at least" : ""} · {lit.source === "heard" ? `heard by the judge${lit.k ? ` in triage ${lit.k}` : ""}` : lit.source === "hand" ? "added by hand" : "proposed by the model"} · learned {day(lit.at)}
{lit.uses?.length ? ` · last ${lit.uses.length} run${lit.uses.length === 1 ? "" : "s"}: ${lit.uses.map((u) => `${u.flagged}/${u.candidates}`).join(", ")} flagged` : ""}
{lit.idle ? " · idle: its name is no longer in the terms" : ""}
{lit.promoted ? ` · promoted to ${lit.promoted.to === "global" ? "the global aliases" : `${lit.promoted.to}'s aliases`} (${lit.promoted.alias})` : ""}
@@ -327,6 +336,9 @@ export default function LearnedSpellings({ view }: { view: LearnedView }) {
>
{busy === "learn" ? "Proposing…" : "Propose spellings"}
</Button>
+ <Button size="sm" variant={adding ? "pressed" : "outline"} aria-expanded={adding} disabled={!hydrated || !view.names.length} data-learned-add="" onClick={() => setAdding(!adding)}>
+ Add spelling
+ </Button>
<span>
{view.rows.length} of {view.cap} kept
{view.blocked.length ? ` · ${view.blocked.length} removed` : ""}
@@ -340,6 +352,50 @@ export default function LearnedSpellings({ view }: { view: LearnedView }) {
</span>
)}
</div>
+ {adding && (
+ <form
+ aria-label="add a spelling"
+ data-learned-add-form=""
+ className="flex flex-wrap items-end gap-2 rounded-[3px] border border-seam-2 p-3 text-[12px]"
+ onSubmit={(e) => {
+ e.preventDefault();
+ const sp = newSpelling.trim();
+ if (!sp || !means) return;
+ void act("add", { action: "add-spelling", spelling: sp, means }, (b) => {
+ const a = b.added as { spelling?: string; hits?: number; partial?: boolean } | undefined;
+ setAdding(false);
+ setNewSpelling("");
+ setLitId(a?.spelling ?? sp);
+ setStatus({ tone: "ok", text: `Added “${a?.spelling ?? sp}” → ${means}: in ${a?.hits ?? 0}${a?.partial ? " or more" : ""} recording${a?.hits === 1 ? "" : "s"}${b.unblocked ? " (no longer removed)" : ""}` });
+ router.refresh();
+ });
+ }}
+ >
+ <label className="flex flex-col gap-1">
+ <span className="text-muted">How the transcripts write it</span>
+ <input
+ aria-label="spelling to add"
+ value={newSpelling}
+ onChange={(e) => setNewSpelling(e.target.value)}
+ className="w-56 rounded-[3px] border border-seam-2 bg-panel px-2 py-1 text-[12.5px]"
+ />
+ </label>
+ <label className="flex flex-col gap-1">
+ <span className="text-muted">The name it means</span>
+ <select aria-label="the name it means" value={means} onChange={(e) => setMeans(e.target.value)} className="rounded-[3px] border border-seam-2 bg-panel px-2 py-1 text-[12.5px]">
+ {view.names.map((n) => (
+ <option key={n} value={n}>
+ {n}
+ </option>
+ ))}
+ </select>
+ </label>
+ <Button type="submit" size="sm" variant="outline" disabled={busy !== null || !newSpelling.trim() || !means}>
+ {busy === "add" ? "Counting…" : "Count and add"}
+ </Button>
+ <span className="basis-full text-muted">counted in the watch's scope; kept only when it occurs there</span>
+ </form>
+ )}
{view.dropped.length > 0 && (
<details className="text-[12px]" data-learned-dropped="">
<summary className="cursor-pointer text-muted">Dropped, newest first ({view.dropped.length})</summary>
diff --git a/umtool/e2e/by-hand.spec.ts b/umtool/e2e/by-hand.spec.ts
@@ -0,0 +1,222 @@
+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.
+//
+// hand-fill-e2e a report-video project made here (an empty timeline): Fill
+// empty fields by hand on its Media tab writes the YouTube text
+// and an X post as the operator's, no drafted mark
+//
+// WRITES articles/hand-respell/, articles/hand-blank/, channels/hand-chan/,
+// hand-fill-e2e/ (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 FILL = "hand-fill-e2e";
+
+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 });
+ rmSync(path.join(FIXTURE, FILL), { 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 }) => {
+ // The drafts review's "fix this mishearing" link: ?heard= opens the form, filled.
+ await page.goto(`${urls.articleHref({ site: "articles", id: RESPELL }, { tab: "iterations" })}&heard=everybody`);
+ const tools = page.getByRole("region", { name: "by hand" });
+ await expect(tools.getByRole("combobox", { name: "iteration to work on" })).toHaveValue("1");
+ const form = tools.getByRole("region", { name: "fix a mishearing" });
+ await expect(form.getByRole("textbox", { name: "heard forms" })).toHaveValue("everybody");
+ await form.getByRole("textbox", { name: "reads as" }).fill("everyone");
+ 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("everyone");
+ // 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 vote was rigged and everyone knew.");
+ expect(doc.respellings).toEqual([{ heard: ["everybody"], reads: "everyone", note: "a synthetic note" }]);
+ }
+ // The report's respellings are listed with their heard forms.
+ await expect(form.getByRole("list", { name: "respellings" })).toContainText("“everybody” → everyone");
+});
+
+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");
+});
+
+test("Fill empty fields by hand on the Media tab: the YouTube text and an X post, written as yours (no drafted mark)", async ({ page, request }) => {
+ rmSync(path.join(FIXTURE, FILL), { recursive: true, force: true });
+ const made = await request.post("/api/projects/new", { data: { kind: "report-video", slug: FILL, title: "Hand fill" } });
+ expect(made.status()).toBe(200);
+ const id = (await made.json()).id as string;
+ await page.goto(urls.projectHref(id, { tab: "media" }));
+ const fill = page.getByRole("region", { name: "fill by hand" });
+ await expect(fill).toHaveAttribute("data-hand-fill", "3");
+ await fill.getByRole("button", { name: "Fill empty fields by hand" }).click();
+ // No deck: the flips and threads say where they come from.
+ await expect(fill).toContainText("drawn by the on-screen deck");
+ await fill.getByRole("textbox", { name: "YouTube title" }).fill("A Synthetic Title");
+ await fill.getByRole("textbox", { name: "YouTube description" }).fill("A synthetic description.");
+ await fill.getByRole("textbox", { name: "X post" }).fill("A synthetic post.");
+ await fill.getByRole("button", { name: "Save what is filled" }).click();
+ await expect(fill.locator("[data-hand-fill-status='ok']")).toContainText("written by hand: publish.youtube, publish.x");
+ await expect(fill).toHaveAttribute("data-hand-fill", "1");
+ const m = json(path.join(FIXTURE, FILL, "video.manifest.json"));
+ expect(m.publish).toEqual({ youtube: { title: "A Synthetic Title", description: "A synthetic description." }, x: { post: "A synthetic post." } });
+ expect(m.drafted ?? {}).toEqual({});
+});
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",
diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs
@@ -172,6 +172,25 @@ export async function chaptersAsClips({ channelsDir, channel, video }) {
}
/**
+ * What a video ref can be seeded from (release 32 R2: the new-project form
+ * offers only these): its digest's chapters (ai-digest.json) and its frame
+ * scan (frame-scan.poker.json, the profile framesAsClips reads). `video` false:
+ * `from` is not a video ref.
+ *
+ * @param {{ channelsDir?: string, from: string | null }} args
+ * @returns {Promise<{ video: boolean, chapters: boolean, frames: boolean }>}
+ */
+export async function seedsFor({ channelsDir = GLOBAL_CHANNELS_DIR(), from }) {
+ const src = detectFrom(from);
+ if (src?.kind !== "video") return { video: false, chapters: false, frames: false };
+ const dir = path.join(channelsDir, src.channel, "data", src.video);
+ if (path.relative(channelsDir, dir).startsWith("..")) return { video: false, chapters: false, frames: false };
+ const has = (name) => stat(path.join(dir, name)).then((x) => x.isFile(), () => false);
+ const [chapters, frames] = await Promise.all([has("ai-digest.json"), has("frame-scan.poker.json")]);
+ return { video: true, chapters, frames };
+}
+
+/**
* A frame scan's events, as a draft supercut (release 30): the video's
* `frame-scan.<profile>.json` (`pnpm ops frame-scan`) through framesCut —
* a clip around each event, cut on the cues' sentence edges — and the scan's
diff --git a/umtool/lib/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts
@@ -14,6 +14,8 @@ export type NewProjectBody = {
from?: string | null;
siteOrigin?: string | null;
seed?: string | null;
+ // The frames seed's length budget, seconds (release 32: the form's "target").
+ target?: number | string | null;
brand?: string | null;
};
@@ -41,6 +43,7 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str
siteOrigin: body.siteOrigin || null,
seed: body.seed || null,
brand: body.brand || null,
+ ...(body.seed === "frames" && body.target !== undefined && body.target !== null && body.target !== "" ? { target: Number(body.target) } : {}),
});
result = { ...r, href: `/projects/${r.id}` };
} catch (e) {
diff --git a/umtool/lib/report/hand-fill.mjs b/umtool/lib/report/hand-fill.mjs
@@ -0,0 +1,120 @@
+// FILL BY HAND (release 32 R2): beside Draft everything on the Media tab, every
+// media field the cut leaves EMPTY offered as a blank a person fills -- the
+// clips' on-screen titles, the teasers' lines, the flips or the threads, the
+// YouTube title and description, the X and Bluesky posts -- so a run with no
+// compute at all reaches a buildable manifest.
+//
+// What a person writes goes through the manifest writer as the operator's edit
+// (manifest.mjs writeDraftedField: the field's own validators, a snapshot, the
+// write token) and carries NO drafted mark: by the drafted-fields contract
+// (common/lib/report/drafted.mjs) a non-empty field with no mark is the
+// operator's -- "written by hand" -- and no draft ever replaces it. A blank is
+// a form field, never a placeholder written into the manifest: an empty value
+// is nobody's (a draft may fill it), and a placeholder would ship in a build.
+//
+// The flips and the threads have no other hand editor, so they are offered
+// whole (their pairs or list as they stand) whenever the deck draws them.
+//
+// Plain ESM: `node --test` runs it.
+import { isEmptyField } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
+import { FIELD_LABELS } from "umtool-report-to-video/drafts-review";
+import { writeDraftedField } from "./manifest.mjs";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** The fields Fill by hand writes, in the order it saves them. */
+export const HAND_FIELDS = Object.freeze(["onscreen", "lines", "render.chrome.flips", "render.chrome.threads", "publish.youtube", "publish.x", "publish.bluesky"]);
+
+const firstOf = (timeline, type) => {
+ const seen = new Set();
+ return timeline.filter((e) => isObj(e) && e.type === type && typeof e.id === "string" && !seen.has(e.id) && seen.add(e.id));
+};
+
+const readPath = (m, field) => field.split(".").reduce((o, k) => (isObj(o) ? o[k] : undefined), m);
+
+/**
+ * What Fill by hand offers for a manifest:
+ * empty every empty field: { address, entry, field, label, context }
+ * clips the cut's clips (id, a label), for the flips' and threads' selects
+ * deck whether the on-screen deck is on (the flips and threads need it)
+ * flips the flips as they stand, else null; threads likewise, with each
+ * clip's thread (`clips`)
+ *
+ * @param {any} manifest
+ */
+export function handFillView(manifest) {
+ const m = isObj(manifest) ? manifest : {};
+ const timeline = Array.isArray(m.timeline) ? m.timeline : [];
+ const empty = [];
+ for (const e of firstOf(timeline, "clip")) {
+ if (!isEmptyField("onscreen", e.onscreen)) continue;
+ empty.push({
+ address: `onscreen/${e.id}`,
+ entry: e.id,
+ field: "onscreen",
+ label: FIELD_LABELS.onscreen,
+ context: [typeof e.quote === "string" ? e.quote : "", typeof e.chapter === "string" ? e.chapter : ""].filter(Boolean).join(" · "),
+ });
+ }
+ for (const e of firstOf(timeline, "teaser")) {
+ if (!isEmptyField("lines", e.lines)) continue;
+ empty.push({ address: `teaser/${e.id}/lines`, entry: e.id, field: "lines", label: FIELD_LABELS.lines, context: "" });
+ }
+ const chrome = isObj(m.render?.chrome) ? m.render.chrome : null;
+ const flips = chrome && !isEmptyField("render.chrome.flips", chrome.flips) ? chrome.flips : null;
+ const threadsList = chrome && !isEmptyField("render.chrome.threads", chrome.threads) ? chrome.threads.list : null;
+ for (const field of ["publish.youtube", "publish.x", "publish.bluesky"]) {
+ if (isEmptyField(field, readPath(m, field))) empty.push({ address: field, entry: null, field, label: FIELD_LABELS[field] ?? field, context: "" });
+ }
+ const clips = firstOf(timeline, "clip").map((e) => ({
+ id: e.id,
+ label: [e.onscreen?.title, typeof e.quote === "string" ? e.quote.slice(0, 60) : ""].find((x) => typeof x === "string" && x.trim()) ?? e.id,
+ thread: typeof e.thread === "string" && e.thread ? e.thread : null,
+ }));
+ return {
+ empty,
+ clips,
+ deck: !!chrome,
+ flips: flips ? { pairs: flips.pairs } : null,
+ threads: threadsList ? { list: threadsList, clips: Object.fromEntries(clips.filter((c) => c.thread).map((c) => [c.id, c.thread])) } : null,
+ };
+}
+
+/** A fill as the form sends it, checked for shape (the writer checks the rest). */
+function cleanFill(f, i) {
+ if (!isObj(f)) throw new Error(`fill ${i + 1} is an object`);
+ const field = String(f.field ?? "");
+ if (!HAND_FIELDS.includes(field)) throw new Error(`fill ${i + 1}: ${field || "(no field)"} is not a field filled by hand`);
+ const onEntry = field === "onscreen" || field === "lines";
+ const entry = onEntry ? String(f.entry ?? "") : null;
+ if (onEntry && !entry) throw new Error(`fill ${i + 1}: ${field} names its entry`);
+ return { entry, field, value: f.value };
+}
+
+/**
+ * Write the fills, one field at a time through writeDraftedField (each its own
+ * checked, snapshotted write; the token carried from one to the next). Stops at
+ * the first refusal: what was written before it stays, and is said.
+ *
+ * @param {string} dir
+ * @param {unknown[]} fills
+ * @param {{ token?: string | null }} [opts]
+ * @returns {Promise<{ written: string[], token: string | null, refused: { field: string, entry: string | null, error: string, errors: string[] } | null }>}
+ */
+export async function applyHandFill(dir, fills, { token = null } = {}) {
+ if (!Array.isArray(fills) || !fills.length) throw new Error("nothing to write: fill a field first");
+ const clean = fills.map(cleanFill).sort((a, b) => HAND_FIELDS.indexOf(a.field) - HAND_FIELDS.indexOf(b.field));
+ const written = [];
+ let t = token;
+ for (const f of clean) {
+ try {
+ const w = await writeDraftedField(dir, { entry: f.entry, field: f.field, value: f.value }, { token: t });
+ t = w.token ?? null;
+ written.push(f.entry ? `${f.field}/${f.entry}` : f.field);
+ } catch (e) {
+ if (e?.name === "StaleToken") throw e;
+ return { written, token: t, refused: { field: f.field, entry: f.entry, error: e instanceof Error ? e.message : String(e), errors: Array.isArray(e?.errors) ? e.errors : [] } };
+ }
+ }
+ return { written, token: t, refused: null };
+}
diff --git a/umtool/lib/report/hand-fill.test.mjs b/umtool/lib/report/hand-fill.test.mjs
@@ -0,0 +1,78 @@
+// Fill by hand (release 32 R2): every empty media field offered, and what a
+// person writes saved through the manifest writer with no drafted mark (the
+// operator's: no draft replaces it). Over the S0 kit's synthetic manifests.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { MANIFEST_NAME } from "./manifest.mjs";
+import { applyHandFill, handFillView } from "./hand-fill.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const kit = (name) => JSON.parse(readFileSync(path.join(HERE, `../../../common/testing/draft/manifests/${name}.video.manifest.json`), "utf8"));
+
+async function project(t, manifest) {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-hand-fill-"));
+ t.after(() => rm(dir, { recursive: true, force: true }));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n");
+ return { dir, read: async () => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")) };
+}
+
+test("handFillView: each empty field once — clips' on-screen text, the publish texts; the threads as they stand", () => {
+ const v = handFillView(kit("full"));
+ assert.deepEqual(
+ v.empty.map((f) => f.address),
+ ["onscreen/c02", "onscreen/c03", "onscreen/c05", "onscreen/c06", "onscreen/c07", "publish.youtube", "publish.x", "publish.bluesky"],
+ );
+ assert.equal(v.deck, true);
+ assert.equal(v.flips, null);
+ assert.deepEqual(v.threads.list.map((x) => x.id), ["bakery", "contest"]);
+ assert.equal(v.threads.clips.c04, "contest");
+ assert.equal(v.clips.length, 7);
+ // A teaser with no lines is offered; a cut with no deck says so.
+ const m = kit("full");
+ m.timeline.find((e) => e.id === "fin").lines = [];
+ delete m.render.chrome;
+ const w = handFillView(m);
+ assert.ok(w.empty.some((f) => f.address === "teaser/fin/lines"));
+ assert.deepEqual([w.deck, w.threads], [false, null]);
+});
+
+test("applyHandFill: written unmarked (the operator's), in the field order; a refusal stops and is said", async (t) => {
+ const p = await project(t, kit("full"));
+ const out = await applyHandFill(p.dir, [
+ { field: "publish.youtube", value: { title: "The bakery and the contest", description: "Synthetic description." } },
+ { field: "onscreen", entry: "c02", value: { title: "The oven" } },
+ { field: "publish.x", value: { post: "A synthetic post." } },
+ ]);
+ assert.equal(out.refused, null);
+ assert.deepEqual(out.written, ["onscreen/c02", "publish.youtube", "publish.x"]);
+ const m = await p.read();
+ assert.deepEqual(m.timeline.find((e) => e.id === "c02").onscreen, { title: "The oven" });
+ assert.equal(m.publish.youtube.title, "The bakery and the contest");
+ assert.equal(m.drafted?.["publish.youtube"], undefined);
+ assert.equal(m.timeline.find((e) => e.id === "c02").drafted?.onscreen, undefined);
+ // Now filled: no longer offered.
+ assert.deepEqual(handFillView(m).empty.map((f) => f.address).filter((a) => a.startsWith("publish")), ["publish.bluesky"]);
+
+ // Threads by hand, with each clip's thread; then a pair of flips is refused (a cut has one or the other).
+ const th = await applyHandFill(p.dir, [{ field: "render.chrome.threads", value: { list: [{ id: "all", label: "All of it" }], clips: { c01: "all", c02: "all" } } }]);
+ assert.equal(th.refused, null);
+ const m2 = await p.read();
+ assert.deepEqual(m2.timeline.filter((e) => e.thread).map((e) => [e.id, e.thread]), [["c01", "all"], ["c02", "all"]]);
+ const bad = await applyHandFill(p.dir, [
+ { field: "onscreen", entry: "c03", value: { title: "Kept" } },
+ { field: "render.chrome.flips", value: { pairs: [{ id: "p1", topic: "Ovens", then: { entry: "c01", when: "2019", words: "a" }, now: { entry: "c02", when: "2025", words: "b" } }] } },
+ ]);
+ assert.deepEqual(bad.written, ["onscreen/c03"]);
+ assert.equal(bad.refused?.field, "render.chrome.flips");
+ assert.ok(bad.refused?.error);
+ await assert.rejects(applyHandFill(p.dir, [{ field: "timeline", value: [] }]), /not a field filled by hand/);
+ await assert.rejects(applyHandFill(p.dir, []), /nothing to write/);
+});
diff --git a/umtool/lib/scaffold-frames.test.mjs b/umtool/lib/scaffold-frames.test.mjs
@@ -6,7 +6,7 @@ import assert from "node:assert/strict";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import { scaffoldReportVideo } from "./projects/scaffold.mjs";
+import { scaffoldReportVideo, seedsFor } from "./projects/scaffold.mjs";
const SCAN = {
format: "archilyzer-frame-scan",
@@ -66,3 +66,21 @@ test("--seed frames: a clip per event, the stats as subtitles, the overlay block
await rm(tmp, { recursive: true, force: true });
}
});
+
+test("seedsFor (release 32): what a video ref can be seeded from — its digest, its frame scan; not a video ref, nothing", async () => {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-seeds-"));
+ try {
+ const channelsDir = path.join(tmp, "channels");
+ const dir = path.join(channelsDir, "synth-poker", "data", "synthstream1");
+ await mkdir(dir, { recursive: true });
+ assert.deepEqual(await seedsFor({ channelsDir, from: "synth-poker/synthstream1" }), { video: true, chapters: false, frames: false });
+ await writeFile(path.join(dir, "frame-scan.poker.json"), JSON.stringify(SCAN));
+ assert.deepEqual(await seedsFor({ channelsDir, from: "synth-poker/synthstream1" }), { video: true, chapters: false, frames: true });
+ await writeFile(path.join(dir, "ai-digest.json"), "{}");
+ assert.deepEqual(await seedsFor({ channelsDir, from: "https://archive.example/?v=synth-poker%2Fsynthstream1&t=5" }), { video: true, chapters: true, frames: true });
+ assert.deepEqual(await seedsFor({ channelsDir, from: "notes.md" }), { video: false, chapters: false, frames: false });
+ assert.deepEqual(await seedsFor({ channelsDir, from: null }), { video: false, chapters: false, frames: false });
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+});