Archilyzer · Source

archilyzer

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

commit 625ef0d1b45df0af54009714d61ae394ff58f626
parent 7747d3cfa66b2d9480f29e6388de53a3afc82877
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 11 Oct 2026 01:54:27 -0400

umtool: the narration review — a cut's script card by card before synthesis; the build holds what is not approved (release 25 T5)

/browse/<project>/narration (linked from the project page when a card is
narrated): each narrated card's words beside what it shows on screen, its
engine and voice, Approve, Reject (a note required), Save words (the manifest
writer's new updateNarration: snapshot, the build's validators, the
generated-manifest note; an edit clears the verdict) and Play (one card asked of
the editor as a job, narrate-via-editor.mjs --only, then played from
/api/report/narration/audio). Verdicts live in narration.review.json beside the
manifest, in takes/verdicts.json's shape (report-to-video/narration-review.mjs),
each on the words and voice it was given on, so an edit or a voice change
leaves the card "edited". The lint and the build read it: no review file is a
warning (existing narrated cuts build as they did); with one, an unreviewed or
edited card refuses the build unless --narration-unreviewed, and a rejected one
always. validateNarration joins the structural writers' checks. The writing
guide is a stub carrying the hard rule, in the README's "Writing narration" and
in the MCP sweep plan (NARRATION_HARD_RULE, narrationStep).

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

Diffstat:
Mmcp/src/instructions.test.ts | 11++++++++++-
Mmcp/src/instructions.ts | 27+++++++++++++++++++++++++++
Aumtool/app/api/report/narration/audio/route.ts | 30++++++++++++++++++++++++++++++
Aumtool/app/api/report/narration/play/route.ts | 29+++++++++++++++++++++++++++++
Aumtool/app/api/report/narration/route.ts | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/NarrationPage.tsx | 49+++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/components/projects/NarrationReview.tsx | 302++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/ProjectView.tsx | 4++++
Mumtool/components/projects/ReportProject.tsx | 13+++++++++++++
Mumtool/docs/report-video.md | 11+++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 12++++++++++++
Aumtool/e2e/narration-review.spec.ts | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/driver.mjs | 26++++++++++++++++++++++++++
Mumtool/lib/report/driver.test.mjs | 8++++++++
Mumtool/lib/report/manifest.mjs | 29+++++++++++++++++++++++++++++
Aumtool/lib/report/narration-review.mjs | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/narration-review.test.mjs | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/README.md | 41+++++++++++++++++++++++++++++++++++------
Mumtool/report-to-video/build-video.mjs | 16++++++++++++++--
Mumtool/report-to-video/lint.mjs | 22+++++++++++++++++++---
Mumtool/report-to-video/narrate-via-editor.mjs | 13+++++++++----
Aumtool/report-to-video/narration-review.mjs | 191+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/narration-review.test.mjs | 137+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/package.json | 1+
24 files changed, 1278 insertions(+), 16 deletions(-)

diff --git a/mcp/src/instructions.test.ts b/mcp/src/instructions.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { buildSweepInstructions, buildAskInstructions } from "./instructions"; +import { NARRATION_HARD_RULE, buildSweepInstructions, buildAskInstructions, narrationStep } from "./instructions"; import { parsePromptRequest } from "./promptRequest"; import { TOOLS } from "./server"; @@ -214,3 +214,12 @@ test("both builders send clip media through fetch_clip, never a hand-run yt-dlp" const askClip = a.indexOf("Media for a cited moment"); assert.ok(cite > 0 && askClip > cite, `citations at ${cite}, clip step at ${askClip}`); }); + +// ─── Writing for the ear (release 25, T5) ─── + +test("a sweep carries the narration hard rule: delivery, never the claims", () => { + const text = sweep("coffee"); + assert.ok(text.includes(NARRATION_HARD_RULE), "the hard rule, verbatim"); + assert.match(text, /no invented quotes, no motives or feelings attributed to real people/); + assert.match(narrationStep(), /reviews every narrated card \(approve \/ edit \/ reject\)/); +}); diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts @@ -160,6 +160,31 @@ function clipStep(ctx: PlanContext): string { ); } +// ─── Writing for the ear (release 25, T5) ─── +// +// A report video's cards may carry a narration spoken by a stock synthetic +// voice (umtool/report-to-video README, "Narration"). The rule below is fixed; +// the concrete writing rules (sentence length, pauses, where expressive tags +// work) are added from the voice tuning round. The same rule is in the +// report-to-video README's "Writing narration". +export const NARRATION_HARD_RULE = + "Storytelling and emotion live in the delivery, never in the claims: every " + + "factual statement stays exactly as the cited evidence supports — no invented " + + "quotes, no motives or feelings attributed to real people, no intensifiers " + + "that change a claim's strength."; + +export function narrationStep(): string { + return ( + `**Narration, only if you draft any.** When I ask for a video's narration ` + + `(a card's \`narration.text\` in a \`video.manifest.json\`), write it for the ` + + `ear — short spoken sentences, a beat before the turn. ${NARRATION_HARD_RULE} ` + + `Each narration line must be traceable to a citation already in the report; ` + + `a line that is not is cut, not softened. The operator reviews every ` + + `narrated card (approve / edit / reject) before it is synthesized, so draft ` + + `the words and leave the verdicts to them.` + ); +} + // The editor-backed writes and reads (release 19 A9): the same rule as // fetch_clip — through the editor, never by hand, and only when asked. function archiveStep(): string { @@ -290,6 +315,8 @@ export function buildSweepInstructions( steps.push(archiveStep()); + steps.push(narrationStep()); + steps.push( `**Finish.** Work to the end of the worklist, then write a summary ` + `section: the scope swept, **how many of the N you actually read**, ` + diff --git a/umtool/app/api/report/narration/audio/route.ts b/umtool/app/api/report/narration/audio/route.ts @@ -0,0 +1,30 @@ +import path from "node:path"; +import { stat } from "node:fs/promises"; +import { resolveInRoots } from "@/lib/paths.mjs"; +import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs"; +import { narrationsOf } from "umtool-report-to-video/narration"; +import { narrationDir, narrationWavPath, readNarrationRecord } from "umtool-report-to-video/narration-store"; + +export const dynamic = "force-dynamic"; + +// GET ?project&card: the narration's kept voice for that card's CURRENT words +// and voice (out/narration/<key>.wav), or a 404 until it is synthesized. Names, +// never paths: the file is found from the manifest's narration. +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 new Response(r.error, { status: r.status }); + const card = url.searchParams.get("card") ?? ""; + const n = narrationsOf(r.manifest).find((x: { id: string }) => x.id === card); + if (!n) return new Response("not a card with a narration", { status: 404 }); + const dir = narrationDir(path.join(r.project.dir, "out")); + if (!(await readNarrationRecord(dir, n.key))) return new Response("this narration has not been synthesized yet", { status: 404 }); + const abs = resolveInRoots(narrationWavPath(dir, n.key)); + const st = abs ? await stat(abs).catch(() => null) : null; + if (!abs || !st?.isFile()) return new Response("this narration has not been synthesized yet", { status: 404 }); + return rangeResponse(request, { + abs, + size: st.size, + headers: { "content-type": "audio/wav", "accept-ranges": "bytes", "cache-control": "private, no-store" }, + }); +} diff --git a/umtool/app/api/report/narration/play/route.ts b/umtool/app/api/report/narration/play/route.ts @@ -0,0 +1,29 @@ +import { jobView, runningJob, startJob } from "@/lib/jobs"; +import { narrateCardSteps } from "@/lib/report/driver.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { narrationsOf } from "umtool-report-to-video/narration"; + +export const dynamic = "force-dynamic"; + +// POST { project, card }: synthesize ONE narrated card's voice by asking the +// editor (narrate-via-editor.mjs --only), as a job the page follows by id +// (GET /api/report/build?job=<id>), then plays from +// /api/report/narration/audio. A voice already kept is a quick no-op job. +// One job at a time, as every job here: a running build is a 409. +export async function POST(request: Request) { + const body = (await request.json().catch(() => null)) as { project?: string; card?: string } | null; + const r = await resolveReport(String(body?.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const card = String(body?.card ?? ""); + if (!narrationsOf(r.manifest).some((n: { id: string }) => n.id === card)) { + return Response.json({ error: `${card || "(no card)"} is not a card with a narration` }, { status: 404 }); + } + const running = runningJob(); + if (running) return Response.json({ error: `a job is already running (${running.kind})` }, { status: 409 }); + try { + const job = startJob(`narrate ${r.project.id} ${card}`, narrateCardSteps(r.project, card), { project: r.project.id }); + return Response.json({ ok: true, job: jobView(job) }, { headers: { "cache-control": "no-store" } }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); + } +} diff --git a/umtool/app/api/report/narration/route.ts b/umtool/app/api/report/narration/route.ts @@ -0,0 +1,93 @@ +import { invalidateProjects } from "@/lib/projects"; +import { withEditNotes } from "@/lib/report/guard"; +import { StaleToken, StructureRefused, manifestToken, updateNarration } from "@/lib/report/manifest.mjs"; +import { narrationReviewView } from "@/lib/report/narration-review.mjs"; +import { resolveReport } from "@/lib/report/serve.mjs"; +import { narrationsOf } from "umtool-report-to-video/narration"; +import { setNarrationReview } from "umtool-report-to-video/narration-review"; + +export const dynamic = "force-dynamic"; + +// The narration review (release 25, T5): a cut's narration script, card by +// card, before synthesis. +// +// GET ?project=<id> the view (lib/report/narration-review.mjs) and the token +// POST { project, card, action, ... } one action on one narrated card: +// approve { note? } approved on its CURRENT words and voice +// reject { note } rejected; the note says what is wrong (required) +// clear {} no verdict (the note is kept) +// note { note } the note alone +// edit { text, token? } the card's narration words, through the manifest +// 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. + +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 narrationReviewView(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 card = String(body.card ?? ""); + const n = narrationsOf(r.manifest).find((x: { id: string }) => x.id === card); + if (!n) return Response.json({ error: `${card || "(no card)"} is not a card with a narration` }, { status: 404 }); + const note = typeof body.note === "string" ? body.note : undefined; + let editNotes = null; + try { + switch (body.action) { + case "approve": + await setNarrationReview(dir, card, { verdict: "approved", key: n.key, text: n.text, ...(note !== undefined ? { note } : {}) }); + break; + case "reject": + await setNarrationReview(dir, card, { verdict: "rejected", key: n.key, text: n.text, note: note ?? "" }); + break; + case "clear": + await setNarrationReview(dir, card, { verdict: null }); + break; + case "note": + await setNarrationReview(dir, card, { note: note ?? "" }); + break; + case "edit": { + const token = typeof body.token === "string" ? body.token : null; + const w = await withEditNotes(r.project, () => updateNarration(dir, card, String(body.text ?? ""), { token })); + editNotes = w.editNotes; + // New words are not the words anybody approved. + if ((w.result as { changed?: boolean }).changed) await setNarrationReview(dir, card, { verdict: null }); + invalidateProjects(); + break; + } + default: + return Response.json({ error: "action must be approve, reject, clear, note or edit" }, { 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 narrationReviewView(dir, manifest)), token: await manifestToken(dir), editNotes }, + { headers: noStore }, + ); +} diff --git a/umtool/components/projects/NarrationPage.tsx b/umtool/components/projects/NarrationPage.tsx @@ -0,0 +1,49 @@ +import Link from "next/link"; +import BrowseHeader from "@/components/BrowseHeader"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { manifestToken } from "@/lib/report/manifest.mjs"; +import { narrationReviewView } from "@/lib/report/narration-review.mjs"; +import type { ProjectRef } from "@/lib/project-types"; +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. +export default async function NarrationPage({ project }: { project: ProjectRef }) { + const manifest = await readManifest(project.dir); + const view = (await narrationReviewView(project.dir, manifest ?? {})) as NarrationView; + const 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: "narration" }, + ]} + note={ + view.rows.length + ? `${view.rows.length} narrated · ${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"> + {view.rows.length === 0 ? ( + <p data-narration-empty="" className="text-[12px] text-[var(--color-dim)]"> + No card in this cut carries a narration.{" "} + <Link href={`/browse/${project.id}`} className="text-[var(--color-sel)] hover:underline"> + back to {project.id} + </Link> + </p> + ) : ( + <NarrationReview project={project.id} initial={view} token={token} /> + )} + </main> + </div> + ); +} diff --git a/umtool/components/projects/NarrationReview.tsx b/umtool/components/projects/NarrationReview.tsx @@ -0,0 +1,302 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { badgeVariants, type BadgeVariants } from "@/components/ui/badge"; +import { buttonVariants } from "@/components/ui/button"; + +// The narration script of one cut, card by card (release 25, T5). +// +// Each narrated card: what it shows on screen, the words it will speak (edited +// in place), the engine and voice, and a verdict -- Approve, or Reject with a +// note saying what is wrong -- on THOSE words. Saving new words clears the +// verdict; the server is the word on every state, and each action answers with +// the whole view. Play asks the editor to synthesize that one card +// (narrate-via-editor --only, a job followed by id) and plays it. +// +// Buttons stay disabled until mount, as TakesBench's do: a click before +// hydration sends nothing, and a verdict lost that way looks like one never given. + +export type NarrationRow = { + id: string; + at: number; + text: string; + engine: string; + voice: string; + speed: number; + words: number; + estimate: number; + seconds: number | string | null; + screen: { kicker: string | null; heading: string | null; sub: string | null; title: string | null; style: string | null }; + state: "approved" | "rejected" | "edited" | "unreviewed"; + verdict: "approved" | "rejected" | null; + note: string; + judgedText: string; + judgedAt: string; + kept: { seconds: number; disclosure: string; mtimeMs: number } | null; +}; +export type NarrationView = { + file: string; + exists: boolean; + error: string | null; + rows: NarrationRow[]; + counts: Record<NarrationRow["state"], number>; +}; + +const STATE: Record<NarrationRow["state"], { label: string; tone: BadgeVariants["variant"] }> = { + approved: { label: "approved", tone: "meter" }, + rejected: { label: "rejected", tone: "blocking" }, + edited: { label: "edited since approved", tone: "on" }, + unreviewed: { label: "not reviewed", tone: "neutral" }, +}; + +const audioSrc = (project: string, r: NarrationRow) => + `/api/report/narration/audio?${new URLSearchParams({ project, card: r.id, v: String(r.kept?.mtimeMs ?? 0) })}`; + +export default function NarrationReview({ project, initial, token: initialToken }: { project: string; initial: NarrationView; token: string | null }) { + const [view, setView] = useState(initial); + const [token, setToken] = useState(initialToken); + const [ready, setReady] = useState(false); + useEffect(() => setReady(true), []); + + const act = async (card: string, action: string, extra: Record<string, unknown> = {}) => { + const r = await fetch("/api/report/narration", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, card, action, ...(action === "edit" ? { token } : {}), ...extra }), + cache: "no-store", + }); + const j = (await r.json()) as NarrationView & { error?: string; token?: string | null; ok?: boolean }; + if (!r.ok || !j.ok) throw new Error(j.error ?? `HTTP ${r.status}`); + setView(j); + if (j.token !== undefined) setToken(j.token); + }; + + const refresh = async () => { + const r = await fetch(`/api/report/narration?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + if (!r.ok) return null; + const j = (await r.json()) as NarrationView & { token?: string | null }; + setView(j); + if (j.token !== undefined) setToken(j.token); + return j; + }; + + return ( + <div className="space-y-3"> + <p data-review-file={view.exists ? "present" : "absent"} className="text-[11px] text-[var(--color-dim)]"> + {view.error ? ( + <span className="text-[var(--color-bad)]">{view.error}</span> + ) : 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). + </> + ) : ( + <> + 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. + </> + )} + </p> + {view.rows.map((r) => ( + <NarrationCard key={r.id} project={project} row={r} ready={ready} act={act} refresh={refresh} /> + ))} + </div> + ); +} + +function NarrationCard({ + project, + row: r, + ready, + act, + refresh, +}: { + project: string; + row: NarrationRow; + ready: boolean; + act: (card: string, action: string, extra?: Record<string, unknown>) => Promise<void>; + refresh: () => Promise<NarrationView | null>; +}) { + const [text, setText] = useState(r.text); + const [note, setNote] = useState(r.note); + const [busy, setBusy] = useState(false); + const [playing, setPlaying] = useState(false); + const [error, setError] = useState<string | null>(null); + const audio = useRef<HTMLAudioElement | null>(null); + const autoplay = useRef(false); + // Adopt server values that moved underneath (a save, another tab). + useEffect(() => setText(r.text), [r.text]); + useEffect(() => setNote(r.note), [r.note]); + useEffect(() => { + if (autoplay.current && r.kept && audio.current) { + autoplay.current = false; + void audio.current.play().catch(() => {}); + } + }, [r.kept]); + + const run = async (fn: () => Promise<void>) => { + setBusy(true); + setError(null); + try { + await fn(); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + }; + + const play = () => + run(async () => { + if (r.kept && audio.current) { + await audio.current.play().catch(() => {}); + return; + } + setPlaying(true); + try { + const res = await fetch("/api/report/narration/play", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, card: r.id }), + }); + const j = (await res.json()) as { error?: string; job?: { id: string } }; + if (!res.ok || !j.job) throw new Error(j.error ?? `HTTP ${res.status}`); + for (;;) { + await new Promise((ok) => setTimeout(ok, 600)); + const p = await fetch(`/api/report/build?job=${encodeURIComponent(j.job.id)}`, { cache: "no-store" }); + if (!p.ok) continue; + const s = (await p.json()) as { state: string; error: string | null }; + if (s.state === "running") continue; + if (s.state !== "done") throw new Error(s.error ?? "the narration was not synthesized"); + break; + } + autoplay.current = true; + await refresh(); + } finally { + setPlaying(false); + } + }); + + const dirty = text.trim() !== r.text; + const screen = [r.screen.kicker, r.screen.heading, r.screen.sub].filter(Boolean); + + return ( + <article + data-narration-card={r.id} + data-state={r.state} + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" + > + <div className="mb-1.5 flex flex-wrap items-center gap-2"> + <span className="font-mono text-[12px] text-[var(--color-text)]">{r.id}</span> + <span data-narration-state="" className={badgeVariants({ variant: STATE[r.state].tone, size: "sm" })}> + {STATE[r.state].label} + </span> + <span className="font-mono text-[11px] text-[var(--color-dim)]" data-narration-voice=""> + {r.engine} · {r.voice} + {r.speed !== 1 ? ` · ×${r.speed}` : ""} + </span> + <span className="num text-[11px] text-[var(--color-dim)]"> + {r.words} words · ~{r.estimate.toFixed(1)} s{r.kept ? ` · voiced ${r.kept.seconds.toFixed(1)} s` : ""} + {typeof r.seconds === "number" ? ` · card ${r.seconds} s` : r.seconds === "auto" ? " · card auto" : ""} + </span> + </div> + <div className="grid grid-cols-1 gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,2fr)]"> + <div data-narration-screen="" className="text-[12px]"> + <div className="micro mb-0.5">on screen{r.screen.style ? ` · ${r.screen.style}` : ""}</div> + {screen.length ? ( + screen.map((line, i) => ( + <div key={i} className={i === (r.screen.kicker ? 1 : 0) ? "text-[var(--color-text)]" : "text-[var(--color-dim)]"}> + {line} + </div> + )) + ) : ( + <div className="text-[var(--color-dim)]">—</div> + )} + {r.screen.title && <div className="mt-1 text-[11px] text-[var(--color-dim)]">deck title: {r.screen.title}</div>} + </div> + <div className="space-y-1.5"> + <textarea + value={text} + onChange={(e) => setText(e.target.value)} + disabled={!ready || busy} + aria-label={`narration of ${r.id}`} + data-narration-text="" + rows={Math.min(8, Math.max(2, Math.ceil(text.length / 90)))} + className="w-full rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-2 py-1 text-[13px] leading-relaxed text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" + /> + {r.state === "edited" && r.judgedText && ( + <p data-narration-judged="" className="text-[11px] text-[var(--color-dim)]"> + {r.verdict} on: <span className="italic">{r.judgedText}</span> + </p> + )} + <div className="flex flex-wrap items-center gap-1.5"> + <button + type="button" + data-action="save-text" + disabled={!ready || busy || !dirty} + className={buttonVariants({ size: "sm" })} + onClick={() => void run(() => act(r.id, "edit", { text }))} + > + Save words + </button> + <button + type="button" + data-verdict-button="approved" + aria-pressed={r.state === "approved"} + disabled={!ready || busy || dirty} + title={dirty ? "save the words first: a verdict is on the words as saved" : "approve these words in this voice"} + className={buttonVariants({ variant: r.state === "approved" ? "primary" : "outline", size: "sm" })} + onClick={() => void run(() => act(r.id, r.state === "approved" ? "clear" : "approve", r.state === "approved" ? {} : { note }))} + > + {r.state === "approved" ? "Approved" : "Approve"} + </button> + <button + type="button" + data-verdict-button="rejected" + aria-pressed={r.state === "rejected"} + disabled={!ready || busy || dirty} + title="reject these words; the note says what is wrong" + className={buttonVariants({ variant: r.state === "rejected" ? "destructive" : "outline", size: "sm" })} + onClick={() => void run(() => act(r.id, r.state === "rejected" ? "clear" : "reject", r.state === "rejected" ? {} : { note }))} + > + {r.state === "rejected" ? "Rejected" : "Reject"} + </button> + <input + value={note} + onChange={(e) => setNote(e.target.value)} + onBlur={() => { + if (note.trim() !== r.note && r.verdict) void run(() => act(r.id, "note", { note })); + }} + disabled={!ready || busy} + placeholder="note (a rejection needs one)" + aria-label={`note on ${r.id}'s narration`} + data-narration-note="" + maxLength={2000} + className="min-w-0 flex-1 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-1 text-[12px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]" + /> + <button + type="button" + data-action="play" + disabled={!ready || busy || dirty} + title={r.kept ? "play the voice kept for these words" : "ask the editor to synthesize this card, then play it"} + className={buttonVariants({ size: "sm" })} + onClick={() => void play()} + > + {playing ? "synthesizing…" : "Play"} + </button> + </div> + {r.kept && ( + <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>} + {error && ( + <p data-narration-error="" className="text-[11px] text-[var(--color-bad)]"> + {error} + </p> + )} + </div> + </div> + </article> + ); +} diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx @@ -7,6 +7,7 @@ import ClipBenchPage from "./ClipBenchPage"; import ClaimBenchPage from "./ClaimBenchPage"; import SweepProject from "./SweepProject"; import TakesPage from "./TakesPage"; +import NarrationPage from "./NarrationPage"; // --------------------------------------------------------------------------- // The one place a kind id is matched against a component. @@ -53,6 +54,9 @@ export default async function ProjectView({ // `/browse/<project>/takes` -- alternative renders of one part of the // cut, side by side, each judged like / maybe / no. if (rest.length === 1 && rest[0] === "takes") return <TakesPage project={project} />; + // `/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} />; return notFound(); } case "sweep-report": { diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx @@ -19,6 +19,7 @@ import { diffManifests, formatChange } from "@/lib/report/manifest-diff.mjs"; 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 DeliverSection from "./DeliverSection"; import FetchUnfetchedButton from "./FetchUnfetchedButton"; import OnscreenSection from "./OnscreenSection"; @@ -143,6 +144,7 @@ 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; // 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 @@ -244,6 +246,17 @@ export default async function ReportProject({ )} {/* Alternative renders of part of the cut, made elsewhere and judged on their own page. Only when there is a takes/ to look at. */} + {/* The narration script, card by card, before synthesis -- only when + some card carries one. */} + {narrated > 0 && ( + <Link + href={`/browse/${project.id}/narration`} + data-narration-link={narrated} + className={buttonVariants({ size: "lg" })} + > + Narration — {narrated} + </Link> + )} {takes.exists && ( <Link href={`/browse/${project.id}/takes`} diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -801,6 +801,17 @@ and `WORKER_TOKEN` as a clip fetch, from the server's environment) and keeps eac sound in `out/narration/`. The README's "Narration" section has the shape, the 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`, +`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. + ## Re-checking sources across projects `check-sources` is one `check-availability.mjs --allow-missing` step per diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -1390,6 +1390,17 @@ writeProject( ]), ); +// The NARRATION REVIEW (release 25, T5): two narrated cards, nothing judged, +// for the review page's spec to approve, reject, edit, play and build. +writeProject( + "narration-review-fixture", + manifest("narration-review-fixture", "The Narration Review Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "card", id: "k01", style: "chapter", seconds: "auto", kicker: "2024", heading: "The county", narration: { text: "Six months later, the county said yes." } }, + { type: "clip", id: "c01", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence" }, + { type: "card", id: "k02", style: "chapter", seconds: "auto", heading: "Then", narration: { text: "And then everybody was furious." } }, + ]), +); + // -- THE ON-SCREEN DECK ------------------------------------------------------- // // A stub HYPERFRAMES_BIN, so a deck build renders offline in a second instead @@ -1931,4 +1942,5 @@ console.log(` onscreen-feed-fixture (writable, posts feed, built by t console.log(` deliver-stop-fixture (writable: six confirmed clips to cut, for Stop and resume)`); 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(` ${taken} candidate files copied, 2 mix tracks synthesised`); diff --git a/umtool/e2e/narration-review.spec.ts b/umtool/e2e/narration-review.spec.ts @@ -0,0 +1,96 @@ +import { test, expect } from "@playwright/test"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// --------------------------------------------------------------------------- +// The narration review (release 25, T5): a cut's narration script, card by +// 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. +// --------------------------------------------------------------------------- + +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"); +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 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 { + return (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; text?: string }[]).filter((r) => r.route === "tts"); + } catch { + return []; + } +}; + +test("review the narration card by card: approve, reject with a note, edit un-approves, play asks the editor", async ({ page }) => { + await page.goto(`/browse/${PROJECT}`); + await page.locator("[data-narration-link]").click(); + await expect(page).toHaveURL(new RegExp(`/browse/${PROJECT}/narration$`)); + const k1 = page.locator('[data-narration-card="k01"]'); + const k2 = page.locator('[data-narration-card="k02"]'); + await expect(k1).toHaveAttribute("data-state", "unreviewed"); + await expect(k2).toHaveAttribute("data-state", "unreviewed"); + await expect(page.locator('[data-review-file="absent"]')).toBeVisible(); + // The words beside what the card shows, and the voice. + await expect(k1.locator("[data-narration-screen]")).toContainText("The county"); + await expect(k1.locator("[data-narration-text]")).toHaveValue("Six months later, the county said yes."); + await expect(k1.locator("[data-narration-voice]")).toContainText("kokoro · af_heart"); + + // Approve the first. + await k1.locator('[data-verdict-button="approved"]').click(); + await expect(k1).toHaveAttribute("data-state", "approved"); + expect(review().k01.verdict).toBe("approved"); + + // A rejection needs its note. + await k2.locator('[data-verdict-button="rejected"]').click(); + await expect(k2.locator("[data-narration-error]")).toContainText("a rejection needs its note"); + await k2.locator("[data-narration-note]").fill("furious is not in the clip"); + await k2.locator('[data-verdict-button="rejected"]').click(); + await expect(k2).toHaveAttribute("data-state", "rejected"); + expect(review().k02).toMatchObject({ verdict: "rejected", note: "furious is not in the clip", text: "And then everybody was furious." }); + + // Edit the rejected words: saved through the manifest, and no longer rejected. + await k2.locator("[data-narration-text]").fill("And then the meeting ran long."); + await expect(k2.locator('[data-verdict-button="approved"]')).toBeDisabled(); + await k2.locator('[data-action="save-text"]').click(); + await expect(k2).toHaveAttribute("data-state", "unreviewed"); + expect(manifest().timeline.find((e) => e.id === "k02")!.narration!.text).toBe("And then the meeting ran long."); + expect(review().k02.verdict).toBeNull(); + + // Play: one card asked of the editor, then its voice on the page. + const before = ttsAsks().length; + await k1.locator('[data-action="play"]').click(); + await expect(k1.locator("[data-narration-audio]")).toBeVisible({ timeout: 60_000 }); + const asks = ttsAsks().slice(before); + expect(asks.map((a) => a.text)).toEqual(["Six months later, the county said yes."]); + const audio = await page.request.get(`/api/report/narration/audio?project=${encodeURIComponent(PROJECT)}&card=k01`); + expect(audio.status()).toBe(200); + expect(audio.headers()["content-type"]).toBe("audio/wav"); + // A played voice does not approve anything. + await expect(k2).toHaveAttribute("data-state", "unreviewed"); +}); + +test("the build refuses a narrated card the review has not approved", async ({ request }) => { + const start = await request.post("/api/report/build", { data: { project: PROJECT, preset: "fast" } }); + expect(start.ok()).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() + 120_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)); + } + expect(done.state).toBe("failed"); + // The build's own sentence, in its events (an `error`) and log. + expect(JSON.stringify(done)).toContain("timeline k02: its narration is not reviewed"); + expect(existsSync(path.join(DIR, "out", "narration-review-fixture.mp4"))).toBe(false); +}); diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs @@ -195,6 +195,32 @@ export function buildSteps(project, { preset = "fast", only = null, skipFetch = } /** + * ONE card's narration, asked of the editor (release 25, T5): what the + * narration review's play runs. The voice is kept in out/narration/, where a + * build finds it. The editor URL and token come from the server's + * environment, never the step's `env` (jobView shows that to the browser). + * + * @param {{ dir: string }} project + * @param {string} cardId + * @returns {import("../trim").Step[]} + */ +export function narrateCardSteps(project, cardId) { + return [ + { + cwd: PIPELINE_DIR, + env: {}, + label: `synthesize ${cardId}'s narration (asks the editor)`, + argv: [ + "node", script("narrate-via-editor.mjs"), path.join(project.dir, "video.manifest.json"), + "--out", path.join(project.dir, "out"), "--only", cardId, "--progress", "ndjson", + ], + ndjson: true, + timeoutMs: 15 * 60_000, + }, + ]; +} + +/** * The widest pad the bench may ask for. * * Here rather than in the route, because the BENCH has to know it too: the diff --git a/umtool/lib/report/driver.test.mjs b/umtool/lib/report/driver.test.mjs @@ -75,3 +75,11 @@ test("podcast: one step, build-podcast over the segments on disk, told the cut", assert.deepEqual(steps[0].argv.slice(2), ["/r/p/video.manifest.json", "--out", "/r/p/out", "--progress", "ndjson", "--variant", "full"]); assert.equal(steps[0].ndjson, true); }); + +test("one card's narration: narrate-via-editor --only, its voice kept in out/", async () => { + const { narrateCardSteps } = await import("./driver.mjs"); + const [s] = narrateCardSteps(project, "k1"); + assert.ok(s.argv[1].endsWith("narrate-via-editor.mjs")); + assert.deepEqual(s.argv.slice(2), ["/r/p/video.manifest.json", "--out", "/r/p/out", "--only", "k1", "--progress", "ndjson"]); + assert.deepEqual(s.env, {}, "the token is the server's environment's, never the step's"); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -33,6 +33,7 @@ import { isCalendarDate } from "umtool-report-to-video/attribution"; import { normalizeOnscreen, validateChrome, validatePosts, validateTeaser, validateTeasers } from "umtool-report-to-video/deck"; import { applySectionEnter } from "./sections.mjs"; import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck"; +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"; @@ -864,6 +865,7 @@ function structureErrors(manifest) { ...validatePosts(manifest.posts, manifest.timeline ?? [], manifest.render), ...validateClaims(manifest), ...validateTeasers(manifest), + ...validateNarration(manifest), ]; } @@ -1054,6 +1056,33 @@ export async function updateTeaser(dir, id, patch, { token = null, at = null } = }); } +/** + * A card's narration WORDS (release 25, T5: the narration review's edit). + * Only `narration.text` changes -- the voice and engine are the manifest's + * decision, made elsewhere -- trimmed, and checked with the build's + * validateNarration. The review row that approved the old words is no longer + * an approval of these (its key differs); the caller clears it too. + * + * @param {string} dir + * @param {string} id + * @param {string} text + * @param {{ token?: string | null, at?: number | null }} [opts] + */ +export async function updateNarration(dir, id, text, { token = null, at = null } = {}) { + if (typeof text !== "string") throw new Error("the narration's words are a string"); + return structural(dir, "narration", token, (m) => { + const e = m.timeline[entryIndex(m.timeline, id, at)]; + if (e.type !== "card" || !e.narration || typeof e.narration !== "object") { + throw new Error(`${id} is not a card with a narration`); + } + const before = e.narration.text; + e.narration.text = text.trim(); + const errors = validateNarration({ render: m.render, timeline: [e] }); + if (errors.length) throw new StructureRefused(errors); + return { id, entry: e, changed: before !== e.narration.text }; + }); +} + 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 @@ -0,0 +1,57 @@ +// The narration review's view of a project (release 25, T5): every narrated +// card of the manifest (every cut's), its words, engine and voice, what the +// 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. +// +// 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 { narrationDir, narrationWavPath, readNarrationRecord } from "umtool-report-to-video/narration-store"; + +/** + * @param {string} projectDir + * @param {any} manifest the whole manifest, as written + */ +export async function narrationReviewView(projectDir, manifest) { + const review = await readNarrationReview(projectDir); + const dir = narrationDir(path.join(projectDir, "out")); + const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const rows = []; + for (const r of reviewRows(manifest, review)) { + const at = timeline.findIndex((e) => e?.id === r.id); + const e = timeline[at] ?? {}; + const rec = await readNarrationRecord(dir, r.key); + const wav = rec ? await stat(narrationWavPath(dir, r.key)).catch(() => null) : null; + rows.push({ + id: r.id, + at, + text: r.text, + engine: r.engine, + voice: r.voice, + speed: r.speed, + words: narrationWords(r.text), + estimate: estimatedNarratedCardSeconds(e, manifest.render), + seconds: e.seconds ?? null, + screen: { + kicker: e.kicker ?? null, + heading: e.heading ?? null, + sub: e.sub ?? null, + title: e.onscreen?.title ?? null, + style: e.style ?? null, + }, + state: r.state, + verdict: r.row?.verdict ?? null, + note: r.row?.note ?? "", + judgedText: r.row?.text ?? "", + judgedAt: r.row?.at ?? "", + kept: rec ? { seconds: rec.seconds, disclosure: rec.disclosure, mtimeMs: wav ? Math.round(wav.mtimeMs) : 0 } : null, + }); + } + 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 }; +} diff --git a/umtool/lib/report/narration-review.test.mjs b/umtool/lib/report/narration-review.test.mjs @@ -0,0 +1,76 @@ +// The narration review's umtool side (release 25, T5): the manifest writer's +// `updateNarration` (only the words change; the build's validator refuses bad +// ones; a snapshot first) and the page's view (each narrated card's words, +// what it shows, its state, whether its voice is kept). +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { StructureRefused, updateNarration } from "./manifest.mjs"; +import { narrationReviewView } from "./narration-review.mjs"; +import { narrationsOf } from "umtool-report-to-video/narration"; +import { setNarrationReview } from "umtool-report-to-video/narration-review"; + +const MANIFEST = { + slug: "nr", title: "NR", render: { transition: 0.5 }, + timeline: [ + { type: "card", id: "k1", kicker: "2024", heading: "Then", sub: "the county", seconds: "auto", narration: { text: "Then it happened." }, onscreen: { title: "Deck title" } }, + { type: "card", id: "k2", heading: "Now", seconds: 6, narration: { text: "And again.", voice: "am_adam" } }, + { type: "card", id: "plain", heading: "Plain", seconds: 2 }, + { type: "clip", id: "c1", video: "v", start: 1, end: 2 }, + ], +}; + +function project(t) { + const dir = mkdtempSync(path.join(tmpdir(), "umtool-narration-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2) + "\n"); + return dir; +} +const read = (dir) => JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8")); + +test("updateNarration changes the words alone, trimmed, after a snapshot; the build's validator refuses bad words", async (t) => { + const dir = project(t); + const r = await updateNarration(dir, "k1", " Then, at last, it happened. <sigh> "); + assert.equal(r.changed, true); + const m = read(dir); + assert.deepEqual(m.timeline[0].narration, { text: "Then, at last, it happened. <sigh>" }); + assert.equal(m.timeline[0].heading, "Then"); + assert.ok(readdirSync(path.join(dir, "revisions")).some((n) => /auto-before-narration/.test(n))); + await assert.rejects(updateNarration(dir, "k1", "a <whisper> b"), (e) => e instanceof StructureRefused && /<whisper>/.test(e.message)); + await assert.rejects(updateNarration(dir, "k1", " "), /text must be non-empty words/); + await assert.rejects(updateNarration(dir, "plain", "Hi."), /plain is not a card with a narration/); + await assert.rejects(updateNarration(dir, "c1", "Hi."), /c1 is not a card with a narration/); + assert.equal((await updateNarration(dir, "k2", "And again.")).changed, false); +}); + +test("the view: each narrated card's words, voice, screen, state and kept voice", async (t) => { + const dir = project(t); + let v = await narrationReviewView(dir, MANIFEST); + assert.equal(v.exists, false); + assert.deepEqual(v.rows.map((r) => [r.id, r.state, r.voice, r.engine]), [["k1", "unreviewed", "af_heart", "kokoro"], ["k2", "unreviewed", "am_adam", "kokoro"]]); + assert.deepEqual(v.rows[0].screen, { kicker: "2024", heading: "Then", sub: "the county", title: "Deck title", style: null }); + assert.equal(v.rows[0].words, 3); + assert.equal(v.rows[0].kept, null); + const [n1] = narrationsOf(MANIFEST); + await setNarrationReview(dir, "k1", { verdict: "approved", key: n1.key, text: n1.text }); + // A kept voice: its record and its sound beside the build. + const store = path.join(dir, "out", "narration"); + mkdirSync(store, { recursive: true }); + writeFileSync(path.join(store, `${n1.key}.json`), JSON.stringify({ key: n1.key, seconds: 1.4, disclosure: "Narration: synthetic voice (Kokoro-82M · af_heart)" })); + writeFileSync(path.join(store, `${n1.key}.wav`), "RIFF"); + v = await narrationReviewView(dir, MANIFEST); + assert.equal(v.exists, true); + assert.deepEqual(v.counts, { approved: 1, rejected: 0, edited: 0, unreviewed: 1 }); + assert.equal(v.rows[0].kept.seconds, 1.4); + // New words: the approval does not carry over, and the old voice is not theirs. + const edited = { ...MANIFEST, timeline: [{ ...MANIFEST.timeline[0], narration: { text: "Other words." } }, ...MANIFEST.timeline.slice(1)] }; + v = await narrationReviewView(dir, edited); + assert.equal(v.rows[0].state, "edited"); + assert.equal(v.rows[0].judgedText, "Then it happened."); + assert.equal(v.rows[0].kept, null); +}); diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -1130,12 +1130,41 @@ exactly as it did — every card's sound is still `anullsrc`. #### Writing narration -Write it for the ear: short sentences, the beat before the turn, a little warmth -or weariness where the moment has it — a tag like `<sigh>` is a delivery note, -not a claim. The drama never outruns the sources. Every factual claim in a -narration is exactly what the cited clips and posts support: the same numbers, -the same dates, the same hedges, nothing a viewer could not check against the -QR on the next clip. When in doubt, cut the line and let the clip say it. +**The hard rule.** Storytelling and emotion live in the delivery, never in the +claims: every factual statement stays exactly as the cited evidence supports — +no invented quotes, no motives or feelings attributed to real people, no +intensifiers that change a claim's strength. (The MCP's sweep plan carries the +same sentence, `mcp/src/instructions.ts` `NARRATION_HARD_RULE`.) + +Write it for the ear: short spoken sentences, the beat before the turn, a +little warmth or weariness where the moment has it — an expressive tag like +`<sigh>` is a delivery note, not a claim. Every line traces to a citation the +cut already carries; a line that does not is cut, not softened. The concrete +rules — sentence length, punctuation for pauses, where Orpheus's tags work — +come from the voice tuning round and are not written here yet. + +#### The narration review + +`/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 + 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. ### The podcast: `build-podcast.mjs` diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -54,6 +54,9 @@ // after its validators and before it renders anything: an // error refuses it, a warning is a note. // --no-lint Build without the lint (an old manifest it refuses) +// --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. // --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 @@ -142,6 +145,7 @@ import { cardNarrationSeconds, resolveNarrationRender, validateNarration, } from "./narration.mjs"; import { narrationDir, narrationWavPath, readCutDisclosure, readNarrationRecords } from "./narration-store.mjs"; +import { readNarrationReview } from "./narration-review.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"; @@ -4130,9 +4134,15 @@ 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. const lint = opts.noLint ? { errors: [], warnings: [] } - : lintManifest(manifest, { manifestDir, whole, only: only ?? null, validators: false }); + : lintManifest(manifest, { + manifestDir, whole, only: only ?? null, validators: false, + narrationReview: await readNarrationReview(manifestDir), narrationUnreviewed: opts.narrationUnreviewed === true, + }); // Where each post's QR goes: its page on the archive (`posts.links` // "archive", the default), which needs the archive channel that keeps it. @@ -4843,6 +4853,7 @@ async function main() { " [--no-rail] [--rail-only] [--preview <start> <dur>]\n" + " [--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" + " [--site-origin <url>] [--resolve-site-ids] [--cue-source auto|local|http]\n" + " [--thumbnail] (render.brand only: out/<slug>.thumbnail.png and stop)", ); @@ -4878,6 +4889,7 @@ async function main() { thumbnailOnly: argv.includes("--thumbnail"), keepFrames: argv.includes("--keep-frames"), noLint: argv.includes("--no-lint"), + narrationUnreviewed: argv.includes("--narration-unreviewed"), }; try { Object.assign(opts, chromeFlags(argv)); @@ -4897,7 +4909,7 @@ 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 }); + const lint = await lintManifestFile(manifestPath, { variant: opts.variant, only: flag("--only") ?? null, narrationUnreviewed: opts.narrationUnreviewed }); 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/lint.mjs b/umtool/report-to-video/lint.mjs @@ -24,11 +24,16 @@ // (narration.mjs), validatePodcast (build-podcast.mjs), and the cut edits, teasers, claims and posts validators // a build runs first -- so `--lint` alone reports what a build would // refuse, all at once; +// - 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`; // - 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 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, @@ -68,6 +73,7 @@ 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"; export const TEASER_HOUSE_CHARS = 34; export const MIN_QR_PX_PER_MODULE_720P = 1.5; @@ -240,7 +246,8 @@ 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 }} [opts] + * only?: string|null, validators?: boolean, narrationSeconds?: Map<string, number> | null, + * narrationReview?: { exists: boolean, rows: object, error?: string } | null, narrationUnreviewed?: 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); @@ -249,6 +256,7 @@ export function narrationLengthErrors(manifest, secondsById, { only = null } = { */ export function lintManifest(manifest, { manifestDir, whole = manifest, exists = existsSync, only = null, validators = true, narrationSeconds = null, + narrationReview = null, narrationUnreviewed = false, } = {}) { const errors = []; const warnings = []; @@ -298,6 +306,13 @@ export function lintManifest(manifest, { } } + // The narration review: `narrationReview` null when it was not read. + { + const r = reviewProblems(manifest, narrationReview, { only, allowUnreviewed: narrationUnreviewed }); + errors.push(...r.errors); + warnings.push(...r.warnings, ...r.notes); + } + if (narrationSeconds) { errors.push(...narrationLengthErrors(manifest, narrationSeconds, { only })); for (const e of manifest.timeline ?? []) { @@ -317,7 +332,7 @@ export function lintManifest(manifest, { * * @returns {Promise<{ errors: string[], warnings: string[], variant: string }>} */ -export async function lintManifestFile(manifestPath, { variant = "sourced", only = null } = {}) { +export async function lintManifestFile(manifestPath, { variant = "sourced", only = null, narrationUnreviewed = false } = {}) { const { readFile } = await import("node:fs/promises"); const { selectVariant } = await import("./build-video.mjs"); const whole = JSON.parse(await readFile(manifestPath, "utf8")); @@ -332,7 +347,8 @@ 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])); } - return { ...lintManifest(manifest, { manifestDir, whole, only, narrationSeconds }), variant }; + const narrationReview = await readNarrationReview(manifestDir); + return { ...lintManifest(manifest, { manifestDir, whole, only, narrationSeconds, narrationReview, narrationUnreviewed }), variant }; } catch (err) { return { errors: [err?.message ?? String(err)], warnings: [], variant }; } diff --git a/umtool/report-to-video/narrate-via-editor.mjs b/umtool/report-to-video/narrate-via-editor.mjs @@ -3,7 +3,10 @@ // engine here (release 25, T2 -- the "no ASR by hand" rule's twin). // // node umtool/report-to-video/narrate-via-editor.mjs <manifest.json> -// [--out <dir>] [--variant sourced|full] [--progress ndjson] +// [--out <dir>] [--variant sourced|full] [--only <cardId>] [--progress ndjson] +// +// `--only <cardId>` asks for that one card's narration (umtool's narration +// review plays it before anything is approved). // // Every card `narration` in the manifest (or in one cut of it, `--variant`) is // one `POST /api/ops/tts` -- `{ text, engine, voice, speed }`, the engine and @@ -214,7 +217,7 @@ async function main() { const i = argv.indexOf(n); return i < 0 ? undefined : argv[i + 1]; }; - const valued = new Set(["--out", "--variant", "--progress"]); + const valued = new Set(["--out", "--variant", "--progress", "--only"]); const manifestPath = argv.find((a, i) => !a.startsWith("--") && !valued.has(argv[i - 1])); let EMIT = (ev, f = {}) => { if (ev === "note") console.log(f.message); @@ -228,7 +231,7 @@ async function main() { if (flag("--progress") === "ndjson") process.stderr.write(`${message}\n`); process.exit(code); }; - if (!manifestPath) die("usage: narrate-via-editor.mjs <manifest.json> [--out <dir>] [--variant sourced|full] [--progress ndjson]", 2); + if (!manifestPath) die("usage: narrate-via-editor.mjs <manifest.json> [--out <dir>] [--variant sourced|full] [--only <cardId>] [--progress ndjson]", 2); const whole = JSON.parse(await readFile(manifestPath, "utf8")); // Validated as the build validates it: a manifest the build would refuse is @@ -241,7 +244,9 @@ async function main() { const { selectVariant } = await import("./build-video.mjs"); cut = selectVariant(whole, flag("--variant")); } - const narrations = narrationsOf(cut); + const only = flag("--only"); + const narrations = narrationsOf(cut).filter((n) => !only || n.id === only); + if (only && !narrations.length) die(`${only} is not a card with a narration in this manifest`); if (!narrations.length) { EMIT("note", { message: "no card carries a narration — nothing to synthesize" }); EMIT("done", { narrations: 0 }); diff --git a/umtool/report-to-video/narration-review.mjs b/umtool/report-to-video/narration-review.mjs @@ -0,0 +1,191 @@ +// The review of a cut's narration script, card by card, before synthesis +// (release 25, T5). +// +// <project>/narration.review.json beside video.manifest.json +// { "<cardId>": { "verdict": "approved" | "rejected" | null, "note": string, +// "key": "<narrationKey when judged>", "text": "<the words judged>", "at": ISO } } +// +// The shape is takes/verdicts.json's (lib/report/takes.mjs): one row per item, +// every row carrying every key, a row with no verdict and no note REMOVED +// rather than stored, its own write queue, tmp + rename, and a file that does +// not parse is an ERROR (never overwritten, never read as empty). +// +// A verdict is about THE WORDS AND THE VOICE IT WAS GIVEN ON: the row keeps +// their key (narration.mjs `narrationKey`: text, engine, voice, speed), so an +// edit -- of the words, or a change of voice -- leaves the row "edited": not +// 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). +// +// Pure but for the file's read and write. +import { readFile, rename, writeFile } from "node:fs/promises"; +import path from "node:path"; + +import { narrationsOf } from "./narration.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 : ""); + +/** Rows that are not the contract's shape are dropped on read, never repaired on disk. */ +export function cleanReview(raw) { + 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), + }; + } + 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. + */ +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` }; + } +} + +/** + * One narration's review state: "approved" or "rejected" on its current words + * and voice, "edited" when the verdict was given on others, else "unreviewed". + * + * @param {{ key: string }} n a narration (narration.mjs `narrationsOf`) + * @param {{ verdict: string | null, key: string } | undefined} row + */ +export function reviewState(n, row) { + if (!row?.verdict) return "unreviewed"; + if (row.key !== n.key) return "edited"; + return row.verdict; +} + +/** Every narrated card of a cut with its review row and state, in timeline order. */ +export function reviewRows(manifest, review) { + return narrationsOf(manifest).map((n) => { + const row = review?.rows?.[n.id] ?? null; + return { ...n, row, state: reviewState(n, row) }; + }); +} + +/** + * What the review says about building this cut: `errors` refuse it, `notes` + * are said. `warnings` is the lint's: no review file for a narrated cut. + * + * @param {any} manifest the cut + * @param {{ exists: boolean, rows: Record<string, any>, error?: string } | null} review + * @param {{ only?: string | null, allowUnreviewed?: boolean }} [opts] + */ +export function reviewProblems(manifest, review, { only = null, allowUnreviewed = false } = {}) { + const errors = []; + const notes = []; + const warnings = []; + const rows = reviewRows(manifest, review).filter((r) => !only || r.id === only); + if (!rows.length || !review) return { errors, notes, warnings }; + 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; ` + + "review it card by card on umtool's narration page before it is published", + ); + return { errors, notes, warnings }; + } + for (const r of rows) { + if (r.state === "approved") continue; + if (r.state === "rejected") { + errors.push( + `timeline ${r.id}: 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 (allowUnreviewed) notes.push(`timeline ${r.id}: its narration is ${why} — built anyway (--narration-unreviewed)`); + else errors.push(`timeline ${r.id}: its narration is ${why} — approve it on umtool's narration page, or build with --narration-unreviewed`); + } + 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. + * + * @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 }; + }); +} diff --git a/umtool/report-to-video/narration-review.test.mjs b/umtool/report-to-video/narration-review.test.mjs @@ -0,0 +1,137 @@ +// narration-review.mjs: the review file (takes/verdicts.json's shape), the +// states -- an edit or a voice change un-approves -- and what the lint and the +// build make of them: no file a warning, an un-approved card an error unless +// --narration-unreviewed, a rejected card an error always. +// +// 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 { 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, +} from "./narration-review.mjs"; + +const card = (id, text, extra = {}) => ({ type: "card", id, heading: id, seconds: "auto", narration: { text, ...extra } }); +const M = (timeline, render = {}) => ({ slug: "rv", title: "RV", render: { transition: 0, ...render }, timeline }); + +test("the file: a missing one is absent, a broken one is an error and is never overwritten", async (t) => { + const dir = mkdtempSync(path.join(tmpdir(), "rtv-review-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + assert.deepEqual(await readNarrationReview(dir), { exists: false, rows: {} }); + writeFileSync(path.join(dir, NARRATION_REVIEW_FILE), "{ not json"); + const broken = await readNarrationReview(dir); + assert.equal(broken.exists, true); + assert.match(broken.error, /does not parse/); + await assert.rejects(setNarrationReview(dir, "k1", { verdict: null, note: "x" }), /does not parse/); + assert.equal(readFileSync(path.join(dir, NARRATION_REVIEW_FILE), "utf8"), "{ not json"); + // Rows not of the shape are dropped on read. + assert.deepEqual(cleanReview({ k1: { verdict: "maybe", note: 3 }, "": {}, k2: "x" }), { k1: { verdict: null, note: "", key: "", text: "", at: "" } }); +}); + +test("setNarrationReview: a verdict is on words; a rejection needs its note; an empty row goes", async (t) => { + const dir = mkdtempSync(path.join(tmpdir(), "rtv-review-set-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + await assert.rejects(setNarrationReview(dir, "k1", { verdict: "approved" }), /key and text are required/); + await assert.rejects(setNarrationReview(dir, "k1", { verdict: "fine", key: "a", text: "b" }), /verdict must be one of approved, rejected/); + await assert.rejects(setNarrationReview(dir, "k1", { verdict: "rejected", key: "a", text: "b" }), /a rejection needs its note/); + const a = await setNarrationReview(dir, "k1", { verdict: "approved", key: "K", text: "Words." }); + assert.equal(a.entry.verdict, "approved"); + assert.equal(a.entry.key, "K"); + const r = await setNarrationReview(dir, "k2", { verdict: "rejected", key: "K2", text: "Bad.", note: " overstates it " }); + assert.equal(r.entry.note, "overstates it"); + // Clearing the verdict forgets the words judged, keeps the note. + const c = await setNarrationReview(dir, "k2", { verdict: null }); + assert.deepEqual([c.entry.verdict, c.entry.key, c.entry.text, c.entry.note], [null, "", "", "overstates it"]); + // 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"]); +}); + +test("states: approved on its words; an edit or another voice leaves it edited; none is unreviewed", () => { + const m = M([card("k1", "Then it happened."), card("k2", "And again.")]); + const [n1, n2] = narrationsOf(m); + const rows = { k1: { verdict: "approved", key: n1.key, text: n1.text, note: "", at: "" } }; + assert.equal(reviewState(n1, rows.k1), "approved"); + assert.equal(reviewState(n2, undefined), "unreviewed"); + const [e1] = narrationsOf(M([card("k1", "Then it happened, twice.")])); + assert.equal(reviewState(e1, rows.k1), "edited"); + const [v1] = narrationsOf(M([card("k1", "Then it happened.", { voice: "am_adam" })])); + assert.equal(reviewState(v1, rows.k1), "edited"); + assert.equal(reviewState(n1, { ...rows.k1, verdict: "rejected" }), "rejected"); + assert.deepEqual(reviewRows(m, { exists: true, rows }).map((r) => [r.id, r.state]), [["k1", "approved"], ["k2", "unreviewed"]]); +}); + +test("reviewProblems: no file warns; a file holds every un-approved card; the flag lets unreviewed and edited through, never rejected", () => { + const m = M([card("k1", "One."), card("k2", "Two."), card("k3", "Three."), { type: "card", id: "plain", seconds: 2 }]); + const [n1, , n3] = narrationsOf(m); + const review = { + exists: true, + rows: { + k1: { verdict: "approved", key: n1.key, text: n1.text, note: "", at: "" }, + k3: { verdict: "rejected", key: n3.key, text: n3.text, note: "says more than the clip", at: "" }, + }, + }; + 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/); + 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/); + assert.match(held.errors[1], /timeline k3: its narration was rejected \("says more than the clip"\) — rewrite it and approve it, or take the narration out/); + const flagged = reviewProblems(m, review, { allowUnreviewed: true }); + assert.deepEqual(flagged.errors.map((e) => e.slice(0, 12)), ["timeline k3:"]); + assert.match(flagged.notes[0], /k2: its narration is not reviewed — built anyway \(--narration-unreviewed\)/); + assert.deepEqual(reviewProblems(m, review, { only: "k1" }), { errors: [], notes: [], warnings: [] }); + assert.match(reviewProblems(m, { exists: true, rows: {}, error: "broken" }).errors[0], /broken/); + // A cut without narration says nothing, file or not. + assert.deepEqual(reviewProblems(M([{ type: "card", id: "a", seconds: 1 }]), { exists: false, rows: {} }), { errors: [], notes: [], warnings: [] }); + // Through the lint. + const lint = lintManifest(m, { narrationReview: review }); + assert.equal(lint.errors.filter((e) => /its narration/.test(e)).length, 2); + assert.ok(lintManifest(m, { narrationReview: { exists: false, rows: {} } }).warnings.some((w) => /has no review/.test(w))); +}); + +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 refuses an un-approved narrated card before it asks for a voice; --narration-unreviewed lets it through", async (t) => { + const dir = mkdtempSync(path.join(tmpdir(), "rtv-review-build-")); + t.after(() => rmSync(dir, { recursive: true, force: true })); + const manifestPath = path.join(dir, "video.manifest.json"); + writeFileSync(manifestPath, JSON.stringify(M([card("k1", "One.")], { audioRate: 48000, audioChannels: 2, fps: 10 }))); + // No editor is reachable: a build that asked for the voice would fail on that instead. + const editor = { url: "http://127.0.0.1:9", token: "t" }; + // No review file: nothing is held -- it goes on to the voice (and, with + // --skip-fetch, refuses for want of one), the lint's warning said. + const free = await quietly(() => buildVideo({ manifestPath, opts: { skipFetch: true, editor } })); + assert.match(String(free.result?.err?.message), /k1: its narration has not been synthesized/); + assert.ok(free.events.some((e) => e.ev === "note" && /lint: the narration \(1 card\) has no review/.test(e.message))); + + await setNarrationReview(dir, "other", { note: "a review file now exists" }); + const held = await quietly(() => buildVideo({ manifestPath, opts: { editor } })); + assert.match(String(held.result?.err?.message), /lint: timeline k1: its narration is not reviewed/); + assert.ok(!held.events.some((e) => e.ev === "note" && /asking the editor/.test(e.message)), "refused before any ask"); + + const through = await quietly(() => buildVideo({ manifestPath, opts: { skipFetch: true, editor, narrationUnreviewed: true } })); + assert.match(String(through.result?.err?.message), /k1: its narration has not been synthesized/); + assert.ok(through.events.some((e) => e.ev === "note" && /built anyway \(--narration-unreviewed\)/.test(e.message))); + + const [n] = narrationsOf(M([card("k1", "One.")])); + await setNarrationReview(dir, "k1", { verdict: "rejected", key: n.key, text: n.text, note: "no" }); + const rejected = await quietly(() => buildVideo({ manifestPath, opts: { skipFetch: true, editor, narrationUnreviewed: true } })); + assert.match(String(rejected.result?.err?.message), /timeline k1: its narration was rejected/); +}); diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -30,6 +30,7 @@ "./local-media": "./local-media.mjs", "./mute": "./mute.mjs", "./narration": "./narration.mjs", + "./narration-review": "./narration-review.mjs", "./narration-store": "./narration-store.mjs", "./package.json": "./package.json", "./post-links": "./post-links.mjs",