commit 2d8359b904712a23b816e360237febdabce15d65
parent d1e856745301d7ba09c3b9974d329c5772effddb
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 13 Oct 2026 21:45:34 -0400
Merge r28/framework: release 28 M0 — drafted fields, the drafts review, the media task scaffold
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
# plans/release-28.md
Diffstat:
42 files changed, 3480 insertions(+), 265 deletions(-)
diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts
@@ -15,7 +15,28 @@ export { sweepAgent, SWEEP_READ_TOOLS, type SweepAgentInput } from "./sweep-agen
export { sweepPipeline, type SweepPipelineInput } from "./sweep-pipeline";
export { reviseReport, type ReviseReportInput } from "./revise-report";
export { reviseVideo, type ReviseVideoInput } from "./revise-video";
-export { narrate, type NarrateInput } from "./narrate";
+export { narrate, NARRATE_SPEC, type NarrateInput } from "./narrate";
+// The media task scaffold (release 28, M0): what every media task is.
+export {
+ ALTERNATIVES_PER_FIELD,
+ defaultScore,
+ draftFileName,
+ isSkip,
+ loadMediaContext,
+ mergeAlternatives,
+ rankAttempts,
+ readDraftFile,
+ runMediaTask,
+ type DraftAlternative,
+ type DraftFile,
+ type MediaAttempt,
+ type MediaContext,
+ type MediaReport,
+ type MediaSkip,
+ type MediaTaskInput,
+ type MediaTaskSpec,
+ type MediaUnit,
+} from "./media";
export { research, RESEARCH_READ_TOOLS, type ResearchInput } from "./research";
export { pickCorpusBuild, listCorpusBuilds, siteOriginOf, NoCorpusBuildError, type CorpusBuild } from "./corpusSource";
export { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
diff --git a/common/lib/report/draft/tasks/media.test.ts b/common/lib/report/draft/tasks/media.test.ts
@@ -0,0 +1,201 @@
+// The media task scaffold (release 28, M0): a toy task over the fake ollama
+// — two attempts, the better kept, an operator's field never replaced and its
+// draft kept as an alternative — and narrate on it writing its drafted marks.
+// Real iterations store and project in a temp dir; no model but the fake.
+
+import { after, before, test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs";
+import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "../../iterations";
+import { reviewAddress } from "../../drafted.mjs";
+import { narrate } from "./narrate";
+import {
+ mergeAlternatives,
+ rankAttempts,
+ runMediaTask,
+ type DraftAlternative,
+ type DraftFile,
+ type MediaTaskSpec,
+ type MediaUnit,
+} from "./media";
+import type { TaskDeps } from "./types";
+
+const DRAFT = new URL("../../../../testing/draft/", import.meta.url);
+const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8"));
+
+let tmp: string;
+let ol: FakeOllama;
+before(async () => {
+ tmp = await mkdtemp(path.join(os.tmpdir(), "media-task-"));
+ ol = await startFakeOllama();
+});
+after(async () => {
+ await ol.close();
+ await rm(tmp, { recursive: true, force: true });
+});
+
+let caseN = 0;
+// A done sweep iteration with a project holding `manifest` and the basic report.
+async function project(manifest: unknown) {
+ caseN++;
+ const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) };
+ const projectsRoot = path.join(tmp, `projects-${caseN}`);
+ await mkdir(paths.articlesDir, { recursive: true });
+ await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths);
+ const report = await kit("reports/basic.report.json");
+ await writeIterationFile("synth-basic", 1, "report.json", report, paths);
+ const dir = projectOf(projectsRoot, "synth-basic", 1);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
+ await writeFile(path.join(dir, "report.json"), JSON.stringify(report));
+ await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths);
+ const lines: string[] = [];
+ const deps: TaskDeps = {
+ llm: { ollama: { baseUrl: ol.url } },
+ corpus: { source: "none", tools: [], call: async () => "" },
+ cuesOf: async () => null,
+ paths,
+ log: (l) => lines.push(l),
+ now: () => new Date("2026-10-13T12:00:00.000Z"),
+ };
+ const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+ return { dir, paths, projectsRoot, deps, lines, manifestNow };
+}
+
+// A toy task: a title for each clip, at most 20 characters, never "BAD".
+type ToyUnit = MediaUnit & { quote: string };
+const TOY: MediaTaskSpec<ToyUnit, { title: string }> = {
+ task: "toy",
+ units: (ctx) =>
+ ctx.manifest.timeline
+ .filter((e) => e.type === "clip")
+ .slice(0, 3)
+ .map((e) => ({ id: e.id, target: { entry: e.id, field: "onscreen" }, quote: String(e.quote ?? "") })),
+ schema: () => ({ type: "object", properties: { title: { type: "string" } }, required: ["title"] }),
+ system: () => "Write a short title. Rules: at most 20 characters.",
+ user: (u) => `Quote: ${u.quote}`,
+ parse: (a) => ({ title: String((a as { title?: unknown }).title ?? "").trim() }),
+ check: (v) => ({
+ hard: [...(v.title.length > 20 ? [`${v.title.length} characters (at most 20)`] : []), ...(v.title === "BAD" ? ["bad"] : [])],
+ soft: v.title.endsWith("!") ? ["an exclamation"] : [],
+ }),
+};
+
+test("the scaffold: two attempts and the better kept; the operator's field kept and the draft an alternative; marks, snapshot, draft file", async () => {
+ const m = await kit("manifests/full.video.manifest.json");
+ const p = await project(m);
+ // c01 has hand-written on-screen text (the operator's); c02 and c03 none.
+ ol.push(
+ // c01 (forced): clean — but the field is the operator's.
+ jsonReply({ title: "Not for sale?" }),
+ // c02: too long, then clean.
+ jsonReply({ title: "A title far too long for the frame" }),
+ jsonReply({ title: "The old oven" }),
+ // c03: a soft flag, then worse (hard): the first is kept.
+ jsonReply({ title: "The mixer!" }),
+ jsonReply({ title: "BAD" }),
+ );
+ const out = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, force: true }, p.deps);
+ assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`);
+ assert.equal(ol.remaining(), 0);
+ assert.match(out.summary, /^2 field\(s\) drafted, 1 as alternatives \(see toy-draft\.json\) \(undo: revisions\/.*-auto-before-toy\.manifest\.json\)$/);
+ const after = await p.manifestNow();
+ const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id);
+ assert.deepEqual(e("c01").onscreen, m.timeline.find((x: { id: string }) => x.id === "c01").onscreen, "the operator's words stand");
+ assert.equal(e("c01").drafted, undefined);
+ assert.deepEqual(e("c02").onscreen, { title: "The old oven" });
+ assert.deepEqual(e("c02").drafted.onscreen, { task: "toy", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 2 });
+ assert.deepEqual(e("c03").onscreen, { title: "The mixer!" });
+ assert.equal(e("c03").drafted.onscreen.attempt, 1, "the better of two: the first");
+ assert.equal((await readdir(path.join(p.dir, "revisions"))).length, 1);
+ const file = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile;
+ assert.equal(file.task, "toy");
+ assert.equal(file.iteration, 1);
+ assert.equal((file.units.c02!.attempts as unknown[]).length, 2);
+ assert.equal(file.units.c01!.applied, "operator");
+ assert.equal(file.units.c02!.applied, "applied");
+ assert.deepEqual(file.alternatives.map((a) => [a.target, a.value, a.reason]), [[{ entry: "c01", field: "onscreen" }, { title: "Not for sale?" }, "operator"]]);
+ assert.equal(file.checks.find((c) => c.name === "toy")!.ok, true);
+ const it = (await readIteration("synth-basic", 1, p.paths))!;
+ assert.equal(it.status, "done", "a step leaves the iteration's status");
+ assert.equal(it.steps.find((s) => s.task === "toy")!.status, "done");
+
+ // Again, unforced: every field has a value now, so nothing is asked; the
+ // alternative from the run before is carried over.
+ const again = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot }, p.deps);
+ assert.equal(again.status, "failed");
+ assert.match(again.summary, /no field drafted/);
+ const file2 = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile;
+ assert.match(String(file2.units.c02!.skipped), /has a value \(a draft\); force re-drafts it/);
+ assert.match(String(file2.units.c01!.skipped), /the operator's/);
+ assert.equal(file2.alternatives.length, 1);
+});
+
+test("the scaffold: entries keeps only the named units; a unit with no clean value is not written", async () => {
+ const m = await kit("manifests/full.video.manifest.json");
+ const p = await project(m);
+ ol.push(jsonReply({ title: "BAD" }), jsonReply({ title: "BAD" }));
+ const out = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, entries: ["c02"] }, p.deps);
+ assert.equal(out.status, "failed");
+ assert.equal(ol.remaining(), 0, "only c02 was asked");
+ const file = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile;
+ assert.deepEqual(Object.keys(file.units), ["c02"]);
+ assert.deepEqual(await p.manifestNow(), m, "nothing written");
+ const it = (await readIteration("synth-basic", 1, p.paths))!;
+ assert.equal(it.checks!.find((c) => c.name === "toy")!.ok, false);
+});
+
+test("rankAttempts and mergeAlternatives", () => {
+ const a = { value: 1, hard: ["x"], soft: [] };
+ const b = { value: 2, hard: [], soft: ["y", "z"] };
+ const c = { value: 3, hard: [], soft: ["y", "z"] };
+ assert.deepEqual(rankAttempts([a, b, c]).map((x) => x.value), [2, 3, 1], "stable among equals");
+ const alt = (entry: string, title: string): DraftAlternative => ({
+ target: { entry, field: "onscreen" },
+ value: { title },
+ provenance: { task: "toy", model: "m", at: "2026-10-13T00:00:00.000Z", attempt: 1 },
+ reason: "operator",
+ });
+ const many = Array.from({ length: 7 }, (_, i) => alt("c01", `t${i}`));
+ const merged = mergeAlternatives(many.slice(0, 4), [...many.slice(4), alt("c01", "t0"), alt("c02", "x")]);
+ assert.deepEqual(
+ merged.map((x) => `${reviewAddress(x.target)}:${(x.value as { title: string }).title}`),
+ ["onscreen/c01/onscreen:t3", "onscreen/c01/onscreen:t4", "onscreen/c01/onscreen:t5", "onscreen/c01/onscreen:t6", "onscreen/c01/onscreen:t0", "onscreen/c02/onscreen:x"],
+ "five per field, the newest; a repeat keeps its newest place",
+ );
+});
+
+test("narrate on the scaffold: a narration it writes carries drafted.narration; the operator's is kept and its draft an alternative", async () => {
+ const m = await kit("manifests/basic.video.manifest.json");
+ const contest = m.timeline.find((e: { id: string }) => e.id === "the-contest");
+ contest.narration = { text: "Words the operator wrote." };
+ const p = await project(m);
+ // Each card's words by its heading, however many times it is asked.
+ const byCard = (body: { messages: { content: string }[] }) => {
+ const user = body.messages.at(-1)!.content;
+ if (/heading on screen: The bakery/.test(user)) return jsonReply({ text: "First, the bakery. She won't sell it, and she paid for the mixer herself." });
+ if (/heading on screen: The contest/.test(user)) return jsonReply({ text: "Then the contest. She stayed out of it this year." });
+ return jsonReply({ text: "What does the baker say about her bakery? And about the contest?" });
+ };
+ ol.push(byCard, byCard, byCard, byCard, byCard, byCard);
+ const out = await narrate({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, force: true }, p.deps);
+ assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`);
+ assert.match(out.summary, /^2 card\(s\) narrated, 1 as alternatives \(see narration-draft\.json\)/);
+ const after = await p.manifestNow();
+ const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id);
+ assert.equal(e("the-bakery").narration.text, "First, the bakery. She won't sell it, and she paid for the mixer herself.");
+ assert.equal(e("the-bakery").seconds, "auto");
+ assert.deepEqual(e("the-bakery").drafted, { narration: { task: "narrate", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 1 } });
+ assert.equal(e("title").drafted.narration.task, "narrate");
+ assert.equal(e("the-contest").narration.text, "Words the operator wrote.");
+ assert.equal(e("the-contest").drafted, undefined);
+ const file = JSON.parse(await readFile(path.join(p.dir, "narration-draft.json"), "utf8")) as DraftFile;
+ assert.deepEqual(file.alternatives.map((a) => [a.target.entry, (a.value as { text: string }).text]), [["the-contest", "Then the contest. She stayed out of it this year."]]);
+ const revisions = await readdir(path.join(p.dir, "revisions"));
+ assert.match(revisions[0]!, /-auto-before-narration\.manifest\.json$/);
+ const it = (await readIteration("synth-basic", 1, p.paths))!;
+ assert.equal(it.checks!.find((c) => c.name === "narration")!.ok, true);
+});
diff --git a/common/lib/report/draft/tasks/media.ts b/common/lib/report/draft/tasks/media.ts
@@ -0,0 +1,406 @@
+// THE MEDIA TASK SCAFFOLD (release 28, M0) — what every task that drafts a
+// field of an iteration's video manifest is, extracted from narrate (the
+// first; ./narrate.ts is now a spec on this). Phase 2's tasks (cut, onscreen,
+// teaser, flips, threads, youtube) are small files on it: a spec and an input.
+//
+// A media task is a STEP on a done iteration (recorded in its `steps`, its
+// status left as it is), run by `runMediaTask(spec, input, deps)`:
+//
+// 1. the iteration's project: its `video.manifest.json` (none: the task
+// cannot start) and its report (the project's `report.json`, else the
+// iteration's source report);
+// 2. `spec.units(ctx)`: one UNIT per field to draft -- its `target`
+// (`{ entry?, field }`, drafted.mjs) and whatever evidence the prompt
+// needs -- or a skip record (`{ id, skipped }`) for one that is not
+// drafted and says why. `input.entries` keeps only the units it names
+// (by entry id or unit id). A unit whose field has a value is skipped
+// unless `input.force` (then an operator's field is drafted anyway, and
+// the refused draft becomes an ALTERNATIVE);
+// 3. per unit, at most two attempts: `structuredAnswer` against
+// `spec.schema(unit)` with `spec.system` / `spec.user` (the second ask
+// carries what the first was refused for), `spec.parse` (a throw is a
+// hard failure of that attempt), then the task's CODE checks
+// (`spec.check` → `{ hard, soft }`: counts, lengths, ids that exist,
+// grounding). A clean first attempt is not asked again;
+// 4. the better attempt (`spec.score`, default fewest hard then fewest soft
+// problems); one still failing a hard check goes to `spec.repair` (narrate
+// removes the failing sentences), and a unit with no clean value is not
+// written;
+// 5. the manifest is snapshotted (`revisions/<stamp>-auto-before-<op>`) and
+// each kept value is written through `applyDraft` (drafted.mjs) -- or
+// `spec.apply`, which must call it -- with the provenance
+// `{ task, model, at, iteration, attempt }`. A field that is the
+// operator's is NEVER replaced: its value goes to `alternatives[]`;
+// 6. orphan marks dropped, the manifest written whole (only when something
+// was applied), and `<task>-draft.json` (`spec.draftFile`) written beside
+// it: every unit's attempts and checks, the kept value, what was applied,
+// and the alternatives (earlier runs' carried over, newest five per field).
+//
+// Q0 binds every spec: counts and lengths are enforced in `check`, never only
+// asked for; prompts carry rules, never worked examples; a local prompt stays
+// under 8k tokens. Progress reporting is not here yet (release 28 F3 adds
+// `TaskDeps.progress`; phase 2 wires the media tasks to it).
+
+import { readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { structuredAnswer } from "../../../llm";
+import { readIteration, readIterationFile, reportSourceOf } from "../../iterations";
+import {
+ applyDraft,
+ makeProvenance,
+ ownerOf,
+ pruneDrafted,
+ reviewAddress,
+ stableStringify,
+ valueKey,
+ type ApplyDraftResult,
+ type DraftTarget,
+ type Provenance,
+} from "../../drafted.mjs";
+import { groundingInputOf, type GroundingInput } from "../grounding";
+import type { VideoManifest } from "../videoOps";
+import { projectDirOf, readManifest, readProjectReport, snapshotManifest, writeManifest } from "./project";
+import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
+import type { TaskDeps, TaskResult } from "./types";
+
+export type { DraftTarget, Provenance } from "../../drafted.mjs";
+
+/** What every media task takes (its own input extends it). */
+export type MediaTaskInput = {
+ article: string;
+ n: number;
+ model: string;
+ projectsRoot: string;
+ // Only these units: an entry id (every unit on it) or a unit id.
+ entries?: string[];
+ // Re-draft a field that has a value. An operator's field is still never
+ // replaced: the draft becomes an alternative.
+ force?: boolean;
+ maxUsd?: number;
+ jobId?: string;
+};
+
+/** A report as a media task reads it (report.json's shape, loosely). */
+export type MediaReport = Record<string, any>;
+
+/** What a spec is handed: the run, the project, the manifest as read, the report. */
+export type MediaContext<I extends MediaTaskInput = MediaTaskInput> = {
+ handle: TaskHandle;
+ input: I;
+ dir: string;
+ manifest: VideoManifest;
+ report: MediaReport;
+ // groundingInputOf(report): what a spec's check grounds numbers and names in.
+ grounding: GroundingInput;
+};
+
+/** One field to draft. A spec's own units extend it with their evidence. */
+export type MediaUnit = { id: string; target: DraftTarget; label?: string };
+
+/** A unit that is not drafted, and why (recorded in the draft file). */
+export type MediaSkip = { id: string; skipped: string };
+
+/** One attempt: the value parsed (null: none), and the code checks' findings. */
+export type MediaAttempt<V> = { value: V | null; hard: string[]; soft: string[] };
+
+/** A refused value kept for the operator: umtool shows it under its field with "Use this". */
+export type DraftAlternative = {
+ target: DraftTarget;
+ value: unknown;
+ provenance: Provenance;
+ reason: "operator" | "drafted" | "missing";
+};
+
+/** `<task>-draft.json`: the run's record. */
+export type DraftFile = {
+ task: string;
+ model: string;
+ at: string;
+ article: string;
+ iteration: number;
+ units: Record<string, Record<string, unknown>>;
+ checks: { name: string; ok: boolean; detail?: string }[];
+ alternatives: DraftAlternative[];
+};
+
+export type MediaTaskSpec<U extends MediaUnit, V, I extends MediaTaskInput = MediaTaskInput> = {
+ // The task's name: the step's, the provenance's, the default file's.
+ task: string;
+ // Default `<task>-draft.json`.
+ draftFile?: string;
+ // The snapshot's op (`auto-before-<op>`); default the task.
+ snapshotOp?: string;
+ // The iteration check's name; default the task.
+ checkName?: string;
+ // turns.jsonl's `kind` per attempt; default the task.
+ turnKind?: string;
+ // Words for the summary: "<n> <noun>(s) <verb>"; defaults "field", "drafted".
+ noun?: string;
+ verb?: string;
+ units(ctx: MediaContext<I>): (U | MediaSkip)[] | Promise<(U | MediaSkip)[]>;
+ schema(unit: U, ctx: MediaContext<I>): object;
+ system(unit: U, ctx: MediaContext<I>): string;
+ user(unit: U, ctx: MediaContext<I>): string;
+ // The model's answer to a value; a throw is that attempt's hard failure.
+ parse(answer: unknown, unit: U, ctx: MediaContext<I>): V;
+ // The code checks: `hard` refuses the value, `soft` is a flag.
+ check(value: V, unit: U, ctx: MediaContext<I>): { hard: string[]; soft: string[] };
+ // Lower is better, compared element by element. Default [hard, soft].
+ score?(a: MediaAttempt<V>): number[];
+ // When the best attempt still fails a hard check: a clean value made from
+ // the attempts (never a new one), or null. Its own `hard` must be empty.
+ repair?(attempts: MediaAttempt<V>[], unit: U, ctx: MediaContext<I>): MediaAttempt<V> | null;
+ // The re-ask's added words; default "Your last draft was refused for: …".
+ retry?(last: MediaAttempt<V>, unit: U): string;
+ // The field's value for a kept value (default: the value itself) -- what is
+ // written, and what an alternative holds (umtool's "Use this" writes it as is).
+ // Narrate's is the card's narration object with the new words.
+ toField?(value: V, unit: U, manifest: VideoManifest): unknown;
+ // After a value is applied (narrate: the card's `seconds` to "auto").
+ afterApply?(manifest: VideoManifest, unit: U): void;
+ // Write the kept value instead of `applyDraft(manifest, { ...unit.target,
+ // value: toField(value), provenance, force })`; an override must go through
+ // applyDraft.
+ apply?(manifest: VideoManifest, unit: U, value: unknown, provenance: Provenance, force: boolean, ctx: MediaContext<I>): ApplyDraftResult;
+ // A line for the log per unit kept; default the value as JSON.
+ describe?(value: V, unit: U): string;
+};
+
+export const isSkip = (u: MediaUnit | MediaSkip): u is MediaSkip => typeof (u as MediaSkip).skipped === "string";
+
+/** Default score: fewest hard problems, then fewest soft ones. */
+export const defaultScore = <V>(a: MediaAttempt<V>) => [a.hard.length, a.soft.length];
+
+const lexLess = (a: number[], b: number[]) => {
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
+ const x = a[i] ?? 0;
+ const y = b[i] ?? 0;
+ if (x !== y) return x < y;
+ }
+ return false;
+};
+
+/** The attempts best first (a stable sort: the earlier of two equals first). */
+export function rankAttempts<V>(attempts: MediaAttempt<V>[], score: (a: MediaAttempt<V>) => number[] = defaultScore): MediaAttempt<V>[] {
+ return attempts
+ .map((a, i) => ({ a, i, s: score(a) }))
+ .sort((x, y) => (lexLess(x.s, y.s) ? -1 : lexLess(y.s, x.s) ? 1 : x.i - y.i))
+ .map((x) => x.a);
+}
+
+export const draftFileName = (task: string) => `${task}-draft.json`;
+
+/** The newest alternatives kept per field. */
+export const ALTERNATIVES_PER_FIELD = 5;
+
+const targetKey = (t: DraftTarget) => reviewAddress({ entry: t.entry ?? null, field: t.field });
+
+/** A project's draft file, or null (absent or unreadable). */
+export async function readDraftFile(dir: string, file: string): Promise<DraftFile | null> {
+ try {
+ const j = JSON.parse(await readFile(path.join(dir, file), "utf8"));
+ return j && typeof j === "object" && !Array.isArray(j) ? (j as DraftFile) : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Earlier alternatives, then these; one per field and value, the newest ALTERNATIVES_PER_FIELD per field. */
+export function mergeAlternatives(earlier: readonly DraftAlternative[], now: readonly DraftAlternative[]): DraftAlternative[] {
+ const seen = new Set<string>();
+ const out: DraftAlternative[] = [];
+ // Newest first while picking, so a repeat keeps its newest copy.
+ for (const a of [...now].reverse().concat([...earlier].reverse())) {
+ if (!a || typeof a !== "object" || !a.target || typeof a.target.field !== "string") continue;
+ const k = `${targetKey(a.target)}\u0000${valueKey(a.value)}`;
+ if (seen.has(k)) continue;
+ if (out.filter((x) => targetKey(x.target) === targetKey(a.target)).length >= ALTERNATIVES_PER_FIELD) continue;
+ seen.add(k);
+ out.push(a);
+ }
+ return out.reverse();
+}
+
+async function writeJsonAtomic(file: string, value: unknown) {
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`);
+ await rename(tmp, file);
+}
+
+/** The project, the manifest and the report a media task reads. */
+export async function loadMediaContext<I extends MediaTaskInput>(h: TaskHandle, input: I): Promise<MediaContext<I>> {
+ const it = (await readIteration(h.article, h.n, h.paths))!;
+ const dir = projectDirOf(it, input.projectsRoot);
+ const manifest = await readManifest(dir);
+ if (!manifest) throw new TaskInputError(`${dir} has no video.manifest.json (run the chain to its manifest first)`);
+ let report = (await readProjectReport(dir)) as MediaReport | null;
+ if (!report) {
+ const from = await reportSourceOf(h.article, h.n, h.paths);
+ const text = from === null ? null : await readIterationFile(h.article, from, "report.json", h.paths);
+ report = text ? (JSON.parse(text) as MediaReport) : null;
+ }
+ if (!report) throw new TaskInputError(`"${h.article}" i${h.n}: no report.json to draft from`);
+ return { handle: h, input, dir, manifest, report, grounding: groundingInputOf(report) };
+}
+
+const refusedFor = <V>(last: MediaAttempt<V>) =>
+ `\n\nYour last draft was refused for: ${[...last.hard, ...last.soft].join("; ")}. Write it again without those problems.`;
+
+/**
+ * Run one media task over an iteration (the shape above). The result is the
+ * step's: `done` when at least one unit kept a clean value (applied, or kept
+ * as an alternative), else `failed`.
+ */
+export async function runMediaTask<U extends MediaUnit, V, I extends MediaTaskInput>(
+ spec: MediaTaskSpec<U, V, I>,
+ input: I,
+ deps: TaskDeps,
+): Promise<TaskResult> {
+ return runOnIteration(
+ {
+ article: input.article,
+ n: input.n,
+ deps,
+ maxUsd: input.maxUsd,
+ step: { task: spec.task, model: input.model, ...(input.jobId ? { jobId: input.jobId } : {}) },
+ },
+ (h) => mediaBody(spec, h, input),
+ );
+}
+
+async function mediaBody<U extends MediaUnit, V, I extends MediaTaskInput>(
+ spec: MediaTaskSpec<U, V, I>,
+ h: TaskHandle,
+ input: I,
+): Promise<TaskOutcome> {
+ const { deps } = h;
+ const now = () => deps.now?.() ?? new Date();
+ const ctx = await loadMediaContext(h, input);
+ const { dir, manifest } = ctx;
+ const file = spec.draftFile ?? draftFileName(spec.task);
+ const noun = spec.noun ?? "field";
+ const verb = spec.verb ?? "drafted";
+ const score = spec.score ?? defaultScore;
+ const only = input.entries?.length ? new Set(input.entries) : null;
+ const units: Record<string, Record<string, unknown>> = {};
+ const kept: { unit: U; value: V; attempt: 1 | 2 }[] = [];
+ h.log(`${spec.task} on i${h.n}, ${input.model} (${dir})`);
+
+ for (const u of await spec.units(ctx)) {
+ if (only && !only.has(u.id) && !(!isSkip(u) && u.target.entry && only.has(u.target.entry))) continue;
+ if (isSkip(u)) {
+ units[u.id] = { skipped: u.skipped };
+ continue;
+ }
+ const owner = ownerOf(manifest, u.target);
+ if (owner !== "empty" && !input.force) {
+ units[u.id] = { target: u.target, skipped: `has a value (${owner === "operator" ? "the operator's" : "a draft"}); force re-drafts it` };
+ continue;
+ }
+ const system = spec.system(u, ctx);
+ const user = spec.user(u, ctx);
+ const attempts: MediaAttempt<V>[] = [];
+ for (let k = 0; k < 2; k++) {
+ deps.signal?.throwIfAborted();
+ const extra = attempts.length ? (spec.retry ?? refusedFor)(attempts.at(-1)!, u) : "";
+ let a: MediaAttempt<V>;
+ try {
+ const answer = await structuredAnswer<unknown>({
+ llm: deps.llm,
+ model: input.model,
+ system,
+ user: user + extra,
+ schema: spec.schema(u, ctx),
+ meter: h.meter,
+ signal: deps.signal,
+ });
+ try {
+ const value = spec.parse(answer, u, ctx);
+ a = { value, ...spec.check(value, u, ctx) };
+ } catch (e) {
+ a = { value: null, hard: [(e as Error).message], soft: [] };
+ }
+ } catch (e) {
+ if (deps.signal?.aborted) throw e;
+ attempts.push({ value: null, hard: [(e as Error).message], soft: [] });
+ continue;
+ }
+ attempts.push(a);
+ h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, ...a }]);
+ if (!a.hard.length && !a.soft.length) break;
+ }
+ const ranked = rankAttempts(attempts, score);
+ let chosen: MediaAttempt<V> | null = ranked[0] ?? null;
+ let attemptNo = (chosen ? attempts.indexOf(chosen) + 1 : 1) as 1 | 2;
+ if (chosen && chosen.hard.length) {
+ const fixed = spec.repair?.(attempts, u, ctx) ?? null;
+ if (fixed && !fixed.hard.length && fixed.value !== null) {
+ chosen = fixed;
+ attemptNo = Math.min(2, attempts.length) as 1 | 2;
+ }
+ }
+ units[u.id] = { target: u.target, ...(u.label ? { label: u.label } : {}), attempts, chosen };
+ if (!chosen || chosen.hard.length || chosen.value === null) {
+ h.log(` ${u.id}: NOT written — ${chosen?.hard.join("; ") ?? "no draft"}`);
+ continue;
+ }
+ kept.push({ unit: u, value: chosen.value, attempt: attemptNo });
+ const said = spec.describe ? spec.describe(chosen.value, u) : JSON.stringify(chosen.value);
+ h.log(` ${u.id}: ${said}${chosen.soft.length ? ` [flag: ${chosen.soft.join("; ")}]` : ""}`);
+ }
+
+ const refused = Object.values(units).filter((r) => (r.chosen as MediaAttempt<V> | null | undefined)?.hard?.length).length;
+ const at = now();
+ const alternatives: DraftAlternative[] = [];
+ const next = JSON.parse(JSON.stringify(manifest)) as VideoManifest;
+ let applied = 0;
+ for (const k of kept) {
+ const provenance = makeProvenance({ task: spec.task, model: input.model, at, iteration: h.n, attempt: k.attempt });
+ const value = spec.toField ? spec.toField(k.value, k.unit, next) : k.value;
+ const res = spec.apply
+ ? spec.apply(next, k.unit, value, provenance, !!input.force, ctx)
+ : applyDraft(next, { ...k.unit.target, value, provenance, force: !!input.force });
+ units[k.unit.id]!.applied = res.applied ? "applied" : res.reason;
+ if (res.applied) {
+ applied++;
+ spec.afterApply?.(next, k.unit);
+ } else alternatives.push({ target: k.unit.target, value, provenance, reason: res.reason });
+ }
+ pruneDrafted(next);
+ let snap: string | null = null;
+ if (applied) {
+ snap = await snapshotManifest(dir, spec.snapshotOp ?? spec.task, at);
+ await writeManifest(dir, next);
+ }
+ h.check({
+ name: spec.checkName ?? spec.task,
+ ok: refused === 0,
+ detail:
+ `${applied} ${noun}(s) ${verb}` +
+ (alternatives.length ? `, ${alternatives.length} kept as an alternative (the field is the operator's)` : "") +
+ (refused ? `, ${refused} not written (a hard check)` : ""),
+ });
+ const earlier = (await readDraftFile(dir, file))?.alternatives ?? [];
+ const record: DraftFile = {
+ task: spec.task,
+ model: input.model,
+ at: at.toISOString(),
+ article: h.article,
+ iteration: h.n,
+ units,
+ checks: h.checks,
+ alternatives: mergeAlternatives(Array.isArray(earlier) ? earlier : [], alternatives),
+ };
+ await writeJsonAtomic(path.join(dir, file), record).catch((e) => h.log(`${file} not written: ${(e as Error).message}`));
+ if (!kept.length) return { status: "failed", summary: `no ${noun} ${verb} (see ${file})` };
+ return {
+ status: "done",
+ summary:
+ `${applied} ${noun}(s) ${verb}` +
+ (alternatives.length ? `, ${alternatives.length} as alternatives (see ${file})` : "") +
+ (snap ? ` (undo: ${snap})` : ""),
+ };
+}
+
+// Exported for tests and for a spec that compares values the way the writer does.
+export { stableStringify, valueKey };
diff --git a/common/lib/report/draft/tasks/narrate.ts b/common/lib/report/draft/tasks/narrate.ts
@@ -11,16 +11,17 @@
// failing a hard check loses its failing sentences, and a card with nothing
// left is not written. The manifest is snapshotted, then written whole; every
// draft and its checks go to the project's narration-draft.json.
+//
+// Release 28 (M0): a spec on the media task scaffold (./media.ts). A narration
+// it writes carries its drafted mark (`entry.drafted.narration`), and a card
+// whose narration is the operator's (words with no mark) is never replaced,
+// even with `force`: the draft goes to narration-draft.json's alternatives.
-import { writeFile } from "node:fs/promises";
-import path from "node:path";
-import { structuredAnswer } from "../../../llm";
-import { readIteration, reportSourceOf, readIterationFile } from "../../iterations";
+import { entriesWithId } from "../../drafted.mjs";
import { NARRATION_HARD_RULE, NARRATION_TASTE, NARRATION_WRITING_RULES, rulesForModel } from "../authoringRules";
import { checkNarration, groundingInputOf, sentencesOf, type GroundingInput } from "../grounding";
import type { ManifestEntry } from "../videoOps";
-import { projectDirOf, readManifest, readProjectReport, snapshotManifest, writeManifest } from "./project";
-import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
+import { runMediaTask, type MediaSkip, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media";
import type { TaskDeps, TaskResult } from "./types";
export const TITLE_WORDS = 35;
@@ -28,17 +29,9 @@ export const CHAPTER_WORDS = 45;
// A draft this far over its limit is refused outright.
export const OVER_LIMIT_SLACK = 10;
-export type NarrateInput = {
- article: string;
- n: number;
- model: string;
- projectsRoot: string;
+export type NarrateInput = MediaTaskInput & {
// Only these card ids (default: every title and chapter card).
cards?: string[];
- // Re-draft a card that has narration already.
- force?: boolean;
- maxUsd?: number;
- jobId?: string;
};
type Section = { title?: string; body?: string | null; claims?: { text?: string; citations?: string[] }[] | null };
@@ -118,97 +111,81 @@ export function chooseDraft(attempts: Attempt[], g: GroundingInput, limit: numbe
return best;
}
-export async function narrate(input: NarrateInput, deps: TaskDeps): Promise<TaskResult> {
- return runOnIteration(
- { article: input.article, n: input.n, deps, maxUsd: input.maxUsd, step: { task: "narrate", model: input.model, ...(input.jobId ? { jobId: input.jobId } : {}) } },
- (h) => narrateBody(h, input),
- );
-}
-
-async function narrateBody(h: TaskHandle, input: NarrateInput): Promise<TaskOutcome> {
- const { deps } = h;
- const it = (await readIteration(h.article, h.n, h.paths))!;
- const dir = projectDirOf(it, input.projectsRoot);
- const manifest = await readManifest(dir);
- if (!manifest) throw new TaskInputError(`${dir} has no video.manifest.json (run the chain to its manifest first)`);
- let report = (await readProjectReport(dir)) as ReportLike | null;
- if (!report) {
- const from = await reportSourceOf(h.article, h.n, h.paths);
- const text = from === null ? null : await readIterationFile(h.article, from, "report.json", h.paths);
- report = text ? (JSON.parse(text) as ReportLike) : null;
- }
- if (!report) throw new TaskInputError(`"${h.article}" i${h.n}: no report.json to narrate from`);
- const base = groundingInputOf(report);
- const only = input.cards?.length ? new Set(input.cards) : null;
- const drafts = new Map<string, string>();
- const record: Record<string, unknown> = {};
- h.log(`narrating i${h.n} on ${input.model} (${dir})`);
+// A unit: one card, its limit and evidence.
+type NarrateUnit = MediaUnit & { card: ManifestEntry; limit: number; g: GroundingInput; ctxText: string };
- for (const card of manifest.timeline) {
- if (card.type !== "card" || (card.style !== "title" && card.style !== "chapter")) continue;
- if (only && !only.has(card.id)) continue;
- if (card.narration?.text && !input.force) continue;
- if ((card.heading ?? "").trim().toLowerCase() === "coverage") {
- record[card.id] = { skipped: "the Coverage card is not narrated (its numbers are on the page)" };
- continue;
- }
- const ctx = cardContext(card, report);
- if (!ctx) {
- record[card.id] = { skipped: "no section in the report matches this card's heading" };
- continue;
- }
- const limit = card.style === "title" ? TITLE_WORDS : CHAPTER_WORDS;
- const g: GroundingInput = { ...base, quotes: ctx.quotes };
- const system = narrationSystem(limit);
- const user = `Card heading on screen: ${card.heading ?? ""}\n\nEvidence for this card (the only facts you may use):\n${ctx.text}\n\nWrite this card's narration.`;
- const attempts: Attempt[] = [];
- for (let k = 0; k < 2; k++) {
- deps.signal?.throwIfAborted();
- const extra = attempts.length
- ? `\n\nYour last draft was refused for: ${[...attempts.at(-1)!.hard, ...attempts.at(-1)!.soft].join("; ")}. Write it again without those problems.`
- : "";
- let text = "";
- try {
- const ans = await structuredAnswer<{ text?: unknown }>({
- llm: deps.llm,
- model: input.model,
- system,
- user: user + extra,
- schema: { type: "object", properties: { text: { type: "string" } }, required: ["text"] },
- meter: h.meter,
- signal: deps.signal,
- });
- text = String(ans.text ?? "").replace(/\s+/g, " ").trim().replace(/^"+|"+$/g, "");
- } catch (e) {
- if (deps.signal?.aborted) throw e;
- attempts.push({ text: "", hard: [(e as Error).message], soft: [] });
+/** Narrate as a media task (./media.ts): one unit per title and chapter card. */
+export const NARRATE_SPEC: MediaTaskSpec<NarrateUnit, string, NarrateInput> = {
+ task: "narrate",
+ // Its audit file kept its release 27 name.
+ draftFile: "narration-draft.json",
+ snapshotOp: "narration",
+ checkName: "narration",
+ turnKind: "narration",
+ noun: "card",
+ verb: "narrated",
+ units(ctx) {
+ const out: (NarrateUnit | MediaSkip)[] = [];
+ const only = ctx.input.cards?.length ? new Set(ctx.input.cards) : null;
+ const seen = new Set<string>();
+ for (const card of ctx.manifest.timeline) {
+ if (card.type !== "card" || (card.style !== "title" && card.style !== "chapter")) continue;
+ if (only && !only.has(card.id)) continue;
+ if (seen.has(card.id)) continue;
+ seen.add(card.id);
+ if ((card.heading ?? "").trim().toLowerCase() === "coverage") {
+ out.push({ id: card.id, skipped: "the Coverage card is not narrated (its numbers are on the page)" });
continue;
}
- const a = checkDraft(text, g, limit);
- attempts.push(a);
- h.turns([{ kind: "narration", card: card.id, attempt: k + 1, ...a }]);
- if (!a.hard.length && !a.soft.length) break;
- }
- const chosen = chooseDraft(attempts, g, limit);
- record[card.id] = { heading: card.heading, attempts, chosen };
- if (chosen.hard.length) {
- h.log(` ${card.id}: NOT written — ${chosen.hard.join("; ")}`);
- continue;
+ const c = cardContext(card, ctx.report as ReportLike);
+ if (!c) {
+ out.push({ id: card.id, skipped: "no section in the report matches this card's heading" });
+ continue;
+ }
+ const limit = card.style === "title" ? TITLE_WORDS : CHAPTER_WORDS;
+ out.push({
+ id: card.id,
+ target: { entry: card.id, field: "narration" },
+ label: card.heading,
+ card,
+ limit,
+ g: { ...ctx.grounding, quotes: c.quotes },
+ ctxText: c.text,
+ });
}
- drafts.set(card.id, chosen.text);
- h.log(` ${card.id}: ${chosen.text}${chosen.soft.length ? ` [flag: ${chosen.soft.join("; ")}]` : ""}`);
- }
- await writeFile(path.join(dir, "narration-draft.json"), `${JSON.stringify(record, null, 2)}\n`).catch(() => {});
- const refused = Object.values(record).filter((r) => (r as { chosen?: Attempt }).chosen?.hard.length).length;
- h.check({ name: "narration", ok: refused === 0, detail: `${drafts.size} card(s) drafted${refused ? `, ${refused} not written (a hard check)` : ""}` });
- if (!drafts.size) return { status: "failed", summary: "no card narrated (see narration-draft.json)" };
- const snap = await snapshotManifest(dir, "narration", deps.now?.() ?? new Date());
- for (const e of manifest.timeline) {
- const text = drafts.get(e.id);
- if (e.type !== "card" || !text) continue;
- e.narration = { ...(e.narration && typeof e.narration === "object" ? e.narration : {}), text };
- e.seconds = "auto";
- }
- await writeManifest(dir, manifest);
- return { status: "done", summary: `${drafts.size} card(s) narrated${snap ? ` (undo: ${snap})` : ""}` };
+ return out;
+ },
+ schema: () => ({ type: "object", properties: { text: { type: "string" } }, required: ["text"] }),
+ system: (u) => narrationSystem(u.limit),
+ user: (u) =>
+ `Card heading on screen: ${u.card.heading ?? ""}\n\nEvidence for this card (the only facts you may use):\n${u.ctxText}\n\nWrite this card's narration.`,
+ parse: (answer) =>
+ String((answer as { text?: unknown } | null)?.text ?? "")
+ .replace(/\s+/g, " ")
+ .trim()
+ .replace(/^"+|"+$/g, ""),
+ check(text, u) {
+ const a = checkDraft(text, u.g, u.limit);
+ return { hard: a.hard, soft: a.soft };
+ },
+ repair(attempts, u) {
+ const chosen = chooseDraft(
+ attempts.map((a) => ({ text: a.value ?? "", hard: a.hard, soft: a.soft })),
+ u.g,
+ u.limit,
+ );
+ return chosen.hard.length ? null : { value: chosen.text, hard: [], soft: chosen.soft };
+ },
+ toField(text, u, manifest) {
+ const cur = entriesWithId(manifest, u.card.id)[0]?.narration;
+ return { ...(cur && typeof cur === "object" ? cur : {}), text };
+ },
+ afterApply(manifest, u) {
+ for (const e of entriesWithId(manifest, u.card.id)) e.seconds = "auto";
+ },
+ describe: (text) => text,
+};
+
+export async function narrate(input: NarrateInput, deps: TaskDeps): Promise<TaskResult> {
+ return runMediaTask(NARRATE_SPEC, input, deps);
}
diff --git a/common/lib/report/drafted.d.mts b/common/lib/report/drafted.d.mts
@@ -0,0 +1,47 @@
+// Types for ./drafted.mjs (release 28, M0): the drafted marks, the one draft
+// writer, and the validators. See the module's header for the rules.
+
+export type DraftedEntryField = "onscreen" | "narration" | "lines";
+export type DraftedManifestField = "timeline" | "render.chrome.flips" | "render.chrome.threads" | "publish.youtube";
+export type DraftedField = DraftedEntryField | DraftedManifestField;
+
+/** Where a draft goes: an entry's field (`entry` an id), or the manifest's (`entry` absent or null). */
+export type DraftTarget = { entry?: string | null; field: DraftedField | string };
+
+/** Who drafted a field: `at` ISO, `attempt` the one kept (1 or 2). */
+export type Provenance = { task: string; model: string; at: string; iteration?: number; attempt: 1 | 2 };
+
+export type ApplyDraftResult = { applied: true } | { applied: false; reason: "operator" | "drafted" | "missing" };
+
+export const DRAFTED_ENTRY_FIELDS: Readonly<Record<DraftedEntryField, readonly string[] | null>>;
+export const DRAFTED_MANIFEST_FIELDS: readonly DraftedManifestField[];
+export const FIELD_TASKS: Readonly<Record<DraftedField, string>>;
+export const PROVENANCE_KEYS: readonly string[];
+export const PUBLISH_YOUTUBE_LIMITS: Readonly<{ title: number; description: number }>;
+
+export function isEntryField(field: string): field is DraftedEntryField;
+export function isManifestField(field: string): field is DraftedManifestField;
+export function provenanceProblems(v: unknown, where: string): string[];
+export function makeProvenance(p: { task: string; model: string; at?: Date | string; iteration?: number; attempt?: number }): Provenance;
+export function entriesWithId(manifest: unknown, id: string): Record<string, any>[];
+export function readField(manifest: unknown, target: DraftTarget): unknown;
+export function isEmptyField(field: string, v: unknown): boolean;
+export function draftedOf(manifest: unknown, target: DraftTarget): Provenance | null;
+export function ownerOf(manifest: unknown, target: DraftTarget): "empty" | "drafted" | "operator";
+export function applyDraft(
+ manifest: unknown,
+ o: { entry?: string | null; field: DraftedField | string; value: unknown; provenance: Provenance; force?: boolean },
+): ApplyDraftResult;
+export function clearDrafted(manifest: unknown, target: DraftTarget): boolean;
+export function stableStringify(v: unknown): string;
+export function fieldSignature(manifest: unknown, target: DraftTarget): unknown;
+export function valueKey(v: unknown): string;
+export function fieldKey(manifest: unknown, target: DraftTarget): string;
+export function draftedFields(manifest: unknown): { entry: string | null; field: DraftedField; provenance: Provenance; value: unknown }[];
+export function reviewAddress(target: DraftTarget): string;
+export function parseReviewAddress(address: unknown): { task: string; entry: string | null; field: string } | null;
+export function orphanDrafts(manifest: unknown): { where: string; entry: string | null; field: string }[];
+export function pruneDrafted(manifest: unknown): string[];
+export function clearEditedDrafts(before: unknown, after: unknown): { entry: string | null; field: string }[];
+export function validateDrafted(manifest: unknown): string[];
+export function validatePublish(manifest: unknown): string[];
diff --git a/common/lib/report/drafted.mjs b/common/lib/report/drafted.mjs
@@ -0,0 +1,521 @@
+// DRAFTED FIELDS — THE one copy of where a generated manifest field says it was
+// drafted, the one writer every draft task goes through, and the rules that
+// keep an operator's words from being overwritten (release 28, M0).
+//
+// Plain JS (with JSDoc types, and ./drafted.d.mts for TypeScript) for the
+// reason ./verdicts.mjs is: umtool's report-to-video scripts and its manifest
+// writer are `.mjs` run by bare `node`, and the common tasks are TypeScript;
+// both read and write the same marks.
+//
+// WHERE THE MARK LIVES. A provenance is `{ task, model, at, iteration?, attempt }`
+// (`at` ISO; `attempt` 1 or 2, the one kept). An ENTRY's field carries it on the
+// entry, keyed by field — `entry.drafted = { onscreen, narration, lines }` (any
+// entry's on-screen text, a card's narration, a teaser's lines). A MANIFEST
+// field carries it in a top-level map keyed by path — `manifest.drafted =
+// { "timeline", "render.chrome.flips", "render.chrome.threads",
+// "publish.youtube" }` ("timeline" is the cut's ORDER; "render.chrome.threads"
+// covers each clip's `thread` key too). Nowhere else.
+//
+// WHO OWNS A FIELD. Empty: nobody (a draft may fill it). Non-empty with a mark:
+// the task that drafted it (a forced re-draft may replace it). Non-empty with
+// NO mark: the operator — written by hand, or edited since it was drafted —
+// and never replaced, forced or not (`applyDraft`). An edit through umtool's
+// manifest writer removes the mark (`clearEditedDrafts`), which is what makes
+// an edited field the operator's.
+//
+// A mark whose field is gone (an orphan) is dropped with a warning
+// (`pruneDrafted`); a mark that is malformed or in a place no field may be
+// drafted is refused (`validateDrafted`).
+
+import { createHash } from "node:crypto";
+
+/** The entry fields that may be drafted, and the entry types each is on (null: any). */
+export const DRAFTED_ENTRY_FIELDS = Object.freeze({
+ onscreen: null,
+ narration: Object.freeze(["card"]),
+ lines: Object.freeze(["teaser"]),
+});
+
+/** The manifest fields that may be drafted, by path. */
+export const DRAFTED_MANIFEST_FIELDS = Object.freeze(["timeline", "render.chrome.flips", "render.chrome.threads", "publish.youtube"]);
+
+/**
+ * Each draftable field's own task: the one that drafts it, and the `<task>` of
+ * its review address (`reviewAddress`), whichever task drafted it this time —
+ * so a field's review has ONE address.
+ */
+export const FIELD_TASKS = Object.freeze({
+ onscreen: "onscreen",
+ narration: "narrate",
+ lines: "teaser",
+ timeline: "cut",
+ "render.chrome.flips": "flips",
+ "render.chrome.threads": "threads",
+ "publish.youtube": "youtube",
+});
+
+/** The keys of a provenance, in the order they are written. */
+export const PROVENANCE_KEYS = Object.freeze(["task", "model", "at", "iteration", "attempt"]);
+
+/** `publish.youtube`'s limits: YouTube's own (a title of 100, a description of 5000). */
+export const PUBLISH_YOUTUBE_LIMITS = Object.freeze({ title: 100, description: 5000 });
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** @param {string} field */
+export const isEntryField = (field) => Object.prototype.hasOwnProperty.call(DRAFTED_ENTRY_FIELDS, field);
+/** @param {string} field */
+export const isManifestField = (field) => DRAFTED_MANIFEST_FIELDS.includes(field);
+
+/**
+ * Every reason `v` is not a provenance, naming `where` (empty: it is one).
+ *
+ * @param {unknown} v
+ * @param {string} where
+ * @returns {string[]}
+ */
+export function provenanceProblems(v, where) {
+ if (!isObj(v)) return [`${where} must be { task, model, at, iteration?, attempt }`];
+ const errors = [];
+ for (const k of Object.keys(v)) if (!PROVENANCE_KEYS.includes(k)) errors.push(`${where}.${k} is not a provenance key (${PROVENANCE_KEYS.join(", ")})`);
+ const word = (k, max) => {
+ if (typeof v[k] !== "string" || !v[k].trim()) errors.push(`${where}.${k} must be a name`);
+ else if (v[k].length > max || /[\r\n]/.test(v[k])) errors.push(`${where}.${k} must be one line of at most ${max} characters`);
+ };
+ word("task", 64);
+ word("model", 200);
+ if (typeof v.at !== "string" || Number.isNaN(Date.parse(v.at))) errors.push(`${where}.at must be an ISO date and time`);
+ if (v.iteration !== undefined && !(Number.isInteger(v.iteration) && v.iteration > 0)) errors.push(`${where}.iteration must be a positive whole number`);
+ if (v.attempt !== 1 && v.attempt !== 2) errors.push(`${where}.attempt must be 1 or 2 (the attempt kept)`);
+ return errors;
+}
+
+/**
+ * A provenance, its keys in order. `at` defaults to now.
+ *
+ * @param {{ task: string, model: string, at?: Date | string, iteration?: number, attempt?: number }} p
+ */
+export function makeProvenance({ task, model, at = new Date(), iteration, attempt = 1 }) {
+ return {
+ task,
+ model,
+ at: typeof at === "string" ? at : at.toISOString(),
+ ...(iteration !== undefined && iteration !== null ? { iteration } : {}),
+ attempt,
+ };
+}
+
+/** Every timeline entry with this id (a cut's `variant` twins share one). */
+export function entriesWithId(manifest, id) {
+ return (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => isObj(e) && e.id === id);
+}
+
+const pathParts = (field) => field.split(".");
+
+function readPath(obj, field) {
+ let cur = obj;
+ for (const p of pathParts(field)) {
+ if (!isObj(cur)) return undefined;
+ cur = cur[p];
+ }
+ return cur;
+}
+
+/**
+ * A field's value: an entry's (`target.entry` an id; the first entry with it)
+ * or the manifest's (`target.entry` absent). "timeline" is the timeline itself.
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ */
+export function readField(manifest, { entry = null, field }) {
+ if (entry !== null && entry !== undefined) return entriesWithId(manifest, entry)[0]?.[field];
+ return readPath(manifest, field);
+}
+
+/**
+ * Is this value of this field empty -- nothing a person wrote? A narration with
+ * no words, an on-screen block with no text, a list with nothing in it.
+ *
+ * @param {string} field
+ * @param {unknown} v
+ */
+export function isEmptyField(field, v) {
+ if (v === undefined || v === null || v === "") return true;
+ if (field === "narration") return !(isObj(v) && typeof v.text === "string" && v.text.trim());
+ if (field === "onscreen") return !(isObj(v) && ["title", "subtitle"].some((k) => typeof v[k] === "string" && v[k].trim()));
+ if (field === "render.chrome.flips") return !(isObj(v) && Array.isArray(v.pairs) && v.pairs.length);
+ if (field === "render.chrome.threads") return !(isObj(v) && Array.isArray(v.list) && v.list.length);
+ if (field === "publish.youtube") return !(isObj(v) && ["title", "description"].some((k) => typeof v[k] === "string" && v[k].trim()));
+ if (Array.isArray(v)) return v.length === 0;
+ if (isObj(v)) return Object.keys(v).length === 0;
+ return false;
+}
+
+/**
+ * A field's drafted mark, or null.
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ */
+export function draftedOf(manifest, { entry = null, field }) {
+ if (entry !== null && entry !== undefined) {
+ const e = entriesWithId(manifest, entry)[0];
+ const p = isObj(e?.drafted) ? e.drafted[field] : undefined;
+ return isObj(p) ? p : null;
+ }
+ const p = isObj(manifest?.drafted) ? manifest.drafted[field] : undefined;
+ return isObj(p) ? p : null;
+}
+
+/**
+ * Who a field belongs to now: "empty", "drafted" or "operator".
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ * @returns {"empty" | "drafted" | "operator"}
+ */
+export function ownerOf(manifest, target) {
+ if (isEmptyField(target.field, readField(manifest, target))) return "empty";
+ return draftedOf(manifest, target) ? "drafted" : "operator";
+}
+
+function assertTarget({ entry = null, field }) {
+ const onEntry = entry !== null && entry !== undefined;
+ if (onEntry && !isEntryField(field)) throw new Error(`${field} is not a field an entry's draft may set (${Object.keys(DRAFTED_ENTRY_FIELDS).join(", ")})`);
+ if (!onEntry && !isManifestField(field)) throw new Error(`${field} is not a manifest field a draft may set (${DRAFTED_MANIFEST_FIELDS.join(", ")})`);
+}
+
+function setMark(manifest, { entry = null, field }, provenance) {
+ if (entry !== null && entry !== undefined) {
+ for (const e of entriesWithId(manifest, entry)) e.drafted = { ...(isObj(e.drafted) ? e.drafted : {}), [field]: { ...provenance } };
+ } else {
+ manifest.drafted = { ...(isObj(manifest.drafted) ? manifest.drafted : {}), [field]: { ...provenance } };
+ }
+}
+
+/**
+ * THE writer every draft task uses. Sets the field to `value` and marks it
+ * drafted -- unless the field is the operator's (non-empty, no mark), which is
+ * never replaced, `force` or not; or is a draft already and `force` is not set.
+ * The caller keeps a refused value as an alternative (`<task>-draft.json`).
+ * Mutates `manifest`.
+ *
+ * applied: true
+ * applied: false, reason "operator" a field somebody wrote or edited
+ * applied: false, reason "drafted" a draft already, and no `force`
+ * applied: false, reason "missing" no entry with that id, or (flips,
+ * threads) no `render.chrome` to hold it
+ *
+ * An entry id names every entry with it (variant twins). "timeline" takes the
+ * new timeline array; "render.chrome.threads" takes `{ list }` (the task sets
+ * each clip's `thread` key itself once applied).
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string, value: unknown, provenance: Record<string, unknown>, force?: boolean }} o
+ * @returns {{ applied: true } | { applied: false, reason: "operator" | "drafted" | "missing" }}
+ */
+export function applyDraft(manifest, { entry = null, field, value, provenance, force = false }) {
+ const target = { entry, field };
+ assertTarget(target);
+ const bad = provenanceProblems(provenance, "provenance");
+ if (bad.length) throw new Error(bad.join("; "));
+ const onEntry = entry !== null && entry !== undefined;
+ if (onEntry) {
+ const es = entriesWithId(manifest, entry);
+ if (!es.length) return { applied: false, reason: "missing" };
+ const types = DRAFTED_ENTRY_FIELDS[field];
+ if (types && !es.every((e) => types.includes(e.type))) throw new Error(`${entry} is a ${es[0].type}: ${field} is drafted only on a ${types.join(" or ")}`);
+ } else if (field.startsWith("render.chrome.") && !isObj(manifest?.render?.chrome)) {
+ return { applied: false, reason: "missing" };
+ }
+ const owner = ownerOf(manifest, target);
+ if (owner === "operator") return { applied: false, reason: "operator" };
+ if (owner === "drafted" && !force) return { applied: false, reason: "drafted" };
+ const copy = () => (value === undefined ? undefined : JSON.parse(JSON.stringify(value)));
+ if (onEntry) {
+ for (const e of entriesWithId(manifest, entry)) e[field] = copy();
+ } else if (field === "timeline") {
+ manifest.timeline = copy();
+ } else {
+ const parts = pathParts(field);
+ let cur = manifest;
+ for (const p of parts.slice(0, -1)) {
+ if (!isObj(cur[p])) cur[p] = {};
+ cur = cur[p];
+ }
+ cur[parts.at(-1)] = copy();
+ }
+ setMark(manifest, target, provenance);
+ return { applied: true };
+}
+
+/**
+ * Remove a field's drafted mark (the operator's edit). True when there was one.
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ */
+export function clearDrafted(manifest, { entry = null, field }) {
+ let had = false;
+ if (entry !== null && entry !== undefined) {
+ for (const e of entriesWithId(manifest, entry)) {
+ if (!isObj(e.drafted) || !(field in e.drafted)) continue;
+ had = true;
+ delete e.drafted[field];
+ if (!Object.keys(e.drafted).length) delete e.drafted;
+ }
+ return had;
+ }
+ if (isObj(manifest?.drafted) && field in manifest.drafted) {
+ had = true;
+ delete manifest.drafted[field];
+ if (!Object.keys(manifest.drafted).length) delete manifest.drafted;
+ }
+ return had;
+}
+
+/** JSON with every object's keys sorted: one text per value, whatever order it was built in. */
+export function stableStringify(v) {
+ if (Array.isArray(v)) return `[${v.map((x) => (x === undefined ? "null" : stableStringify(x))).join(",")}]`;
+ if (isObj(v)) {
+ return `{${Object.keys(v)
+ .filter((k) => v[k] !== undefined)
+ .sort()
+ .map((k) => `${JSON.stringify(k)}:${stableStringify(v[k])}`)
+ .join(",")}}`;
+ }
+ return JSON.stringify(v ?? null);
+}
+
+/**
+ * What a field IS, for telling an edit from no edit and for a review's key: the
+ * value -- except "timeline", whose draft is the ORDER (the entries' ids), and
+ * "render.chrome.threads", which is the list and every clip's `thread` key.
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ */
+export function fieldSignature(manifest, target) {
+ if ((target.entry === null || target.entry === undefined) && target.field === "timeline") {
+ return (Array.isArray(manifest?.timeline) ? manifest.timeline : []).map((e) => e?.id ?? null);
+ }
+ if ((target.entry === null || target.entry === undefined) && target.field === "render.chrome.threads") {
+ const clips = {};
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) if (isObj(e) && e.thread !== undefined) clips[e.id] = e.thread;
+ return { threads: readField(manifest, target) ?? null, clips };
+ }
+ return readField(manifest, target) ?? null;
+}
+
+/** A value's content key: sha256 of its stable JSON, hex. */
+export function valueKey(v) {
+ return createHash("sha256").update(stableStringify(v)).digest("hex");
+}
+
+/**
+ * A field's content key (`fieldSignature` hashed). A review's verdict is on
+ * this key, so an edit or a re-draft leaves it unapproved. (A card's narration
+ * is keyed by umtool's `narrationKey` instead -- the words and the voice --
+ * report-to-video/drafts-review.mjs.)
+ */
+export function fieldKey(manifest, target) {
+ return valueKey(fieldSignature(manifest, target));
+}
+
+/**
+ * Every drafted field of a manifest, in timeline order then the manifest's:
+ * `{ entry, field, provenance, value }`. An entry id is listed once (variant
+ * twins share a field). Orphans (a mark on an empty field) are left out.
+ *
+ * @param {any} manifest
+ * @returns {{ entry: string | null, field: string, provenance: Record<string, unknown>, value: unknown }[]}
+ */
+export function draftedFields(manifest) {
+ const out = [];
+ const seen = new Set();
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) {
+ if (!isObj(e) || !isObj(e.drafted)) continue;
+ for (const [field, p] of Object.entries(e.drafted)) {
+ const k = `${e.id}\u0000${field}`;
+ if (seen.has(k) || !isEntryField(field) || !isObj(p) || isEmptyField(field, e[field])) continue;
+ seen.add(k);
+ out.push({ entry: e.id, field, provenance: p, value: e[field] });
+ }
+ }
+ if (isObj(manifest?.drafted)) {
+ for (const field of DRAFTED_MANIFEST_FIELDS) {
+ const p = manifest.drafted[field];
+ const value = readField(manifest, { field });
+ if (!isObj(p) || isEmptyField(field, value)) continue;
+ out.push({ entry: null, field, provenance: p, value });
+ }
+ }
+ return out;
+}
+
+/** The review address of a field: `<its task>/<entry id or *>/<field>`. */
+export function reviewAddress({ entry = null, field }) {
+ const task = FIELD_TASKS[field] ?? "draft";
+ return `${task}/${entry === null || entry === undefined ? "*" : entry}/${field}`;
+}
+
+/** An address back to its parts, or null. */
+export function parseReviewAddress(address) {
+ if (typeof address !== "string") return null;
+ const m = /^([A-Za-z0-9_-]{1,64})\/([^/]{1,200})\/([A-Za-z0-9_.-]{1,64})$/.exec(address);
+ if (!m) return null;
+ const [, task, entry, field] = m;
+ return { task, entry: entry === "*" ? null : entry, field };
+}
+
+/**
+ * The marks whose field is gone or empty (or whose key is not a field at
+ * all), as `{ where, entry, field }`. Read-only: `pruneDrafted` drops them.
+ *
+ * @param {any} manifest
+ */
+export function orphanDrafts(manifest) {
+ const out = [];
+ (Array.isArray(manifest?.timeline) ? manifest.timeline : []).forEach((e, i) => {
+ if (!isObj(e) || !isObj(e.drafted)) return;
+ for (const field of Object.keys(e.drafted)) {
+ if (isEntryField(field) && isEmptyField(field, e[field])) out.push({ where: `timeline[${i}] (${e.id}).drafted.${field}`, entry: e.id, field });
+ }
+ });
+ if (isObj(manifest?.drafted)) {
+ for (const field of Object.keys(manifest.drafted)) {
+ if (isManifestField(field) && isEmptyField(field, readField(manifest, { field }))) out.push({ where: `drafted["${field}"]`, entry: null, field });
+ }
+ }
+ return out;
+}
+
+/**
+ * Drop every orphan mark (and a `drafted` map left empty). Mutates; returns a
+ * sentence per mark dropped.
+ *
+ * @param {any} manifest
+ * @returns {string[]}
+ */
+export function pruneDrafted(manifest) {
+ const dropped = orphanDrafts(manifest);
+ for (const o of dropped) {
+ if (o.entry === null) clearDrafted(manifest, { field: o.field });
+ else {
+ for (const e of Array.isArray(manifest.timeline) ? manifest.timeline : []) {
+ if (!isObj(e) || e.id !== o.entry || !isObj(e.drafted) || !(o.field in e.drafted) || !isEmptyField(o.field, e[o.field])) continue;
+ delete e.drafted[o.field];
+ if (!Object.keys(e.drafted).length) delete e.drafted;
+ }
+ }
+ }
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) if (isObj(e) && isObj(e.drafted) && !Object.keys(e.drafted).length) delete e.drafted;
+ if (isObj(manifest?.drafted) && !Object.keys(manifest.drafted).length) delete manifest.drafted;
+ return dropped.map((o) => `${o.where}: its field is gone, so the drafted mark is dropped`);
+}
+
+/**
+ * The operator's write: every drafted field whose value differs between
+ * `before` and `after` loses its mark in `after` (it is the operator's now),
+ * and orphans are dropped. Mutates `after`; returns the fields cleared as
+ * `{ entry, field }`. What umtool's manifest writer runs on every write.
+ *
+ * @param {any} before
+ * @param {any} after
+ */
+export function clearEditedDrafts(before, after) {
+ const cleared = [];
+ for (const d of draftedFields(after)) {
+ const t = { entry: d.entry, field: d.field };
+ // A mark that was not there before is the writer's own (a draft applied in
+ // this write): leave it.
+ if (!draftedOf(before, t)) continue;
+ if (stableStringify(fieldSignature(before, t)) !== stableStringify(fieldSignature(after, t))) {
+ clearDrafted(after, t);
+ cleared.push(t);
+ }
+ }
+ pruneDrafted(after);
+ return cleared;
+}
+
+/**
+ * Every reason the manifest's drafted marks cannot be built: a mark that is
+ * not a provenance, or one in a place no field may be drafted (an unknown
+ * field, `narration` on a clip, `lines` on a card, a `drafted` key under the
+ * render block or `publish`). An orphan is NOT an error (`orphanDrafts`).
+ *
+ * @param {any} manifest
+ * @returns {string[]}
+ */
+export function validateDrafted(manifest) {
+ const errors = [];
+ if (manifest?.drafted !== undefined) {
+ if (!isObj(manifest.drafted)) errors.push("drafted must be an object of field path → provenance");
+ else {
+ for (const [k, p] of Object.entries(manifest.drafted)) {
+ if (!isManifestField(k)) {
+ errors.push(`drafted["${k}"] is not a manifest field a draft may set (${DRAFTED_MANIFEST_FIELDS.join(", ")}; an entry's own fields are marked on the entry)`);
+ continue;
+ }
+ errors.push(...provenanceProblems(p, `drafted["${k}"]`));
+ }
+ }
+ }
+ (Array.isArray(manifest?.timeline) ? manifest.timeline : []).forEach((e, i) => {
+ if (!isObj(e)) return;
+ for (const field of Object.keys(DRAFTED_ENTRY_FIELDS)) {
+ if (isObj(e[field]) && "drafted" in e[field]) errors.push(`timeline[${i}] (${e.id}).${field}.drafted: the mark goes on the entry (drafted.${field}), not inside the field`);
+ }
+ if (e.drafted === undefined) return;
+ const w = `timeline[${i}] (${e.id}).drafted`;
+ if (!isObj(e.drafted)) {
+ errors.push(`${w} must be an object of field → provenance`);
+ return;
+ }
+ for (const [field, p] of Object.entries(e.drafted)) {
+ if (!isEntryField(field)) {
+ errors.push(`${w}.${field} is not an entry field a draft may set (${Object.keys(DRAFTED_ENTRY_FIELDS).join(", ")})`);
+ continue;
+ }
+ const types = DRAFTED_ENTRY_FIELDS[field];
+ if (types && !types.includes(e.type)) errors.push(`${w}.${field}: a ${e.type ?? "entry"} has no ${field} to draft (only a ${types.join(" or ")})`);
+ errors.push(...provenanceProblems(p, `${w}.${field}`));
+ }
+ });
+ if (isObj(manifest?.render) && "drafted" in manifest.render) errors.push("render.drafted: a manifest field's mark goes in the top-level drafted map");
+ if (isObj(manifest?.publish)) {
+ if ("drafted" in manifest.publish) errors.push("publish.drafted: a manifest field's mark goes in the top-level drafted map");
+ if (isObj(manifest.publish.youtube) && "drafted" in manifest.publish.youtube) errors.push("publish.youtube.drafted: the mark goes in the top-level drafted map");
+ }
+ return errors;
+}
+
+/**
+ * `publish` (release 28): what is published beside the video. Only
+ * `publish.youtube { title, description }`, two strings, for now (M6 fills it).
+ *
+ * @param {any} manifest
+ * @returns {string[]}
+ */
+export function validatePublish(manifest) {
+ const p = manifest?.publish;
+ if (p === undefined) return [];
+ if (!isObj(p)) return ["publish must be an object ({ youtube })"];
+ const errors = [];
+ for (const k of Object.keys(p)) if (k !== "youtube" && k !== "drafted") errors.push(`publish.${k} is not a publish key (youtube)`);
+ const y = p.youtube;
+ if (y === undefined) return errors;
+ if (!isObj(y)) return [...errors, "publish.youtube must be { title, description }"];
+ for (const k of Object.keys(y)) if (k !== "title" && k !== "description" && k !== "drafted") errors.push(`publish.youtube.${k} is not a YouTube field (title, description)`);
+ for (const k of ["title", "description"]) {
+ if (typeof y[k] !== "string") {
+ errors.push(`publish.youtube.${k} must be a string`);
+ continue;
+ }
+ if (y[k].length > PUBLISH_YOUTUBE_LIMITS[k]) errors.push(`publish.youtube.${k} is ${y[k].length} characters (at most ${PUBLISH_YOUTUBE_LIMITS[k]})`);
+ }
+ if (typeof y.title === "string" && /[\r\n]/.test(y.title)) errors.push("publish.youtube.title must be one line");
+ return errors;
+}
diff --git a/common/lib/report/drafted.test.ts b/common/lib/report/drafted.test.ts
@@ -0,0 +1,183 @@
+// drafted.mjs (release 28, M0): the marks, the one draft writer, the
+// operator's edit, orphans, and the validators — over the S0 kit's `full`
+// manifest (every media field a draft task writes).
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import {
+ applyDraft,
+ clearEditedDrafts,
+ draftedFields,
+ draftedOf,
+ fieldKey,
+ makeProvenance,
+ orphanDrafts,
+ ownerOf,
+ parseReviewAddress,
+ pruneDrafted,
+ reviewAddress,
+ validateDrafted,
+ validatePublish,
+} from "./drafted.mjs";
+
+const full = () => JSON.parse(readFileSync(new URL("../../testing/draft/manifests/full.video.manifest.json", import.meta.url), "utf8"));
+const P = (o: Partial<{ task: string; attempt: number }> = {}) =>
+ makeProvenance({ task: o.task ?? "onscreen", model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 2, attempt: o.attempt ?? 1 });
+const entry = (m: { timeline: Record<string, any>[] }, id: string) => m.timeline.find((e) => e.id === id)!;
+
+test("applyDraft: an empty field is drafted and marked; the operator's is never replaced, force or not", () => {
+ const m = full();
+ // c02 has no on-screen text: a draft fills it and says so.
+ assert.deepEqual(applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "The oven" }, provenance: P() }), { applied: true });
+ assert.deepEqual(entry(m, "c02").onscreen, { title: "The oven" });
+ assert.deepEqual(entry(m, "c02").drafted, { onscreen: { task: "onscreen", model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 2, attempt: 1 } });
+ assert.equal(ownerOf(m, { entry: "c02", field: "onscreen" }), "drafted");
+ // c01's was written by hand: kept, with or without force.
+ const before = JSON.stringify(entry(m, "c01"));
+ assert.deepEqual(applyDraft(m, { entry: "c01", field: "onscreen", value: { title: "X" }, provenance: P() }), { applied: false, reason: "operator" });
+ assert.deepEqual(applyDraft(m, { entry: "c01", field: "onscreen", value: { title: "X" }, provenance: P(), force: true }), { applied: false, reason: "operator" });
+ assert.equal(JSON.stringify(entry(m, "c01")), before);
+ // A draft is re-drafted only with force.
+ assert.deepEqual(applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "Again" }, provenance: P({ attempt: 2 }) }), { applied: false, reason: "drafted" });
+ assert.deepEqual(applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "Again" }, provenance: P({ attempt: 2 }), force: true }), { applied: true });
+ assert.equal(entry(m, "c02").onscreen.title, "Again");
+ assert.equal(entry(m, "c02").drafted.onscreen.attempt, 2);
+ // No such entry; flips with no deck to hold them.
+ assert.deepEqual(applyDraft(m, { entry: "nope", field: "onscreen", value: { title: "x" }, provenance: P() }), { applied: false, reason: "missing" });
+ const bare = { timeline: [] as unknown[] };
+ assert.deepEqual(applyDraft(bare, { field: "render.chrome.flips", value: { pairs: [{}] }, provenance: P({ task: "flips" }) }), { applied: false, reason: "missing" });
+ // A field in the wrong place is the task's bug, thrown.
+ assert.throws(() => applyDraft(m, { entry: "c01", field: "narration", value: { text: "x" }, provenance: P() }), /narration is drafted only on a card/);
+ assert.throws(() => applyDraft(m, { field: "title", value: "x", provenance: P() }), /not a manifest field/);
+ assert.throws(() => applyDraft(m, { entry: "c03", field: "onscreen", value: { title: "x" }, provenance: { ...P(), attempt: 3 } as never }), /attempt must be 1 or 2/);
+});
+
+test("applyDraft: manifest fields — the teaser's lines on the entry, publish.youtube made, the cut's order; marks in the top-level map", () => {
+ const m = full();
+ // The fixture's teaser lines are hand-written: the operator's.
+ assert.deepEqual(applyDraft(m, { entry: "fin", field: "lines", value: ["a"], provenance: P({ task: "teaser" }), force: true }), { applied: false, reason: "operator" });
+ assert.deepEqual(applyDraft(m, { field: "publish.youtube", value: { title: "T", description: "D" }, provenance: P({ task: "youtube" }) }), { applied: true });
+ assert.deepEqual(m.publish, { youtube: { title: "T", description: "D" } });
+ assert.equal(m.drafted["publish.youtube"].task, "youtube");
+ // The threads exist and are the operator's.
+ assert.deepEqual(applyDraft(m, { field: "render.chrome.threads", value: { list: [] }, provenance: P({ task: "threads" }), force: true }), { applied: false, reason: "operator" });
+ // A cut's timeline with no mark is the operator's (M1 decides what the converter's order counts as).
+ assert.equal(ownerOf(m, { field: "timeline" }), "operator");
+ assert.deepEqual(validateDrafted(m), []);
+ assert.deepEqual(validatePublish(m), []);
+ assert.deepEqual(draftedFields(m).map((d) => [d.entry, d.field]), [[null, "publish.youtube"]]);
+});
+
+test("an operator's edit clears the mark; an untouched field keeps it; each field by its own signature", () => {
+ const m = full();
+ applyDraft(m, { entry: "c02", field: "onscreen", value: { title: "The oven" }, provenance: P() });
+ m.drafted = {
+ timeline: P({ task: "cut" }),
+ "render.chrome.threads": P({ task: "threads" }),
+ "publish.youtube": P({ task: "youtube" }),
+ };
+ m.publish = { youtube: { title: "T", description: "D" } };
+ entry(m, "the-contest").drafted = { narration: P({ task: "narrate" }) };
+ entry(m, "fin").drafted = { lines: P({ task: "teaser" }) };
+ const base = JSON.parse(JSON.stringify(m));
+
+ // Each field edited alone clears only its own mark.
+ const edits: [string, (x: any) => void, string | null, string][] = [
+ ["onscreen", (x) => (entry(x, "c02").onscreen = { title: "Hand" }), "c02", "onscreen"],
+ ["narration", (x) => (entry(x, "the-contest").narration.text = "Mine now."), "the-contest", "narration"],
+ ["lines", (x) => (entry(x, "fin").lines = ["One", "Two", "Three"]), "fin", "lines"],
+ ["order", (x) => x.timeline.splice(3, 0, x.timeline.splice(2, 1)[0]), null, "timeline"],
+ ["a clip's thread", (x) => (entry(x, "c02").thread = "contest"), null, "render.chrome.threads"],
+ ["youtube", (x) => (x.publish.youtube.title = "Mine"), null, "publish.youtube"],
+ ];
+ for (const [what, edit, id, field] of edits) {
+ const after = JSON.parse(JSON.stringify(base));
+ edit(after);
+ const cleared = clearEditedDrafts(base, after);
+ assert.deepEqual(cleared, [{ entry: id, field }], what);
+ assert.equal(draftedOf(after, { entry: id, field }), null, what);
+ assert.equal(ownerOf(after, { entry: id, field }), "operator", what);
+ assert.equal(draftedFields(after).length, draftedFields(base).length - 1, `${what}: the others keep theirs`);
+ }
+ // An edit elsewhere in the entry (its on-screen text) leaves the cut's order and the narration drafted.
+ const same = JSON.parse(JSON.stringify(base));
+ entry(same, "c01").onscreen.title = "Edited";
+ assert.deepEqual(clearEditedDrafts(base, same), []);
+ // A mark the write itself made (a draft applied in it) is the writer's, kept.
+ const fresh = JSON.parse(JSON.stringify(base));
+ applyDraft(fresh, { entry: "c03", field: "onscreen", value: { title: "New" }, provenance: P() });
+ assert.deepEqual(clearEditedDrafts(base, fresh), []);
+ assert.equal(draftedOf(fresh, { entry: "c03", field: "onscreen" })?.task, "onscreen");
+});
+
+test("orphans: a mark whose field is gone is listed, then dropped with a sentence; validation does not refuse it", () => {
+ const m = full();
+ entry(m, "c03").drafted = { onscreen: P() };
+ m.drafted = { "render.chrome.flips": P({ task: "flips" }) };
+ assert.deepEqual(validateDrafted(m), []);
+ assert.deepEqual(orphanDrafts(m).map((o) => o.where), ["timeline[4] (c03).drafted.onscreen", 'drafted["render.chrome.flips"]']);
+ const said = pruneDrafted(m);
+ assert.equal(said.length, 2);
+ assert.match(said[0]!, /its field is gone, so the drafted mark is dropped/);
+ assert.equal(entry(m, "c03").drafted, undefined);
+ assert.equal(m.drafted, undefined);
+ assert.deepEqual(orphanDrafts(m), []);
+});
+
+test("validateDrafted: a mark where no field may be drafted, or not a provenance, is refused", () => {
+ const m = full();
+ entry(m, "c01").drafted = { onscreen: P(), quote: P() };
+ entry(m, "title").drafted = { lines: P() };
+ entry(m, "c02").drafted = { narration: P() };
+ entry(m, "c04").drafted = { onscreen: { task: "", model: "m", at: "yesterday", attempt: 1, extra: true } };
+ entry(m, "c05").onscreen = { title: "x", drafted: P() } as never;
+ m.drafted = { title: P(), timeline: P({ task: "cut" }) };
+ m.render.drafted = {};
+ const errors = validateDrafted(m);
+ for (const re of [
+ /\(c01\)\.drafted\.quote is not an entry field a draft may set/,
+ /\(title\)\.drafted\.lines: a card has no lines to draft \(only a teaser\)/,
+ /\(c02\)\.drafted\.narration: a clip has no narration to draft \(only a card\)/,
+ /\(c04\)\.drafted\.onscreen\.extra is not a provenance key/,
+ /\(c04\)\.drafted\.onscreen\.task must be a name/,
+ /\(c04\)\.drafted\.onscreen\.at must be an ISO date and time/,
+ /\(c05\)\.onscreen\.drafted: the mark goes on the entry/,
+ /drafted\["title"\] is not a manifest field a draft may set/,
+ /render\.drafted: a manifest field's mark goes in the top-level drafted map/,
+ ]) {
+ assert.ok(errors.some((e) => re.test(e)), `${re}\n${errors.join("\n")}`);
+ }
+ assert.equal(errors.length, 9, errors.join("\n"));
+});
+
+test("validatePublish: publish.youtube is two strings, YouTube's limits; nothing else under publish", () => {
+ assert.deepEqual(validatePublish({}), []);
+ assert.deepEqual(validatePublish({ publish: { youtube: { title: "T", description: "" } } }), []);
+ const bad = validatePublish({ publish: { youtube: { title: "a\nb", description: 3, tags: [] }, x: 1 } });
+ assert.deepEqual(bad, [
+ "publish.x is not a publish key (youtube)",
+ "publish.youtube.tags is not a YouTube field (title, description)",
+ "publish.youtube.description must be a string",
+ "publish.youtube.title must be one line",
+ ]);
+ assert.match(validatePublish({ publish: { youtube: { title: "t".repeat(101), description: "" } } })[0]!, /101 characters \(at most 100\)/);
+ assert.deepEqual(validatePublish({ publish: [] }), ["publish must be an object ({ youtube })"]);
+});
+
+test("review addresses and keys: one address per field, a key that moves with the value", () => {
+ assert.equal(reviewAddress({ entry: "k1", field: "narration" }), "narrate/k1/narration");
+ assert.equal(reviewAddress({ field: "render.chrome.flips" }), "flips/*/render.chrome.flips");
+ assert.equal(reviewAddress({ entry: "c01", field: "onscreen" }), "onscreen/c01/onscreen");
+ assert.deepEqual(parseReviewAddress("teaser/fin/lines"), { task: "teaser", entry: "fin", field: "lines" });
+ assert.deepEqual(parseReviewAddress("cut/*/timeline"), { task: "cut", entry: null, field: "timeline" });
+ assert.equal(parseReviewAddress("no"), null);
+ const m = full();
+ const k = fieldKey(m, { entry: "c01", field: "onscreen" });
+ assert.equal(fieldKey(JSON.parse(JSON.stringify(m)), { entry: "c01", field: "onscreen" }), k, "same value, same key");
+ // Key order in the object does not matter.
+ entry(m, "c01").onscreen = { subtitle: entry(m, "c01").onscreen.subtitle, title: entry(m, "c01").onscreen.title };
+ assert.equal(fieldKey(m, { entry: "c01", field: "onscreen" }), k);
+ entry(m, "c01").onscreen.title = "Edited";
+ assert.notEqual(fieldKey(m, { entry: "c01", field: "onscreen" }), k);
+});
diff --git a/common/package.json b/common/package.json
@@ -35,6 +35,7 @@
"./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs",
"./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
+ "./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
"./lib/report/verdicts.mjs": "./lib/report/verdicts.mjs",
"./lib/toolProbe.mjs": "./lib/toolProbe.mjs",
"./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs",
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,9 @@
# Changelog
## [Unreleased]
+- **A drafted field of a report video says it was drafted, and a final build refuses it until it is approved.** A field a generation task writes (a card's narration today; on-screen text, a teaser's lines, the cut's order, the flips, the threads and the YouTube text as their tasks land) carries `drafted` — who drafted it, on which model, when — in the manifest. umtool shows **drafted by <model>** and its review state beside the field (the On-screen table, the teaser editor, the narration page) with **Approve** and **Reject** (with a note), and `/browse/<project>/review` (**Review drafts — N** on the project page) lists every drafted field of the cut and what a final build would refuse. Verdicts are kept in `drafts.review.json` beside the manifest, each on the value it was given on, so a re-draft or an edit needs approving again. A **final** build refuses a drafted field not approved (`--drafts-unreviewed` builds the unapproved anyway, never a rejected one); preview and fast builds only warn. A narration written by hand keeps the rule it had, and existing `narration.review.json` verdicts read as they were (new ones are written to `drafts.review.json`).
+- **A draft never overwrites what you wrote.** A field with words in it and no `drafted` mark is yours: no generation task replaces it, even when asked to redraft. Its draft is kept aside in `<task>-draft.json` and shown under the field in umtool with **Use this**, which writes it as your own edit. Editing a drafted field in umtool makes it yours (its mark goes).
+- **A report video manifest may carry `publish.youtube { title, description }`** — two strings, a title of at most 100 characters — for the YouTube text a later task drafts.
- **Articles, iterations, report-video projects and takes can be deleted, and every delete shows its plan first.** `archilyzer reports delete <id>` prints what would go — each path with its size, what is kept and why, and anything that stops it — and deletes nothing until `--apply`; `--iteration <n>` deletes one iteration. Deleting an article removes its directory (report, video, history, notes, iterations), each iteration's video project under `settings.generation.projectsRoot` and its staged exports. A published article is refused unless `--force`, which unpublishes it first; an article with a running iteration is always refused. An iteration is refused while it is the current article or video, the one the article's report came from, running, or the parent or original of another iteration, and its number is never given out again. The usage ledger, the shared prepared-media cache and the corpus's git history are kept. The same deletes run over HTTP as `pnpm ops delete-article {id, force?, dryRun?}` and `pnpm ops delete-iteration {id, n, dryRun?}`, which answer a refusal as a 409 with the plan.
- **umtool: Delete article, `Delete i<n>`, Delete project and `Delete take <id>`.** Each button reads the plan, shows it (what goes with sizes, what is kept, what refuses) and deletes only on **Confirm delete**; **Keep it** closes it. **Delete article** is on an article's page (one in the making too) and returns to `/articles`, which says what went; `Delete i<n>` is on each iteration of the Iterations tab. **Delete project** on a report-video project removes its directory, and its `out/` or deliverables on the media drive when they are its own copy; it is refused while a job works in the project, for an article's current video, and — unless you tick **delete anyway** — for a project whose manifest names an article with a video attached. `Delete take <id>` removes `takes/<id>/`; the take whose manifest is the project's own needs **delete anyway**, and its verdict and notes are kept.
- **Reports and their revisions can be generated by the editor: `pnpm ops report-draft`.** `{"task": "sweep", "article", "question", "channels"}` drafts a new report of an article as its next iteration; `{"task": "revise-report" | "revise-video", "article", "iteration", "feedback"}` revises one; `{"task": "narrate", "article", "iteration"}` drafts the narration of an iteration's video cut; `"copyOf": N` runs iteration N again on another `"model"`. Each is a **Report draft** job on /jobs, on the Claude API (`draft:api`) or the local model (`draft:local`) by the model, and `pnpm ops job cancel` stops one. Every quote a model writes must be the transcript's words within 90 seconds of its link, or the finding is dropped; links cite the archive, never the platform. The answer names the job and the iteration; the job's log ends with the outcome. Needs a restart of the editor.
diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts
@@ -303,8 +303,9 @@ test("narrate: a step on a done iteration; a quote read out is re-asked; the man
assert.equal(revisions.length, 1);
assert.match(revisions[0]!, /-auto-before-narration\.manifest\.json$/);
const draft = JSON.parse(await readFile(path.join(projectDir!, "narration-draft.json"), "utf8"));
- assert.equal(draft["the-bakery"].attempts.length, 2);
- assert.match(draft["the-bakery"].attempts[0].hard.join(" "), /quotation marks|quote/);
+ assert.equal(draft.units["the-bakery"].attempts.length, 2);
+ assert.match(draft.units["the-bakery"].attempts[0].hard.join(" "), /quotation marks|quote/);
+ assert.equal(cards["the-bakery"].drafted.narration.task, "narrate", "a narration it writes carries its drafted mark");
// The prompts carry rules, never worked examples, and no tag rule.
const sys = ol.requests.at(-1).messages[0].content as string;
assert.ok(!sys.includes("One file. No title."), "no worked example");
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -9185,3 +9185,50 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
ops batch as a `structuredAnswer`; a revision with no ops at all is a failing `ops` check, never "done, 0 applied".
- **The stopgap's `~/.config/archilyzer/generation.json` is retired** (absent on this machine at 2026-10-13); its runs
come in once through `archilyzer reports import-local-runs` (`common/bin/reports-import-local-runs.ts`).
+
+## Drafted fields and the drafts review (verified 2026-10-13, release 28 M0, branch `r28/framework`)
+
+- **The mark.** `common/lib/report/drafted.mjs` (plain JS, typed by `drafted.d.mts`, exported as
+ `yt-dlp-transcript-common/lib/report/drafted.mjs`) is the one copy. A provenance is
+ `{ task, model, at, iteration?, attempt }` (`at` ISO, `attempt` 1 or 2). Entry fields:
+ `entry.drafted.{onscreen | narration | lines}` (on-screen on any entry, narration on a card, lines on a teaser).
+ Manifest fields: the top-level `drafted` map keyed by path — `timeline` (the cut's ORDER: the entries' ids),
+ `render.chrome.flips`, `render.chrome.threads` (the list AND every clip's `thread` key), `publish.youtube`.
+ `validateDrafted` refuses a mark anywhere else or not a provenance; an orphan (a mark whose field is empty) is
+ not an error: the lint warns, `pruneDrafted` drops it.
+- **`publish` is a new top-level manifest key**: only `publish.youtube { title, description }`, two strings, title
+ one line ≤ 100, description ≤ 5000 (`validatePublish`; the build, the lint and umtool's structural writes run it).
+- **Who owns a field** (`ownerOf`): empty → nobody; a value with a mark → the draft; a value with NO mark → the
+ operator. `applyDraft(manifest, { entry?, field, value, provenance, force? })` is the one writer every task
+ uses: `{ applied: true }` or `{ applied: false, reason: "operator" | "drafted" | "missing" }`. The operator's
+ field is never replaced, `force` or not; `force` only re-drafts a field still marked. An entry id names every
+ entry with it (variant twins). A timeline with no `drafted.timeline` is the operator's — M1 decides what the
+ converter's order counts as.
+- **An edit clears the mark.** umtool's manifest writer (`lib/report/manifest.mjs` `writeManifestAtomic`)
+ re-reads the file and runs `clearEditedDrafts(before, after)` on EVERY write: a marked field whose
+ `fieldSignature` changed loses its mark; orphans go. A mark the write itself added is kept. `writeDraftedField`
+ is "Use this" (onscreen, lines, narration, flips, threads, publish.youtube; not `timeline`).
+- **The review file** is `<project>/drafts.review.json`, `{ "<task>/<entry id | *>/<field>": { verdict:
+ "approved" | "rejected" | null, note, key, text, at } }` (`umtool/report-to-video/drafts-review.mjs`). The
+ address's task is the FIELD's own (`FIELD_TASKS`: onscreen→`onscreen`, narration→`narrate`, lines→`teaser`,
+ timeline→`cut`, flips→`flips`, threads→`threads`, publish.youtube→`youtube`), whichever task drafted it.
+ `key` is `narrationKey` for a narration (words + voice), else `fieldKey` (sha256 of the stable JSON of
+ `fieldSignature`). Release 25's `narration.review.json` (`{ <cardId>: row }`) is READ as
+ `narrate/<cardId>/narration`; the drafts file wins; nothing writes the old file. A cleared row the old file
+ still has stays in the drafts file as an empty verdict so the old approval does not show through.
+- **The gate** (`draftsReviewProblems`, run by the lint): a marked field not approved on its current key is a
+ warning (one line) in preview/fast and an ERROR with `--final` unless `--drafts-unreviewed`
+ (`--narration-unreviewed` too for a narration); rejected is an error in final whatever the flags, a warning
+ otherwise. A narration with NO mark keeps release 25's rule in every build, where "the narration has a review"
+ now means a narration row in either file (an onscreen verdict does not start it). The driver's `final` preset
+ passes `--final`; `fast` and `preview` do not.
+- **The media task scaffold** is `common/lib/report/draft/tasks/media.ts` (`runMediaTask(spec, input, deps)`,
+ exported from `tasks/index.ts`). A spec: `task`, `units(ctx)` (a unit `{ id, target: { entry?, field } }` or a
+ skip `{ id, skipped }`), `schema`, `system`, `user`, `parse`, `check` → `{ hard, soft }`, and optional `score`,
+ `repair`, `retry`, `toField`, `afterApply`, `apply`, `draftFile`, `snapshotOp`, `checkName`, `turnKind`,
+ `noun`, `verb`, `describe`. A unit whose field has a value is skipped unless `force`. The draft file
+ (`<task>-draft.json`; narrate keeps `narration-draft.json`) is `{ task, model, at, article, iteration, units:
+ { <id>: { target, attempts, chosen, applied | skipped } }, checks, alternatives: [{ target, value, provenance,
+ reason }] }`; alternatives from earlier runs are carried over, newest five per field. The step is recorded in
+ the iteration's `steps` (a done iteration's status is left). umtool reads alternatives from every
+ `*-draft.json` beside the manifest (`lib/report/drafts.mjs` `readAlternatives`).
diff --git a/plans/release-28.md b/plans/release-28.md
@@ -244,6 +244,51 @@ source-mirror publish; the hub deploy (H6). No public site changes otherwise.
Gates: common tsc clean; `testing/fakes.test.ts` 10/10; `fixtures-r28.test.mjs` 3/3.
+### M0, as shipped (2026-10-13, lane A, `r28/framework`)
+
+The draft framework, the drafts review and the final gate, as the orchestrator's eight M0 rulings, with narration
+moved onto them. The rulings held as given, with these as built:
+- `applyDraft`'s refusals are `operator`, `drafted` (a draft already, no `force`) and `missing` (no such entry, or
+ flips/threads with no `render.chrome`); a field in the wrong place (narration on a clip) throws.
+- A review address's `<task>` is the FIELD's own (`onscreen`, `narrate`, `teaser`, `cut`, `flips`, `threads`,
+ `youtube`), whichever task drafted it, so a field has one address; narration's is `narrate/<cardId>/narration`.
+- A drafted narration follows the drafts gate (a warning in fast, refused in final); one with no mark keeps
+ release 25's rule in every build. "The narration has a review" is now a narration row in either file, so an
+ on-screen verdict does not start it.
+- Narrate's audit file kept its name, `narration-draft.json`, in the scaffold's shape (`units`, `alternatives`);
+ `mcp/src/draftTasks.test.ts`'s narrate test reads `units[...]` (two lines, lane B's file) and asserts the mark.
+- Badges (ruling 8): the narration page STAYS (it edits and plays the words) and writes the new file; the general
+ page is `/browse/<project>/review`, linked as **Review drafts — N**. Badges sit in the On-screen table's title
+ cell, the teaser editor and the narration page.
+- "Use this" writes onscreen, lines, narration, flips, threads and publish.youtube; not the cut's order (an order
+ replaces every entry: the cut task's to apply). A timeline with no `drafted.timeline` is the operator's — M1
+ decides what the converter's order counts as.
+
+| Commit | What |
+| --- | --- |
+| `e4fe6039` | common: `drafted.mjs` (+ `.d.mts`): the marks, `applyDraft`, `clearEditedDrafts`, `pruneDrafted`, `validateDrafted`, `validatePublish`, review addresses and keys; `tasks/media.ts`, the scaffold (`runMediaTask`); narrate refactored onto it |
+| `994fc97b` | umtool: `report-to-video/drafts-review.mjs` (the file, release 25's read unchanged, the gate); the lint and build-video (`--final`, `--drafts-unreviewed`); the driver's `final` passes `--final`; the manifest writer clears an edited draft's mark; `writeDraftedField`; `lib/report/drafts.mjs` and `/api/report/drafts` |
+| `1b185182` | umtool: the badges, the alternatives with **Use this**, `/browse/<project>/review` |
+| `f281b714` | umtool: e2e `draft-review.spec.ts` and its fixtures; `narration-review.spec.ts` reads the drafts file |
+| `da4b123e` | the README's drafts review section, umtool's report-video doc; the scaffold exported from `tasks/index.ts` |
+| (this commit) | this record, FACTS "Drafted fields and the drafts review", CHANGELOG |
+
+Gates (from the worktree root):
+- `pnpm -r exec tsc --noEmit`: clean at every commit.
+- common: 4018 (2 failing, flaky at the branch's start) → 4029, all pass (+11: `drafted.test.ts` 7,
+ `media.test.ts` 4).
+- `test:scripts`: 863 (+3 skipped) → 874; 869 pass + 3 skipped, 2 failing in `scripts/queue-lock.test.mjs`
+ (timing, H2's flake) under the full run, 37/37 alone (+11: `drafts-review.test.mjs` 7, `drafted-writer.test.mjs`
+ 3, `drafts.test.mjs` 1).
+- mcp 343/343; editor 288/288.
+- `docs env|files|cli --check` and `settings example --check`: clean.
+- umtool capped build, corpus linked, through the heavy slot: compiled in 10.2 s (83 s with 50 s waiting for memory).
+- umtool e2e, single specs in the foreground: `draft-review.spec.ts` 3/3 (6.9 s; a real offline final build:
+ refused, approved on the review page, built); `narration-review.spec.ts` + `build.spec.ts` 8 (1 failure:
+ narration-review read the old file, fixed) then `narration-review.spec.ts` + `onscreen.spec.ts` 10/10;
+ `timeline-edit.spec.ts` + `undo.spec.ts` 9/9.
+
+Left for phase 2: the media tasks themselves (M1–M6) on the scaffold; `TaskDeps.progress` (F3) is not wired.
### F4, H4, H6, as run (2026-10-13, orchestrator, phase 1)
- **F4:** the stopgap retired. Its two remaining runs were already iterations (`piratesoftware-ai-friends` i1,
diff --git a/umtool/app/api/report/drafts/route.ts b/umtool/app/api/report/drafts/route.ts
@@ -0,0 +1,85 @@
+import { invalidateProjects } from "@/lib/projects";
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, StructureRefused, manifestToken, writeDraftedField } from "@/lib/report/manifest.mjs";
+import { alternativeById, draftsView } from "@/lib/report/drafts.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { draftsReviewRows, readDraftsReview, setDraftReview } from "umtool-report-to-video/drafts-review";
+
+export const dynamic = "force-dynamic";
+
+// The drafts review (release 28, M0): every drafted field of a cut, its
+// review, and the alternatives the draft tasks kept.
+//
+// GET ?project=<id> the view (lib/report/drafts.mjs) and the token
+// POST { project, action, ... } one action:
+// approve { address, note? } approved on the field's CURRENT value
+// reject { address, note } rejected; the note says what is wrong (required)
+// clear { address } no verdict (the note is kept)
+// note { address, note } the note alone
+// use { alternative, token? } "Use this": the alternative (`<file>#<i>`) written
+// through the manifest writer as the operator's edit
+// (snapshot, validators, the edit-notes guard)
+//
+// Verdicts live in <project>/drafts.review.json (report-to-video's
+// drafts-review.mjs); a final build refuses a drafted field not approved.
+
+type Body = Record<string, unknown>;
+const noStore = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ return Response.json({ ...(await draftsView(r.project.dir, r.manifest)), token: await manifestToken(r.project.dir) }, { headers: noStore });
+}
+
+export async function POST(request: Request) {
+ let body: Body;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const dir = r.project.dir;
+ const note = typeof body.note === "string" ? body.note : undefined;
+ let editNotes = null;
+ try {
+ if (body.action === "use") {
+ const alt = await alternativeById(dir, String(body.alternative ?? ""));
+ if (!alt) return Response.json({ error: `no alternative ${String(body.alternative ?? "")}` }, { status: 404 });
+ const token = typeof body.token === "string" ? body.token : null;
+ const w = await withEditNotes(r.project, () => writeDraftedField(dir, { entry: alt.entry, field: alt.field, value: alt.value }, { token }));
+ editNotes = w.editNotes;
+ invalidateProjects();
+ } else {
+ const address = String(body.address ?? "");
+ const row = draftsReviewRows(r.manifest, await readDraftsReview(dir)).find((x: { address: string }) => x.address === address);
+ if (!row) return Response.json({ error: `${address || "(no address)"} is not a field this cut has to review` }, { status: 404 });
+ switch (body.action) {
+ case "approve":
+ await setDraftReview(dir, address, { verdict: "approved", key: row.key, text: row.text, ...(note !== undefined ? { note } : {}) });
+ break;
+ case "reject":
+ await setDraftReview(dir, address, { verdict: "rejected", key: row.key, text: row.text, note: note ?? "" });
+ break;
+ case "clear":
+ await setDraftReview(dir, address, { verdict: null });
+ break;
+ case "note":
+ await setDraftReview(dir, address, { note: note ?? "" });
+ break;
+ default:
+ return Response.json({ error: "action must be approve, reject, clear, note or use" }, { status: 400 });
+ }
+ }
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+ const fresh = await resolveReport(String(body.project));
+ const manifest = "error" in fresh ? r.manifest : fresh.manifest;
+ return Response.json({ ok: true, ...(await draftsView(dir, manifest)), token: await manifestToken(dir), editNotes }, { headers: noStore });
+}
diff --git a/umtool/app/api/report/narration/route.ts b/umtool/app/api/report/narration/route.ts
@@ -21,9 +21,11 @@ export const dynamic = "force-dynamic";
// writer (snapshot, validators, the edit-notes
// guard); an edit clears the verdict
//
-// Verdicts live in <project>/narration.review.json (report-to-video's
-// narration-review.mjs, takes/verdicts.json's shape); the build refuses an
-// un-approved narrated card once that file exists.
+// Verdicts live in <project>/drafts.review.json as `narrate/<cardId>/narration`
+// (report-to-video's narration-review.mjs over drafts-review.mjs; release 25's
+// narration.review.json is still read); the build refuses an un-approved
+// narrated card once the cut's narration has a verdict, and a final build a
+// drafted one.
type Body = Record<string, unknown>;
const noStore = { "cache-control": "no-store" };
diff --git a/umtool/components/projects/DraftsReview.tsx b/umtool/components/projects/DraftsReview.tsx
@@ -0,0 +1,89 @@
+"use client";
+
+import Link from "next/link";
+import { DraftAlternatives, DraftBadge, useDrafts, type DraftsView } from "./drafts";
+
+// `/browse/<project>/review`'s list (release 28, M0): every drafted field of
+// the cut -- who drafted it, its value as words, its review -- and every
+// alternative a draft task kept, with "Use this". A narration's words are
+// edited and played on the narration page; here they are judged like any
+// other draft.
+
+export default function DraftsReview({ project, initial }: { project: string; initial: DraftsView }) {
+ const { view, act } = useDrafts(project, initial);
+ const v = view ?? initial;
+ const drafted = v.rows.filter((r) => r.drafted);
+ const shown = new Set(drafted.map((r) => r.address));
+ // Alternatives for fields that are not drafted (the operator's), by field.
+ const loose = [...new Set(v.alternatives.filter((a) => !a.inUse && !shown.has(a.address)).map((a) => a.address))];
+ const where = (entry: string | null, field: string) => (entry ? `${entry}` : field);
+ return (
+ <div className="space-y-3">
+ <p
+ data-drafts-gate={v.gate.errors.length ? "refuses" : "passes"}
+ data-gate-errors={v.gate.errors.length}
+ className="text-[11px] text-[var(--color-dim)]"
+ >
+ {v.error ? (
+ <span className="text-[var(--color-bad)]">{v.error}</span>
+ ) : v.gate.errors.length ? (
+ <>
+ A final build refuses {v.gate.errors.length} field{v.gate.errors.length === 1 ? "" : "s"} until approved (
+ <code className="font-mono">--drafts-unreviewed</code> builds the unapproved anyway; never a rejected one).
+ </>
+ ) : (
+ <>A final build takes every draft as it is.</>
+ )}{" "}
+ Verdicts in <code className="font-mono">{v.file}</code>.
+ </p>
+ {drafted.length === 0 && loose.length === 0 && (
+ <p data-drafts-empty="" className="text-[12px] text-[var(--color-dim)]">
+ Nothing in this cut was drafted.{" "}
+ <Link href={`/browse/${project}`} className="text-[var(--color-sel)] hover:underline">
+ back to {project}
+ </Link>
+ </p>
+ )}
+ {drafted.map((r) => (
+ <article
+ key={r.address}
+ data-draft-row={r.address}
+ data-state={r.state}
+ className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"
+ >
+ <div className="mb-1 flex flex-wrap items-center gap-2">
+ <span className="font-mono text-[12px] text-[var(--color-text)]">{where(r.entry, r.field)}</span>
+ <span className="micro">{r.label}</span>
+ {r.field === "narration" && (
+ <Link href={`/browse/${project}/narration`} className="text-[11px] text-[var(--color-sel)] hover:underline">
+ edit and play on the narration page
+ </Link>
+ )}
+ </div>
+ <p data-draft-text="" className="mb-1 whitespace-pre-wrap text-[13px] text-[var(--color-text)]">
+ {r.text || "—"}
+ </p>
+ {r.state === "edited" && r.judgedText && (
+ <p className="mb-1 text-[11px] text-[var(--color-dim)]">
+ {r.verdict} on: <span className="italic">{r.judgedText}</span>
+ </p>
+ )}
+ <DraftBadge address={r.address} view={v} act={act} />
+ <DraftAlternatives address={r.address} view={v} act={act} />
+ </article>
+ ))}
+ {loose.map((address) => {
+ const a = v.alternatives.find((x) => x.address === address)!;
+ return (
+ <article key={address} data-draft-row={address} data-state="operator" className="rounded border border-[var(--color-line)] px-3 py-2">
+ <div className="mb-1 flex flex-wrap items-center gap-2">
+ <span className="font-mono text-[12px] text-[var(--color-text)]">{where(a.entry, a.field)}</span>
+ <span className="micro">{a.label} · yours; a draft was kept aside</span>
+ </div>
+ <DraftAlternatives address={address} view={v} act={act} />
+ </article>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/NarrationPage.tsx b/umtool/components/projects/NarrationPage.tsx
@@ -9,8 +9,9 @@ import NarrationReview, { type NarrationView } from "./NarrationReview";
// `/browse/<project>/narration` -- the cut's narration script, card by card,
// before synthesis (release 25, T5): each narrated card's words beside what
// the card shows, approved, edited or rejected, and played through the editor.
-// Verdicts are <project>/narration.review.json; the build refuses an
-// un-approved card once that file exists.
+// Verdicts are <project>/drafts.review.json (release 25's
+// narration.review.json still read); the build refuses an un-approved card
+// once the cut's narration has a verdict, and a final build a drafted one.
export default async function NarrationPage({ project }: { project: ProjectRef }) {
const manifest = await readManifest(project.dir);
const view = (await narrationReviewView(project.dir, manifest ?? {})) as NarrationView;
diff --git a/umtool/components/projects/NarrationReview.tsx b/umtool/components/projects/NarrationReview.tsx
@@ -3,6 +3,8 @@
import { useEffect, useRef, useState } from "react";
import { badgeVariants, type BadgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
+import { MANIFEST_CHANGED } from "./timelineApi";
+import { DraftAlternatives, useDrafts, type DraftAct, type DraftsView } from "./drafts";
// The narration script of one cut, card by card (release 25, T5).
//
@@ -27,6 +29,8 @@ export type NarrationRow = {
estimate: number;
seconds: number | string | null;
screen: { kicker: string | null; heading: string | null; sub: string | null; title: string | null; style: string | null };
+ /** Who drafted these words (release 28); null: written by hand. */
+ drafted: { task: string; model: string; at: string; iteration?: number; attempt: number } | null;
state: "approved" | "rejected" | "edited" | "unreviewed";
verdict: "approved" | "rejected" | null;
note: string;
@@ -57,6 +61,17 @@ export default function NarrationReview({ project, initial, token: initialToken
const [token, setToken] = useState(initialToken);
const [ready, setReady] = useState(false);
useEffect(() => setReady(true), []);
+ // The alternatives a draft task kept for a card whose words are the
+ // operator's (release 28); "Use this" rewrites the manifest, so re-read.
+ const drafts = useDrafts(project);
+ useEffect(() => {
+ const on = (e: Event) => {
+ if ((e as CustomEvent).detail?.project === project) void refresh();
+ };
+ window.addEventListener(MANIFEST_CHANGED, on);
+ return () => window.removeEventListener(MANIFEST_CHANGED, on);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [project]);
const act = async (card: string, action: string, extra: Record<string, unknown> = {}) => {
const r = await fetch("/api/report/narration", {
@@ -88,18 +103,18 @@ export default function NarrationReview({ project, initial, token: initialToken
) : view.exists ? (
<>
Verdicts in <code className="font-mono">{view.file}</code>: a build refuses any narrated card not approved on
- its current words (<code className="font-mono">--narration-unreviewed</code> builds them anyway; never a
- rejected one).
+ its current words — a drafted one, a final build (<code className="font-mono">--narration-unreviewed</code>{" "}
+ builds them anyway; never a rejected one).
</>
) : (
<>
Nothing judged yet. The first verdict writes <code className="font-mono">{view.file}</code>, and from then on a
- build refuses any narrated card not approved.
+ build refuses any narrated card not approved (a drafted one: a final build, judged or not).
</>
)}
</p>
{view.rows.map((r) => (
- <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} />
+ <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} drafts={drafts.view} draftAct={drafts.act} />
))}
</div>
);
@@ -111,12 +126,16 @@ function NarrationCard({
ready,
act,
refresh,
+ drafts,
+ draftAct,
}: {
project: string;
row: NarrationRow;
ready: boolean;
act: (card: string, action: string, extra?: Record<string, unknown>) => Promise<void>;
refresh: () => Promise<NarrationView | null>;
+ drafts: DraftsView | null;
+ draftAct: DraftAct;
}) {
const [text, setText] = useState(r.text);
const [note, setNote] = useState(r.note);
@@ -192,6 +211,15 @@ function NarrationCard({
<span data-narration-state="" className={badgeVariants({ variant: STATE[r.state].tone, size: "sm" })}>
{STATE[r.state].label}
</span>
+ {r.drafted && (
+ <span
+ data-narration-drafted={r.drafted.model}
+ className={badgeVariants({ variant: "info", size: "sm" })}
+ title={`drafted by ${r.drafted.task} on ${r.drafted.model}, ${r.drafted.at}`}
+ >
+ drafted by {r.drafted.model}
+ </span>
+ )}
<span className="font-mono text-[11px] text-[var(--color-dim)]" data-narration-voice="">
{r.engine} · {r.voice}
{r.speed !== 1 ? ` · ×${r.speed}` : ""}
@@ -290,6 +318,7 @@ function NarrationCard({
<audio ref={audio} controls preload="none" src={audioSrc(project, r)} data-narration-audio="" className="h-8 w-full" />
)}
{r.kept && <p className="text-[11px] text-[var(--color-dim)]">{r.kept.disclosure}</p>}
+ <DraftAlternatives address={`narrate/${r.id}/narration`} view={drafts} act={draftAct} />
{error && (
<p data-narration-error="" className="text-[11px] text-[var(--color-bad)]">
{error}
diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx
@@ -4,6 +4,7 @@ import GeneratedBanner from "@/components/notes/GeneratedBanner";
import { TimedVideo } from "@/components/notes/TimedNotes";
import StructureEditors from "./StructureEditors";
import { MANIFEST_CHANGED } from "./timelineApi";
+import { DraftAlternatives, DraftBadge, announceDraftsChanged, useDrafts } from "./drafts";
import { announceNotesChanged, wroteNotes } from "@/components/notes/NotesProvider";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { badgeVariants } from "@/components/ui/badge";
@@ -835,6 +836,9 @@ export default function OnscreenSection({
// The switch as pressed, while its write is in flight: the box follows the
// hand at once and falls back to the manifest's answer if the write fails.
const [switching, setSwitching] = useState<boolean | null>(null);
+ // The drafts review (release 28): a drafted title's badge, and the
+ // alternatives kept for a title that is the operator's.
+ const review = useDrafts(project);
// One token for the manifest, shared by both writers here: a settings save
// moves it, and the table's next save must carry the moved one. A ref, as
// in the clip bench, because two saves can be in flight before a render.
@@ -1133,6 +1137,8 @@ export default function OnscreenSection({
return next;
});
setNote(`saved ${Object.keys(saved).length} row${Object.keys(saved).length === 1 ? "" : "s"}`);
+ // An edited draft is the operator's now: the badges re-read.
+ announceDraftsChanged(project);
}),
[queued, dirtyIds, project, draftMap, rows],
);
@@ -1415,6 +1421,8 @@ export default function OnscreenSection({
}}
className={`${field} w-full ${over(shown) ? "border-[var(--color-dirty)]" : "border-[var(--color-line)]"}`}
/>
+ <DraftBadge address={`onscreen/${row.id}/onscreen`} view={review.view} act={review.act} compact />
+ <DraftAlternatives address={`onscreen/${row.id}/onscreen`} view={review.view} act={review.act} />
</td>
<td
className={`num px-1.5 py-1 text-right font-mono text-[11px] ${over(shown) ? "text-[var(--color-dirty)]" : "text-[var(--color-dim)]"}`}
diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -8,6 +8,7 @@ import ClaimBenchPage from "./ClaimBenchPage";
import SweepProject from "./SweepProject";
import TakesPage from "./TakesPage";
import NarrationPage from "./NarrationPage";
+import ReviewPage from "./ReviewPage";
// ---------------------------------------------------------------------------
// The one place a kind id is matched against a component.
@@ -57,6 +58,9 @@ export default async function ProjectView({
// `/browse/<project>/narration` -- the narration script, card by card,
// approved / edited / rejected before synthesis.
if (rest.length === 1 && rest[0] === "narration") return <NarrationPage project={project} />;
+ // `/browse/<project>/review` -- every drafted field, approved / rejected
+ // before a final build, and the alternatives a draft task kept.
+ if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} />;
return notFound();
}
case "sweep-report": {
diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx
@@ -20,6 +20,8 @@ import { listSnapshots, readSnapshot } from "@/lib/report/snapshots.mjs";
import { listTakes } from "@/lib/report/takes.mjs";
import { podcastFor } from "@/lib/report/serve.mjs";
import { narrationsOf } from "umtool-report-to-video/narration";
+import { draftedFields } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
+import { readAlternatives } from "@/lib/report/drafts.mjs";
import DeliverSection from "./DeliverSection";
import FetchUnfetchedButton from "./FetchUnfetchedButton";
import OnscreenSection from "./OnscreenSection";
@@ -149,6 +151,9 @@ export default async function ReportProject({
const podcasts = new Map(await Promise.all(variants.map(async (v) => [v, await podcastOf(v)] as const)));
const takes = await listTakes(project.dir);
const narrated = narrationsOf(m).length;
+ // The drafts review (release 28): drafted fields, and alternatives kept.
+ const draftedCount = draftedFields(m).length;
+ const alternativesCount = (await readAlternatives(project.dir)).length;
// Provenance splits by SHAPE: a scalar or a URL stays in the table; a long
// string, or one with a newline, is prose the author wrote and reads as a
@@ -261,6 +266,17 @@ export default async function ReportProject({
Narration — {narrated}
</Link>
)}
+ {/* Every drafted field, judged before a final build -- only when a
+ draft task wrote one, or kept an alternative. */}
+ {(draftedCount > 0 || alternativesCount > 0) && (
+ <Link
+ href={`/browse/${project.id}/review`}
+ data-review-link={draftedCount}
+ className={buttonVariants({ size: "lg" })}
+ >
+ Review drafts — {draftedCount}
+ </Link>
+ )}
{takes.exists && (
<Link
href={`/browse/${project.id}/takes`}
diff --git a/umtool/components/projects/ReviewPage.tsx b/umtool/components/projects/ReviewPage.tsx
@@ -0,0 +1,39 @@
+import BrowseHeader from "@/components/BrowseHeader";
+import { readManifest } from "@/lib/projects/report.mjs";
+import { manifestToken } from "@/lib/report/manifest.mjs";
+import { draftsView } from "@/lib/report/drafts.mjs";
+import type { ProjectRef } from "@/lib/project-types";
+import DraftsReview from "./DraftsReview";
+import type { DraftsView } from "./drafts";
+
+// `/browse/<project>/review` -- every drafted field of the cut, approved or
+// rejected before a final build (release 28, M0). Verdicts are
+// <project>/drafts.review.json; a final build refuses a drafted field not
+// approved on its current value. The narration page is the narration's own
+// view of the same verdicts.
+export default async function ReviewPage({ project }: { project: ProjectRef }) {
+ const manifest = await readManifest(project.dir);
+ const view = { ...((await draftsView(project.dir, manifest ?? {})) as DraftsView), token: await manifestToken(project.dir) };
+ const { counts } = view;
+ return (
+ <div className="flex h-full flex-col">
+ <BrowseHeader
+ crumbs={[
+ { href: "/browse", label: "projects" },
+ { href: `/browse/${project.id}`, label: project.id },
+ { label: "review" },
+ ]}
+ note={
+ view.drafted
+ ? `${view.drafted} drafted · ${counts.approved} approved` +
+ (counts.rejected ? ` · ${counts.rejected} rejected` : "") +
+ (counts.edited + counts.unreviewed ? ` · ${counts.edited + counts.unreviewed} to review` : "")
+ : undefined
+ }
+ />
+ <main className="deck-main flex-1 space-y-4 p-4">
+ <DraftsReview project={project.id} initial={view} />
+ </main>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/StructureEditors.tsx b/umtool/components/projects/StructureEditors.tsx
@@ -5,6 +5,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { announceNotesChanged, wroteNotes } from "@/components/notes/NotesProvider";
import { buttonVariants } from "@/components/ui/button";
import { MANIFEST_CHANGED, announceManifestChanged, refusalOf, timelineOp } from "./timelineApi";
+import { DraftAlternatives, DraftBadge, useDrafts, type DraftAct, type DraftsView } from "./drafts";
// The parts of the cut that are lists, edited in place: each teaser's lines
// and timing, the posts, and the fact-check's labels and colours. Every save
@@ -34,6 +35,8 @@ export default function StructureEditors({ project }: { project: string }) {
const [doc, setDoc] = useState<Doc | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
+ // The drafts review (release 28): a drafted teaser's badge and alternatives.
+ const drafts = useDrafts(project);
const load = useCallback(async () => {
const r = await fetch(`/api/report/timeline?project=${encodeURIComponent(project)}`, { cache: "no-store" });
@@ -79,7 +82,14 @@ export default function StructureEditors({ project }: { project: string }) {
</p>
)}
{doc.teasers.map((t) => (
- <TeaserEditor key={`${t.id}@${t.at}`} teaser={t} busy={busy} save={(patch) => run("teaser", { id: t.id, at: t.at, patch })} />
+ <TeaserEditor
+ key={`${t.id}@${t.at}`}
+ teaser={t}
+ busy={busy}
+ save={(patch) => run("teaser", { id: t.id, at: t.at, patch })}
+ drafts={drafts.view}
+ act={drafts.act}
+ />
))}
<PostsEditor posts={doc.posts} busy={busy} save={(post) => run("post", { post })} remove={(id) => run("post-remove", { id })} />
{doc.deckOn && <FactcheckEditor doc={doc} busy={busy} save={(factcheck) => run("factcheck", { factcheck })} />}
@@ -87,7 +97,19 @@ export default function StructureEditors({ project }: { project: string }) {
);
}
-function TeaserEditor({ teaser: t, busy, save }: { teaser: Teaser; busy: boolean; save: (patch: Record<string, unknown>) => Promise<boolean> }) {
+function TeaserEditor({
+ teaser: t,
+ busy,
+ save,
+ drafts,
+ act,
+}: {
+ teaser: Teaser;
+ busy: boolean;
+ save: (patch: Record<string, unknown>) => Promise<boolean>;
+ drafts: DraftsView | null;
+ act: DraftAct;
+}) {
// Plain lines edit as one per row; a teaser whose lines carry settings
// (break, role, replace…) edits as the JSON it is, so nothing is dropped.
const plain = t.lines.every((l) => typeof l === "string");
@@ -147,6 +169,8 @@ function TeaserEditor({ teaser: t, busy, save }: { teaser: Teaser; busy: boolean
</button>
{local && <span className="text-[var(--color-bad)]">{local}</span>}
</div>
+ <DraftBadge address={`teaser/${t.id}/lines`} view={drafts} act={act} />
+ <DraftAlternatives address={`teaser/${t.id}/lines`} view={drafts} act={act} />
</div>
);
}
diff --git a/umtool/components/projects/drafts.tsx b/umtool/components/projects/drafts.tsx
@@ -0,0 +1,233 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { badgeVariants, type BadgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { MANIFEST_CHANGED, announceManifestChanged } from "./timelineApi";
+
+// The drafts review on the page (release 28, M0): who drafted a field, its
+// review state, Approve / Reject (with a note), and the alternatives a draft
+// task kept for a field it was not allowed to replace, each with "Use this".
+//
+// One view per section (`useDrafts`), read from /api/report/drafts and
+// re-read after any write to the manifest (MANIFEST_CHANGED) or the review
+// (DRAFTS_CHANGED), so a badge in the On-screen table and one on the review
+// page agree. The server is the word on every state: each action answers with
+// the whole view.
+
+export type Provenance = { task: string; model: string; at: string; iteration?: number; attempt: number };
+export type DraftRow = {
+ address: string;
+ entry: string | null;
+ field: string;
+ label: string;
+ drafted: Provenance | null;
+ text: string;
+ state: "approved" | "rejected" | "edited" | "unreviewed";
+ verdict: "approved" | "rejected" | null;
+ note: string;
+ judgedText: string;
+ judgedAt: string;
+};
+export type DraftAlternative = {
+ id: string;
+ file: string;
+ address: string;
+ entry: string | null;
+ field: string;
+ label: string;
+ text: string;
+ value: unknown;
+ provenance: Provenance | null;
+ reason: string;
+ inUse: boolean;
+};
+export type DraftsView = {
+ file: string;
+ exists: boolean;
+ error: string | null;
+ rows: DraftRow[];
+ alternatives: DraftAlternative[];
+ counts: Record<DraftRow["state"], number>;
+ drafted: number;
+ gate: { errors: string[]; warnings: string[] };
+ token?: string | null;
+};
+
+export const DRAFTS_CHANGED = "umtool:drafts-changed";
+export function announceDraftsChanged(project: string) {
+ window.dispatchEvent(new CustomEvent(DRAFTS_CHANGED, { detail: { project } }));
+}
+
+export type DraftAct = (action: string, extra?: Record<string, unknown>) => Promise<void>;
+
+/** The project's drafts view, kept fresh; `act` runs one action and adopts the answer. */
+export function useDrafts(project: string, initial: DraftsView | null = null): { view: DraftsView | null; act: DraftAct; reload: () => Promise<void> } {
+ const [view, setView] = useState<DraftsView | null>(initial);
+ const reload = useCallback(async () => {
+ const r = await fetch(`/api/report/drafts?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ if (r.ok) setView((await r.json()) as DraftsView);
+ }, [project]);
+ useEffect(() => {
+ if (!initial) void reload();
+ const on = (e: Event) => {
+ if ((e as CustomEvent).detail?.project === project) void reload();
+ };
+ window.addEventListener(MANIFEST_CHANGED, on);
+ window.addEventListener(DRAFTS_CHANGED, on);
+ return () => {
+ window.removeEventListener(MANIFEST_CHANGED, on);
+ window.removeEventListener(DRAFTS_CHANGED, on);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [project, reload]);
+ const act = useCallback<DraftAct>(
+ async (action, extra = {}) => {
+ const r = await fetch("/api/report/drafts", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, action, ...extra }),
+ cache: "no-store",
+ });
+ const j = (await r.json().catch(() => ({ error: `HTTP ${r.status}` }))) as DraftsView & { ok?: boolean; error?: string; errors?: string[] };
+ if (!r.ok || !j.ok) throw new Error(j.errors?.length ? j.errors.join("; ") : (j.error ?? `HTTP ${r.status}`));
+ setView(j);
+ // A taken alternative changed the manifest: every editor re-reads it.
+ if (action === "use") announceManifestChanged(project);
+ else announceDraftsChanged(project);
+ },
+ [project],
+ );
+ return { view, act, reload };
+}
+
+const STATE: Record<DraftRow["state"], { label: string; tone: BadgeVariants["variant"] }> = {
+ approved: { label: "approved", tone: "meter" },
+ rejected: { label: "rejected", tone: "blocking" },
+ edited: { label: "changed since approved", tone: "on" },
+ unreviewed: { label: "not reviewed", tone: "open" },
+};
+
+/**
+ * "drafted by <model>", its review state, and Approve / Reject (+ note) for the
+ * field at `address`. Nothing when the field is not drafted.
+ */
+export function DraftBadge({ address, view, act, compact = false }: { address: string; view: DraftsView | null; act: DraftAct; compact?: boolean }) {
+ const row = view?.rows.find((r) => r.address === address && r.drafted) ?? null;
+ const [note, setNote] = useState(row?.note ?? "");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [ready, setReady] = useState(false);
+ useEffect(() => setReady(true), []);
+ useEffect(() => setNote(row?.note ?? ""), [row?.note]);
+ if (!row || !row.drafted) return null;
+ const run = async (action: string, extra: Record<string, unknown> = {}) => {
+ setBusy(true);
+ setError(null);
+ try {
+ await act(action, { address, ...extra });
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+ const s = STATE[row.state];
+ return (
+ <div data-draft-badge={address} data-state={row.state} className={`flex flex-wrap items-center gap-1 ${compact ? "mt-0.5" : ""} text-[11px]`}>
+ <span
+ data-draft-by=""
+ className={badgeVariants({ variant: "info", size: "sm" })}
+ title={`drafted by ${row.drafted.task} on ${row.drafted.model}, ${row.drafted.at}${row.drafted.iteration ? ` (i${row.drafted.iteration})` : ""}, attempt ${row.drafted.attempt}`}
+ >
+ drafted by {row.drafted.model}
+ </span>
+ <span data-draft-state="" className={badgeVariants({ variant: s.tone, size: "sm" })}>
+ {s.label}
+ </span>
+ <button
+ type="button"
+ data-draft-action="approve"
+ aria-pressed={row.state === "approved"}
+ disabled={!ready || busy}
+ title="approve this draft as it is now"
+ className={buttonVariants({ variant: row.state === "approved" ? "primary" : "outline", size: "sm" })}
+ onClick={() => void run(row.state === "approved" ? "clear" : "approve", row.state === "approved" ? {} : { note })}
+ >
+ {row.state === "approved" ? "Approved" : "Approve"}
+ </button>
+ <button
+ type="button"
+ data-draft-action="reject"
+ aria-pressed={row.state === "rejected"}
+ disabled={!ready || busy}
+ title="reject this draft; the note says what is wrong"
+ className={buttonVariants({ variant: row.state === "rejected" ? "destructive" : "outline", size: "sm" })}
+ onClick={() => void run(row.state === "rejected" ? "clear" : "reject", row.state === "rejected" ? {} : { note })}
+ >
+ {row.state === "rejected" ? "Rejected" : "Reject"}
+ </button>
+ <input
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ onBlur={() => {
+ if (note.trim() !== row.note && row.verdict) void run("note", { note });
+ }}
+ disabled={!ready || busy}
+ placeholder="note (a rejection needs one)"
+ aria-label={`note on the draft of ${address}`}
+ data-draft-note=""
+ maxLength={2000}
+ className="min-w-0 flex-1 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]"
+ />
+ {error && (
+ <span data-draft-error="" className="basis-full text-[var(--color-bad)]">
+ {error}
+ </span>
+ )}
+ </div>
+ );
+}
+
+/** The alternatives kept for the field at `address`, each with "Use this". */
+export function DraftAlternatives({ address, view, act }: { address: string; view: DraftsView | null; act: DraftAct }) {
+ const alts = (view?.alternatives ?? []).filter((a) => a.address === address && !a.inUse);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [ready, setReady] = useState(false);
+ useEffect(() => setReady(true), []);
+ if (!alts.length) return null;
+ return (
+ <div data-draft-alternatives={address} className="mt-0.5 space-y-0.5 text-[11px]">
+ {alts.map((a) => (
+ <div key={a.id} data-draft-alternative={a.id} className="flex flex-wrap items-center gap-1.5 text-[var(--color-dim)]">
+ <span className="micro">alternative{a.provenance ? ` · ${a.provenance.model}` : ""}</span>
+ <span data-draft-alternative-text="" className="italic text-[var(--color-text)]">
+ {a.text || "(empty)"}
+ </span>
+ <button
+ type="button"
+ data-draft-use=""
+ disabled={!ready || busy !== null}
+ title="write this instead of what the field holds, as your own edit"
+ className={buttonVariants({ size: "sm" })}
+ onClick={() => {
+ setBusy(a.id);
+ setError(null);
+ act("use", { alternative: a.id })
+ .catch((e) => setError(e instanceof Error ? e.message : String(e)))
+ .finally(() => setBusy(null));
+ }}
+ >
+ {busy === a.id ? "writing…" : "Use this"}
+ </button>
+ </div>
+ ))}
+ {error && (
+ <p data-draft-error="" className="text-[var(--color-bad)]">
+ {error}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -811,14 +811,27 @@ rules and the validator.
**The narration review** — `/browse/<project>/narration`, linked from the
project page as **Narration — N** — is the script card by card before synthesis:
-the words beside what the card shows, Approve / Reject (a note required) / Save
-words / Play. Verdicts live in `narration.review.json` beside the manifest
-(the shape of `takes/verdicts.json`); `GET|POST /api/report/narration`,
+the words beside what the card shows, who drafted them, Approve / Reject (a note
+required) / Save words / Play. `GET|POST /api/report/narration`,
`POST /api/report/narration/play` (a job: `narrate-via-editor.mjs --only`),
-`GET /api/report/narration/audio`. Once the file exists, a build refuses any
-narrated card not approved on its current words (`--narration-unreviewed`
-builds unreviewed and edited ones; a rejected one never). The README's "The
-narration review" has the rules.
+`GET /api/report/narration/audio`. Once a narration verdict exists, a build
+refuses any hand-written narrated card not approved on its current words
+(`--narration-unreviewed` builds unreviewed and edited ones; a rejected one
+never).
+
+**The drafts review** (release 28) — `/browse/<project>/review`, linked as
+**Review drafts — N** when a draft task wrote a field — lists every drafted
+field (on-screen text, a narration, a teaser's lines, the cut's order, the
+flips, the threads, the YouTube text): who drafted it, its value, Approve /
+Reject (a note required), and the alternatives a task kept for a field that is
+the operator's, each with **Use this**. The same badge sits beside the field in
+the On-screen table, the teaser editor and on the narration page. Verdicts —
+the narration's included — live in `drafts.review.json` beside the manifest
+(release 25's `narration.review.json` is still read); `GET|POST
+/api/report/drafts`. A final build refuses a drafted field not approved on its
+current value (`--drafts-unreviewed` builds the unapproved; a rejected one
+never); a preview or fast build warns. An edit in umtool makes a drafted field
+the operator's: its mark goes. The README's "The drafts review" has the rules.
## Re-checking sources across projects
diff --git a/umtool/e2e/draft-review.spec.ts b/umtool/e2e/draft-review.spec.ts
@@ -0,0 +1,125 @@
+import { test, expect, type APIRequestContext } from "@playwright/test";
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// ---------------------------------------------------------------------------
+// The drafts review (release 28, M0). A drafted field shows "drafted by
+// <model>" and its review state beside it, with Approve / Reject (a note
+// required); an edit makes it the operator's (the mark goes); the review page
+// lists every drafted field, and an alternative a draft task kept for the
+// operator's field is written with "Use this"; a FINAL build refuses a drafted
+// field until it is approved, then builds. Verdicts are drafts.review.json
+// beside the manifest. Fixtures: e2e/fixtures/draft-review-fixture.mjs.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/draft-review-fixture";
+const DIR = path.join(FIXTURE, "reports", "draft-review-fixture");
+const BUILD_PROJECT = "reports/draft-review-build-fixture";
+const BUILD_DIR = path.join(FIXTURE, "reports", "draft-review-build-fixture");
+
+type Entry = { id: string; onscreen?: { title?: string }; drafted?: Record<string, unknown>; lines?: unknown[] };
+const manifest = (dir = DIR) => JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8")) as { timeline: Entry[] };
+const entry = (id: string, dir = DIR) => manifest(dir).timeline.find((e) => e.id === id)!;
+const review = (dir = DIR): Record<string, { verdict: string | null; note: string }> => {
+ const f = path.join(dir, "drafts.review.json");
+ return existsSync(f) ? JSON.parse(readFileSync(f, "utf8")) : {};
+};
+
+test("badges: drafted by <model>, approve, reject with a note; an edit makes the field the operator's", async ({ page }) => {
+ await page.goto(`/browse/${PROJECT}`);
+ await expect(page.locator("[data-review-link]")).toHaveAttribute("data-review-link", "3");
+
+ // The On-screen table (folded: the deck is off) -- c02's title was drafted, c01's was not.
+ await page.getByTestId("onscreen-words-folded").locator("summary").click();
+ const c02 = page.locator('[data-draft-badge="onscreen/c02/onscreen"]');
+ await expect(c02).toHaveAttribute("data-state", "unreviewed");
+ await expect(c02.locator("[data-draft-by]")).toHaveText("drafted by qwen3:8b");
+ await expect(page.locator('[data-draft-badge="onscreen/c01/onscreen"]')).toHaveCount(0);
+ await c02.locator('[data-draft-action="approve"]').click();
+ await expect(c02).toHaveAttribute("data-state", "approved");
+ expect(review()["onscreen/c02/onscreen"].verdict).toBe("approved");
+
+ // The teaser's lines: a rejection needs its note.
+ await page.getByTestId("structure-folded").locator("summary").click();
+ const t01 = page.locator('[data-draft-badge="teaser/t01/lines"]');
+ await expect(t01.locator("[data-draft-by]")).toHaveText("drafted by claude-sonnet-5-5");
+ await t01.locator('[data-draft-action="reject"]').click();
+ await expect(t01.locator("[data-draft-error]")).toContainText("a rejection needs its note");
+ await t01.locator("[data-draft-note]").fill("the lease is not next season");
+ await t01.locator('[data-draft-action="reject"]').click();
+ await expect(t01).toHaveAttribute("data-state", "rejected");
+ expect(review()["teaser/t01/lines"]).toMatchObject({ verdict: "rejected", note: "the lease is not next season" });
+
+ // Edit c02's drafted title: saved through the manifest writer, it is the
+ // operator's now -- no mark, no badge.
+ const row = page.locator('[data-testid="onscreen-row"][data-entry="c02"]');
+ await row.getByTestId("onscreen-title").fill("My own title");
+ await page.getByTestId("onscreen-save").click();
+ await expect(c02).toHaveCount(0);
+ expect(entry("c02").onscreen).toEqual({ title: "My own title" });
+ expect(entry("c02").drafted).toBeUndefined();
+});
+
+test("the review page: every drafted field, the narration's badge, and Use this for the operator's field", async ({ page }) => {
+ await page.goto(`/browse/${PROJECT}`);
+ await page.locator("[data-review-link]").click();
+ await expect(page).toHaveURL(new RegExp(`/browse/${PROJECT}/review$`));
+ // The narration and the teaser are drafted; a final build would refuse them.
+ const k01 = page.locator('[data-draft-row="narrate/k01/narration"]');
+ await expect(k01).toHaveAttribute("data-state", "unreviewed");
+ await expect(k01.locator("[data-draft-text]")).toHaveText("Half a year on, the county said yes.");
+ await expect(page.locator('[data-draft-row="teaser/t01/lines"]')).toBeVisible();
+ await expect(page.locator("[data-drafts-gate]")).toHaveAttribute("data-drafts-gate", "refuses");
+
+ // c01's title is the operator's: the draft that could not replace it is an
+ // alternative under it. Use this writes it as the operator's edit.
+ const alt = page.locator('[data-draft-alternatives="onscreen/c01/onscreen"]');
+ await expect(alt.locator("[data-draft-alternative-text]")).toHaveText("Kept aside title");
+ await alt.locator("[data-draft-use]").click();
+ await expect(alt).toHaveCount(0);
+ expect(entry("c01").onscreen).toEqual({ title: "Kept aside title" });
+ expect(entry("c01").drafted).toBeUndefined();
+
+ // Approve the narration here; the narration page shows who drafted it, and its state.
+ await k01.locator('[data-draft-action="approve"]').click();
+ await expect(k01).toHaveAttribute("data-state", "approved");
+ await page.goto(`/browse/${PROJECT}/narration`);
+ const card = page.locator('[data-narration-card="k01"]');
+ await expect(card.locator("[data-narration-drafted]")).toHaveText("drafted by qwen3:8b");
+ await expect(card).toHaveAttribute("data-state", "approved");
+});
+
+async function build(request: APIRequestContext, replace = false) {
+ const start = await request.post(`/api/report/build${replace ? "?replace=1" : ""}`, { data: { project: BUILD_PROJECT, preset: "final" } });
+ expect(start.ok(), await start.text()).toBeTruthy();
+ const { job } = (await start.json()) as { job: { id: string } };
+ let done: { state: string; error: string | null } = { state: "running", error: null };
+ const until = Date.now() + 240_000;
+ while (Date.now() < until) {
+ done = (await (await request.get(`/api/report/build?job=${job.id}`)).json()) as typeof done;
+ if (done.state !== "running") break;
+ await new Promise((r) => setTimeout(r, 400));
+ }
+ return done;
+}
+
+test("a final build refuses an unapproved draft, and builds once it is approved", async ({ page, request }) => {
+ test.setTimeout(360_000);
+ const refused = await build(request);
+ expect(refused.state).toBe("failed");
+ expect(JSON.stringify(refused)).toContain("timeline c02: its on-screen text (drafted by qwen3:8b) is not approved");
+ expect(existsSync(path.join(BUILD_DIR, "out", "draft-review-build-fixture.mp4"))).toBe(false);
+
+ await page.goto(`/browse/${BUILD_PROJECT}/review`);
+ const row = page.locator('[data-draft-row="onscreen/c02/onscreen"]');
+ await row.locator('[data-draft-action="approve"]').click();
+ await expect(row).toHaveAttribute("data-state", "approved");
+ await expect(page.locator("[data-drafts-gate]")).toHaveAttribute("data-drafts-gate", "passes");
+
+ const done = await build(request);
+ expect(done.state, done.error ?? "").toBe("done");
+ expect(existsSync(path.join(BUILD_DIR, "out", "draft-review-build-fixture.mp4"))).toBe(true);
+});
diff --git a/umtool/e2e/fixtures/draft-review-fixture.mjs b/umtool/e2e/fixtures/draft-review-fixture.mjs
@@ -0,0 +1,80 @@
+// What draft-review.spec.ts reviews (release 28, M0): two report projects whose
+// fields carry drafted marks, so the badges, the review page, "Use this" and
+// the final build's refusal have something to act on. Their own, so the other
+// specs' projects are never touched.
+//
+// reports/draft-review-fixture/ writable, deck off, never built:
+// c01 on-screen text written BY HAND (the operator's), and an
+// alternative for it in onscreen-draft.json (a draft that was not
+// allowed to replace it)
+// c02 on-screen text DRAFTED by qwen3:8b
+// k01 a chapter card whose narration was DRAFTED
+// t01 a teaser whose lines were DRAFTED by claude-sonnet-5-5
+// reports/draft-review-build-fixture/ two clips over the cached window, c02's
+// on-screen text DRAFTED: a final build refuses it until approved
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+const AT = "2026-10-13T10:00:00.000Z";
+const P = (task, model = "qwen3:8b") => ({ task, model, at: AT, iteration: 1, attempt: 1 });
+
+const write = (dir, name, doc) => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n");
+};
+
+/**
+ * @param {{ reports: string, manifest: Function, cachedWindow: string }} o
+ * `manifest` is make-fixture's manifest(slug, title, provenance, timeline);
+ * `cachedWindow` the vid1 0-9 s window the build fixtures share.
+ */
+export function makeDraftReviewFixture({ reports, manifest, cachedWindow }) {
+ const ui = path.join(reports, "draft-review-fixture");
+ write(
+ ui,
+ "video.manifest.json",
+ manifest("draft-review-fixture", "The Draft Review Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "and because", onscreen: { title: "Hand title" } },
+ {
+ type: "clip", id: "c02", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence",
+ onscreen: { title: "Drafted title" }, drafted: { onscreen: P("onscreen") },
+ },
+ {
+ type: "card", id: "k01", style: "chapter", seconds: "auto", heading: "The county",
+ narration: { text: "Half a year on, the county said yes." }, drafted: { narration: P("narrate") },
+ },
+ {
+ type: "teaser", id: "t01", lines: ["Next Season", "The lease", "Spring 2027"],
+ drafted: { lines: P("teaser", "claude-sonnet-5-5") },
+ },
+ ]),
+ );
+ write(ui, "onscreen-draft.json", {
+ task: "onscreen",
+ model: "qwen3:8b",
+ at: AT,
+ article: "draft-review",
+ iteration: 1,
+ units: {},
+ checks: [],
+ alternatives: [{ target: { entry: "c01", field: "onscreen" }, value: { title: "Kept aside title" }, provenance: P("onscreen"), reason: "operator" }],
+ });
+
+ const build = path.join(reports, "draft-review-build-fixture");
+ write(
+ build,
+ "video.manifest.json",
+ manifest("draft-review-build-fixture", "The Draft Review Build Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "and because" },
+ {
+ type: "clip", id: "c02", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence",
+ onscreen: { title: "Drafted title" }, drafted: { onscreen: P("onscreen") },
+ },
+ ]),
+ );
+ mkdirSync(path.join(build, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(build, "out", "clips-raw", path.basename(cachedWindow)));
+ return { ui, build };
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -25,6 +25,7 @@ import { songCapabilities } from "./song-capabilities.mjs";
import { makeSitesFixture } from "./sites-fixture.mjs";
import { makeIterationsFixture } from "./iterations-fixture.mjs";
import { makeDeleteFixture } from "./delete-fixture.mjs";
+import { makeDraftReviewFixture } from "./draft-review-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1652,6 +1653,10 @@ for (const dir of [BENCH, BUILD, ONSCREEN, ONSCREEN_BUILD, ONSCREEN_POSTS, ONSCR
);
}
+// Release 28: drafted fields to review, and a final build they hold
+// (draft-review.spec.ts).
+makeDraftReviewFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
+
// TWO MORE cached windows for vid1, and they are the regression rather than
// decoration.
//
@@ -1952,4 +1957,5 @@ console.log(` deliver-stop-fixture (writable: six confirmed clips to
console.log(` takes-fixture (writable: takes/ with 4 takes over 2 groups, 1 skipped)`);
console.log(` narration-fixture (writable: a narrated card, voiced by the editor stub's tone)`);
console.log(` narration-review-fixture (writable: two narrated cards, nothing judged)`);
+console.log(` draft-review-fixture (writable: drafted on-screen, narration, teaser; an alternative), draft-review-build-fixture`);
console.log(` ${taken} candidate files copied, 2 mix tracks synthesised`);
diff --git a/umtool/e2e/narration-review.spec.ts b/umtool/e2e/narration-review.spec.ts
@@ -8,19 +8,23 @@ import { fileURLToPath } from "node:url";
// card, before synthesis. Approve / reject (a note required) / edit the words
// (which un-approves them) / play one card through the editor -- the suite's
// stub, whose "voice" is an ffmpeg tone -- and a build that refuses what is not
-// approved once verdicts exist. Verdicts are narration.review.json beside the
-// manifest.
+// approved once verdicts exist. Verdicts are drafts.review.json beside the
+// manifest (release 28; release 25's narration.review.json is still read).
// ---------------------------------------------------------------------------
const HERE = path.dirname(fileURLToPath(import.meta.url));
const FIXTURE = path.join(HERE, "..", ".e2e-song");
const PROJECT = "reports/narration-review-fixture";
const DIR = path.join(FIXTURE, "reports", "narration-review-fixture");
-const REVIEW = path.join(DIR, "narration.review.json");
+// Since release 28 the verdicts are the drafts review's: a card's are
+// `narrate/<cardId>/narration` in drafts.review.json.
+const REVIEW = path.join(DIR, "drafts.review.json");
const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
-const review = (): Record<string, { verdict: string | null; note: string; text: string }> =>
- existsSync(REVIEW) ? JSON.parse(readFileSync(REVIEW, "utf8")) : {};
+const review = (): Record<string, { verdict: string | null; note: string; text: string }> => {
+ const all = existsSync(REVIEW) ? (JSON.parse(readFileSync(REVIEW, "utf8")) as Record<string, { verdict: string | null; note: string; text: string }>) : {};
+ return Object.fromEntries(Object.entries(all).map(([address, row]) => [address.replace(/^narrate\/(.+)\/narration$/, "$1"), row]));
+};
const manifest = () => JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { timeline: { id: string; narration?: { text: string } }[] };
const ttsAsks = (): { route?: string; text?: string }[] => {
try {
diff --git a/umtool/lib/report/drafted-writer.test.mjs b/umtool/lib/report/drafted-writer.test.mjs
@@ -0,0 +1,105 @@
+// The manifest writer is the operator (release 28, M0): every umtool write
+// that changes a drafted field removes its drafted mark -- one test per field
+// -- an unrelated write keeps every mark, a re-save of the same value keeps
+// it, an orphan is dropped, and "Use this" (writeDraftedField) writes an
+// alternative as the operator's. Over the S0 kit's `full` manifest.
+//
+// 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, StructureRefused, moveEntry, updateChrome, updateNarration, updateOnscreen, updateTeaser, writeDraftedField,
+} from "./manifest.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const full = () => JSON.parse(readFileSync(path.join(HERE, "../../../common/testing/draft/manifests/full.video.manifest.json"), "utf8"));
+const P = (task) => ({ task, model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 1, attempt: 1 });
+
+// Every field drafted: c02's on-screen text, the contest card's narration,
+// the teaser's lines, the threads, the cut's order, the YouTube text.
+function drafted() {
+ const m = full();
+ const e = (id) => m.timeline.find((x) => x.id === id);
+ e("c02").onscreen = { title: "The oven" };
+ e("c02").drafted = { onscreen: P("onscreen") };
+ e("the-contest").drafted = { narration: P("narrate") };
+ e("fin").drafted = { lines: P("teaser") };
+ m.publish = { youtube: { title: "T", description: "D" } };
+ m.drafted = { timeline: P("cut"), "render.chrome.threads": P("threads"), "publish.youtube": P("youtube") };
+ return m;
+}
+
+async function project(t, manifest = drafted()) {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-drafted-"));
+ t.after(() => rm(dir, { recursive: true, force: true }));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n");
+ const read = async () => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+ return { dir, read };
+}
+
+/** Every mark, as `<entry or *>:<field>`. */
+const marks = (m) => [
+ ...m.timeline.flatMap((e) => Object.keys(e.drafted ?? {}).map((f) => `${e.id}:${f}`)),
+ ...Object.keys(m.drafted ?? {}).map((f) => `*:${f}`),
+];
+const ALL = ["c02:onscreen", "the-contest:narration", "fin:lines", "*:timeline", "*:render.chrome.threads", "*:publish.youtube"];
+
+test("each field: the operator's edit removes its mark, and only its own", async (t) => {
+ const edits = [
+ ["on-screen text", (dir) => updateOnscreen(dir, { c02: { title: "Mine" } }), "c02:onscreen"],
+ ["teaser lines", (dir) => updateTeaser(dir, "fin", { lines: ["One", "Two", "Three"] }), "fin:lines"],
+ ["narration words", (dir) => updateNarration(dir, "the-contest", "My own words."), "the-contest:narration"],
+ ["the cut's order", (dir) => moveEntry(dir, "c03", 3), "*:timeline"],
+ ["the threads", async (dir) => {
+ const m = JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+ const chrome = { ...m.render.chrome, threads: { list: [...m.render.chrome.threads.list.map((x) => ({ ...x })), { id: "lease", label: "The lease" }] } };
+ return updateChrome(dir, chrome);
+ }, "*:render.chrome.threads"],
+ ["the YouTube text", (dir) => writeDraftedField(dir, { field: "publish.youtube", value: { title: "Mine", description: "D" } }), "*:publish.youtube"],
+ ];
+ for (const [what, edit, mark] of edits) {
+ const p = await project(t);
+ assert.deepEqual(marks(await p.read()), ALL);
+ await edit(p.dir);
+ assert.deepEqual(marks(await p.read()), ALL.filter((x) => x !== mark), what);
+ }
+});
+
+test("a write that leaves a drafted field as it was keeps its mark; an orphan is dropped", async (t) => {
+ const p = await project(t);
+ // c01's text (the operator's) changes; c02's re-saved exactly as it is.
+ await updateOnscreen(p.dir, { c01: { title: "Edited" }, c02: { title: "The oven" } });
+ assert.deepEqual(marks(await p.read()), ALL);
+ // A chrome save that leaves the threads alone keeps their mark.
+ const m = await p.read();
+ await updateChrome(p.dir, { ...m.render.chrome, factcheck: { stamp: { seconds: 2 } } });
+ assert.deepEqual(marks(await p.read()), ALL);
+ // Clearing c02's text leaves its mark an orphan: dropped by the write.
+ await updateOnscreen(p.dir, { c02: null });
+ assert.deepEqual(marks(await p.read()), ALL.filter((x) => x !== "c02:onscreen"));
+});
+
+test("writeDraftedField: Use this writes an alternative as the operator's, checked as its editor checks it", async (t) => {
+ const p = await project(t);
+ // c01's text is the operator's; an alternative replaces it, unmarked.
+ await writeDraftedField(p.dir, { entry: "c01", field: "onscreen", value: { title: "Not for sale?" } });
+ const m = await p.read();
+ assert.deepEqual(m.timeline.find((e) => e.id === "c01").onscreen, { title: "Not for sale?" });
+ assert.equal(m.timeline.find((e) => e.id === "c01").drafted, undefined);
+ // A drafted field taken from an alternative is the operator's too.
+ await writeDraftedField(p.dir, { entry: "fin", field: "lines", value: ["Synth Kitchen", "Next: the lease"] });
+ assert.ok(!marks(await p.read()).includes("fin:lines"));
+ // Refusals leave the file as it was.
+ const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8");
+ await assert.rejects(writeDraftedField(p.dir, { entry: "fin", field: "lines", value: [] }), StructureRefused);
+ await assert.rejects(writeDraftedField(p.dir, { field: "timeline", value: [] }), /applied by the cut task/);
+ await assert.rejects(writeDraftedField(p.dir, { entry: "c01", field: "quote", value: "x" }), /not a drafted field/);
+ await assert.rejects(writeDraftedField(p.dir, { field: "publish.youtube", value: { title: 3 } }), StructureRefused);
+ assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before);
+});
diff --git a/umtool/lib/report/drafts.mjs b/umtool/lib/report/drafts.mjs
@@ -0,0 +1,117 @@
+// The drafts review's view of a project (release 28, M0): every drafted field
+// of the manifest (every cut's) and every narrated card, with who drafted it,
+// its value as words, its review state (report-to-video's drafts-review.mjs),
+// the alternatives the draft tasks kept for it (`<task>-draft.json`), and what
+// a final build of the default cut would say. What the review page and the
+// badges draw, and what the route answers after each action -- one shape.
+//
+// Plain ESM: `node --test` runs it with no TypeScript.
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video";
+import {
+ DRAFTS_REVIEW_FILE, FIELD_LABELS, draftsReviewProblems, draftsReviewRows, judgedText, readDraftsReview,
+} from "umtool-report-to-video/drafts-review";
+import { fieldSignature, reviewAddress, stableStringify } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
+
+/** A task's draft file beside the manifest: `<task>-draft.json`. */
+export const DRAFT_FILE_RE = /^[a-z0-9][a-z0-9-]{0,62}-draft\.json$/;
+
+/**
+ * Every alternative the draft tasks kept in this project, in file order:
+ * `{ id: "<file>#<i>", file, index, address, entry, field, value, provenance, reason }`.
+ * A file that does not parse is skipped (its task wrote it; it is not this
+ * view's to repair).
+ *
+ * @param {string} projectDir
+ */
+export async function readAlternatives(projectDir) {
+ let names = [];
+ try {
+ names = (await readdir(projectDir)).filter((n) => DRAFT_FILE_RE.test(n)).sort();
+ } catch {
+ return [];
+ }
+ const out = [];
+ for (const file of names) {
+ let doc;
+ try {
+ doc = JSON.parse(await readFile(path.join(projectDir, file), "utf8"));
+ } catch {
+ continue;
+ }
+ const list = Array.isArray(doc?.alternatives) ? doc.alternatives : [];
+ list.forEach((a, index) => {
+ const t = a?.target;
+ if (!t || typeof t.field !== "string" || a.value === undefined) return;
+ const entry = typeof t.entry === "string" && t.entry ? t.entry : null;
+ out.push({
+ id: `${file}#${index}`,
+ file,
+ index,
+ address: reviewAddress({ entry, field: t.field }),
+ entry,
+ field: t.field,
+ value: a.value,
+ provenance: a.provenance ?? null,
+ reason: typeof a.reason === "string" ? a.reason : "operator",
+ });
+ });
+ }
+ return out;
+}
+
+/** One alternative by its id, or null. */
+export async function alternativeById(projectDir, id) {
+ return (await readAlternatives(projectDir)).find((a) => a.id === id) ?? null;
+}
+
+/**
+ * @param {string} projectDir
+ * @param {any} manifest the whole manifest, as written
+ */
+export async function draftsView(projectDir, manifest) {
+ const review = await readDraftsReview(projectDir);
+ const m = manifest && typeof manifest === "object" ? manifest : { timeline: [] };
+ const alternatives = (await readAlternatives(projectDir)).map((a) => {
+ const current = fieldSignature(m, { entry: a.entry, field: a.field });
+ // "in use": the field holds this value now (somebody took it).
+ const proposed = a.field === "timeline" ? null : a.value;
+ return { ...a, label: FIELD_LABELS[a.field] ?? a.field, text: judgedText(a.field, a.value), inUse: proposed !== null && stableStringify(current) === stableStringify(proposed) };
+ });
+ const rows = draftsReviewRows(m, review).map((r) => ({
+ address: r.address,
+ entry: r.entry,
+ field: r.field,
+ label: FIELD_LABELS[r.field] ?? r.field,
+ drafted: r.provenance,
+ text: r.text,
+ key: r.key,
+ state: r.state,
+ verdict: r.row?.verdict ?? null,
+ note: r.row?.note ?? "",
+ judgedText: r.row?.text ?? "",
+ judgedAt: r.row?.at ?? "",
+ }));
+ const counts = { approved: 0, rejected: 0, edited: 0, unreviewed: 0 };
+ for (const r of rows) if (r.drafted) counts[r.state] += 1;
+ // What a final build of the default cut would say of the review.
+ let gate = { errors: [], warnings: [] };
+ try {
+ const cut = selectVariant(m, DEFAULT_VARIANT);
+ const fin = draftsReviewProblems(cut, review, { final: true });
+ gate = { errors: fin.errors, warnings: fin.warnings };
+ } catch (e) {
+ gate = { errors: [e instanceof Error ? e.message : String(e)], warnings: [] };
+ }
+ return {
+ file: DRAFTS_REVIEW_FILE,
+ exists: review.exists,
+ error: review.error ?? null,
+ rows,
+ alternatives,
+ counts,
+ drafted: rows.filter((r) => r.drafted).length,
+ gate,
+ };
+}
diff --git a/umtool/lib/report/drafts.test.mjs b/umtool/lib/report/drafts.test.mjs
@@ -0,0 +1,59 @@
+// The drafts review's umtool view (release 28, M0): the drafted rows, the
+// alternatives read from every `<task>-draft.json`, "in use" once taken, and
+// what a final build would say.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { draftsView, readAlternatives } from "./drafts.mjs";
+import { MANIFEST_NAME, writeDraftedField } from "./manifest.mjs";
+import { setDraftReview } from "umtool-report-to-video/drafts-review";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const full = () => JSON.parse(readFileSync(path.join(HERE, "../../../common/testing/draft/manifests/full.video.manifest.json"), "utf8"));
+const P = (task) => ({ task, model: "qwen3:8b", at: "2026-10-13T10:00:00.000Z", iteration: 1, attempt: 1 });
+
+test("the view: drafted rows, alternatives from the draft files, in use once taken, the final gate", async (t) => {
+ const dir = mkdtempSync(path.join(tmpdir(), "umtool-drafts-view-"));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const m = full();
+ m.timeline.find((e) => e.id === "c02").onscreen = { title: "The oven" };
+ m.timeline.find((e) => e.id === "c02").drafted = { onscreen: P("onscreen") };
+ writeFileSync(path.join(dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n");
+ writeFileSync(
+ path.join(dir, "onscreen-draft.json"),
+ JSON.stringify({ task: "onscreen", alternatives: [{ target: { entry: "c01", field: "onscreen" }, value: { title: "Not for sale?" }, provenance: P("onscreen"), reason: "operator" }] }),
+ );
+ writeFileSync(path.join(dir, "broken-draft.json"), "{ nope");
+ writeFileSync(path.join(dir, "notes.json"), JSON.stringify({ alternatives: [{ target: { field: "onscreen" }, value: 1 }] }));
+ const alts = await readAlternatives(dir);
+ assert.deepEqual(alts.map((a) => [a.id, a.address]), [["onscreen-draft.json#0", "onscreen/c01/onscreen"]], "only <task>-draft.json files, and only those that parse");
+
+ const v = await draftsView(dir, m);
+ assert.equal(v.drafted, 1);
+ // The rows: c02's drafted text, and the contest card's hand-written narration.
+ assert.deepEqual(v.rows.map((r) => [r.address, r.drafted?.model ?? null, r.state]), [
+ ["onscreen/c02/onscreen", "qwen3:8b", "unreviewed"],
+ ["narrate/the-contest/narration", null, "unreviewed"],
+ ]);
+ assert.equal(v.alternatives[0].text, "Not for sale?");
+ assert.equal(v.alternatives[0].inUse, false);
+ assert.equal(v.gate.errors.length, 1);
+ assert.match(v.gate.errors[0], /timeline c02: its on-screen text \(drafted by qwen3:8b\) is not approved/);
+
+ // Approved: the gate passes.
+ await setDraftReview(dir, "onscreen/c02/onscreen", { verdict: "approved", key: v.rows[0].key, text: v.rows[0].text });
+ const ok = await draftsView(dir, m);
+ assert.deepEqual(ok.gate.errors, []);
+ assert.equal(ok.counts.approved, 1);
+
+ // Use this: the alternative is the field's value now, and in use.
+ await writeDraftedField(dir, { entry: "c01", field: "onscreen", value: { title: "Not for sale?" } });
+ const after = JSON.parse(readFileSync(path.join(dir, MANIFEST_NAME), "utf8"));
+ assert.equal((await draftsView(dir, after)).alternatives[0].inUse, true);
+});
diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs
@@ -52,7 +52,9 @@ const script = (name) => path.join(/* turbopackIgnore: true */ PIPELINE_DIR, nam
export const PRESETS = {
preview: { label: "preview one clip", xfade: false, chapters: false, only: true },
fast: { label: "fast pass (hard cuts)", xfade: false, chapters: true, only: false },
- final: { label: "final", xfade: true, chapters: true, only: false },
+ // `final` is the deliverable: the build is told so (`--final`), and refuses a
+ // drafted field the drafts review has not approved (drafts-review.mjs).
+ final: { label: "final", xfade: true, chapters: true, only: false, final: true },
};
/** A build's timeout, scaled to the work rather than to a global guess. */
@@ -179,6 +181,7 @@ export function buildSteps(project, { preset = "fast", only = null, skipFetch =
if (!p.chapters) buildArgv.push("--no-chapters");
if (skipFetch) buildArgv.push("--skip-fetch");
if (p.only && only) buildArgv.push("--only", only);
+ if (p.final) buildArgv.push("--final");
if (options.chaptersOnly) buildArgv.push("--chapters-only");
if (options.chromeOnly) buildArgv.push("--chrome-only");
if (options.preview) buildArgv.push("--preview", String(options.preview.at), String(options.preview.dur));
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -37,6 +37,9 @@ import { validateNarration } from "umtool-report-to-video/narration";
import { parseMuteFrom } from "./playback.mjs";
import { DELIVERABLES_MODES } from "./storage.mjs";
import { createSnapshot, listSnapshots } from "./snapshots.mjs";
+import {
+ DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, pruneDrafted, validateDrafted, validatePublish,
+} from "yt-dlp-transcript-common/lib/report/drafted.mjs";
// Its own write queue, not lib/state.ts's.
//
@@ -100,8 +103,18 @@ async function backupOnce(file) {
await copyFile(file, bak).catch(() => {});
}
+/**
+ * THIS WRITER IS THE OPERATOR (release 28, M0): a drafted field whose value
+ * this write changes loses its drafted mark -- it is the operator's now, and
+ * no draft task replaces it again -- and a mark whose field is gone is
+ * dropped (drafted.mjs `clearEditedDrafts`). Compared with the file as it is
+ * on disk, which every caller read inside the same lock.
+ */
async function writeManifestAtomic(dir, manifest) {
const file = manifestFile(dir);
+ const before = await readFile(file, "utf8").then((t) => JSON.parse(t), () => null);
+ if (before) clearEditedDrafts(before, manifest);
+ else pruneDrafted(manifest);
await backupOnce(file);
const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
await writeFile(tmp, serialise(manifest), "utf8");
@@ -866,6 +879,8 @@ function structureErrors(manifest) {
...validateClaims(manifest),
...validateTeasers(manifest),
...validateNarration(manifest),
+ ...validateDrafted(manifest),
+ ...validatePublish(manifest),
];
}
@@ -1083,6 +1098,73 @@ export async function updateNarration(dir, id, text, { token = null, at = null }
});
}
+/**
+ * A drafted field's whole value, written as THE OPERATOR's (release 28, M0):
+ * what umtool's "Use this" under an alternative (`<task>-draft.json`) runs.
+ * Checked as the field's own editor checks it; a structural write (snapshot
+ * first). Written without a drafted mark -- and the one it had, if any, goes
+ * (writeManifestAtomic): an alternative taken is the operator's choice.
+ *
+ * onscreen any entry's `{ title?, subtitle? }`
+ * lines a teaser's lines (validateTeaser)
+ * narration a card's narration object (validateNarration)
+ * render.chrome.flips the deck's flips (validateChrome)
+ * render.chrome.threads the deck's thread list (validateChrome; each
+ * clip's `thread` key is the build's to check)
+ * publish.youtube `{ title, description }` (validatePublish)
+ *
+ * The cut's order ("timeline") is not taken this way: an order replaces every
+ * entry, and is the cut task's to apply.
+ *
+ * @param {string} dir
+ * @param {{ entry?: string | null, field: string, value: unknown }} draft
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function writeDraftedField(dir, { entry = null, field, value }, { token = null } = {}) {
+ const onEntry = entry !== null && entry !== undefined && entry !== "";
+ if (onEntry ? !isEntryField(field) : !DRAFTED_MANIFEST_FIELDS.includes(field)) throw new Error(`${field} is not a drafted field`);
+ if (field === "timeline") throw new Error("a cut's order is applied by the cut task, not taken field by field");
+ if (value === undefined) throw new Error("no value to write");
+ return structural(dir, "use-draft", token, (m) => {
+ const copy = () => JSON.parse(JSON.stringify(value));
+ if (onEntry) {
+ const es = (m.timeline ?? []).filter((e) => e?.id === entry);
+ if (!es.length) throw new Error(`no timeline entry with id ${entry}`);
+ for (const e of es) {
+ if (field === "onscreen") setOnscreen(e, value);
+ else if (field === "lines") {
+ if (e.type !== "teaser") throw new Error(`${entry} is a ${e.type ?? "non-teaser"} entry, not a teaser`);
+ e.lines = copy();
+ const errors = validateTeaser(e);
+ if (errors.length) throw new StructureRefused(errors);
+ } else if (field === "narration") {
+ if (e.type !== "card") throw new Error(`${entry} is not a card`);
+ e.narration = copy();
+ }
+ }
+ return { entry, field, value: es[0][field] ?? null };
+ }
+ if (field === "publish.youtube") {
+ m.publish = { ...(m.publish && typeof m.publish === "object" ? m.publish : {}), youtube: copy() };
+ const errors = validatePublish(m);
+ if (errors.length) throw new StructureRefused(errors);
+ return { entry: null, field, value: m.publish.youtube };
+ }
+ const render = m.render ?? {};
+ if (!render.chrome || typeof render.chrome !== "object") {
+ throw new Error("flips and threads are drawn by the on-screen deck, and this manifest has none — turn the deck on first");
+ }
+ const key = field === "render.chrome.flips" ? "flips" : "threads";
+ const chrome = { ...render.chrome, [key]: copy() };
+ const { chrome: _old, ...rest } = render;
+ const already = new Set(validateChrome(render.chrome, rest));
+ const errors = validateChrome(chrome, rest).filter((e) => !already.has(e));
+ if (errors.length) throw new StructureRefused(errors);
+ m.render = { ...render, chrome };
+ return { entry: null, field, value: chrome[key] };
+ });
+}
+
const POST_TEXT_KEYS = ["platform", "author", "handle", "date", "text", "url", "shot", "flag", "accent", "logo", "siteChannel", "siteUrl", "postId", "variant"];
/**
diff --git a/umtool/lib/report/narration-review.mjs b/umtool/lib/report/narration-review.mjs
@@ -3,13 +3,15 @@
// card shows on screen, its review state (report-to-video's
// narration-review.mjs), and whether its voice is already kept beside the
// build (`out/narration/`, from a play or a build). What the page draws and
-// what the route answers after each action -- one shape.
+// what the route answers after each action -- one shape. Since release 28 the
+// verdicts are the drafts review's (drafts.review.json, narration's rows
+// `narrate/<cardId>/narration`; release 25's narration.review.json still read).
//
// Plain ESM: `node --test` runs it with no TypeScript.
import path from "node:path";
import { stat } from "node:fs/promises";
import { estimatedNarratedCardSeconds, narrationWords } from "umtool-report-to-video/narration";
-import { NARRATION_REVIEW_FILE, readNarrationReview, reviewRows } from "umtool-report-to-video/narration-review";
+import { DRAFTS_REVIEW_FILE, readNarrationReview, reviewRows } from "umtool-report-to-video/narration-review";
import { narrationDir, narrationWavPath, readNarrationRecord } from "umtool-report-to-video/narration-store";
/**
@@ -43,6 +45,8 @@ export async function narrationReviewView(projectDir, manifest) {
title: e.onscreen?.title ?? null,
style: e.style ?? null,
},
+ // Who drafted these words (release 28; null: written by hand).
+ drafted: e.drafted?.narration && typeof e.drafted.narration === "object" ? e.drafted.narration : null,
state: r.state,
verdict: r.row?.verdict ?? null,
note: r.row?.note ?? "",
@@ -53,5 +57,5 @@ export async function narrationReviewView(projectDir, manifest) {
}
const counts = { approved: 0, rejected: 0, edited: 0, unreviewed: 0 };
for (const r of rows) counts[r.state] += 1;
- return { file: NARRATION_REVIEW_FILE, exists: review.exists, error: review.error ?? null, rows, counts };
+ return { file: DRAFTS_REVIEW_FILE, exists: review.exists, error: review.error ?? null, rows, counts };
}
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -1205,25 +1205,68 @@ so the vote lands last), the length of the sentences, one beat, and a short
punch to end each paragraph. No tag: nothing in it is a sound a person would
make; and nothing says the council *ignored* anyone — the minutes do not.
-#### The narration review
+#### The drafts review (and the narration review)
+
+A field a draft task wrote (release 28) says so: **`drafted`**, a provenance
+`{ task, model, at, iteration?, attempt }` (`at` ISO; `attempt` the one of two
+kept). An entry's field carries it on the entry, keyed by field —
+`"drafted": { "onscreen": {…}, "narration": {…}, "lines": {…} }` (any entry's
+on-screen text, a card's narration, a teaser's lines); a manifest field carries
+it in a top-level map keyed by path — `"drafted": { "timeline": {…},
+"render.chrome.flips": {…}, "render.chrome.threads": {…}, "publish.youtube": {…} }`
+(the cut's order; the flips; the threads, each clip's `thread` key included; the
+YouTube title and description, `publish.youtube { title, description }`, a new
+top-level key). The one copy of these rules is
+`common/lib/report/drafted.mjs`; the build and the lint refuse a mark anywhere
+else (`validateDrafted`) and warn of one whose field is gone.
+
+- **No overwrite.** A field with a value and no mark is the operator's: no
+ draft task replaces it, forced or not. Its draft is kept as an
+ **alternative** in `<task>-draft.json` beside the manifest
+ (`narration-draft.json` for narration), shown under the field in umtool with
+ **Use this**, which writes it as the operator's own edit.
+- **An edit makes it the operator's.** umtool's manifest writer removes a
+ field's mark whenever a write changes that field (`clearEditedDrafts`).
+- **The review.** `/browse/<project>/review` lists every drafted field of the
+ cut — who drafted it, its value, **Approve**, **Reject** (with a note) — and
+ every alternative; the same badge sits beside the field on the project page
+ (the On-screen table's title, the teaser editor) and on the narration page.
+ Verdicts are `<project>/drafts.review.json` (`drafts-review.mjs`):
+ `{ "<task>/<entry id | *>/<field>": { verdict: "approved" | "rejected" | null,
+ note, key, text, at } }`, the task being the field's own (`onscreen/c01/onscreen`,
+ `narrate/k01/narration`, `teaser/fin/lines`, `threads/*/render.chrome.threads`).
+ A verdict is on the value it was given on (`key`), so **an edit or a re-draft
+ leaves it "changed since approved"**.
+- **The gate.** A drafted field not approved on its current value is a
+ **warning** in a preview or fast build and an **error** in a final one
+ (`--final`, which the driver's `final` preset passes): `--drafts-unreviewed`
+ builds the unapproved anyway, never a rejected one. A rejected draft is a
+ warning in a fast build and refuses a final one.
`/browse/<project>/narration` in umtool reviews the script card by card before
synthesis: each narrated card's words beside what the card shows on screen, its
-engine and voice, **Approve**, **Reject** (with a note saying what is wrong),
-the words edited in place (**Save words**, through the manifest writer:
-snapshot, validators, the generated-manifest note), and **Play**, which asks the
-editor for that one card (`narrate-via-editor.mjs --only <id>`) and plays it.
-
-Verdicts are `<project>/narration.review.json` (`narration-review.mjs`; the
-shape of `takes/verdicts.json`): `{ "<cardId>": { verdict: "approved" |
-"rejected" | null, note, key, text, at } }`. A verdict is on the words and voice
-it was given on (`key` is the narration's key), so **an edit or a voice change
-leaves the card "edited" — not approved** — and the page's edit clears the
-verdict as well.
-
-- **No review file**: nothing is held — a cut narrated before reviews existed
- builds as it did — and the lint WARNS that the narration has no review.
-- **A review file**: every narrated card in the cut must be approved on its
+engine and voice, who drafted it, **Approve**, **Reject** (with a note saying
+what is wrong), the words edited in place (**Save words**, through the manifest
+writer: snapshot, validators, the generated-manifest note), and **Play**, which
+asks the editor for that one card (`narrate-via-editor.mjs --only <id>`) and
+plays it.
+
+Its verdicts are the drafts review's rows `narrate/<cardId>/narration`
+(`narration-review.mjs` is that view of it). Release 25's
+`<project>/narration.review.json` — `{ "<cardId>": { verdict, note, key, text,
+at } }` — is still READ, unchanged; the drafts file wins on a card both have,
+and every new verdict goes to the drafts file. A verdict is on the words and
+voice it was given on (`key` is the narration's key), so **an edit or a voice
+change leaves the card "edited" — not approved** — and the page's edit clears
+the verdict as well.
+
+A narration that carries a `drafted` mark follows the drafts gate above. One
+written by hand (or before release 28) keeps release 25's rule, in every build:
+
+- **No narration verdict anywhere**: nothing is held — a cut narrated before
+ reviews existed builds as it did — and the lint WARNS that the narration has
+ no review.
+- **Once there is one**: every narrated card in the cut must be approved on its
current words. An unreviewed or edited card refuses the build (a lint error)
unless `--narration-unreviewed`; a **rejected** card refuses it always —
rewrite it and approve it, or take the narration out.
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -57,6 +57,12 @@
// --narration-unreviewed Build narrated cards the narration review has not
// approved (unreviewed, or edited since); a rejected one
// still refuses. Without a review file nothing is held.
+// --final The deliverable (the driver's `final` preset passes it):
+// every DRAFTED field (drafts-review.mjs) must be approved
+// on its current value -- unapproved or rejected refuses.
+// Without it they are warnings.
+// --drafts-unreviewed With --final: build drafted fields the review has not
+// approved; a rejected one still refuses.
// --no-xfade Hard cuts instead of crossfades (much faster; concat copy)
// --progress ndjson One JSON event per line instead of prose (for umtool)
// --continue-on-error Record a failed entry and carry on, instead of aborting
@@ -145,7 +151,8 @@ import {
cardNarrationSeconds, resolveNarrationRender, validateNarration,
} from "./narration.mjs";
import { narrationDir, narrationWavPath, readCutDisclosure, readNarrationRecords } from "./narration-store.mjs";
-import { readNarrationReview } from "./narration-review.mjs";
+import { readDraftsReview } from "./drafts-review.mjs";
+import { validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
// The lint a build runs before it renders, and the prune after its final mux.
import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs";
import { pruneChromeFrames } from "./prune-frames.mjs";
@@ -4118,7 +4125,7 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
{
const errors = [
...validateCutEdits(whole), ...validateTeasers(whole), ...validateClaims(whole), ...validateThreadEntries(whole),
- ...validateFlipEntries(whole), ...validateNarration(whole),
+ ...validateFlipEntries(whole), ...validateNarration(whole), ...validateDrafted(whole), ...validatePublish(whole),
];
if (errors.length) throw new Error(`manifest: ${errors.join("; ")}`);
}
@@ -4134,14 +4141,17 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// scan at 720p, a teaser line over house style. The validators above have
// spoken already; `--only` lints its one entry. Enforced below, once the runs
// that render nothing (a bench fetch, the thumbnail) are out of the way.
- // The narration review (narration-review.mjs) is part of the lint: an
- // un-approved narrated card refuses the build, unless --narration-unreviewed;
- // a narrated cut with no review file at all is a warning.
+ // The drafts review (drafts-review.mjs) is part of the lint: a drafted
+ // field not approved refuses a --final build (unless --drafts-unreviewed)
+ // and is a warning in any other; a hand-written narration keeps release
+ // 25's rule (narration-review.mjs) -- un-approved refuses once the cut's
+ // narration has a review, unless --narration-unreviewed.
const lint = opts.noLint
? { errors: [], warnings: [] }
: lintManifest(manifest, {
manifestDir, whole, only: only ?? null, validators: false,
- narrationReview: await readNarrationReview(manifestDir), narrationUnreviewed: opts.narrationUnreviewed === true,
+ draftsReview: await readDraftsReview(manifestDir), narrationUnreviewed: opts.narrationUnreviewed === true,
+ final: opts.final === true, draftsUnreviewed: opts.draftsUnreviewed === true,
});
// Where each post's QR goes: its page on the archive (`posts.links`
@@ -4854,6 +4864,7 @@ async function main() {
" [--chrome-only] [--no-chrome] [--chrome-preview <at> <dur>] [--keep-frames] (render.chrome, the deck)\n" +
" [--lint] [--no-lint] (lint the manifest and stop / build without the lint)\n" +
" [--narration-unreviewed] (build narrated cards the review has not approved; never a rejected one)\n" +
+ " [--final] [--drafts-unreviewed] (the deliverable: drafted fields must be approved / build the unapproved anyway)\n" +
" [--site-origin <url>] [--resolve-site-ids] [--cue-source auto|local|http]\n" +
" [--thumbnail] (render.brand only: out/<slug>.thumbnail.png and stop)",
);
@@ -4890,6 +4901,8 @@ async function main() {
keepFrames: argv.includes("--keep-frames"),
noLint: argv.includes("--no-lint"),
narrationUnreviewed: argv.includes("--narration-unreviewed"),
+ final: argv.includes("--final"),
+ draftsUnreviewed: argv.includes("--drafts-unreviewed"),
};
try {
Object.assign(opts, chromeFlags(argv));
@@ -4909,7 +4922,10 @@ async function main() {
// The lint alone: every warning and error, exit 1 on an error.
if (argv.includes("--lint")) {
- const lint = await lintManifestFile(manifestPath, { variant: opts.variant, only: flag("--only") ?? null, narrationUnreviewed: opts.narrationUnreviewed });
+ const lint = await lintManifestFile(manifestPath, {
+ variant: opts.variant, only: flag("--only") ?? null, narrationUnreviewed: opts.narrationUnreviewed,
+ final: opts.final, draftsUnreviewed: opts.draftsUnreviewed,
+ });
for (const w of lint.warnings) EMIT("note", { message: `lint: ${w}` });
for (const e of lint.errors) EMIT("note", { message: `lint ERROR: ${e}` });
EMIT("note", { message: `lint: ${lint.errors.length} error(s), ${lint.warnings.length} warning(s)` });
diff --git a/umtool/report-to-video/drafts-review.mjs b/umtool/report-to-video/drafts-review.mjs
@@ -0,0 +1,375 @@
+// THE DRAFTS REVIEW — one file of verdicts on every drafted field of a cut,
+// and the gate a build applies with it (release 28, M0; release 25's
+// narration review, generalised).
+//
+// <project>/drafts.review.json beside video.manifest.json
+// { "<task>/<entry id | *>/<field>": { "verdict": "approved" | "rejected" | null,
+// "note": string, "key": "<the field's key when judged>", "text": "<what was judged>", "at": ISO } }
+//
+// The address is drafted.mjs's `reviewAddress`: the field's own task (narrate,
+// onscreen, teaser, cut, flips, threads, youtube), the entry it is on (`*` for a
+// manifest field), the field -- `narrate/<cardId>/narration` for a card's
+// narration. The shape and its rules are the narration review's: every row
+// carries every key, a row with no verdict and no note is REMOVED, its own
+// write queue, tmp + rename, a file that does not parse is an ERROR (never
+// overwritten, never read as empty), and a rejection needs its note.
+//
+// A verdict is about THE VALUE IT WAS GIVEN ON: the row keeps its key
+// (`draftKey`: a card's narration by narration.mjs `narrationKey` -- the words
+// and the voice; any other field by drafted.mjs `fieldKey`), so an edit or a
+// re-draft leaves it "edited", not approved, without anything having to
+// remember to clear it.
+//
+// RELEASE 25's FILES READ UNCHANGED. `narration.review.json` ({ "<cardId>":
+// row }) is read beside the drafts file, its rows as `narrate/<cardId>/narration`;
+// the drafts file wins on an address both have. Every write goes to the drafts
+// file -- a cleared row whose address the old file still approves is kept in
+// the drafts file as an empty verdict, so the old approval does not show
+// through.
+//
+// THE GATE (`draftsReviewProblems`), per field the cut carries:
+// - a DRAFTED field (it carries a drafted mark) must be approved on its
+// current value. Unapproved (unreviewed, or edited since): a WARNING in a
+// preview or fast build, an ERROR in a `final` one unless
+// `--drafts-unreviewed` (`--narration-unreviewed` for a narration). Rejected:
+// an ERROR in `final` (no flag lets it through), a warning otherwise;
+// - a NARRATION with no drafted mark (written by hand, or before release 28)
+// keeps release 25's rule in every build: until the cut's narration has a
+// review (a narration row in either file) it is a warning; once it has one,
+// every narrated card must be approved -- unreviewed or edited refuses unless
+// `--narration-unreviewed` (or `--drafts-unreviewed`), rejected refuses always.
+//
+// Pure but for the files' read and write.
+import { readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+import { draftedFields, fieldKey, parseReviewAddress, reviewAddress } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
+import { narrationsOf } from "./narration.mjs";
+
+export const DRAFTS_REVIEW_FILE = "drafts.review.json";
+/** Release 25's file, read unchanged; never written any more. */
+export const NARRATION_REVIEW_FILE = "narration.review.json";
+export const REVIEW_VERDICTS = Object.freeze(["approved", "rejected"]);
+export const REVIEW_NOTE_LIMIT = 2000;
+
+/** `<manifest's directory>/drafts.review.json`. */
+export const draftsReviewFileOf = (manifestDir) => path.join(manifestDir, DRAFTS_REVIEW_FILE);
+
+/** The narration review address of a card. */
+export const narrationAddress = (cardId) => reviewAddress({ entry: cardId, field: "narration" });
+
+const str = (v) => (typeof v === "string" ? v : "");
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+/** One row, cleaned to the contract's shape. */
+export function cleanRow(row) {
+ return {
+ verdict: REVIEW_VERDICTS.includes(row?.verdict) ? row.verdict : null,
+ note: str(row?.note),
+ key: str(row?.key),
+ text: str(row?.text),
+ at: str(row?.at),
+ };
+}
+
+/** A drafts file's rows: those whose address is an address, cleaned. */
+export function cleanDraftsReview(raw) {
+ const out = {};
+ if (!isObj(raw)) return out;
+ for (const [address, row] of Object.entries(raw)) {
+ if (!parseReviewAddress(address) || !isObj(row)) continue;
+ out[address] = cleanRow(row);
+ }
+ return out;
+}
+
+const isCardId = (v) => typeof v === "string" && v.length > 0 && v.length <= 200;
+
+/** Release 25's file: rows by card id, cleaned. */
+export function cleanNarrationRows(raw) {
+ const out = {};
+ if (!isObj(raw)) return out;
+ for (const [id, row] of Object.entries(raw)) {
+ if (!isCardId(id) || !isObj(row)) continue;
+ out[id] = cleanRow(row);
+ }
+ return out;
+}
+
+async function readJson(file, name) {
+ let text;
+ try {
+ text = await readFile(file, "utf8");
+ } catch (err) {
+ if (err?.code === "ENOENT") return { exists: false, value: null };
+ return { exists: true, value: null, error: `${name} cannot be read: ${err?.message ?? err}` };
+ }
+ try {
+ return { exists: true, value: JSON.parse(text) };
+ } catch {
+ return { exists: true, value: null, error: `${name} does not parse; fix or remove it` };
+ }
+}
+
+/**
+ * The review of a cut: both files merged by address.
+ * exists either file is there
+ * rows address → row (the drafts file wins)
+ * files which of the two are there
+ * narration the cut's narration has a review (release 25's rule)
+ * error a file that does not parse -- a build must not read that as
+ * "nothing approved", nor a writer overwrite it
+ *
+ * @param {string} manifestDir
+ */
+export async function readDraftsReview(manifestDir) {
+ const [drafts, legacy] = await Promise.all([
+ readJson(draftsReviewFileOf(manifestDir), DRAFTS_REVIEW_FILE),
+ readJson(path.join(manifestDir, NARRATION_REVIEW_FILE), NARRATION_REVIEW_FILE),
+ ]);
+ const files = { drafts: drafts.exists, narration: legacy.exists };
+ const error = drafts.error ?? legacy.error;
+ if (error) return { exists: true, rows: {}, files, narration: true, error };
+ const rows = {};
+ for (const [id, row] of Object.entries(cleanNarrationRows(legacy.value))) rows[narrationAddress(id)] = row;
+ Object.assign(rows, cleanDraftsReview(drafts.value));
+ return reviewOf(rows, files);
+}
+
+function reviewOf(rows, files) {
+ const narration = files.narration || Object.keys(rows).some((a) => parseReviewAddress(a)?.field === "narration");
+ return { exists: files.drafts || files.narration, rows, files, narration };
+}
+
+/**
+ * A release 25 narration review (`{ exists, rows: { <cardId>: row }, error? }`,
+ * narration-review.mjs `readNarrationReview`) as a drafts review.
+ */
+export function draftsReviewFromNarration(review) {
+ if (!review) return null;
+ if (review.error) return { exists: true, rows: {}, files: { drafts: false, narration: true }, narration: true, error: review.error };
+ const rows = {};
+ for (const [id, row] of Object.entries(review.rows ?? {})) rows[narrationAddress(id)] = cleanRow(row);
+ return { ...reviewOf(rows, { drafts: false, narration: !!review.exists }), exists: !!review.exists };
+}
+
+/**
+ * The key a verdict on this field is given on: a card's narration by its
+ * words and voice (narrationKey), anything else by its value (fieldKey).
+ *
+ * @param {any} manifest
+ * @param {{ entry?: string | null, field: string }} target
+ */
+export function draftKey(manifest, target) {
+ if (target.field === "narration" && target.entry) {
+ return narrationsOf(manifest).find((n) => n.id === target.entry)?.key ?? fieldKey(manifest, target);
+ }
+ return fieldKey(manifest, target);
+}
+
+/** A row's state on a field's current key: approved, rejected, edited (judged on another value) or unreviewed. */
+export function draftReviewState(key, row) {
+ if (!row?.verdict) return "unreviewed";
+ if (row.key !== key) return "edited";
+ return row.verdict;
+}
+
+/** The words a verdict is given on: a short text of the field's value. */
+export function judgedText(field, value) {
+ if (value === undefined || value === null) return "";
+ if (field === "narration") return str(value?.text).trim();
+ if (field === "onscreen") return [value?.title, value?.subtitle].filter((s) => typeof s === "string" && s).join(" — ");
+ if (field === "lines" && Array.isArray(value)) return value.map((l) => (typeof l === "string" ? l : str(l?.text))).join(" / ");
+ if (field === "publish.youtube") return str(value?.title);
+ if (field === "timeline" && Array.isArray(value)) return value.map((e) => e?.id).join(", ");
+ return JSON.stringify(value).slice(0, 500);
+}
+
+/** How a field reads in a sentence. */
+export const FIELD_LABELS = Object.freeze({
+ onscreen: "on-screen text",
+ narration: "narration",
+ lines: "teaser lines",
+ timeline: "cut (its order)",
+ "render.chrome.flips": "flips",
+ "render.chrome.threads": "threads",
+ "publish.youtube": "YouTube title and description",
+});
+
+/**
+ * Every field the review covers, in timeline order then the manifest's: each
+ * drafted field (drafted.mjs `draftedFields`) and each narrated card (drafted
+ * or not, as the narration page lists them). Each row:
+ * { address, entry, field, provenance (null: not drafted), key, text, row, state }
+ *
+ * @param {any} manifest
+ * @param {{ rows?: Record<string, any> } | null} review
+ */
+export function draftsReviewRows(manifest, review) {
+ const out = [];
+ const seen = new Set();
+ const push = (entry, field, provenance, value) => {
+ const address = reviewAddress({ entry, field });
+ if (seen.has(address)) return;
+ seen.add(address);
+ const key = draftKey(manifest, { entry, field });
+ const row = review?.rows?.[address] ?? null;
+ out.push({ address, entry, field, provenance, key, text: judgedText(field, value), row, state: draftReviewState(key, row) });
+ };
+ const drafted = draftedFields(manifest);
+ const byAddress = new Map(drafted.map((d) => [reviewAddress(d), d]));
+ // Narration rows in timeline order, interleaved with the other entry fields.
+ const narrated = new Map(narrationsOf(manifest).map((n) => [n.id, n]));
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) {
+ for (const field of ["onscreen", "narration", "lines"]) {
+ const d = byAddress.get(reviewAddress({ entry: e?.id, field }));
+ if (d) push(d.entry, field, d.provenance, d.value);
+ else if (field === "narration" && narrated.has(e?.id)) push(e.id, "narration", null, e.narration);
+ }
+ }
+ for (const d of drafted) if (d.entry === null) push(null, d.field, d.provenance, d.value);
+ return out;
+}
+
+const whereOf = (r) => (r.entry ? `timeline ${r.entry}` : r.field);
+const LIST_AT_MOST = 8;
+
+/**
+ * What the review says about building this cut: `errors` refuse it, `notes`
+ * and `warnings` are said.
+ *
+ * @param {any} manifest the cut
+ * @param {{ exists: boolean, rows: Record<string, any>, narration?: boolean, error?: string } | null} review
+ * null: not read (a run that says nothing about reviews)
+ * @param {{ final?: boolean, allowUnreviewed?: boolean, allowNarrationUnreviewed?: boolean, only?: string | null }} [opts]
+ */
+export function draftsReviewProblems(manifest, review, { final = false, allowUnreviewed = false, allowNarrationUnreviewed = false, only = null } = {}) {
+ const errors = [];
+ const notes = [];
+ const warnings = [];
+ if (!review) return { errors, notes, warnings };
+ const rows = draftsReviewRows(manifest, review).filter((r) => !only || r.entry === only);
+ if (!rows.length) return { errors, notes, warnings };
+ if (review.error) return { errors: [review.error], notes, warnings };
+
+ // Release 25's rule, for a narration nobody drafted.
+ const hand = rows.filter((r) => r.field === "narration" && !r.provenance);
+ if (hand.length && !review.narration) {
+ warnings.push(
+ `the narration (${hand.length} card${hand.length === 1 ? "" : "s"}) has no review — ${DRAFTS_REVIEW_FILE} has no narration verdicts; ` +
+ "review it card by card on umtool's narration page before it is published",
+ );
+ } else if (hand.length) {
+ for (const r of hand) {
+ if (r.state === "approved") continue;
+ if (r.state === "rejected") {
+ errors.push(
+ `timeline ${r.entry}: its narration was rejected${r.row?.note ? ` ("${r.row.note}")` : ""} — rewrite it and approve it, or take the narration out`,
+ );
+ continue;
+ }
+ const why = r.state === "edited" ? "edited since it was approved" : "not reviewed";
+ if (allowNarrationUnreviewed || allowUnreviewed) {
+ notes.push(`timeline ${r.entry}: its narration is ${why} — built anyway (${allowNarrationUnreviewed ? "--narration-unreviewed" : "--drafts-unreviewed"})`);
+ } else errors.push(`timeline ${r.entry}: its narration is ${why} — approve it on umtool's narration page, or build with --narration-unreviewed`);
+ }
+ }
+
+ // The drafted fields.
+ const pending = [];
+ for (const r of rows.filter((x) => x.provenance)) {
+ if (r.state === "approved") continue;
+ const what = `${whereOf(r)}: its ${FIELD_LABELS[r.field] ?? r.field} (drafted by ${r.provenance.model})`;
+ if (r.state === "rejected") {
+ const said = `${what} was rejected${r.row?.note ? ` ("${r.row.note}")` : ""}`;
+ if (final) errors.push(`${said} — redraft or rewrite it and approve it; a final build takes no rejected draft`);
+ else warnings.push(`${said} — a final build refuses it`);
+ continue;
+ }
+ const why = r.state === "edited" ? "changed since it was approved" : "not approved";
+ if (!final) {
+ pending.push(r);
+ continue;
+ }
+ const flag = allowUnreviewed ? "--drafts-unreviewed" : allowNarrationUnreviewed && r.field === "narration" ? "--narration-unreviewed" : null;
+ if (flag) notes.push(`${what} is ${why} — built anyway (${flag})`);
+ else errors.push(`${what} is ${why} — approve it on umtool's review page, or build with --drafts-unreviewed`);
+ }
+ if (pending.length) {
+ const names = pending.slice(0, LIST_AT_MOST).map((r) => r.address);
+ warnings.push(
+ `${pending.length} drafted field${pending.length === 1 ? " is" : "s are"} not approved (${names.join(", ")}` +
+ `${pending.length > LIST_AT_MOST ? `, and ${pending.length - LIST_AT_MOST} more` : ""}) — a final build refuses ${pending.length === 1 ? "it" : "them"} until approved`,
+ );
+ }
+ return { errors, notes, warnings };
+}
+
+/** @type {Promise<unknown>} */
+let queue = Promise.resolve();
+function withReviewLock(fn) {
+ const run = queue.then(fn, fn);
+ queue = run.then(
+ () => undefined,
+ () => undefined,
+ );
+ return run;
+}
+
+/**
+ * Set one field's review. `patch.verdict` "approved" | "rejected" | null (null
+ * clears it); `note` replaces the note; `key` and `text` are the value the
+ * verdict is about (a key is required with a verdict). A rejection needs its
+ * note. Returns the row as stored (null when removed) and every row of the
+ * merged review. Writes the drafts file only.
+ *
+ * @param {string} manifestDir
+ * @param {string} address
+ * @param {{ verdict?: string | null, note?: string, key?: string, text?: string }} patch
+ */
+export async function setDraftReview(manifestDir, address, patch) {
+ if (!parseReviewAddress(address)) throw new Error(`${JSON.stringify(address)} is not a review address (<task>/<entry or *>/<field>)`);
+ if (patch.verdict !== undefined && patch.verdict !== null && !REVIEW_VERDICTS.includes(patch.verdict)) {
+ throw new Error(`verdict must be one of ${REVIEW_VERDICTS.join(", ")} or null`);
+ }
+ if (patch.note !== undefined && typeof patch.note !== "string") throw new Error("note must be a string");
+ if (patch.verdict && !(typeof patch.key === "string" && patch.key && typeof patch.text === "string")) {
+ throw new Error("a verdict is given on words: key and text are required");
+ }
+ const file = draftsReviewFileOf(manifestDir);
+ return withReviewLock(async () => {
+ const cur = await readDraftsReview(manifestDir);
+ if (cur.error) throw new Error(cur.error);
+ const own = await readJson(file, DRAFTS_REVIEW_FILE);
+ if (own.error) throw new Error(own.error);
+ const map = cleanDraftsReview(own.value);
+ const prev = cur.rows[address] ?? { verdict: null, note: "", key: "", text: "", at: "" };
+ const row = {
+ verdict: patch.verdict === undefined ? prev.verdict : patch.verdict,
+ note: patch.note === undefined ? prev.note : patch.note.slice(0, REVIEW_NOTE_LIMIT).trim(),
+ key: patch.verdict ? patch.key : patch.verdict === null ? "" : prev.key,
+ text: patch.verdict ? patch.text : patch.verdict === null ? "" : prev.text,
+ at: new Date().toISOString(),
+ };
+ if (row.verdict === "rejected" && !row.note) {
+ throw new Error("a rejection needs its note: say what is wrong with the words");
+ }
+ // An empty row goes -- unless release 25's file still has this address,
+ // whose row would show through: then the empty row stays, and wins.
+ const target = parseReviewAddress(address);
+ let legacyHas = false;
+ if (target.field === "narration" && target.entry && cur.files.narration) {
+ const legacy = await readJson(path.join(manifestDir, NARRATION_REVIEW_FILE), NARRATION_REVIEW_FILE);
+ legacyHas = isObj(legacy.value) && isObj(legacy.value[target.entry]);
+ }
+ if (row.verdict === null && !row.note && !legacyHas) delete map[address];
+ else map[address] = row;
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8");
+ await rename(tmp, file);
+ const stored = row.verdict === null && !row.note ? null : row;
+ const rows = { ...cur.rows, ...map };
+ if (!map[address]) delete rows[address];
+ return { entry: stored, rows };
+ });
+}
diff --git a/umtool/report-to-video/drafts-review.test.mjs b/umtool/report-to-video/drafts-review.test.mjs
@@ -0,0 +1,213 @@
+// drafts-review.mjs (release 28, M0): one review file for every drafted
+// field, release 25's narration file read unchanged, the edit-unapproves rule,
+// and the gate -- a warning in a preview or fast build, refused in a final one
+// -- over the S0 kit's `full` manifest.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { buildVideo, setProgressMode } from "./build-video.mjs";
+import {
+ DRAFTS_REVIEW_FILE, NARRATION_REVIEW_FILE, draftKey, draftsReviewProblems, draftsReviewRows, readDraftsReview, setDraftReview,
+} from "./drafts-review.mjs";
+import { lintManifest, lintManifestFile } from "./lint.mjs";
+import { narrationsOf } from "./narration.mjs";
+import { readNarrationReview, setNarrationReview } from "./narration-review.mjs";
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const full = () => JSON.parse(readFileSync(path.join(HERE, "../../common/testing/draft/manifests/full.video.manifest.json"), "utf8"));
+const P = (task, model = "qwen3:8b") => ({ task, model, at: "2026-10-13T10:00:00.000Z", iteration: 1, attempt: 1 });
+const entry = (m, id) => m.timeline.find((e) => e.id === id);
+const tmp = (t, name) => {
+ const dir = mkdtempSync(path.join(tmpdir(), `rtv-drafts-${name}-`));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ return dir;
+};
+
+// The full fixture with drafted fields: c01's on-screen text and the teaser's
+// lines and the threads drafted; the contest card's narration drafted.
+function drafted() {
+ const m = full();
+ entry(m, "c01").drafted = { onscreen: P("onscreen") };
+ entry(m, "fin").drafted = { lines: P("teaser", "claude-sonnet-5-5") };
+ entry(m, "the-contest").drafted = { narration: P("narrate") };
+ m.drafted = { "render.chrome.threads": P("threads") };
+ return m;
+}
+const review = (rows = {}, o = {}) => ({ exists: true, rows, files: { drafts: true, narration: false }, narration: false, ...o });
+const approve = (m, entryId, field) => ({ verdict: "approved", key: draftKey(m, { entry: entryId, field }), text: "", note: "", at: "" });
+
+test("the rows: every drafted field and every narrated card, in timeline order, with its address and key", () => {
+ const m = drafted();
+ const rows = draftsReviewRows(m, null);
+ assert.deepEqual(rows.map((r) => [r.address, r.provenance?.task ?? null, r.state]), [
+ ["onscreen/c01/onscreen", "onscreen", "unreviewed"],
+ ["narrate/the-contest/narration", "narrate", "unreviewed"],
+ ["teaser/fin/lines", "teaser", "unreviewed"],
+ ["threads/*/render.chrome.threads", "threads", "unreviewed"],
+ ]);
+ assert.equal(rows[0].text, "Not for sale — The baker on selling to a chain");
+ // A narration's key is narration.mjs's: the words and the voice.
+ assert.equal(rows[1].key, narrationsOf(m).find((n) => n.id === "the-contest").key);
+});
+
+test("the gate: preview and fast warn in one line; final refuses each; --drafts-unreviewed lets the unapproved through", () => {
+ const m = drafted();
+ const none = review();
+ const fast = draftsReviewProblems(m, none);
+ assert.deepEqual(fast.errors, []);
+ assert.equal(fast.warnings.length, 1);
+ assert.match(fast.warnings[0], /^4 drafted fields are not approved \(onscreen\/c01\/onscreen, narrate\/the-contest\/narration, teaser\/fin\/lines, threads\/\*\/render\.chrome\.threads\) — a final build refuses them until approved$/);
+ const fin = draftsReviewProblems(m, none, { final: true });
+ assert.equal(fin.errors.length, 4, fin.errors.join("\n"));
+ assert.match(fin.errors[0], /^timeline c01: its on-screen text \(drafted by qwen3:8b\) is not approved — approve it on umtool's review page, or build with --drafts-unreviewed$/);
+ assert.match(fin.errors[2], /^timeline fin: its teaser lines \(drafted by claude-sonnet-5-5\) is not approved/);
+ assert.match(fin.errors[3], /^render\.chrome\.threads: its threads \(drafted by qwen3:8b\) is not approved/);
+ const through = draftsReviewProblems(m, none, { final: true, allowUnreviewed: true });
+ assert.deepEqual(through.errors, []);
+ assert.equal(through.notes.length, 4);
+ assert.match(through.notes[0], /built anyway \(--drafts-unreviewed\)/);
+ // --narration-unreviewed is the alias for the narration rows only.
+ const narr = draftsReviewProblems(m, none, { final: true, allowNarrationUnreviewed: true });
+ assert.equal(narr.errors.length, 3);
+ assert.match(narr.notes[0], /timeline the-contest: its narration \(drafted by qwen3:8b\) is not approved — built anyway \(--narration-unreviewed\)/);
+ // `only` keeps one entry's rows.
+ assert.equal(draftsReviewProblems(m, none, { final: true, only: "c01" }).errors.length, 1);
+ // Not read: nothing said.
+ assert.deepEqual(draftsReviewProblems(m, null, { final: true }), { errors: [], notes: [], warnings: [] });
+});
+
+test("the gate: approved passes; an edit or re-draft leaves it unapproved; a rejected one refuses a final build, flag or not", () => {
+ const m = drafted();
+ const rows = {
+ "onscreen/c01/onscreen": approve(m, "c01", "onscreen"),
+ "narrate/the-contest/narration": approve(m, "the-contest", "narration"),
+ "teaser/fin/lines": { ...approve(m, "fin", "lines"), verdict: "rejected", note: "too long" },
+ "threads/*/render.chrome.threads": approve(m, null, "render.chrome.threads"),
+ };
+ const fin = draftsReviewProblems(m, review(rows), { final: true, allowUnreviewed: true });
+ assert.deepEqual(fin.errors, [
+ 'timeline fin: its teaser lines (drafted by claude-sonnet-5-5) was rejected ("too long") — redraft or rewrite it and approve it; a final build takes no rejected draft',
+ ]);
+ const fast = draftsReviewProblems(m, review(rows));
+ assert.deepEqual(fast.errors, []);
+ assert.match(fast.warnings[0], /timeline fin: its teaser lines .* was rejected \("too long"\) — a final build refuses it/);
+ // A re-draft (or any change of value) of an approved field: edited, not approved.
+ entry(m, "c01").onscreen.title = "Redrafted";
+ entry(m, "c02").thread = "contest";
+ const after = draftsReviewRows(m, review(rows));
+ assert.equal(after.find((r) => r.address === "onscreen/c01/onscreen").state, "edited");
+ assert.equal(after.find((r) => r.address === "threads/*/render.chrome.threads").state, "edited");
+ assert.equal(after.find((r) => r.address === "narrate/the-contest/narration").state, "approved");
+ const again = draftsReviewProblems(m, review(rows), { final: true });
+ assert.match(again.errors.find((e) => e.startsWith("timeline c01")), /is changed since it was approved/);
+ // Another voice un-approves a narration, as in release 25.
+ m.timeline.find((e) => e.id === "the-contest").narration.voice = "am_adam";
+ assert.equal(draftsReviewRows(m, review(rows)).find((r) => r.field === "narration").state, "edited");
+});
+
+test("a hand-written narration keeps release 25's rule in every build: no review, a warning even in final", () => {
+ const m = full(); // the contest card's narration has no drafted mark
+ const fin = draftsReviewProblems(m, review({}, { exists: false, files: { drafts: false, narration: false } }), { final: true });
+ assert.deepEqual(fin.errors, []);
+ assert.match(fin.warnings[0], /the narration \(1 card\) has no review/);
+ // Once the cut's narration has a review, it must be approved -- in any build.
+ const started = review({ "narrate/other/narration": { verdict: null, note: "x", key: "", text: "", at: "" } }, { narration: true });
+ assert.match(draftsReviewProblems(m, started).errors[0], /timeline the-contest: its narration is not reviewed — approve it on umtool's narration page, or build with --narration-unreviewed/);
+ assert.deepEqual(draftsReviewProblems(m, started, { allowUnreviewed: true }).errors, []);
+});
+
+test("the files: release 25's narration.review.json reads unchanged; the drafts file wins; writes go to the drafts file", async (t) => {
+ const dir = tmp(t, "files");
+ const m = drafted();
+ const [n] = narrationsOf(m);
+ assert.deepEqual(await readDraftsReview(dir), { exists: false, rows: {}, files: { drafts: false, narration: false }, narration: false });
+ // A release 25 file, as it was written.
+ writeFileSync(path.join(dir, NARRATION_REVIEW_FILE), JSON.stringify({ "the-contest": { verdict: "approved", note: "", key: n.key, text: n.text, at: "2026-10-10T00:00:00.000Z" } }));
+ const r = await readDraftsReview(dir);
+ assert.equal(r.rows["narrate/the-contest/narration"].verdict, "approved");
+ assert.equal(r.narration, true);
+ assert.equal(draftsReviewRows(m, r).find((x) => x.field === "narration").state, "approved");
+ assert.deepEqual((await readNarrationReview(dir)).rows["the-contest"].verdict, "approved");
+ // A verdict on another field writes the drafts file; the old file is untouched.
+ const before = readFileSync(path.join(dir, NARRATION_REVIEW_FILE), "utf8");
+ await setDraftReview(dir, "onscreen/c01/onscreen", { verdict: "approved", key: draftKey(m, { entry: "c01", field: "onscreen" }), text: "t" });
+ assert.equal(readFileSync(path.join(dir, NARRATION_REVIEW_FILE), "utf8"), before);
+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(path.join(dir, DRAFTS_REVIEW_FILE), "utf8"))), ["onscreen/c01/onscreen"]);
+ // Clearing the old file's approval: the drafts file keeps an empty row, which wins.
+ await setNarrationReview(dir, "the-contest", { verdict: null });
+ const cleared = await readDraftsReview(dir);
+ assert.equal(cleared.rows["narrate/the-contest/narration"].verdict, null);
+ assert.equal(JSON.parse(readFileSync(path.join(dir, DRAFTS_REVIEW_FILE), "utf8"))["narrate/the-contest/narration"].verdict, null);
+ // The drafts file wins on an address both have.
+ await setNarrationReview(dir, "the-contest", { verdict: "rejected", key: n.key, text: n.text, note: "no" });
+ assert.equal((await readDraftsReview(dir)).rows["narrate/the-contest/narration"].verdict, "rejected");
+ // Refusals.
+ await assert.rejects(setDraftReview(dir, "nope", { verdict: null }), /not a review address/);
+ await assert.rejects(setDraftReview(dir, "onscreen/c02/onscreen", { verdict: "rejected", key: "k", text: "t" }), /a rejection needs its note/);
+ // A drafts file that does not parse is an error, never overwritten.
+ writeFileSync(path.join(dir, DRAFTS_REVIEW_FILE), "{ nope");
+ assert.match((await readDraftsReview(dir)).error, /drafts\.review\.json does not parse/);
+ await assert.rejects(setDraftReview(dir, "onscreen/c01/onscreen", { verdict: null }), /does not parse/);
+ assert.equal(readFileSync(path.join(dir, DRAFTS_REVIEW_FILE), "utf8"), "{ nope");
+});
+
+test("the lint: severities per mode, an orphan mark warned, a misplaced one refused", async (t) => {
+ const dir = tmp(t, "lint");
+ const m = drafted();
+ const file = path.join(dir, "video.manifest.json");
+ writeFileSync(file, JSON.stringify(m));
+ const fast = await lintManifestFile(file);
+ assert.deepEqual(fast.errors, []);
+ assert.ok(fast.warnings.some((w) => /^4 drafted fields are not approved/.test(w)), fast.warnings.join("\n"));
+ const fin = await lintManifestFile(file, { final: true });
+ assert.equal(fin.errors.filter((e) => /is not approved — approve it on umtool's review page/.test(e)).length, 4, fin.errors.join("\n"));
+ assert.deepEqual((await lintManifestFile(file, { final: true, draftsUnreviewed: true })).errors, []);
+ // Approve them all through the file: the final lint is clean.
+ for (const r of draftsReviewRows(m, null)) await setDraftReview(dir, r.address, { verdict: "approved", key: r.key, text: r.text });
+ assert.deepEqual((await lintManifestFile(file, { final: true })).errors, []);
+ // An orphan is a warning; a mark where no field may be drafted is an error.
+ const o = drafted();
+ entry(o, "c02").drafted = { onscreen: P("onscreen") };
+ entry(o, "c03").drafted = { narration: P("narrate") };
+ const lint = lintManifest(o, {});
+ assert.ok(lint.warnings.some((w) => /timeline\[3\] \(c02\)\.drafted\.onscreen: its field is gone — the drafted mark is an orphan/.test(w)), lint.warnings.join("\n"));
+ assert.ok(lint.errors.some((e) => /\(c03\)\.drafted\.narration: a clip has no narration to draft/.test(e)), lint.errors.join("\n"));
+ // publish: a YouTube text is accepted, anything else refused.
+ assert.deepEqual(lintManifest({ ...full(), publish: { youtube: { title: "T", description: "D" } } }, {}).errors, []);
+ assert.ok(lintManifest({ ...full(), publish: { tiktok: {} } }, {}).errors.some((e) => /publish\.tiktok is not a publish key/.test(e)));
+});
+
+async function quietly(fn) {
+ const events = [];
+ setProgressMode((e) => events.push(e));
+ try {
+ return { result: await fn().catch((err) => ({ err })), events };
+ } finally {
+ setProgressMode("human");
+ }
+}
+
+test("the build: --final refuses an unapproved draft before anything is fetched; approved, it goes on", async (t) => {
+ const dir = tmp(t, "build");
+ const manifestPath = path.join(dir, "video.manifest.json");
+ const m = {
+ slug: "rv", title: "RV", render: { transition: 0, audioRate: 48000, audioChannels: 2, fps: 10 },
+ timeline: [{ type: "card", id: "k1", heading: "K", seconds: 1, onscreen: { title: "Drafted" }, drafted: { onscreen: P("onscreen") } }],
+ };
+ writeFileSync(manifestPath, JSON.stringify(m));
+ const held = await quietly(() => buildVideo({ manifestPath, opts: { final: true, skipFetch: true } }));
+ assert.match(String(held.result?.err?.message), /lint: timeline k1: its on-screen text \(drafted by qwen3:8b\) is not approved/);
+ // Not final: the lint says it, and nothing is refused for it.
+ const fast = await quietly(() => buildVideo({ manifestPath, opts: { skipFetch: true, out: dir } }));
+ assert.ok(fast.events.some((e) => e.ev === "note" && /lint: 1 drafted field is not approved \(onscreen\/k1\/onscreen\)/.test(e.message)), JSON.stringify(fast.events.slice(0, 5)));
+ assert.doesNotMatch(String(fast.result?.err?.message ?? ""), /is not approved/);
+ await setDraftReview(dir, "onscreen/k1/onscreen", { verdict: "approved", key: draftKey(m, { entry: "k1", field: "onscreen" }), text: "Drafted" });
+ const ok = await quietly(() => buildVideo({ manifestPath, opts: { final: true, skipFetch: true } }));
+ assert.doesNotMatch(String(ok.result?.err?.message ?? ""), /is not approved/);
+});
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -2,7 +2,7 @@
// THE MANIFEST LINT — what a render would get wrong that no validator refuses,
// said before a single frame is drawn.
//
-// node umtool/report-to-video/lint.mjs <manifest.json> [--variant sourced|full] [--json]
+// node umtool/report-to-video/lint.mjs <manifest.json> [--variant sourced|full] [--final] [--json]
// node umtool/report-to-video/build-video.mjs <manifest.json> --lint [--variant …]
//
// Both print every warning and error and exit 1 on an error. A build runs the
@@ -27,13 +27,25 @@
// - a narrated card not approved on its current words when the cut has a
// narration review (narration-review.mjs): rejected, edited since it was
// approved, or not reviewed -- the last two pass with `--narration-unreviewed`;
+// - in a `--final` build, a DRAFTED field (drafts-review.mjs: an entry's
+// on-screen text, a card's narration, a teaser's lines, the cut's order,
+// the flips, the threads, the YouTube text) not approved on its current
+// value -- `--drafts-unreviewed` lets the unapproved through, never a
+// rejected one;
+// - a `drafted` mark that is malformed or where no field may be drafted, and
+// a `publish` block that is not `{ youtube: { title, description } }`
+// (drafted.mjs `validateDrafted`, `validatePublish`);
// - a narrated card whose `seconds` is a number shorter than its narration
// needs (the lead, the words, the tail). The words' length is known once
// the voice is synthesized: the build checks it then, and `--lint` reads
// the kept narrations (out/narration/) and checks those it finds.
// WARNINGS
-// - a narrated cut with no review file at all (narration.review.json): a
-// cut narrated before reviews existed builds as it did, and is told so;
+// - a narrated cut with no narration review at all: a cut narrated before
+// reviews existed builds as it did, and is told so;
+// - in a preview or fast build, the drafted fields not approved yet (one
+// line), and each rejected one: a final build refuses them;
+// - a `drafted` mark whose field is gone (an orphan): umtool's next write
+// drops it;
// - a teaser line over TEASER_HOUSE_CHARS -- an overline's or a kicker's
// first tier, or any line's break: house style, not a fit. (A title's
// first tier is held to the same 34 by the frame itself, TEASER_LIMITS.fit,
@@ -73,7 +85,8 @@ import { validateFlipEntries } from "./flips.mjs";
import { qrUrlFor } from "./render-cards.mjs";
import { cardNarrationSeconds, hasNarration, narrationsOf, validateNarration } from "./narration.mjs";
import { validatePodcast } from "./build-podcast.mjs";
-import { readNarrationReview, reviewProblems } from "./narration-review.mjs";
+import { draftsReviewFromNarration, draftsReviewProblems, readDraftsReview } from "./drafts-review.mjs";
+import { orphanDrafts, validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
export const TEASER_HOUSE_CHARS = 34;
export const MIN_QR_PX_PER_MODULE_720P = 1.5;
@@ -209,6 +222,8 @@ export function validatorErrors(whole) {
...validateThreadEntries(whole), ...validateFlipEntries(whole), ...validateNarration(whole),
// The podcast's settings: its render refuses them, and `--lint` says so first.
...validatePodcast(whole),
+ // Release 28: where a field says it was drafted, and the publish block.
+ ...validateDrafted(whole), ...validatePublish(whole),
];
if (deckOn(whole.render)) {
errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`));
@@ -247,16 +262,22 @@ export function narrationLengthErrors(manifest, secondsById, { only = null } = {
* @param {any} manifest the cut, as selectVariant returns it
* @param {{ manifestDir?: string, whole?: any, exists?: (p: string) => boolean,
* only?: string|null, validators?: boolean, narrationSeconds?: Map<string, number> | null,
- * narrationReview?: { exists: boolean, rows: object, error?: string } | null, narrationUnreviewed?: boolean }} [opts]
+ * narrationReview?: { exists: boolean, rows: object, error?: string } | null, narrationUnreviewed?: boolean,
+ * draftsReview?: { exists: boolean, rows: object, narration?: boolean, error?: string } | null,
+ * final?: boolean, draftsUnreviewed?: boolean }} [opts]
* `whole` is the manifest as written (what the validators read);
* `validators: false` leaves them out (a build has run them already);
* `only` lints one timeline entry (and the posts attached to it);
- * `narrationSeconds` the kept narrations' seconds by card id (null: not read).
+ * `narrationSeconds` the kept narrations' seconds by card id (null: not read);
+ * `draftsReview` the cut's drafts review (drafts-review.mjs `readDraftsReview`;
+ * null: not read -- `narrationReview`, release 25's shape, is read as one);
+ * `final` a final build (drafted fields not approved refuse it);
+ * `draftsUnreviewed` / `narrationUnreviewed` let the unapproved through.
* @returns {{ errors: string[], warnings: string[] }}
*/
export function lintManifest(manifest, {
manifestDir, whole = manifest, exists = existsSync, only = null, validators = true, narrationSeconds = null,
- narrationReview = null, narrationUnreviewed = false,
+ narrationReview = null, narrationUnreviewed = false, draftsReview = null, final = false, draftsUnreviewed = false,
} = {}) {
const errors = [];
const warnings = [];
@@ -306,12 +327,17 @@ export function lintManifest(manifest, {
}
}
- // The narration review: `narrationReview` null when it was not read.
+ // The drafts review, narration's included: null when it was not read.
{
- const r = reviewProblems(manifest, narrationReview, { only, allowUnreviewed: narrationUnreviewed });
+ const review = draftsReview ?? draftsReviewFromNarration(narrationReview);
+ const r = draftsReviewProblems(manifest, review, {
+ final, only, allowUnreviewed: draftsUnreviewed, allowNarrationUnreviewed: narrationUnreviewed,
+ });
errors.push(...r.errors);
warnings.push(...r.warnings, ...r.notes);
}
+ // A mark whose field is gone: dropped by umtool's next write, said here.
+ if (!only) for (const o of orphanDrafts(whole)) warnings.push(`${o.where}: its field is gone — the drafted mark is an orphan (umtool's next write drops it)`);
if (narrationSeconds) {
errors.push(...narrationLengthErrors(manifest, narrationSeconds, { only }));
@@ -332,7 +358,9 @@ export function lintManifest(manifest, {
*
* @returns {Promise<{ errors: string[], warnings: string[], variant: string }>}
*/
-export async function lintManifestFile(manifestPath, { variant = "sourced", only = null, narrationUnreviewed = false } = {}) {
+export async function lintManifestFile(manifestPath, {
+ variant = "sourced", only = null, narrationUnreviewed = false, final = false, draftsUnreviewed = false,
+} = {}) {
const { readFile } = await import("node:fs/promises");
const { selectVariant } = await import("./build-video.mjs");
const whole = JSON.parse(await readFile(manifestPath, "utf8"));
@@ -347,8 +375,11 @@ export async function lintManifestFile(manifestPath, { variant = "sourced", only
const recs = await readNarrationRecords(narrationDir(path.join(manifestDir, "out")), narrationsOf(manifest));
narrationSeconds = new Map([...recs].map(([id, r]) => [id, r.seconds]));
}
- const narrationReview = await readNarrationReview(manifestDir);
- return { ...lintManifest(manifest, { manifestDir, whole, only, narrationSeconds, narrationReview, narrationUnreviewed }), variant };
+ const draftsReview = await readDraftsReview(manifestDir);
+ return {
+ ...lintManifest(manifest, { manifestDir, whole, only, narrationSeconds, draftsReview, narrationUnreviewed, final, draftsUnreviewed }),
+ variant,
+ };
} catch (err) {
return { errors: [err?.message ?? String(err)], warnings: [], variant };
}
@@ -369,10 +400,15 @@ if (import.meta.url === `file://${process.argv[1]}`) {
const valued = new Set(["--variant"]);
const manifestPath = argv.find((a, i) => !a.startsWith("--") && !valued.has(argv[i - 1]));
if (!manifestPath) {
- console.error("usage: lint.mjs <manifest.json> [--variant sourced|full] [--json]");
+ console.error("usage: lint.mjs <manifest.json> [--variant sourced|full] [--final] [--drafts-unreviewed] [--narration-unreviewed] [--json]");
process.exit(2);
}
- lintManifestFile(manifestPath, { variant: flag("--variant") ?? "sourced" }).then((r) => {
+ lintManifestFile(manifestPath, {
+ variant: flag("--variant") ?? "sourced",
+ final: argv.includes("--final"),
+ draftsUnreviewed: argv.includes("--drafts-unreviewed"),
+ narrationUnreviewed: argv.includes("--narration-unreviewed"),
+ }).then((r) => {
if (argv.includes("--json")) console.log(JSON.stringify(r, null, 2));
else for (const line of lintReport(r)) console.log(line);
process.exit(r.errors.length ? 1 : 0);
diff --git a/umtool/report-to-video/narration-review.mjs b/umtool/report-to-video/narration-review.mjs
@@ -1,7 +1,10 @@
// The review of a cut's narration script, card by card, before synthesis
-// (release 25, T5).
+// (release 25, T5) -- since release 28 (M0) a view of the drafts review
+// (drafts-review.mjs), whose rows for a card's narration are
+// `narrate/<cardId>/narration`.
//
-// <project>/narration.review.json beside video.manifest.json
+// <project>/drafts.review.json every verdict, written here
+// <project>/narration.review.json release 25's file, READ UNCHANGED:
// { "<cardId>": { "verdict": "approved" | "rejected" | null, "note": string,
// "key": "<narrationKey when judged>", "text": "<the words judged>", "at": ISO } }
//
@@ -16,64 +19,47 @@
// approved any more, without anything having to remember to clear it. The
// writer that edits the words (umtool's narration page) clears it as well.
//
-// The rule the build applies (`reviewProblems`): with NO review file, nothing
-// is held -- a cut narrated before reviews existed builds as it did, and the
-// lint says the file is missing (a warning). With one, every narrated card in
-// the cut must be approved on its current words: an unreviewed or edited card
-// refuses the build unless `--narration-unreviewed`; a REJECTED card refuses
-// it always (rewrite and approve it, or take the narration out).
+// The rule the build applies is drafts-review.mjs's `draftsReviewProblems`:
+// a narration with no drafted mark keeps this file's `reviewProblems` rule --
+// with NO narration verdict anywhere, nothing is held (a warning); once there
+// is one, every narrated card must be approved on its current words, an
+// unreviewed or edited card refusing unless `--narration-unreviewed` and a
+// REJECTED card always. A DRAFTED narration (release 28) follows the drafts
+// rule: a warning until a `final` build, which refuses it unapproved.
//
-// Pure but for the file's read and write.
-import { readFile, rename, writeFile } from "node:fs/promises";
-import path from "node:path";
-
+// Pure but for the files' read and write.
import { narrationsOf } from "./narration.mjs";
+import {
+ DRAFTS_REVIEW_FILE, NARRATION_REVIEW_FILE, REVIEW_NOTE_LIMIT, REVIEW_VERDICTS, cleanNarrationRows, narrationAddress,
+ readDraftsReview, setDraftReview,
+} from "./drafts-review.mjs";
-export const NARRATION_REVIEW_FILE = "narration.review.json";
-export const REVIEW_VERDICTS = Object.freeze(["approved", "rejected"]);
-export const REVIEW_NOTE_LIMIT = 2000;
-
-/** `<manifest's directory>/narration.review.json`. */
-export const reviewFileOf = (manifestDir) => path.join(manifestDir, NARRATION_REVIEW_FILE);
-
-const isCardId = (v) => typeof v === "string" && v.length > 0 && v.length <= 200;
-const str = (v) => (typeof v === "string" ? v : "");
+export { DRAFTS_REVIEW_FILE, NARRATION_REVIEW_FILE, REVIEW_NOTE_LIMIT, REVIEW_VERDICTS };
/** Rows that are not the contract's shape are dropped on read, never repaired on disk. */
-export function cleanReview(raw) {
+export const cleanReview = cleanNarrationRows;
+
+/** A drafts review's narration rows, by card id. */
+function narrationRowsOf(rows) {
const out = {};
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
- for (const [id, row] of Object.entries(raw)) {
- if (!isCardId(id) || !row || typeof row !== "object") continue;
- out[id] = {
- verdict: REVIEW_VERDICTS.includes(row.verdict) ? row.verdict : null,
- note: str(row.note),
- key: str(row.key),
- text: str(row.text),
- at: str(row.at),
- };
+ for (const [address, row] of Object.entries(rows ?? {})) {
+ const m = /^narrate\/([^/]+)\/narration$/.exec(address);
+ if (m && m[1] !== "*") out[m[1]] = row;
}
return out;
}
/**
- * The review file of a cut: `{ exists, rows }`, or `{ exists: true, rows: {},
- * error }` when it does not parse -- a build must not read that as "nothing
- * approved", nor a writer overwrite it.
+ * The narration review of a cut: `{ exists, rows }` -- `exists` when any
+ * narration verdict or note is kept (either file), `rows` by card id -- or
+ * `{ exists: true, rows: {}, error }` when a file does not parse: a build must
+ * not read that as "nothing approved", nor a writer overwrite it.
*/
export async function readNarrationReview(manifestDir) {
- let text;
- try {
- text = await readFile(reviewFileOf(manifestDir), "utf8");
- } catch (err) {
- if (err?.code === "ENOENT") return { exists: false, rows: {} };
- return { exists: true, rows: {}, error: `${NARRATION_REVIEW_FILE} cannot be read: ${err?.message ?? err}` };
- }
- try {
- return { exists: true, rows: cleanReview(JSON.parse(text)) };
- } catch {
- return { exists: true, rows: {}, error: `${NARRATION_REVIEW_FILE} does not parse; fix or remove it` };
- }
+ const r = await readDraftsReview(manifestDir);
+ if (r.error) return { exists: true, rows: {}, error: r.error };
+ const rows = narrationRowsOf(r.rows);
+ return { exists: r.narration, rows };
}
/**
@@ -114,7 +100,7 @@ export function reviewProblems(manifest, review, { only = null, allowUnreviewed
if (review.error) return { errors: [review.error], notes, warnings };
if (!review.exists) {
warnings.push(
- `the narration (${rows.length} card${rows.length === 1 ? "" : "s"}) has no review — ${NARRATION_REVIEW_FILE} is not there; ` +
+ `the narration (${rows.length} card${rows.length === 1 ? "" : "s"}) has no review — ${DRAFTS_REVIEW_FILE} has no narration verdicts; ` +
"review it card by card on umtool's narration page before it is published",
);
return { errors, notes, warnings };
@@ -134,58 +120,20 @@ export function reviewProblems(manifest, review, { only = null, allowUnreviewed
return { errors, notes, warnings };
}
-/** @type {Promise<unknown>} */
-let queue = Promise.resolve();
-function withReviewLock(fn) {
- const run = queue.then(fn, fn);
- queue = run.then(
- () => undefined,
- () => undefined,
- );
- return run;
-}
-
/**
* Set one card's review. `patch.verdict` "approved" | "rejected" | null (null
* clears it); `note` replaces the note; `key` and `text` are the words and
* voice the verdict is about (required with a verdict). A rejection needs its
* note -- what is wrong with the words -- as an incorrect clip does. Returns
- * the row as stored (null when removed) and every row.
+ * the row as stored (null when removed) and every narration row. Written to
+ * drafts.review.json as `narrate/<cardId>/narration`.
*
* @param {string} manifestDir
* @param {string} cardId
* @param {{ verdict?: string | null, note?: string, key?: string, text?: string }} patch
*/
export async function setNarrationReview(manifestDir, cardId, patch) {
- if (!isCardId(cardId)) throw new Error("not a card id");
- if (patch.verdict !== undefined && patch.verdict !== null && !REVIEW_VERDICTS.includes(patch.verdict)) {
- throw new Error(`verdict must be one of ${REVIEW_VERDICTS.join(", ")} or null`);
- }
- if (patch.note !== undefined && typeof patch.note !== "string") throw new Error("note must be a string");
- if (patch.verdict && !(typeof patch.key === "string" && patch.key && typeof patch.text === "string")) {
- throw new Error("a verdict is given on words: key and text are required");
- }
- const file = reviewFileOf(manifestDir);
- return withReviewLock(async () => {
- const cur = await readNarrationReview(manifestDir);
- if (cur.error) throw new Error(cur.error);
- const map = cur.rows;
- const prev = map[cardId] ?? { verdict: null, note: "", key: "", text: "", at: "" };
- const row = {
- verdict: patch.verdict === undefined ? prev.verdict : patch.verdict,
- note: patch.note === undefined ? prev.note : patch.note.slice(0, REVIEW_NOTE_LIMIT).trim(),
- key: patch.verdict ? patch.key : patch.verdict === null ? "" : prev.key,
- text: patch.verdict ? patch.text : patch.verdict === null ? "" : prev.text,
- at: new Date().toISOString(),
- };
- if (row.verdict === "rejected" && !row.note) {
- throw new Error("a rejection needs its note: say what is wrong with the words");
- }
- if (row.verdict === null && !row.note) delete map[cardId];
- else map[cardId] = row;
- const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
- await writeFile(tmp, JSON.stringify(map, null, 2) + "\n", "utf8");
- await rename(tmp, file);
- return { entry: map[cardId] ?? null, rows: map };
- });
+ if (!(typeof cardId === "string" && cardId.length > 0 && cardId.length <= 200 && !cardId.includes("/"))) throw new Error("not a card id");
+ const r = await setDraftReview(manifestDir, narrationAddress(cardId), patch);
+ return { entry: r.entry, rows: narrationRowsOf(r.rows) };
}
diff --git a/umtool/report-to-video/narration-review.test.mjs b/umtool/report-to-video/narration-review.test.mjs
@@ -14,7 +14,7 @@ import { buildVideo, setProgressMode } from "./build-video.mjs";
import { lintManifest } from "./lint.mjs";
import { narrationsOf } from "./narration.mjs";
import {
- NARRATION_REVIEW_FILE, cleanReview, readNarrationReview, reviewProblems, reviewRows, reviewState, setNarrationReview,
+ DRAFTS_REVIEW_FILE, NARRATION_REVIEW_FILE, cleanReview, readNarrationReview, reviewProblems, reviewRows, reviewState, setNarrationReview,
} from "./narration-review.mjs";
const card = (id, text, extra = {}) => ({ type: "card", id, heading: id, seconds: "auto", narration: { text, ...extra } });
@@ -51,7 +51,9 @@ test("setNarrationReview: a verdict is on words; a rejection needs its note; an
// No verdict and no note: removed.
const gone = await setNarrationReview(dir, "k2", { note: "" });
assert.equal(gone.entry, null);
- assert.deepEqual(Object.keys(JSON.parse(readFileSync(path.join(dir, NARRATION_REVIEW_FILE), "utf8"))), ["k1"]);
+ // Written to the drafts review, by the card's address.
+ assert.deepEqual(Object.keys(JSON.parse(readFileSync(path.join(dir, DRAFTS_REVIEW_FILE), "utf8"))), ["narrate/k1/narration"]);
+ assert.deepEqual(Object.keys((await readNarrationReview(dir)).rows), ["k1"]);
});
test("states: approved on its words; an edit or another voice leaves it edited; none is unreviewed", () => {
@@ -80,7 +82,7 @@ test("reviewProblems: no file warns; a file holds every un-approved card; the fl
};
const none = reviewProblems(m, { exists: false, rows: {} });
assert.deepEqual(none.errors, []);
- assert.match(none.warnings[0], /the narration \(3 cards\) has no review — narration\.review\.json is not there/);
+ assert.match(none.warnings[0], /the narration \(3 cards\) has no review — drafts\.review\.json has no narration verdicts/);
const held = reviewProblems(m, review);
assert.equal(held.errors.length, 2, held.errors.join("\n"));
assert.match(held.errors[0], /timeline k2: its narration is not reviewed — approve it on umtool's narration page, or build with --narration-unreviewed/);
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -24,6 +24,7 @@
"./compose-chrome": "./compose-chrome.mjs",
"./cues": "./cues.mjs",
"./deck": "./deck.mjs",
+ "./drafts-review": "./drafts-review.mjs",
"./factcheck": "./factcheck.mjs",
"./ledger-totals": "./ledger-totals.mjs",
"./lint": "./lint.mjs",