Archilyzer · Source

archilyzer

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

commit 1fa201ef21b6f5fc3b4499396151451361ce71f8
parent bcaa31578c53c9a14aca2fdde2bba472d1e3b9e8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 21:23:39 -0400

umtool: the drafts review, the final gate, and the writer as the operator

report-to-video/drafts-review.mjs is one review file for every drafted
field, drafts.review.json, keyed `<task>/<entry|*>/<field>` (narration's rows
`narrate/<cardId>/narration`); release 25's narration.review.json reads
unchanged and the drafts file wins. The lint gets it: a drafted field not
approved on its current value is a warning in preview and fast builds and an
error in a `--final` build (`--drafts-unreviewed` lets the unapproved
through, never a rejected one; `--narration-unreviewed` still works for the
narration rows). A hand-written narration keeps release 25's rule. The
driver's `final` preset passes `--final`. The lint and the build validate
`drafted` marks and the new `publish.youtube` block, and warn of an orphan.

umtool's manifest writer is the operator: a write that changes a drafted
field removes its mark, and drops orphans. `writeDraftedField` is "Use this"
for an alternative. lib/report/drafts.mjs is the review's view and
/api/report/drafts its route; the narration page writes the new file.

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

Diffstat:
Aumtool/app/api/report/drafts/route.ts | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/drafted-writer.test.mjs | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/drafts.mjs | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/driver.mjs | 5++++-
Mumtool/lib/report/manifest.mjs | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/narration-review.mjs | 10+++++++---
Mumtool/report-to-video/build-video.mjs | 30+++++++++++++++++++++++-------
Aumtool/report-to-video/drafts-review.mjs | 375+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/drafts-review.test.mjs | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/lint.mjs | 64++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mumtool/report-to-video/narration-review.mjs | 130++++++++++++++++++++++++-------------------------------------------------------
Mumtool/report-to-video/narration-review.test.mjs | 8+++++---
Mumtool/report-to-video/package.json | 1+
13 files changed, 1106 insertions(+), 119 deletions(-)

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/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/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/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",