Archilyzer · Source

archilyzer

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

commit 2a9b597b4ef7810b149321dafebd101e8269f879
parent 4cc0e748e8bab5067644b713b7e420305577fb25
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 22 Oct 2026 10:06:56 -0400

knobs: writers and routes for the video knobs; agent token on every manifest write

updateClaimKnobs (claim at/hold/stamp/count/label), updateClip audio, the
fact-check's stamp scale/motion/opacity and stampLabel, updateDeckMarkers
(markers + markerLayout), updateVariants (render.variants), checked by
lib/report/knobs.mjs; the clip editor's claim and audio ops; Make variants as
a deliver action and /api/report/variants for the read-back and sync.json.
Every manifest-write route takes the page or Bearer <WORKER_TOKEN>.

Shims for lane/knobs-core: report-to-video/clip-audio.mjs (validateClipAudio)
and report-to-video/variants.mjs (encodeVariants + CLI), exported in
report-to-video/package.json; the core lane's files replace them at merge.

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

Diffstat:
Mumtool/app/api/report/build/route.ts | 3+++
Mumtool/app/api/report/chrome/preview/route.ts | 3++-
Mumtool/app/api/report/chrome/route.ts | 41+++++++++++++++++++++++++++++++++++++++--
Mumtool/app/api/report/claim/route.ts | 3+++
Mumtool/app/api/report/clip-editor/route.ts | 3+++
Mumtool/app/api/report/cut/route.ts | 3+++
Mumtool/app/api/report/deliver/route.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/drafts/route.ts | 3+++
Mumtool/app/api/report/hand-fill/route.ts | 3+++
Mumtool/app/api/report/narration/route.ts | 3+++
Mumtool/app/api/report/onscreen/route.ts | 3+++
Mumtool/app/api/report/posts/route.ts | 3+++
Mumtool/app/api/report/render/route.ts | 27+++++++++++++++++++++++++--
Mumtool/app/api/report/still/route.ts | 3++-
Mumtool/app/api/report/timeline/route.ts | 3+++
Aumtool/app/api/report/variants/route.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/video-assist/route.ts | 3+++
Mumtool/app/api/report/window/route.ts | 3+++
Aumtool/lib/report/caller.ts | 13+++++++++++++
Mumtool/lib/report/clipEditor.mjs | 51++++++++++++++++++++++++++++++++++++++++++++++++++-
Mumtool/lib/report/clipEditor.test.mjs | 26++++++++++++++++++++++++++
Mumtool/lib/report/clipEditorTypes.ts | 13+++++++++++++
Mumtool/lib/report/driver.mjs | 30++++++++++++++++++++++++++++++
Aumtool/lib/report/knobs.mjs | 381+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/knobs.test.mjs | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 242++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Aumtool/lib/report/variantsView.mjs | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
27 files changed, 1301 insertions(+), 16 deletions(-)

diff --git a/umtool/app/api/report/build/route.ts b/umtool/app/api/report/build/route.ts @@ -6,6 +6,7 @@ import { clipsOf, readManifest } from "@/lib/projects/report.mjs"; import { projectRef } from "@/lib/projects"; import { recordBuildSnapshot } from "@/lib/report/snapshots.mjs"; import { DEFAULT_VARIANT, VARIANTS, variantPaths } from "umtool-report-to-video/build-video"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -49,6 +50,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/build"); + if (refused) return refused; const url = new URL(request.url); const dry = url.searchParams.get("dry") === "1"; const replace = url.searchParams.get("replace") === "1"; diff --git a/umtool/app/api/report/chrome/preview/route.ts b/umtool/app/api/report/chrome/preview/route.ts @@ -13,6 +13,7 @@ import { deckPreviewSrc, feedPreviewSrc, postsPreviewSrc, resolveReport, stampPr import { deckGeometry, deckLayout, deckOn, feedGeometry, postsGeometry, stampGeometry, validateChrome, } from "umtool-report-to-video/deck"; +import { chromeForRenderer } from "@/lib/report/knobs.mjs"; import { stampsDrawn, tallyOf } from "umtool-report-to-video/factcheck"; export const dynamic = "force-dynamic"; @@ -92,7 +93,7 @@ export async function POST(request: Request) { ); } const { chrome, ...rest } = render; - const errors = validateChrome(chrome, rest); + const errors = validateChrome(chromeForRenderer(chrome), rest); if (errors.length) { return Response.json({ error: `render.chrome: ${errors.join("; ")}`, errors }, { status: 400 }); } diff --git a/umtool/app/api/report/chrome/route.ts b/umtool/app/api/report/chrome/route.ts @@ -1,7 +1,10 @@ import { withEditNotes } from "@/lib/report/guard"; -import { ChromeRefused, StaleToken, manifestToken, updateChrome } from "@/lib/report/manifest.mjs"; +import { ChromeRefused, StaleToken, StructureRefused, manifestToken, updateChrome, updateDeckMarkers } from "@/lib/report/manifest.mjs"; +import { MARKER_ALIGNS, MARKER_LAYOUTS, chromeForRenderer, chromeKnobProblems } from "@/lib/report/knobs.mjs"; +import { invalidateProjects } from "@/lib/projects"; import { resolveReport } from "@/lib/report/serve.mjs"; import { DECK_DEFAULTS, deckOn, resolveDeck, validateChrome } from "umtool-report-to-video/deck"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -12,6 +15,11 @@ export const dynamic = "force-dynamic"; // sends a path. Validation is deck.mjs's validateChrome, run by the writer, so // a block this route accepts is one the build accepts; a refusal comes back // as the same sentences the build would print, one per problem. +// +// PUT { project, token, markers?, markerLayout? } (no `chrome`) sets only the +// deck's markers and/or their layout (video knobs: the Markers editor, `umtool +// look deck.markers=…`), leaving the rest of the deck as it is -- a +// structural edit, snapshotted first (lib/report/manifest.mjs updateDeckMarkers). type Body = Record<string, unknown>; @@ -32,7 +40,10 @@ export async function GET(request: Request) { defaults: DECK_DEFAULTS, // A block somebody hand-edited into a state the build would refuse. The // form shows these rather than pretending the saved settings are fine. - errors: chrome ? validateChrome(chrome, rest) : [], + errors: chrome ? [...validateChrome(chromeForRenderer(chrome), rest), ...chromeKnobProblems(chrome)] : [], + // The Markers editor's choices (video knobs). + markerAligns: MARKER_ALIGNS, + markerLayouts: MARKER_LAYOUTS, token: await manifestToken(r.project.dir), }, { headers: noStore }, @@ -40,12 +51,15 @@ export async function GET(request: Request) { } export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/chrome"); + if (refused) return refused; let body: Body; try { body = await request.json(); } catch { return Response.json({ error: "expected JSON" }, { status: 400 }); } + if (!("chrome" in body) && ("markers" in body || "markerLayout" in body)) return putMarkers(body); if (!("chrome" in body)) { return Response.json({ error: "chrome is required — an object, or null to turn the deck off" }, { status: 400 }); } @@ -82,3 +96,26 @@ export async function PUT(request: Request) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); } } + +/** The Markers editor's save: `deck.markers` and/or `deck.markerLayout`, nothing else. */ +async function putMarkers(body: Body) { + const r = await resolveReport(String(body.project ?? "")); + if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + const patch: { markers?: unknown[] | null; markerLayout?: string | null } = {}; + if ("markers" in body) patch.markers = (body.markers ?? null) as unknown[] | null; + if ("markerLayout" in body) patch.markerLayout = (body.markerLayout ?? null) as string | null; + try { + const { result: res, editNotes } = await withEditNotes(r.project, () => + updateDeckMarkers(r.project.dir, patch, { token: typeof body.token === "string" ? body.token : null }), + ); + // revisions/ changed: the project page lists them. + invalidateProjects(); + return Response.json({ ok: true, ...res, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) { + return Response.json({ error: e.message, expected: e.expected, got: e.got, 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 }); + } +} diff --git a/umtool/app/api/report/claim/route.ts b/umtool/app/api/report/claim/route.ts @@ -2,6 +2,7 @@ import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, manifestToken, updateClaim } from "@/lib/report/manifest.mjs"; import { resolveClaim } from "@/lib/report/serve.mjs"; import { readClaimDetail } from "@/lib/projects/report.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -35,6 +36,8 @@ export async function GET(request: Request) { } export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/claim"); + if (refused) return refused; const body = (await request.json().catch(() => ({}))) as Record<string, unknown>; const projectId = String(body.project ?? ""); const claimId = String(body.claim ?? ""); diff --git a/umtool/app/api/report/clip-editor/route.ts b/umtool/app/api/report/clip-editor/route.ts @@ -1,6 +1,7 @@ import { projectRef } from "@/lib/projects"; import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; import { OpError, StaleToken, StructureRefused, clipEditorView, clipNeighbourhood, runClipEditorOp } from "@/lib/report/clipEditor.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -46,6 +47,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/clip-editor"); + if (refused) return refused; const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); const r = await editorProject(body.project); diff --git a/umtool/app/api/report/cut/route.ts b/umtool/app/api/report/cut/route.ts @@ -4,6 +4,7 @@ import { cleanRespellings } from "yt-dlp-transcript-common/lib/citations/respell import { cuesInWindow } from "@/lib/projects/report.mjs"; import { resolveClip } from "@/lib/report/serve.mjs"; import { cutToQuote } from "umtool-report-to-video/resolve-windows"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -22,6 +23,8 @@ export const dynamic = "force-dynamic"; const LOOK = 30; export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/cut"); + if (refused) return refused; const body = (await request.json().catch(() => ({}))) as Record<string, unknown>; const projectId = String(body.project ?? ""); const clipId = String(body.clip ?? ""); diff --git a/umtool/app/api/report/deliver/route.ts b/umtool/app/api/report/deliver/route.ts @@ -5,12 +5,17 @@ import { moveDeliverablesSteps, rebuildReportSteps, shareBatchSteps, + variantsSteps, } from "@/lib/report/driver.mjs"; import { SHARE_PREFIX, deliverStateOf } from "@/lib/report/deliver.mjs"; import { deliverablesProblems, isDeliverableName } from "@/lib/report/storage.mjs"; import { readClipDetail } from "@/lib/projects/report.mjs"; import { projectRef } from "@/lib/projects"; import type { Step } from "@/lib/trim"; +import { refuseCaller } from "@/lib/report/caller"; +import { outDirOf, variantsState } from "@/lib/report/variantsView.mjs"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; export const dynamic = "force-dynamic"; @@ -24,6 +29,9 @@ export const dynamic = "force-dynamic"; // move the deliverables (clips/, every share-*) to the media root or // back, then the manifest's storage.deliverables (release 17) -- // a job like the others, so nothing cuts or shares while it moves +// variants (a report video, video knobs) the build's encode ladder, +// render.variants -- `{ action: "variants", take? }`; read back +// through /api/report/variants // // Each is a JOB, and jobs.ts allows exactly one at a time. That is not a // limitation to work around here: every one of these reads or writes the same @@ -74,6 +82,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/deliver"); + if (refused) return refused; const url = new URL(request.url); const cancel = url.searchParams.get("cancel"); // Stop ABANDONS THE REST, it does not undo what finished. Every artefact @@ -82,6 +92,9 @@ export async function POST(request: Request) { if (cancel) return Response.json({ cancelled: cancelJob(cancel) }); const body = (await request.json().catch(() => ({}))) as Record<string, unknown>; + // Make variants (video knobs): a report video's built cut, or a take's, in + // the ladder render.variants names. No walk state is read for it. + if (body.action === "variants") return startVariants(body); const action = String(body.action ?? "") as Action; if (!ACTIONS.includes(action)) { return Response.json({ error: `action must be one of ${ACTIONS.join(", ")}` }, { status: 400 }); @@ -205,3 +218,36 @@ export async function POST(request: Request) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 }); } } + +/** + * `action: "variants"`, `take?`: the encode ladder of the project's build (or + * of that take's), as one job (driver.mjs variantsSteps; the encoder takes the + * heavy slot). Refused with no build to encode, or while another job runs. + */ +async function startVariants(body: Record<string, unknown>) { + const project = await projectRef(String(body.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404 }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "variants are made of a report video's build" }, { status: 400 }); + const manifest = await readManifest(project.dir); + if (!manifest) return Response.json({ error: "no manifest" }, { status: 400 }); + const take = typeof body.take === "string" && body.take ? body.take : null; + let state: Awaited<ReturnType<typeof variantsState>>; + try { + state = await variantsState(project, manifest, take); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } + if (!state.built) { + return Response.json({ error: take ? `take ${take} has no build to make variants of` : "this cut has not been built yet — build it first" }, { status: 409 }); + } + const running = runningJob(); + if (running) { + return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 }); + } + try { + const job = startJob(`variants ${project.id}${take ? ` (take ${take})` : ""}`, variantsSteps(project, outDirOf(project, take)), { project: project.id }); + return Response.json({ ok: true, action: "variants", take, 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/drafts/route.ts b/umtool/app/api/report/drafts/route.ts @@ -6,6 +6,7 @@ import { currentFieldValue, valueFromEdit } from "@/lib/report/draftEdit.mjs"; import { readManifest } from "@/lib/projects/report.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { draftsReviewRows, readDraftsReview, setDraftReview } from "umtool-report-to-video/drafts-review"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -41,6 +42,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/drafts"); + if (refused) return refused; let body: Body; try { body = await request.json(); diff --git a/umtool/app/api/report/hand-fill/route.ts b/umtool/app/api/report/hand-fill/route.ts @@ -5,6 +5,7 @@ import { withEditNotes } from "@/lib/report/guard"; import { MANIFEST_NAME, StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; import { applyHandFill, handFillView } from "@/lib/report/hand-fill.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -31,6 +32,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/hand-fill"); + if (refused) return refused; const body = (await request.json().catch(() => null)) as Record<string, unknown> | null; if (!body) return Response.json({ error: "expected JSON" }, { status: 400, headers: noStore }); const r = await resolveReport(String(body.project ?? "")); diff --git a/umtool/app/api/report/narration/route.ts b/umtool/app/api/report/narration/route.ts @@ -5,6 +5,7 @@ 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"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -41,6 +42,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/narration"); + if (refused) return refused; let body: Body; try { body = await request.json(); diff --git a/umtool/app/api/report/onscreen/route.ts b/umtool/app/api/report/onscreen/route.ts @@ -3,6 +3,7 @@ import { StaleToken, manifestToken, updateOnscreen } from "@/lib/report/manifest import { postRows, scheduleForPreview } from "@/lib/report/onscreen.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { deckText, isMultiChannel, resolveDeck } from "umtool-report-to-video/deck"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -76,6 +77,8 @@ export async function GET(request: Request) { } export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/onscreen"); + if (refused) return refused; let body: Record<string, unknown>; try { body = await request.json(); diff --git a/umtool/app/api/report/posts/route.ts b/umtool/app/api/report/posts/route.ts @@ -1,6 +1,7 @@ import { withEditNotes } from "@/lib/report/guard"; import { PostsRefused, StaleToken, updatePosts } from "@/lib/report/manifest.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -18,6 +19,8 @@ export const dynamic = "force-dynamic"; const noStore = { "cache-control": "no-store" }; export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/posts"); + if (refused) return refused; let body: Record<string, unknown>; try { body = await request.json(); diff --git a/umtool/app/api/report/render/route.ts b/umtool/app/api/report/render/route.ts @@ -1,9 +1,11 @@ import { withEditNotes } from "@/lib/report/guard"; -import { LOOK_KEYS, RenderRefused, StaleToken, lookOf, manifestToken, updateRender } from "@/lib/report/manifest.mjs"; +import { LOOK_KEYS, RenderRefused, StaleToken, lookOf, manifestToken, updateRender, updateVariants } from "@/lib/report/manifest.mjs"; +import { VARIANTS_DEFAULT, variantsProblems } from "@/lib/report/knobs.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { deckOn } from "umtool-report-to-video/deck"; import { validateLook } from "umtool-report-to-video/look"; import { TRANSITION_STYLES, validateTransitionStyle } from "umtool-report-to-video/transition"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -16,6 +18,8 @@ export const dynamic = "force-dynamic"; // // GET ?project=<id> { look, deck, montage, styles, keys, errors, token } // PUT { project, token, patch } { ok, look, token } | 409 stale | 400 { errors } +// PUT { project, token, variants } render.variants, the ladder Make variants encodes +// (null: the default ladder) → { ok, variants, token } const noStore = { "cache-control": "no-store" }; @@ -32,7 +36,10 @@ export async function GET(request: Request) { styles: TRANSITION_STYLES, keys: LOOK_KEYS, // A look somebody hand-edited into a state the build would refuse. - errors: [...validateTransitionStyle(r.manifest), ...validateLook(r.manifest)], + errors: [...validateTransitionStyle(r.manifest), ...validateLook(r.manifest), ...variantsProblems(render.variants)], + // The encode ladder (video knobs): as written, and the default when it is absent. + variants: render.variants ?? null, + variantsDefault: VARIANTS_DEFAULT, token: await manifestToken(r.project.dir), }, { headers: noStore }, @@ -40,6 +47,8 @@ export async function GET(request: Request) { } export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/render"); + if (refused) return refused; let body: Record<string, unknown>; try { body = await request.json(); @@ -48,6 +57,20 @@ export async function PUT(request: Request) { } const r = await resolveReport(String(body.project ?? "")); if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); + if ("variants" in body && !("patch" in body)) { + try { + const { result: res, editNotes } = await withEditNotes(r.project, () => + updateVariants(r.project.dir, (body.variants ?? null) as unknown[] | null, { + token: body.token === undefined || body.token === null ? null : String(body.token), + }), + ); + return Response.json({ ok: true, variants: res.variants, token: res.token, editNotes }, { headers: noStore }); + } catch (e) { + if (e instanceof StaleToken) return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 }); + if (e instanceof RenderRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 }); + } + } try { const { result: res, editNotes } = await withEditNotes(r.project, () => updateRender(r.project.dir, (body.patch ?? null) as Record<string, unknown>, { diff --git a/umtool/app/api/report/still/route.ts b/umtool/app/api/report/still/route.ts @@ -1,6 +1,7 @@ import { deckStill, scheduleForPreview, stillTimeOf } from "@/lib/report/onscreen.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { deckOn, validateChrome } from "umtool-report-to-video/deck"; +import { chromeForRenderer } from "@/lib/report/knobs.mjs"; export const dynamic = "force-dynamic"; @@ -27,7 +28,7 @@ export async function GET(request: Request) { const render = (variantManifest.render ?? {}) as Record<string, unknown>; if (!deckOn(render)) return new Response("the deck is off for this manifest", { status: 409 }); const { chrome, ...rest } = render; - const errors = validateChrome(chrome, rest); + const errors = validateChrome(chromeForRenderer(chrome), rest); if (errors.length) return new Response(`render.chrome: ${errors.join("; ")}`, { status: 400 }); const clip = url.searchParams.get("clip"); diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts @@ -17,6 +17,7 @@ import { import { resolveReport } from "@/lib/report/serve.mjs"; import { deckOn } from "umtool-report-to-video/deck"; import { VERDICTS, resolveFactcheck } from "umtool-report-to-video/factcheck"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -77,6 +78,8 @@ export async function GET(request: Request) { const atOf = (v: unknown) => (v === undefined || v === null || v === "" ? null : Number(v)); export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/timeline"); + if (refused) return refused; let body: Body; try { body = await request.json(); diff --git a/umtool/app/api/report/variants/route.ts b/umtool/app/api/report/variants/route.ts @@ -0,0 +1,46 @@ +import { projectRef } from "@/lib/projects"; +import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; +import { readManifest } from "@/lib/projects/report.mjs"; +import { rangeResponse } from "@/lib/report/serve.mjs"; +import { variantFile, variantsState } from "@/lib/report/variantsView.mjs"; + +export const dynamic = "force-dynamic"; + +// MAKE VARIANTS and SYNC, read back (video knobs, plans/video-knobs-ui.md). +// "Make variants" itself is a job: POST /api/report/deliver +// { action: "variants", take? }. +// +// GET ?project=<id>[&take=<id>] { take, slug, built, ladder, made, stale, sync, takes } +// GET ?project=<id>[&take=<id>]&file=<name> that variant's mp4 (a name from the ladder, never a path) + +const noStore = { "cache-control": "no-store" }; + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers: noStore }); + if (!kindMakesTakes(project.kind)) return Response.json({ error: "variants are a report video's" }, { status: 400, headers: noStore }); + const manifest = await readManifest(project.dir); + if (!manifest) return Response.json({ error: "no manifest" }, { status: 400, headers: noStore }); + const take = url.searchParams.get("take") || null; + const name = url.searchParams.get("file"); + try { + if (name !== null) { + const f = await variantFile(project, manifest, name, take); + if (!f) return new Response("that variant has not been made", { status: 404 }); + return rangeResponse(request, { + abs: f.abs, + size: f.size, + headers: { + "content-type": "video/mp4", + "accept-ranges": "bytes", + "cache-control": "private, no-store", + "content-disposition": `inline; filename="${f.rel}"`, + }, + }); + } + return Response.json(await variantsState(project, manifest, take), { headers: noStore }); + } catch (e) { + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400, headers: noStore }); + } +} diff --git a/umtool/app/api/report/video-assist/route.ts b/umtool/app/api/report/video-assist/route.ts @@ -16,6 +16,7 @@ import { readAssistJob, writeAssistJob, } from "@/lib/report/videoAssist.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -94,6 +95,8 @@ export async function GET(request: Request) { } export async function POST(request: Request) { + const refused = refuseCaller(request, "/api/report/video-assist"); + if (refused) return refused; const url = new URL(request.url); const cancel = url.searchParams.get("cancel"); if (cancel) { diff --git a/umtool/app/api/report/window/route.ts b/umtool/app/api/report/window/route.ts @@ -1,6 +1,7 @@ import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, updateClip } from "@/lib/report/manifest.mjs"; import { resolveClip } from "@/lib/report/serve.mjs"; +import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; @@ -15,6 +16,8 @@ export const dynamic = "force-dynamic"; // writer is usually `resolve-windows --write` or an agent running `umtool`, and // what it wrote is somebody's judgement. export async function PUT(request: Request) { + const refused = refuseCaller(request, "/api/report/window"); + if (refused) return refused; let body: Record<string, unknown>; try { body = await request.json(); diff --git a/umtool/lib/report/caller.ts b/umtool/lib/report/caller.ts @@ -0,0 +1,13 @@ +import { agentToken, routeCaller } from "@/lib/annotations/agentAuth.mjs"; + +// WHO MAY WRITE A MANIFEST (video knobs, plans/video-knobs-ui.md): every +// manifest-write route takes the app's own page (no Authorization header, as +// before) and an agent or the editor carrying `Bearer <umtool's WORKER_TOKEN>` +// -- routeCaller's rule (lib/annotations/agentAuth.mjs). Any other header is a +// 401, so a wrong token is refused rather than read as the page. + +/** null when the caller may write; else the 401 to send. */ +export function refuseCaller(request: Request, what: string): Response | null { + const who = routeCaller(request.headers.get("authorization"), agentToken(), what); + return who.ok ? null : Response.json({ error: who.error }, { status: who.status }); +} diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -35,8 +35,11 @@ import { mergeClips, restoreClip, splitClip, + updateClaimKnobs, updateClip, } from "./manifest.mjs"; +import { CLAIM_KNOB_DEFAULTS, stampingEntryId } from "./knobs.mjs"; +import { resolveFactcheck } from "umtool-report-to-video/factcheck"; import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs"; import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerLabel, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs"; import { readShorts } from "./shorts.mjs"; @@ -120,6 +123,11 @@ export async function clipEditorView(project) { // written, and the edges it gets with the cut's render.room. room: e.room === false ? false : isObj(e.room) ? e.room : null, roomEdges: roomEdgesOf(e, manifest.render), + // The video knobs: the claim as written (its id, verdict and knobs), + // the entry that stamps it (the last carrying its id), and the sound. + claim: isObj(e.claim) && typeof e.claim.id === "string" ? e.claim : null, + stampsOn: isObj(e.claim) && typeof e.claim.id === "string" ? stampingEntryId(manifest, e.claim.id) : null, + audio: isObj(e.audio) ? e.audio : null, }; }); const shorts = await readShorts(project.dir, manifest); @@ -143,9 +151,27 @@ export async function clipEditorView(project) { repropose: { available: reproposeAvailable, why: reproposeAvailable ? null : REPROPOSE_UNAVAILABLE }, shorts: Object.fromEntries(shorts.filter((x) => !x.gone).map((x) => [x.clip, { mtimeMs: x.mtimeMs, size: x.size, stale: x.stale }])), room: roomViewOf(manifest.render), + knobs: knobDefaultsOf(manifest.render), }; } +/** + * What a claim knob is when the claim does not set it (the Count & stamp box's + * placeholders): the cut's stamp seconds, whether the cut draws stamps at all, + * the default count, and each verdict's stamp word (its `stampLabel`, else its + * label). + */ +function knobDefaultsOf(render) { + const fc = resolveFactcheck(render); + const given = isObj(render?.chrome?.factcheck?.verdicts) ? render.chrome.factcheck.verdicts : {}; + const labels = {}; + for (const [v, x] of Object.entries(fc.verdicts)) { + const own = isObj(given[v]) && typeof given[v].stampLabel === "string" && given[v].stampLabel.trim() ? given[v].stampLabel.trim() : null; + labels[v] = own ?? x.label; + } + return { hold: fc.stamp.seconds, stampShown: fc.stamp.show !== false, count: CLAIM_KNOB_DEFAULTS.count, labels }; +} + /** A clip's room edges (room.mjs clipRoom), or null when it has none. */ function roomEdgesOf(entry, render) { const r = clipRoom(entry, render); @@ -271,6 +297,10 @@ const num = (v, what) => { * vertical { clip, crop | null, aspect? } the clip's 9:16 box for its short * room { clip, room: false | {tail?, head?} | null } room at this clip's edges * (null: the cut's render.room again) + * claim { clip, knobs: { at?, hold?, stamp?, count?, label? } } the claim's stamp and + * count (null on a knob: its default again) + * audio { clip, audio: { offset?, gain?, fadeIn?, fadeOut? } | null } the clip's sound + * (null on a key, or the whole: the default) * with `token` (the manifest's, from the view) on every manifest edit. * Returns `{ op, result, carried, view }`. */ @@ -405,8 +435,25 @@ export async function runClipEditorOp(project, body, { now = null } = {}) { structural = false; break; } + case "claim": { + // The video knobs (plans/video-knobs-ui.md): when the stamp lands and the count steps, how long it stays, + // whether it is drawn, how much it counts, what it says. Not structural: no clip moves. + const e = needClip(); + if (!isObj(body.knobs)) throw new OpError("claim needs knobs: { at?, hold?, stamp?, count?, label? }"); + result = await updateClaimKnobs(dir, e.id, body.knobs, { token }); + structural = false; + break; + } + case "audio": { + const e = needClip(); + if (body.audio !== null && !isObj(body.audio)) throw new OpError("audio is { offset?, gain?, fadeIn?, fadeOut? }, or null for none"); + // A "trim" that leaves the cut where it is, as `vertical` is. + result = await updateClip(dir, e.id, { audio: body.audio }, { token, edit: "trim", now }); + structural = false; + break; + } default: - throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical or room"); + throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical, room, claim or audio"); } let carried = null; if (structural) { @@ -423,6 +470,8 @@ function summarise(r) { for (const k of ["id", "second", "absorbed", "at"]) if (r[k] !== undefined) out[k] = r[k]; if (isObj(r.entry) && typeof r.entry.id === "string") out.id ??= r.entry.id; if (isObj(r.speaker)) out.speaker = r.speaker; + if (isObj(r.claim)) out.claim = r.claim; + if (typeof r.stamps === "boolean") out.stamps = r.stamps; if (r.ruling !== undefined) out.ruling = r.ruling; return out; } diff --git a/umtool/lib/report/clipEditor.test.mjs b/umtool/lib/report/clipEditor.test.mjs @@ -341,3 +341,29 @@ test("manifestToken changes with every operation (the page's next write carries await rm(p.dir, { recursive: true, force: true }); } }); + +test("runClipEditorOp: the video knobs -- claim (Count & stamp) and audio; the view carries them and their defaults", async () => { + const p = await project({ withReactions: false }); + try { + const m = JSON.parse(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8")); + m.timeline[3].claim = { id: "k7", verdict: "CONTRADICTED" }; + m.render.chrome = { engine: "hyperframes", layout: "deck", factcheck: { stamp: { seconds: 4 }, verdicts: { CONTRADICTED: { label: "Seizures", stampLabel: "SEIZURE" } } } }; + await writeFile(path.join(p.dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n"); + const v0 = await clipEditorView(p); + assert.deepEqual(v0.knobs, { hold: 4, stampShown: true, count: 1, labels: { ...v0.knobs.labels, CONTRADICTED: "SEIZURE" } }); + assert.equal(v0.knobs.labels.PARTLY, "Partly true"); + const r = await runClipEditorOp(p, { op: "claim", clip: "r003", token: v0.token, knobs: { at: 55.5, count: 2 } }); + assert.deepEqual(r.result.claim, { id: "k7", verdict: "CONTRADICTED", at: 55.5, count: 2 }); + assert.equal(r.result.stamps, true); + const c = r.view.clips.find((x) => x.id === "r003"); + assert.equal(c.stampsOn, "r003"); + assert.equal(c.claim.at, 55.5); + const a = await runClipEditorOp(p, { op: "audio", clip: "r003", token: r.view.token, audio: { offset: 120, gain: -3 } }); + assert.deepEqual(a.view.clips.find((x) => x.id === "r003").audio, { offset: 120, gain: -3 }); + await assert.rejects(runClipEditorOp(p, { op: "claim", clip: "r001", knobs: { count: 2 } }), /carries no claim/); + await assert.rejects(runClipEditorOp(p, { op: "audio", clip: "r003", audio: 5 }), /audio is/); + await assert.rejects(runClipEditorOp(p, { op: "claim", clip: "r003", token: "stale", knobs: { count: 2 } }), StaleToken); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -30,8 +30,19 @@ export type EditorClip = { /** Room at its edges (release 36 lane E): the clip's own `room` as written (false: none), and the edges it gets. */ room?: false | { tail?: boolean; head?: boolean } | null; roomEdges?: { tail: boolean; head: boolean } | null; + /** The video knobs: the claim as written (id, verdict, and its stamp's knobs), the entry that stamps it, the sound. */ + claim?: ClaimKnobs | null; + stampsOn?: string | null; + audio?: ClipAudio | null; }; +/** A claim with its knobs (plans/video-knobs-plan.md): `at` is a source second. */ +export type ClaimKnobs = { id: string; verdict: string; at?: number; hold?: number; stamp?: boolean; count?: number; label?: string }; +/** A clip's sound at the encode: offset in ms (+ = later), gain in dB, fades in s. */ +export type ClipAudio = { offset?: number; gain?: number; fadeIn?: number; fadeOut?: number }; +/** What a claim knob is when absent: the cut's stamp seconds, whether stamps are drawn, the count, each verdict's stamp word. */ +export type KnobDefaults = { hold: number; stampShown: boolean; count: number; labels: Record<string, string> }; + export type Speaker = { index: number; role?: "host" | "subject" | "other"; label?: string; seconds?: number; turns?: number; how?: "auto" | "operator"; sameAs?: number }; export type Proposal = { id: string; start: number; end: number; score?: number; why?: string; moments?: string[]; used?: boolean; clipId?: string | null }; @@ -54,6 +65,8 @@ export type EditorView = { shorts: Record<string, { mtimeMs: number; size: number; stale: boolean }>; /** The cut's render.room and its join's length (release 36 lane E). */ room?: { tail: boolean; head: boolean; minGap: number | null; maxS: number | null; join: number }; + /** The claim knobs' defaults (video knobs). */ + knobs?: KnobDefaults; }; export type Turn = { start: number; end: number; speaker: number }; diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs @@ -584,3 +584,33 @@ export function rebuildReportSteps(project, variants) { timeoutMs: 15 * 60_000, })); } + +/** + * MAKE VARIANTS (video knobs, plans/video-knobs-ui.md): the encode ladder of a + * built cut -- the project's out/ or a take's -- as one step: + * `node report-to-video/variants.mjs <out dir>`, which reads the manifest + * beside the out/ for the slug and `render.variants` and takes the heavy slot + * itself (heavy-gate.mjs), as build-video does. The out dir is computed from + * the project and a take id by the caller, never sent by a client. + * + * E2E_UMTOOL_VARIANTS_SCRIPT (test-only, playwright.config.ts) names a stub + * encoder with the same command line. + * + * @param {{ dir: string }} project + * @param {string} outDir + * @param {Record<string, string | undefined>} [env] + * @returns {import("../trim").Step[]} + */ +export function variantsSteps(project, outDir, env = process.env) { + const bin = env.E2E_UMTOOL_VARIANTS_SCRIPT || script("variants.mjs"); + return [ + { + cwd: PIPELINE_DIR, + env: {}, + label: `make the variants of ${path.relative(project.dir, outDir) || "out"}`, + argv: ["node", bin, outDir], + // A size-capped variant is two passes over the whole cut, per variant. + timeoutMs: 90 * 60_000, + }, + ]; +} diff --git a/umtool/lib/report/knobs.mjs b/umtool/lib/report/knobs.mjs @@ -0,0 +1,381 @@ +// THE VIDEO KNOBS' RULES, writer side (plans/video-knobs-ui.md): every knob a +// person sets in the clip editor, the fact-check editor, the markers editor or +// Deliver -- and an agent sets with `umtool set` / `umtool look` -- is checked +// HERE before manifest.mjs writes it, so the UI, the routes and the CLI refuse +// the same things in the same words. +// +// a claimed entry claim.at / hold / stamp / count / label +// a clip audio: { offset, gain, fadeIn, fadeOut } (clip-audio.mjs validateClipAudio) +// the fact-check render.chrome.factcheck.stamp.scale / motion / opacity, +// verdicts[V].stampLabel +// the deck render.chrome.deck.markers[].align, deck.markerLayout +// the encode ladder render.variants +// +// The renderer (report-to-video, plans/video-knobs-core.md) draws them and +// validates them again with its own functions. Until its validators know a +// knob, the writers hand them the value WITHOUT the knobs (`forRenderer*`), +// having checked the knobs here; once they know it (probed below), the whole +// value goes through both. +// +// PURE: no fs. Plain ESM so `umtool set` runs it under bare node. +import { VERDICT_LABEL_MAX, VERDICTS } from "yt-dlp-transcript-common/lib/report/verdicts.mjs"; +import { normalizeClaim, validateFactcheck } from "umtool-report-to-video/factcheck"; +import { validateChrome } from "umtool-report-to-video/deck"; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); +const num = (v) => typeof v === "number" && Number.isFinite(v); +const numIn = (v, lo, hi) => num(v) && v >= lo && v <= hi; +const q = (v) => JSON.stringify(v); +const round = (n, dp) => Number(Number(n).toFixed(dp)); + +/** Same tolerance the writer uses for a stored 2 dp edge. */ +const EPS = 0.02; + +// --------------------------------------------------------------------------- +// A claim's knobs (per entry). +// --------------------------------------------------------------------------- + +/** The knobs a claim may carry beside its id and verdict, in the editor's order. */ +export const CLAIM_KNOBS = Object.freeze(["at", "hold", "stamp", "count", "label"]); + +export const CLAIM_KNOB_LIMITS = Object.freeze({ + hold: Object.freeze([0.5, 10]), + count: Object.freeze([1, 99]), + label: 20, +}); + +/** The defaults a claim with no knob gets (hold's is the cut's `factcheck.stamp.seconds`). */ +export const CLAIM_KNOB_DEFAULTS = Object.freeze({ stamp: true, count: 1 }); + +/** + * One knob's value, checked and normalised. `null` (or "") = clear the knob. + * Throws a sentence naming `claim.<key>`. + * + * @param {string} key + * @param {unknown} v + * @returns {unknown} + */ +export function claimKnobValue(key, v) { + if (v === null || v === undefined || v === "") return null; + switch (key) { + case "at": { + const x = typeof v === "string" ? Number(v) : v; + if (!num(x) || x < 0) throw new Error(`claim.at must be a source second ≥ 0 (got ${q(v)})`); + return round(x, 2); + } + case "hold": { + const x = typeof v === "string" ? Number(v) : v; + const [lo, hi] = CLAIM_KNOB_LIMITS.hold; + if (!numIn(x, lo, hi)) throw new Error(`claim.hold must be seconds from ${lo} to ${hi} (got ${q(v)})`); + return round(x, 2); + } + case "stamp": { + const x = v === "true" ? true : v === "false" ? false : v; + if (typeof x !== "boolean") throw new Error(`claim.stamp must be true or false (got ${q(v)})`); + return x; + } + case "count": { + const x = typeof v === "string" ? Number(v) : v; + const [lo, hi] = CLAIM_KNOB_LIMITS.count; + if (!(Number.isInteger(x) && x >= lo && x <= hi)) throw new Error(`claim.count must be a whole number from ${lo} to ${hi} (got ${q(v)})`); + return x; + } + case "label": { + if (typeof v !== "string") throw new Error(`claim.label must be a text (got ${q(v)})`); + const s = v.trim(); + if (!s) return null; + if ([...s].length > CLAIM_KNOB_LIMITS.label) throw new Error(`claim.label is ${[...s].length} characters (at most ${CLAIM_KNOB_LIMITS.label})`); + return s; + } + default: + throw new Error(`claim.${key} is not a claim knob (${CLAIM_KNOBS.join(", ")})`); + } +} + +/** + * A patch of claim knobs: `{ at?, hold?, stamp?, count?, label? }`, each a + * value or null (clear). A knob set to its default is CLEARED -- `stamp: true` + * and `count: 1` are what an absent key already says. + * + * @param {unknown} patch + * @returns {Record<string, unknown>} key -> value, or null to remove + */ +export function normalizeClaimKnobPatch(patch) { + if (!isObj(patch)) throw new Error("the claim knobs are an object of at, hold, stamp, count, label"); + const keys = Object.keys(patch); + if (!keys.length) throw new Error("nothing to change"); + /** @type {Record<string, unknown>} */ + const out = {}; + for (const k of keys) { + if (!CLAIM_KNOBS.includes(k)) throw new Error(`claim.${k} is not a claim knob (${CLAIM_KNOBS.join(", ")})`); + const v = claimKnobValue(k, /** @type {Record<string, unknown>} */ (patch)[k]); + out[k] = v !== null && k in CLAIM_KNOB_DEFAULTS && v === CLAIM_KNOB_DEFAULTS[/** @type {"stamp"|"count"} */ (k)] ? null : v; + } + return out; +} + +/** The knobs of a claim as written (absent keys left out). */ +export function claimKnobsOf(claim) { + /** @type {Record<string, unknown>} */ + const out = {}; + if (!isObj(claim)) return out; + for (const k of CLAIM_KNOBS) if (claim[k] !== undefined) out[k] = claim[k]; + return out; +} + +/** A claim without its knobs: `{ id, verdict }` (anything else it carries is kept). */ +export function claimWithoutKnobs(claim) { + if (!isObj(claim)) return claim; + const out = { ...claim }; + for (const k of CLAIM_KNOBS) delete out[k]; + return out; +} + +/** + * The entry that STAMPS a claim: the last in the timeline carrying its id + * (per variant: an entry with `variant` set counts only in that cut, one with + * none in every cut). Its knobs are the ones the build reads. + * + * @param {{ timeline?: unknown[] }} manifest + * @param {string} claimId + * @param {string | null} [variant] null: the last in the whole timeline + */ +export function stampingEntryId(manifest, claimId, variant = null) { + let last = null; + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + if (!isObj(e) || !isObj(e.claim) || e.claim.id !== claimId) continue; + if (variant && e.variant && e.variant !== variant) continue; + last = e.id; + } + return last; +} + +/** + * Every problem with the claim knobs in a timeline, as sentences: each knob's + * value, and `at` inside its entry's window (`start`–`end`, the source clock). + * + * @param {{ timeline?: unknown[] }} manifest + * @returns {string[]} + */ +export function claimKnobProblems(manifest) { + const errors = []; + (Array.isArray(manifest?.timeline) ? manifest.timeline : []).forEach((e, i) => { + if (!isObj(e) || !isObj(e.claim)) return; + const where = `timeline[${i}] (${e.id ?? "?"})`; + for (const k of CLAIM_KNOBS) { + if (e.claim[k] === undefined) continue; + try { + if (claimKnobValue(k, e.claim[k]) === null) errors.push(`${where}.claim.${k} is empty: remove the key`); + } catch (err) { + errors.push(`${where}.${err instanceof Error ? err.message : String(err)}`); + } + } + if (num(e.claim.at) && num(e.start) && num(e.end) && (e.claim.at < e.start - EPS || e.claim.at > e.end + EPS)) { + errors.push(`${where}.claim.at ${e.claim.at} must lie inside the clip's window ${e.start}–${e.end}`); + } + }); + return errors; +} + +// --------------------------------------------------------------------------- +// The fact-check's stamp knobs (render.chrome.factcheck). +// --------------------------------------------------------------------------- + +export const STAMP_MOTIONS = Object.freeze(["slam", "pop", "fade", "none"]); +export const STAMP_KNOB_LIMITS = Object.freeze({ scale: Object.freeze([0.5, 2]), opacity: Object.freeze([0.3, 1]) }); +export const STAMP_KNOB_DEFAULTS = Object.freeze({ scale: 1, motion: "slam", opacity: 1 }); +/** The stamp knobs `render.chrome.factcheck.stamp` gains. */ +export const STAMP_KNOBS = Object.freeze(["scale", "motion", "opacity"]); + +/** + * The fact-check knobs' problems: stamp scale / motion / opacity and each + * verdict's `stampLabel`. Everything else in the block is the renderer's + * validateFactcheck's. + * + * @param {unknown} f render.chrome.factcheck + * @returns {string[]} + */ +export function factcheckKnobProblems(f, where = "render.chrome.factcheck") { + if (!isObj(f)) return []; + const errors = []; + if (isObj(f.stamp)) { + const s = f.stamp; + const [slo, shi] = STAMP_KNOB_LIMITS.scale; + if (s.scale !== undefined && !numIn(s.scale, slo, shi)) errors.push(`${where}.stamp.scale must be from ${slo} to ${shi}`); + if (s.motion !== undefined && !STAMP_MOTIONS.includes(s.motion)) errors.push(`${where}.stamp.motion must be ${STAMP_MOTIONS.map((m) => `"${m}"`).join(", ")}`); + const [olo, ohi] = STAMP_KNOB_LIMITS.opacity; + if (s.opacity !== undefined && !numIn(s.opacity, olo, ohi)) errors.push(`${where}.stamp.opacity must be from ${olo} to ${ohi}`); + } + if (isObj(f.verdicts)) { + for (const [k, v] of Object.entries(f.verdicts)) { + if (!isObj(v) || v.stampLabel === undefined) continue; + const w = `${where}.verdicts.${k}.stampLabel`; + if (typeof v.stampLabel !== "string" || !v.stampLabel.trim()) errors.push(`${w} must be a text (remove the key for the verdict's label)`); + else if ([...v.stampLabel.trim()].length > VERDICT_LABEL_MAX) errors.push(`${w} is ${[...v.stampLabel.trim()].length} characters (at most ${VERDICT_LABEL_MAX})`); + } + } + return errors; +} + +/** The fact-check block without the knobs (the renderer's validator before it knows them). */ +function factcheckWithoutKnobs(f) { + if (!isObj(f)) return f; + const out = { ...f }; + if (isObj(f.stamp)) { + const s = { ...f.stamp }; + for (const k of STAMP_KNOBS) delete s[k]; + out.stamp = s; + } + if (isObj(f.verdicts)) { + out.verdicts = Object.fromEntries( + Object.entries(f.verdicts).map(([k, v]) => { + if (!isObj(v)) return [k, v]; + const { stampLabel: _s, ...rest } = v; + return [k, rest]; + }), + ); + } + return out; +} + +// --------------------------------------------------------------------------- +// The deck's markers (render.chrome.deck.markers, deck.markerLayout). +// --------------------------------------------------------------------------- + +export const MARKER_ALIGNS = Object.freeze(["auto", "left", "right", "center"]); +export const MARKER_LAYOUTS = Object.freeze(["stagger", "truncate"]); + +/** The marker knobs' problems: each marker's `align`, and the deck's `markerLayout`. */ +export function markerKnobProblems(deck, where = "render.chrome.deck") { + if (!isObj(deck)) return []; + const errors = []; + if (Array.isArray(deck.markers)) { + deck.markers.forEach((m, i) => { + if (isObj(m) && m.align !== undefined && !MARKER_ALIGNS.includes(m.align)) { + errors.push(`${where}.markers[${i}].align must be ${MARKER_ALIGNS.map((a) => `"${a}"`).join(", ")}`); + } + }); + } + if (deck.markerLayout !== undefined && !MARKER_LAYOUTS.includes(deck.markerLayout)) { + errors.push(`${where}.markerLayout must be ${MARKER_LAYOUTS.map((a) => `"${a}"`).join(" or ")}`); + } + return errors; +} + +function deckWithoutKnobs(deck) { + if (!isObj(deck)) return deck; + const { markerLayout: _l, ...out } = deck; + if (Array.isArray(deck.markers)) { + out.markers = deck.markers.map((m) => { + if (!isObj(m)) return m; + const { align: _a, ...rest } = m; + return rest; + }); + } + return out; +} + +/** Every knob problem in a `render.chrome` block (fact-check and markers). */ +export function chromeKnobProblems(chrome) { + if (!isObj(chrome)) return []; + return [...factcheckKnobProblems(chrome.factcheck), ...markerKnobProblems(chrome.deck)]; +} + +// --------------------------------------------------------------------------- +// The encode ladder (render.variants). +// --------------------------------------------------------------------------- + +/** The ladder "Make variants" encodes when the manifest names none. */ +export const VARIANTS_DEFAULT = Object.freeze([ + Object.freeze({ name: "master" }), + Object.freeze({ name: "1080p", height: 1080, crf: 22 }), + Object.freeze({ name: "720p", height: 720, crf: 23 }), + Object.freeze({ name: "fit24", maxMiB: 24 }), +]); +export const VARIANT_NAME_RE = /^[a-z0-9][a-z0-9-]{0,23}$/; +export const VARIANTS_MAX = 8; +export const VARIANT_LIMITS = Object.freeze({ height: Object.freeze([240, 2160]), crf: Object.freeze([0, 51]), maxMiB: Object.freeze([1, 4096]) }); + +/** The ladder a cut encodes: its own, else the default. */ +export const variantsOf = (render) => (Array.isArray(render?.variants) ? render.variants : VARIANTS_DEFAULT); + +/** + * `render.variants`: a list of `{ name, height?, crf?, maxMiB? }`. `master` + * is the build's own file and takes no setting; a `maxMiB` variant picks its + * own height, so it names no height or crf. + * + * @returns {string[]} + */ +export function variantsProblems(v, where = "render.variants") { + if (v === undefined || v === null) return []; + if (!Array.isArray(v)) return [`${where} must be a list of { name, height?, crf?, maxMiB? }`]; + const errors = []; + if (!v.length) errors.push(`${where} is empty: remove it for the default ladder`); + if (v.length > VARIANTS_MAX) errors.push(`${where} has ${v.length} variants (at most ${VARIANTS_MAX})`); + const seen = new Set(); + v.forEach((x, i) => { + const w = `${where}[${i}]`; + if (!isObj(x)) { + errors.push(`${w} must be { name, height?, crf?, maxMiB? }`); + return; + } + for (const k of Object.keys(x)) if (!["name", "height", "crf", "maxMiB"].includes(k)) errors.push(`${w}.${k} is not a variant setting (name, height, crf, maxMiB)`); + if (typeof x.name !== "string" || !VARIANT_NAME_RE.test(x.name)) errors.push(`${w}.name must be lower-case letters, digits and dashes (at most 24)`); + else if (seen.has(x.name)) errors.push(`${w}.name ${x.name} is used twice`); + else seen.add(x.name); + const [hlo, hhi] = VARIANT_LIMITS.height; + if (x.height !== undefined && !(Number.isInteger(x.height) && x.height >= hlo && x.height <= hhi && x.height % 2 === 0)) { + errors.push(`${w}.height must be an even whole number of pixels from ${hlo} to ${hhi}`); + } + const [clo, chi] = VARIANT_LIMITS.crf; + if (x.crf !== undefined && !(Number.isInteger(x.crf) && x.crf >= clo && x.crf <= chi)) errors.push(`${w}.crf must be a whole number from ${clo} to ${chi}`); + const [mlo, mhi] = VARIANT_LIMITS.maxMiB; + if (x.maxMiB !== undefined && !numIn(x.maxMiB, mlo, mhi)) errors.push(`${w}.maxMiB must be from ${mlo} to ${mhi}`); + if (x.name === "master" && (x.height !== undefined || x.crf !== undefined || x.maxMiB !== undefined)) errors.push(`${w}: master is the build's own file and takes no setting`); + if (x.maxMiB !== undefined && (x.height !== undefined || x.crf !== undefined)) errors.push(`${w}: a maxMiB variant picks its own height and quality (no height or crf with it)`); + if (x.name !== "master" && x.height === undefined && x.maxMiB === undefined) errors.push(`${w} needs a height or a maxMiB`); + }); + return errors; +} + +// --------------------------------------------------------------------------- +// Until the renderer's validators know the knobs. +// +// Probed once: a renderer whose normalizeClaim / validateFactcheck / +// validateChrome refuses a knob is handed the value without it (the knob was +// checked above); one that accepts it is handed the whole value. +// --------------------------------------------------------------------------- + +const probe = (fn) => { + try { + return fn(); + } catch { + return false; + } +}; +const RENDERER_KNOWS = { + claim: probe(() => !!normalizeClaim({ id: "k", verdict: VERDICTS[0], count: 2, at: 1, hold: 2, stamp: false, label: "X" })), + factcheck: probe(() => validateFactcheck({ stamp: { scale: 1, motion: "pop", opacity: 1 }, verdicts: { [VERDICTS[0]]: { stampLabel: "X" } } }).length === 0), + markers: probe(() => !validateChrome({ engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "a", label: "b", align: "left" }], markerLayout: "stagger" } }, {}).some((e) => /align|markerLayout/.test(e))), +}; + +/** Does the renderer's validator know this group of knobs? */ +export const rendererKnows = (group) => RENDERER_KNOWS[group] === true; + +/** A manifest as the renderer's claim validator can read it. */ +export function claimsForRenderer(manifest) { + if (rendererKnows("claim") || !Array.isArray(manifest?.timeline)) return manifest; + return { ...manifest, timeline: manifest.timeline.map((e) => (isObj(e) && isObj(e.claim) ? { ...e, claim: claimWithoutKnobs(e.claim) } : e)) }; +} + +/** A `render.chrome` block as the renderer's validateChrome can read it. */ +export function chromeForRenderer(chrome) { + if (!isObj(chrome)) return chrome; + let out = chrome; + if (!rendererKnows("factcheck") && isObj(chrome.factcheck)) out = { ...out, factcheck: factcheckWithoutKnobs(chrome.factcheck) }; + if (!rendererKnows("markers") && isObj(chrome.deck)) out = { ...out, deck: deckWithoutKnobs(chrome.deck) }; + return out; +} + +/** A fact-check block as the renderer's validateFactcheck can read it. */ +export const factcheckForRenderer = (f) => (rendererKnows("factcheck") ? f : factcheckWithoutKnobs(f)); diff --git a/umtool/lib/report/knobs.test.mjs b/umtool/lib/report/knobs.test.mjs @@ -0,0 +1,213 @@ +// The video knobs' writers (plans/video-knobs-ui.md): a claim's stamp and +// count, a clip's sound, the fact-check's stamp, the deck's markers, the +// encode ladder -- each token-guarded, each refusal leaving the file as it was, +// and the variants/sync read-back. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +// The read-back resolves files inside the reports root: this suite's own. +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-knobs-")); +process.env.REPORTS_DIR = ROOT; + +const { + MANIFEST_NAME, + StaleToken, + StructureRefused, + manifestToken, + moveEntry, + updateClaimKnobs, + updateClip, + updateDeckMarkers, + updateFactcheck, + updateOnscreen, + updateVariants, +} = await import("./manifest.mjs"); +const knobs = await import("./knobs.mjs"); +const { variantsState, variantFile } = await import("./variantsView.mjs"); + +const base = () => ({ + slug: "t", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, transition: 0.5, chrome: { engine: "hyperframes", layout: "deck" } }, + timeline: [ + { type: "clip", id: "c01", video: "v1", start: 10, end: 20, claim: { id: "k1", verdict: "CONTRADICTED" } }, + { type: "clip", id: "c02", video: "v2", start: 30, end: 41, claim: { id: "k1", verdict: "CONTRADICTED" } }, + { type: "clip", id: "c03", video: "v3", start: 50, end: 55 }, + ], +}); + +let n = 0; +async function project(manifest = base()) { + const dir = path.join(ROOT, `p${(n += 1)}`); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n"); + return dir; +} +const readRaw = (dir) => readFile(path.join(dir, MANIFEST_NAME), "utf8"); +const read = async (dir) => JSON.parse(await readRaw(dir)); +const clip = (m, id) => m.timeline.find((e) => e.id === id); + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("updateClaimKnobs: sets each knob, says which entry stamps, clears with null and with the default", async () => { + const dir = await project(); + const r = await updateClaimKnobs(dir, "c02", { at: 35.123, hold: 4, stamp: false, count: 2, label: " 2 SEIZURES " }, { token: await manifestToken(dir) }); + assert.equal(r.stamps, true); + assert.equal(r.stampsOn, "c02"); + assert.deepEqual(clip(await read(dir), "c02").claim, { id: "k1", verdict: "CONTRADICTED", at: 35.12, hold: 4, stamp: false, count: 2, label: "2 SEIZURES" }); + const r2 = await updateClaimKnobs(dir, "c02", { at: null, stamp: true, count: 1, label: "" }); + assert.deepEqual(r2.claim, { id: "k1", verdict: "CONTRADICTED", hold: 4 }); + // c01 carries the claim but does not stamp it: its knobs are inert, and the answer says so. + const r3 = await updateClaimKnobs(dir, "c01", { count: 3 }); + assert.equal(r3.stamps, false); + assert.equal(r3.stampsOn, "c02"); +}); + +test("updateClaimKnobs: refuses a bad value, an at outside the window, an entry with no claim, a stale token", async () => { + const dir = await project(); + const before = await readRaw(dir); + await assert.rejects(updateClaimKnobs(dir, "c02", { at: 50 }), /claim\.at 50 must lie inside the clip's window 30–41/); + await assert.rejects(updateClaimKnobs(dir, "c02", { hold: 0.2 }), /claim\.hold must be seconds from 0\.5 to 10/); + await assert.rejects(updateClaimKnobs(dir, "c02", { count: 1.5 }), /whole number from 1 to 99/); + await assert.rejects(updateClaimKnobs(dir, "c02", { label: "x".repeat(21) }), /at most 20/); + await assert.rejects(updateClaimKnobs(dir, "c02", { colour: 1 }), /not a claim knob/); + await assert.rejects(updateClaimKnobs(dir, "c03", { count: 2 }), /carries no claim/); + await assert.rejects(updateClaimKnobs(dir, "nope", { count: 2 }), /no timeline entry/); + await assert.rejects(updateClaimKnobs(dir, "c02", { count: 2 }, { token: "1" }), StaleToken); + assert.equal(await readRaw(dir), before); +}); + +test("updateClaimKnobs: a variant's twin gets the same knobs", async () => { + const m = base(); + m.timeline.push({ type: "clip", id: "c02", variant: "full", video: "v2", start: 30, end: 41, claim: { id: "k1", verdict: "CONTRADICTED" } }); + const dir = await project(m); + await updateClaimKnobs(dir, "c02", { count: 2 }); + assert.deepEqual((await read(dir)).timeline.filter((e) => e.id === "c02").map((e) => e.claim.count), [2, 2]); +}); + +test("updateOnscreen: a row naming only id and verdict keeps the knobs; a new claim id drops them; a row with knobs replaces them", async () => { + const dir = await project(); + await updateClaimKnobs(dir, "c02", { count: 2, at: 33 }); + await updateOnscreen(dir, { c02: { title: "T", claim: { id: "k1", verdict: "CONTRADICTED" } } }); + assert.deepEqual(clip(await read(dir), "c02").claim, { id: "k1", verdict: "CONTRADICTED", count: 2, at: 33 }); + await updateOnscreen(dir, { c02: { title: "T", claim: { id: "k1", verdict: "CONTRADICTED", hold: 2 } } }); + assert.deepEqual(clip(await read(dir), "c02").claim, { id: "k1", verdict: "CONTRADICTED", hold: 2 }); + await updateOnscreen(dir, { c01: { claim: { id: "k9", verdict: "CONTRADICTED" } }, c02: { title: "T", claim: { id: "k9", verdict: "CONTRADICTED" } } }); + assert.deepEqual(clip(await read(dir), "c02").claim, { id: "k9", verdict: "CONTRADICTED" }); + await assert.rejects(updateOnscreen(dir, { c02: { claim: { id: "k9", verdict: "CONTRADICTED", count: 0 } } }), /claim\.count/); +}); + +test("updateClip audio: merged per key, rounded, a 0 or null removes a key, null removes all; out of range is refused", async () => { + const dir = await project(); + await updateClip(dir, "c03", { audio: { offset: -68.4, gain: 1.26 } }); + assert.deepEqual(clip(await read(dir), "c03").audio, { offset: -68, gain: 1.3 }); + await updateClip(dir, "c03", { audio: { fadeIn: 0.333, gain: null } }); + assert.deepEqual(clip(await read(dir), "c03").audio, { offset: -68, fadeIn: 0.33 }); + await updateClip(dir, "c03", { audio: { offset: 0, fadeIn: 0 } }); + assert.equal("audio" in clip(await read(dir), "c03"), false); + await updateClip(dir, "c03", { audio: { offset: 40 } }); + await updateClip(dir, "c03", { audio: null }); + assert.equal("audio" in clip(await read(dir), "c03"), false); + const before = await readRaw(dir); + await assert.rejects(updateClip(dir, "c03", { audio: { offset: 2500 } }), /offset must be a number from -2000 to 2000/); + await assert.rejects(updateClip(dir, "c03", { audio: { pan: 1 } }), /not an audio setting/); + await assert.rejects(updateClip(dir, "c03", { audio: 3 }), /audio must be/); + assert.equal(await readRaw(dir), before); +}); + +test("updateClip: a window that leaves claim.at outside is refused", async () => { + const dir = await project(); + await updateClaimKnobs(dir, "c02", { at: 31 }); + await assert.rejects(updateClip(dir, "c02", { start: 32 }), /claim\.at 31\) must lie inside the window 32–41/); + await updateClip(dir, "c02", { start: 30.5 }); +}); + +test("updateFactcheck: stamp scale, motion, opacity and a verdict's stampLabel; refused out of range", async () => { + const dir = await project(); + const r = await updateFactcheck(dir, { stamp: { scale: 1.4, motion: "pop", opacity: 0.8 }, verdicts: { CONTRADICTED: { label: "Seizures", stampLabel: "SEIZURE" } } }, { token: await manifestToken(dir) }); + assert.deepEqual(r.factcheck.stamp, { scale: 1.4, motion: "pop", opacity: 0.8 }); + assert.equal((await read(dir)).render.chrome.factcheck.verdicts.CONTRADICTED.stampLabel, "SEIZURE"); + const before = await readRaw(dir); + await assert.rejects(updateFactcheck(dir, { stamp: { motion: "spin" } }), (e) => e instanceof StructureRefused && /stamp\.motion/.test(e.message)); + await assert.rejects(updateFactcheck(dir, { stamp: { scale: 3 } }), /stamp\.scale must be from 0\.5 to 2/); + await assert.rejects(updateFactcheck(dir, { stamp: { opacity: 0.1 } }), /stamp\.opacity must be from 0\.3 to 1/); + await assert.rejects(updateFactcheck(dir, { verdicts: { CONTRADICTED: { stampLabel: "x".repeat(30) } } }), /stampLabel is 30 characters/); + assert.equal(await readRaw(dir), before); +}); + +test("updateDeckMarkers: sets the list (align auto dropped) and the layout, leaves the rest of the deck, refuses bad ones", async () => { + const m = base(); + m.render.chrome.deck = { height: 300 }; + const dir = await project(m); + const r = await updateDeckMarkers(dir, { markers: [{ after: "c01", label: " Arrival ", color: "", align: "auto" }, { after: "c02", label: "Rescue", color: "accent", align: "right" }], markerLayout: "truncate" }, { token: await manifestToken(dir) }); + assert.deepEqual(r.markers, [{ after: "c01", label: "Arrival" }, { after: "c02", label: "Rescue", color: "accent", align: "right" }]); + const deck = (await read(dir)).render.chrome.deck; + assert.equal(deck.height, 300); + assert.equal(deck.markerLayout, "truncate"); + const before = await readRaw(dir); + await assert.rejects(updateDeckMarkers(dir, { markers: [{ after: "c01", label: "x", align: "middle" }] }), /align must be/); + await assert.rejects(updateDeckMarkers(dir, { markerLayout: "wrap" }), /markerLayout must be/); + await assert.rejects(updateDeckMarkers(dir, { markers: [{ after: "zz", label: "x" }] }), /zz/); + await assert.rejects(updateDeckMarkers(dir, { markers: [{ after: "c01", label: "x".repeat(25) }] }), /at most 24/); + await assert.rejects(updateDeckMarkers(dir, { markers: Array.from({ length: 13 }, () => ({ after: "c01", label: "x" })) }), /at most 12/); + assert.equal(await readRaw(dir), before); + await updateDeckMarkers(dir, { markers: [], markerLayout: null }); + const after = (await read(dir)).render.chrome.deck; + assert.equal("markers" in after, false); + assert.equal("markerLayout" in after, false); +}); + +test("a structural edit works on a manifest carrying knobs", async () => { + const m = base(); + m.render.chrome.deck = { markers: [{ after: "c01", label: "A", align: "left" }], markerLayout: "stagger" }; + m.timeline[1].claim = { id: "k1", verdict: "CONTRADICTED", count: 2, at: 33 }; + const dir = await project(m); + await moveEntry(dir, "c03", 0, { token: await manifestToken(dir) }); + assert.deepEqual((await read(dir)).timeline.map((e) => e.id), ["c03", "c01", "c02"]); +}); + +test("updateVariants: sets the ladder, null restores the default, a bad ladder is refused", async () => { + const dir = await project(); + await updateVariants(dir, [{ name: "master" }, { name: "4k", height: 2160, crf: 18 }, { name: "fit8", maxMiB: 8 }]); + assert.equal((await read(dir)).render.variants.length, 3); + await assert.rejects(updateVariants(dir, [{ name: "x", maxMiB: 8, height: 720 }]), /picks its own height/); + await assert.rejects(updateVariants(dir, [{ name: "a", height: 720 }, { name: "a", height: 480 }]), /used twice/); + await assert.rejects(updateVariants(dir, [{ name: "A b" }]), /name must be/); + await assert.rejects(updateVariants(dir, [{ name: "master", crf: 20 }]), /master/); + await assert.rejects(updateVariants(dir, [{ name: "x" }]), /needs a height or a maxMiB/); + await updateVariants(dir, null); + assert.equal("variants" in (await read(dir)).render, false); +}); + +test("knobs: normalizeClaimKnobPatch and the problems lists", () => { + assert.deepEqual(knobs.normalizeClaimKnobPatch({ at: "12.345", stamp: "false", count: "2" }), { at: 12.35, stamp: false, count: 2 }); + assert.deepEqual(knobs.normalizeClaimKnobPatch({ stamp: true, count: 1 }), { stamp: null, count: null }); + assert.throws(() => knobs.normalizeClaimKnobPatch({}), /nothing to change/); + assert.deepEqual(knobs.claimKnobProblems({ timeline: [{ id: "a", start: 1, end: 2, claim: { id: "k", verdict: "PARTLY", at: 5 } }] }), ["timeline[0] (a).claim.at 5 must lie inside the clip's window 1–2"]); + assert.deepEqual(knobs.variantsProblems(knobs.VARIANTS_DEFAULT), []); + assert.equal(knobs.stampingEntryId({ timeline: [{ id: "a", claim: { id: "k" } }, { id: "b", claim: { id: "k" } }, { id: "c", variant: "full", claim: { id: "k" } }] }, "k", "sourced"), "b"); +}); + +test("variantsState: the build, the variants made, the sync report with the lags past a frame flagged", async () => { + const dir = await project(); + const out = path.join(dir, "out"); + await mkdir(path.join(out, "sourced"), { recursive: true }); + await writeFile(path.join(out, "t.mp4"), "x".repeat(100)); + await writeFile(path.join(out, "t.720p.mp4"), "x".repeat(40)); + await writeFile(path.join(out, "variants.json"), JSON.stringify({ at: new Date(Date.now() + 5000).toISOString(), source: "t.mp4", items: [{ name: "720p", path: "t.720p.mp4", width: 1280, height: 720, bytes: 40, kbps: 900 }, { name: "../evil", path: "x" }] })); + await writeFile(path.join(out, "sourced", "sync.json"), JSON.stringify({ fps: 30, items: [{ id: "c01", start: 0, lagMs: 0, peak: 0.9 }, { id: "c02", start: 9.5, lagMs: -469, peak: 0.8 }] })); + const s = await variantsState({ id: "p", dir }, await read(dir)); + assert.equal(s.built.size, 100); + assert.equal(s.ladderIsDefault, true); + assert.deepEqual(s.made.items.map((i) => [i.name, i.exists, i.bytes]), [["720p", true, 40]]); + assert.equal(s.stale, false); + assert.deepEqual(s.sync.items.map((i) => [i.id, i.flagged, i.clip]), [["c01", false, true], ["c02", true, true]]); + assert.equal((await variantFile({ dir }, { slug: "t" }, "720p"))?.size, 40); + assert.equal(await variantFile({ dir }, { slug: "t" }, "../t"), null); + await assert.rejects(variantsState({ id: "p", dir }, await read(dir), "../x"), /not a take id/); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -38,6 +38,21 @@ import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/ import { validateRoom } from "umtool-report-to-video/room"; import { applySectionEnter } from "./sections.mjs"; import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck"; +import { validateClipAudio } from "umtool-report-to-video/clip-audio"; +import { + CLAIM_KNOBS, + chromeForRenderer, + chromeKnobProblems, + claimKnobProblems, + claimKnobsOf, + claimKnobValue, + claimsForRenderer, + factcheckKnobProblems, + markerKnobProblems, + normalizeClaimKnobPatch, + stampingEntryId, + variantsProblems, +} from "./knobs.mjs"; import { validateNarration } from "umtool-report-to-video/narration"; import { parseMuteFrom } from "./playback.mjs"; import { DELIVERABLES_MODES } from "./storage.mjs"; @@ -339,6 +354,49 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri } } + // ---- a claim's `at` stays inside the window (video knobs) --------------- + // + // The source second its stamp lands, on the entry's clock: a window save + // that leaves it outside is refused, as the mute mark's is, rather than + // keeping a mark that no longer says anything about the clip. + if ((patch.start !== undefined || patch.end !== undefined) && isObj(entry.claim) && typeof entry.claim.at === "number") { + if (entry.claim.at < entry.start - WIN_EPS || entry.claim.at > entry.end + WIN_EPS) { + throw new Error( + `the stamp's second (claim.at ${entry.claim.at}) must lie inside the window ` + + `${entry.start}–${entry.end} — widen the window, or clear claim.at`, + ); + } + } + + // ---- the clip's sound (video knobs) ------------------------------------- + // + // `audio: { offset, gain, fadeIn, fadeOut }` -- applied at the segment + // encode (report-to-video clip-audio.mjs, whose validateClipAudio is the + // check). Each key is merged into what the clip has; a key set to null + // removes it, and `audio: null` (or "") removes them all. A key at 0 is + // removed (0 is what absent says), and nothing left removes `audio`: + // absent is the build as it always was. + if (patch.audio !== undefined) { + const v = patch.audio; + if (v === null || v === "") delete entry.audio; + else { + if (!isObj(v)) throw new Error("audio must be { offset?, gain?, fadeIn?, fadeOut? }, or null to clear it"); + const next = { ...(isObj(entry.audio) ? entry.audio : {}) }; + for (const [k, x] of Object.entries(v)) { + if (x === null || x === "") delete next[k]; + else next[k] = typeof x === "string" ? Number(x) : x; + } + const errors = validateClipAudio(next); + if (errors.length) throw new Error(errors.join("; ")); + if (typeof next.offset === "number") next.offset = Math.round(next.offset); + if (typeof next.gain === "number") next.gain = Number(next.gain.toFixed(1)); + for (const k of ["fadeIn", "fadeOut"]) if (typeof next[k] === "number") next[k] = round2(next[k]); + for (const k of Object.keys(next)) if (next[k] === 0) delete next[k]; + if (Object.keys(next).length) entry.audio = next; + else delete entry.audio; + } + } + // ---- the walk's verdict ------------------------------------------------- // // Whether somebody has LOOKED at this clip and said the description is what @@ -776,6 +834,22 @@ export function splitOnscreenRow(row) { return { onscreen: normalizeOnscreen(row) }; } const { claim, ...text } = /** @type {Record<string, unknown>} */ (row); + // A claim's knobs (at, hold, stamp, count, label) may ride on the row: each + // checked here (knobs.mjs), the id and verdict by the renderer's normalizeClaim. + // Such a row REPLACES the entry's knobs; a row without them keeps them. + if (isObj(claim) && CLAIM_KNOBS.some((k) => k in claim)) { + const base = { ...claim }; + /** @type {Record<string, unknown>} */ + const knobs = {}; + for (const k of CLAIM_KNOBS) { + if (!(k in base)) continue; + const v = claimKnobValue(k, base[k]); + delete base[k]; + if (v !== null && !(k === "stamp" && v === true) && !(k === "count" && v === 1)) knobs[k] = v; + } + const c = normalizeClaim(base); + return { onscreen: normalizeOnscreen(text), claim: c ? { ...c, ...knobs } : c, knobs: true }; + } return { onscreen: normalizeOnscreen(text), claim: normalizeClaim(claim) }; } @@ -814,11 +888,14 @@ export async function updateOnscreen(dir, onscreen, { token = null } = {}) { const next = {}; /** @type {Record<string, { id: string, verdict: string } | null>} */ const claims = {}; + /** The rows whose claim names its knobs: those REPLACE the entry's; any other keeps them. */ + const withKnobs = new Set(); for (const id of ids) { try { const row = splitOnscreenRow(onscreen[id]); next[id] = row.onscreen; if (row.claim !== undefined) claims[id] = row.claim; + if (row.knobs) withKnobs.add(id); } catch (e) { throw new Error(`${id}: ${e instanceof Error ? e.message : String(e)}`); } @@ -840,13 +917,19 @@ export async function updateOnscreen(dir, onscreen, { token = null } = {}) { for (const e of manifest.timeline) { if (e.id in next) setOnscreen(e, next[e.id]); if (e.id in claims) { - if (claims[e.id]) e.claim = claims[e.id]; + const c = claims[e.id]; + // A row that does not name the knobs keeps the entry's while the claim + // stays the same claim: the On-screen table edits the id and verdict, + // the clip editor the knobs, and neither may drop the other's work. + const keep = c && !withKnobs.has(e.id) && isObj(e.claim) && e.claim.id === c.id ? claimKnobsOf(e.claim) : {}; + if (c) e.claim = { ...c, ...keep }; else delete e.claim; } } // The claims as the build will read them: one verdict per claim id, none - // on a teaser. Refused before the write, so the file is as it was. - const bad = validateClaims(manifest); + // on a teaser, each knob in range. Refused before the write, so the file + // is as it was. + const bad = [...validateClaims(claimsForRenderer(manifest)), ...claimKnobProblems(manifest)]; if (bad.length) throw new Error(`claim: ${bad.join("; ")} — nothing was written`); const nextToken = await writeManifestAtomic(dir, manifest); @@ -880,11 +963,11 @@ export async function updateChrome(dir, chrome, { token = null } = {}) { if (chrome === null) { if (manifest.render) delete manifest.render.chrome; } else { - const errors = validateChrome(chrome, renderWithoutChrome); + const errors = [...validateChrome(chromeForRenderer(chrome), renderWithoutChrome), ...chromeKnobProblems(chrome)]; if (errors.length) throw new ChromeRefused(errors); manifest.render = { ...(manifest.render ?? {}), chrome }; // The deck's markers against the timeline: each follows a clip in it. - const markers = validateDeckMarkers(manifest); + const markers = validateDeckMarkers(rendererView(manifest)); if (markers.length) throw new ChromeRefused(markers); } @@ -1222,9 +1305,10 @@ export function freshEntryId(timeline, base) { function structureErrors(manifest) { return [ ...validatePosts(manifest.posts, manifest.timeline ?? [], manifest.render), - ...validateClaims(manifest), + ...validateClaims(claimsForRenderer(manifest)), + ...claimKnobProblems(manifest), // The deck's markers follow clips: removing one a marker names is refused. - ...validateDeckMarkers(manifest), + ...validateDeckMarkers(rendererView(manifest)), ...validateTeasers(manifest), ...validateNarration(manifest), ...validateDrafted(manifest), @@ -1616,14 +1700,154 @@ export async function updateFactcheck(dir, factcheck, { token = null } = {}) { if (factcheck === null) delete chrome.factcheck; else chrome.factcheck = factcheck; const { chrome: _old, ...rest } = render; - const already = new Set(validateChrome(render.chrome, rest)); - const errors = validateChrome(chrome, rest).filter((e) => !already.has(e)); + const already = new Set(validateChrome(chromeForRenderer(render.chrome), rest)); + const errors = [ + ...validateChrome(chromeForRenderer(chrome), rest).filter((e) => !already.has(e)), + ...factcheckKnobProblems(chrome.factcheck), + ]; if (errors.length) throw new StructureRefused(errors); m.render = { ...render, chrome }; return { factcheck: chrome.factcheck ?? null }; }); } +// --------------------------------------------------------------------------- +// THE VIDEO KNOBS (plans/video-knobs-ui.md): a claim's stamp and count, the +// deck's markers, the encode ladder. Checked by ./knobs.mjs, and by the +// renderer's own validators once they know the knobs (knobs.mjs probes them). +// A clip's `audio` is updateClip's. +// --------------------------------------------------------------------------- + +/** A manifest as the renderer's validators read it: knobs they do not know yet left out. */ +function rendererView(manifest) { + const m = claimsForRenderer(manifest); + const chrome = manifest?.render?.chrome; + return isObj(chrome) ? { ...m, render: { ...manifest.render, chrome: chromeForRenderer(chrome) } } : m; +} + +/** + * Patch the knobs of ONE claimed entry's `claim`: `{ at?, hold?, stamp?, + * count?, label? }`, each a value or null (back to the default: the key is + * removed). Every entry carrying the id (a variant's twin) gets the same + * knobs. The entry must carry a claim; `at` must lie in its window. + * + * The build reads the knobs of the entry that STAMPS the claim -- the last + * carrying its id -- so `stamps` in the answer says whether this one does. + * + * @param {string} dir + * @param {string} entryId + * @param {Record<string, unknown>} patch + * @param {{ token?: string | null }} [opts] + * @returns {Promise<{ claim: Record<string, unknown>, stamps: boolean, stampsOn: string | null, token: string | null }>} + */ +export async function updateClaimKnobs(dir, entryId, patch, { token = null } = {}) { + const next = normalizeClaimKnobPatch(patch); + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const entries = (manifest.timeline ?? []).filter((e) => isObj(e) && e.id === entryId); + if (!entries.length) throw new Error(`no timeline entry with id ${entryId}`); + if (!isObj(entries[0].claim)) throw new Error(`${entryId} carries no claim — give it one (the On-screen table's claim column) before its stamp's knobs`); + for (const e of entries) { + if (!isObj(e.claim)) continue; + for (const [k, v] of Object.entries(next)) { + if (v === null) delete e.claim[k]; + else e.claim[k] = v; + } + } + const bad = claimKnobProblems({ timeline: entries }); + if (bad.length) throw new Error(`${bad.join("; ")} — nothing was written`); + const nextToken = await writeManifestAtomic(dir, manifest); + const stampsOn = stampingEntryId(manifest, entries[0].claim.id); + return { claim: entries[0].claim, stamps: stampsOn === entryId, stampsOn, token: nextToken }; + }); +} + +/** + * Normalise a list of deck markers as the editor sends them: each `{ after, + * label, color?, align? }`, the label trimmed, an empty colour and `align: + * "auto"` (the default) left out. + * + * @param {unknown} markers + */ +export function normalizeMarkers(markers) { + if (!Array.isArray(markers)) throw new Error("markers must be a list of { after, label, color?, align? }"); + return markers.map((m, i) => { + if (!isObj(m)) throw new Error(`markers[${i}] must be { after, label, color?, align? }`); + const out = { after: String(m.after ?? "").trim(), label: String(m.label ?? "").trim() }; + const color = typeof m.color === "string" ? m.color.trim() : ""; + if (color) out.color = color; + if (m.align !== undefined && m.align !== null && m.align !== "" && m.align !== "auto") out.align = m.align; + for (const k of Object.keys(m)) if (!["after", "label", "color", "align"].includes(k)) out[k] = m[k]; + return out; + }); +} + +/** + * Set the deck's markers (`render.chrome.deck.markers`) and/or their layout + * (`deck.markerLayout`), leaving the rest of the deck as it is. `markers: []` + * or null removes the list; `markerLayout: null` (or "") removes the key. + * Only on a cut whose deck is on. A structural edit: snapshotted first (Undo + * takes it back), checked by the build's validateChrome and validateDeckMarkers. + * + * @param {string} dir + * @param {{ markers?: unknown[] | null, markerLayout?: string | null }} patch + * @param {{ token?: string | null }} [opts] + */ +export async function updateDeckMarkers(dir, patch, { token = null } = {}) { + if (!isObj(patch) || (!("markers" in patch) && !("markerLayout" in patch))) { + throw new Error("send markers and/or markerLayout"); + } + const markers = patch.markers === undefined || patch.markers === null ? patch.markers : normalizeMarkers(patch.markers); + return structural(dir, "markers", token, (m) => { + const render = m.render ?? {}; + if (!isObj(render.chrome)) throw new Error("markers are drawn by the on-screen deck, and this manifest has none — turn the deck on first"); + const deck = { ...(isObj(render.chrome.deck) ? render.chrome.deck : {}) }; + if (markers !== undefined) { + if (markers === null || !markers.length) delete deck.markers; + else deck.markers = markers; + } + if ("markerLayout" in patch) { + const v = patch.markerLayout; + if (v === null || v === undefined || v === "") delete deck.markerLayout; + else deck.markerLayout = v; + } + const chrome = { ...render.chrome, deck }; + const { chrome: _old, ...rest } = render; + const already = new Set(validateChrome(chromeForRenderer(render.chrome), rest)); + const errors = [...validateChrome(chromeForRenderer(chrome), rest).filter((e) => !already.has(e)), ...markerKnobProblems(deck)]; + if (errors.length) throw new StructureRefused(errors); + m.render = { ...render, chrome }; + return { markers: deck.markers ?? [], markerLayout: deck.markerLayout ?? null }; + }); +} + +/** + * Set or remove `render.variants`, the ladder "Make variants" encodes + * (knobs.mjs VARIANTS_DEFAULT when absent). null removes it. + * + * @param {string} dir + * @param {unknown[] | null} variants + * @param {{ token?: string | null }} [opts] + */ +export async function updateVariants(dir, variants, { token = null } = {}) { + if (variants === undefined) throw new Error("variants must be a list, or null for the default ladder"); + const errors = variantsProblems(variants); + if (errors.length) throw new RenderRefused(errors); + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const render = { ...(isObj(manifest.render) ? manifest.render : {}) }; + if (variants === null) delete render.variants; + else render.variants = variants; + manifest.render = render; + const nextToken = await writeManifestAtomic(dir, manifest); + return { variants: render.variants ?? null, token: nextToken }; + }); +} + /** * Replace the WHOLE manifest with `manifest` (release 33: "Use this take" puts * a take's video.manifest.json in the project's place). The same path as a diff --git a/umtool/lib/report/variantsView.mjs b/umtool/lib/report/variantsView.mjs @@ -0,0 +1,146 @@ +// MAKE VARIANTS and the SYNC report, read back for Deliver (video knobs, +// plans/video-knobs-ui.md). The encode is the renderer's (report-to-video +// variants.mjs encodeVariants, run as a job by driver.mjs variantsSteps); the +// sync report is the build's (`<out>/<variant>/sync.json`). This only reads +// what they wrote, by NAME -- a variant's name, a take's id -- never a path. +// +// <out>/<slug>.mp4 the build (the `master` variant is this file) +// <out>/<slug>.<name>.mp4 one variant +// <out>/variants.json { at, source, items: [{ name, path, width, height, bytes, kbps }] } +// <out>/sourced/sync.json { fps, items: [{ id, start, lagMs, peak }] } +// +// `<out>` is the project's out/, or a take's (takes/<id>/out). +// +// Plain ESM: `umtool variants` runs it under bare node. +import { readdir, readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { DEFAULT_VARIANT, variantPaths } from "umtool-report-to-video/build-video"; +import { resolveInRoots } from "../paths.mjs"; +import { VARIANT_NAME_RE, VARIANTS_DEFAULT, variantsOf } from "./knobs.mjs"; +import { isTakeId, takesDirOf } from "./takes.mjs"; + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +const fin = (v) => typeof v === "number" && Number.isFinite(v); + +/** A lag past one frame is flagged (the plan's acceptance: every clip within ±1 frame). */ +export const frameMs = (fps) => 1000 / (fin(fps) && fps > 0 ? fps : 30); + +/** + * The out/ a take or the project builds into. Throws on a take id that is not one. + * @param {{ dir: string }} project + * @param {string | null} [take] + */ +export function outDirOf(project, take = null) { + if (take === null || take === undefined || take === "") return path.join(project.dir, "out"); + if (!isTakeId(take)) throw new Error(`not a take id: ${take}`); + return path.join(takesDirOf(project.dir), take, "out"); +} + +async function fileInfo(file) { + const abs = resolveInRoots(file); + if (!abs) return null; + const st = await stat(abs).catch(() => null); + return st?.isFile() ? { abs, size: st.size, mtimeMs: Math.round(st.mtimeMs) } : null; +} + +async function readJson(file) { + const abs = resolveInRoots(file); + if (!abs) return null; + try { + return JSON.parse(await readFile(abs, "utf8")); + } catch { + return null; + } +} + +/** The takes with a build in their out/ (their `<slug>.mp4`), by id. */ +export async function builtTakes(project, slug) { + const dirs = await readdir(takesDirOf(project.dir), { withFileTypes: true }).catch(() => []); + const out = []; + for (const d of dirs) { + if (!isTakeId(d.name)) continue; + const got = await fileInfo(variantPaths(outDirOf(project, d.name), slug, DEFAULT_VARIANT).final); + if (got) out.push(d.name); + } + return out.sort(); +} + +/** + * What Deliver shows for one out/: the build, the ladder, the variants made, + * the sync report. + * + * @param {{ id: string, dir: string }} project + * @param {{ slug?: string, render?: Record<string, unknown>, timeline?: unknown[] }} manifest + * @param {string | null} [take] + */ +export async function variantsState(project, manifest, take = null) { + const slug = manifest.slug ?? path.basename(project.dir); + const outDir = outDirOf(project, take); + const built = await fileInfo(variantPaths(outDir, slug, DEFAULT_VARIANT).final); + const doc = await readJson(path.join(outDir, "variants.json")); + const items = []; + if (isObj(doc) && Array.isArray(doc.items)) { + for (const it of doc.items) { + if (!isObj(it) || typeof it.name !== "string" || !VARIANT_NAME_RE.test(it.name)) continue; + const f = await fileInfo(path.join(outDir, `${slug}.${it.name}.mp4`)); + items.push({ + name: it.name, + width: fin(it.width) ? it.width : null, + height: fin(it.height) ? it.height : null, + bytes: f?.size ?? (fin(it.bytes) ? it.bytes : null), + kbps: fin(it.kbps) ? it.kbps : null, + exists: !!f, + mtimeMs: f?.mtimeMs ?? null, + }); + } + } + const syncDoc = await readJson(path.join(outDir, DEFAULT_VARIANT, "sync.json")); + const fps = isObj(syncDoc) && fin(syncDoc.fps) ? syncDoc.fps : null; + const limit = frameMs(fps); + const clipIds = new Set((manifest.timeline ?? []).filter((e) => isObj(e) && e.type === "clip").map((e) => e.id)); + const sync = isObj(syncDoc) && Array.isArray(syncDoc.items) + ? { + fps, + frameMs: Math.round(limit * 10) / 10, + items: syncDoc.items + .filter((x) => isObj(x) && typeof x.id === "string") + .map((x) => ({ + id: x.id, + start: fin(x.start) ? x.start : null, + lagMs: fin(x.lagMs) ? x.lagMs : null, + peak: fin(x.peak) ? x.peak : null, + flagged: fin(x.lagMs) && Math.abs(x.lagMs) > limit, + clip: clipIds.has(x.id), + })), + } + : null; + const render = isObj(manifest.render) ? manifest.render : {}; + return { + take: take || null, + slug, + built: built ? { size: built.size, mtimeMs: built.mtimeMs } : null, + ladder: variantsOf(render), + ladderIsDefault: !Array.isArray(render.variants), + ladderDefault: VARIANTS_DEFAULT, + made: isObj(doc) ? { at: typeof doc.at === "string" ? doc.at : null, items } : null, + // A variants.json older than the build was made from another build. + stale: !!(built && isObj(doc) && typeof doc.at === "string" && Date.parse(doc.at) < built.mtimeMs), + sync, + takes: await builtTakes(project, slug), + }; +} + +/** + * One variant's file, by name, for the route that serves it. + * @param {{ dir: string }} project + * @param {{ slug?: string }} manifest + * @param {string} name + * @param {string | null} [take] + * @returns {Promise<{ abs: string, size: number, mtimeMs: number, rel: string } | null>} + */ +export async function variantFile(project, manifest, name, take = null) { + if (typeof name !== "string" || !VARIANT_NAME_RE.test(name)) return null; + const slug = manifest.slug ?? path.basename(project.dir); + const f = await fileInfo(path.join(outDirOf(project, take), `${slug}.${name}.mp4`)); + return f ? { ...f, rel: `${slug}.${name}.mp4` } : null; +}