Archilyzer · Source

archilyzer

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

commit d74e4b9f944097a6ea4bd6e5a7451c889627631c
parent fe333e0691c9a25907b4db407c2a34778bfaa6ae
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 22 Oct 2026 10:14:04 -0400

umtool set / look / variants, and the knobs in umtool show: every knob from a terminal, through the same writers

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

Diffstat:
Mumtool/bin/umtool.mjs | 24+++++++++++++++++++++++-
Aumtool/e2e/fixtures/variants.e2e.mjs | 26++++++++++++++++++++++++++
Aumtool/lib/report/knobsCli.mjs | 365+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/knobsCli.test.mjs | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 528 insertions(+), 1 deletion(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -23,6 +23,11 @@ // [--title T] [--date YYYY-MM-DD] [--cite S] [--cite-url U] [--quote Q] // [--correction TEXT] [--verdict confirmed|incorrect|''] // [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent +// umtool set <project> <clip> key=value … a clip's knobs: claim.at|hold|stamp|count|label, +// audio.offset|gain|fadeIn|fadeOut (`key=` clears) (docs/knobs.md) +// umtool look <project> key=value … the cut's knobs: factcheck.stamp.*, factcheck.verdicts.<V>.*, +// deck.markers=<json>, deck.markerLayout, variants=<json>, the look's keys +// umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder; the sync report // umtool corrections <project> what the report got wrong, as markdown for the next pass // umtool build <project> [--preset preview|fast|final] [--only ID] [--dry] // [--run [--url URL] [--replace]] run it as the app's job, follow it, Ctrl-C cancels @@ -229,7 +234,8 @@ async function cmdShow() { if (json) { const src = detail ? await sourcesOf(p.dir, { manifest: detail.manifest }) : null; const snapshots = detail ? await listSnapshots(p.dir) : null; - return out({ ...s, decisions: ds, entries: detail?.entries ?? null, sources: src?.rows ?? null, snapshots }); + const knobs = detail ? (await import("../lib/report/knobsCli.mjs")).knobsOf(detail.manifest) : null; + return out({ ...s, decisions: ds, entries: detail?.entries ?? null, sources: src?.rows ?? null, snapshots, knobs }); } console.log(`${s.title}`); @@ -294,6 +300,10 @@ async function cmdShow() { ].filter(Boolean); console.log(` ${r.key.padEnd(w)} ${r.clips.join(",").padEnd(12)} ${marks.join(" · ")}`); } + // The video knobs (umtool set / umtool look): what this cut sets beyond the defaults. + const { knobsLines } = await import("../lib/report/knobsCli.mjs"); + console.log(`\nknobs:`); + for (const line of knobsLines(detail.manifest)) console.log(line); const snaps = await listSnapshots(p.dir); if (snaps.length) { console.log(`\nsnapshots (${snaps.length}):`); @@ -698,6 +708,14 @@ function usage() { " --verdict confirmed|incorrect what the walk said; incorrect needs --correction", " --cut-start S --cut-end E --lock-cut the cut the video renders", " an empty value (--title '') deletes the field", + " umtool set <project> <clip> key=value … a clip's knobs (`key=` clears; umtool/docs/knobs.md):", + " claim.at (a source second: the stamp lands, the count steps) claim.hold claim.stamp", + " claim.count claim.label · audio.offset (ms, + later) audio.gain (dB) audio.fadeIn audio.fadeOut", + " umtool look <project> key=value … the cut's knobs: factcheck.stamp.scale|motion|opacity|seconds,", + " factcheck.verdicts.<V>.stampLabel|label|color, deck.markers=<json>, deck.markerLayout,", + " variants=<json>, and the look's keys (transition=0.3, …)", + " umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder of a build (render.variants);", + " --list: what was made, and the build's sync report (each clip's lag, past a frame flagged)", " umtool corrections <project> what the report got wrong + the walk's coverage", " umtool build <project> [--preset preview|fast|final] [--only ID]", " --run: the app's build job (UMTOOL_URL, else http://localhost:3050; --url), followed here;", @@ -770,6 +788,10 @@ function usage() { const COMMANDS = { ls: cmdLs, window: cmdWindow, + // The video knobs (plans/video-knobs-ui.md): lib/report/knobsCli.mjs. + set: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).setCommand(argv.slice(argv.indexOf("set") + 1))), + look: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).lookCommand(argv.slice(argv.indexOf("look") + 1))), + variants: async () => process.exit(await (await import("../lib/report/knobsCli.mjs")).variantsCommand(argv.slice(argv.indexOf("variants") + 1))), corrections: cmdCorrections, build: cmdBuild, chain: cmdChain, diff --git a/umtool/e2e/fixtures/variants.e2e.mjs b/umtool/e2e/fixtures/variants.e2e.mjs @@ -0,0 +1,26 @@ +#!/usr/bin/env node +// The variants encoder, STUBBED (E2E_UMTOOL_VARIANTS_SCRIPT, set in +// playwright.config.ts): the command line of report-to-video/variants.mjs +// (`node variants.mjs <out dir>`, the manifest beside the out dir), and its +// outputs -- `<out>/<slug>.<name>.mp4` per rung and variants.json -- with no +// ffmpeg: each "variant" is a copy of the first bytes of the build. The suite +// tests the button, the job and the list, not an encode. +import { readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; + +const outDir = path.resolve(process.argv[2] ?? ""); +const manifest = JSON.parse(await readFile(path.join(path.dirname(outDir), "video.manifest.json"), "utf8")); +const slug = manifest.slug; +const ladder = Array.isArray(manifest.render?.variants) + ? manifest.render.variants + : [{ name: "master" }, { name: "1080p", height: 1080, crf: 22 }, { name: "720p", height: 720, crf: 23 }, { name: "fit24", maxMiB: 24 }]; +const source = await readFile(path.join(outDir, `${slug}.mp4`)); +const items = []; +for (const [i, v] of ladder.entries()) { + const bytes = v.name === "master" ? source : source.subarray(0, Math.max(1, Math.floor(source.length / (i + 1)))); + await writeFile(path.join(outDir, `${slug}.${v.name}.mp4`), bytes); + const height = v.height ?? (v.maxMiB ? 480 : 1080); + items.push({ name: v.name, path: `${slug}.${v.name}.mp4`, width: Math.round((height * 16) / 9), height, bytes: bytes.length, kbps: 1000 }); + console.log(`variant ${v.name}: ${bytes.length} bytes (stub)`); +} +await writeFile(path.join(outDir, "variants.json"), JSON.stringify({ at: new Date().toISOString(), source: `${slug}.mp4`, items }, null, 2) + "\n"); diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -0,0 +1,365 @@ +// THE VIDEO KNOBS FROM A TERMINAL (plans/video-knobs-ui.md): every knob a +// person sets in umtool, an agent sets here -- through the SAME writers +// (lib/report/manifest.mjs) and the same generated-manifest guard +// (edit-guard.mjs), each write carrying the token read from the file just +// before it, so a write here beside an open page is refused rather than lost. +// +// umtool set <project> <clip> key=value … claim.at claim.hold claim.stamp claim.count claim.label +// audio.offset audio.gain audio.fadeIn audio.fadeOut +// umtool look <project> key=value … factcheck.stamp.<k>, factcheck.verdicts.<V>.<k>, +// deck.markers=<json>, deck.markerLayout=…, variants=<json>, +// and the look's keys (transition=0.3, …) +// umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder (or list it) +// +// `key=` (nothing after the =) clears the key: the default again. A value is +// read as JSON when it parses (2, true, [..], {..}), else as text. +// +// Plain ESM: the CLI runs under bare node. +import { spawn } from "node:child_process"; +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { readManifest } from "../projects/report.mjs"; +import { withEditNotes } from "./edit-guard.mjs"; +import { + LOOK_KEYS, + manifestToken, + updateClaimKnobs, + updateClip, + updateDeckMarkers, + updateFactcheck, + updateRender, + updateVariants, +} from "./manifest.mjs"; +import { CLAIM_KNOBS, STAMP_KNOB_DEFAULTS, VARIANTS_DEFAULT, stampingEntryId, variantsOf } from "./knobs.mjs"; +import { variantsSteps } from "./driver.mjs"; +import { outDirOf, variantsState } from "./variantsView.mjs"; + +export const AUDIO_KNOBS = Object.freeze(["offset", "gain", "fadeIn", "fadeOut"]); +const SET_KEYS = [...CLAIM_KNOBS.map((k) => `claim.${k}`), ...AUDIO_KNOBS.map((k) => `audio.${k}`)]; + +export const SET_USAGE = [ + "usage: umtool set <project> <clip> key=value … [--json]", + ` keys: ${SET_KEYS.join(" ")}`, + " claim.at is a SOURCE second inside the clip's window: the stamp lands and the count steps there", + " (read from the last clip carrying the claim); claim.hold s (0.5–10); claim.stamp true|false;", + " claim.count 1–99; claim.label ≤ 20 chars. audio.offset ms (-2000…2000, + = sound later),", + " audio.gain dB (-20…20), audio.fadeIn / audio.fadeOut s (0–5). `key=` clears it (the default).", +].join("\n"); + +export const LOOK_USAGE = [ + "usage: umtool look <project> key=value … [--json]", + " factcheck.stamp.scale (0.5–2) .motion (slam|pop|fade|none) .opacity (0.3–1) .seconds .show .position", + " factcheck.verdicts.<VERDICT>.stampLabel | .label | .color", + " deck.markers='[{\"after\":\"c01\",\"label\":\"Arrival\",\"align\":\"left\"}]' deck.markerLayout=stagger|truncate", + " variants='[{\"name\":\"master\"},{\"name\":\"720p\",\"height\":720,\"crf\":23},{\"name\":\"fit24\",\"maxMiB\":24}]'", + ` the look: ${LOOK_KEYS.join(", ")} (a JSON value each)`, + " `key=` clears it (the default).", +].join("\n"); + +class CliError extends Error {} + +/** `a=b` words into [key, value]: JSON when it parses, else the text; `a=` is null (clear). */ +export function parseAssignments(words) { + return words.map((w) => { + const i = w.indexOf("="); + if (i <= 0) throw new CliError(`not key=value: ${w}`); + const key = w.slice(0, i); + const raw = w.slice(i + 1); + if (raw === "") return [key, null]; + try { + return [key, JSON.parse(raw)]; + } catch { + return [key, raw]; + } + }); +} + +async function projectOf(arg, root) { + if (!arg) throw new CliError("which project?"); + const r = await resolveProject(arg, root); + if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${arg}"`); + return r.project; +} + +const splitArgs = (args) => { + const words = []; + const flags = new Map(); + for (let i = 0; i < args.length; i += 1) { + const a = args[i]; + if (a === "--take") { + flags.set(a, args[i + 1] ?? ""); + i += 1; + } else if (a.startsWith("--")) flags.set(a, true); + else words.push(a); + } + return { words, flags }; +}; + +const noted = (editNotes) => + !editNotes + ? "" + : editNotes.errors.length + ? ` edit NOT noted (${editNotes.errors.join("; ")}) — ${editNotes.generatedBy} will overwrite it on the next rebuild` + : ` edit noted for ${editNotes.generatedBy} — port it into the generator's inputs`; + +/** + * `umtool set <project> <clip> key=value …` + * @param {string[]} args the words after `set` + * @returns {Promise<number>} + */ +export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + const { words, flags } = splitArgs(args); + const json = flags.has("--json"); + try { + const [projectArg, clipId, ...rest] = words; + if (!projectArg || !clipId || !rest.length || flags.has("--help")) { + err(SET_USAGE); + return 2; + } + const project = await projectOf(projectArg, root); + const claim = {}; + const audio = {}; + for (const [key, value] of parseAssignments(rest)) { + if (!SET_KEYS.includes(key)) throw new CliError(`${key} is not a clip knob (${SET_KEYS.join(", ")})`); + const [group, k] = key.split("."); + (group === "claim" ? claim : audio)[k] = value; + } + const results = {}; + let notes = null; + if (Object.keys(claim).length) { + const token = await manifestToken(project.dir); + const { result, editNotes } = await withEditNotes(project, () => updateClaimKnobs(project.dir, clipId, claim, { token })); + results.claim = result.claim; + results.stamps = result.stamps; + results.stampsOn = result.stampsOn; + notes = editNotes; + } + if (Object.keys(audio).length) { + const token = await manifestToken(project.dir); + const { result, editNotes } = await withEditNotes(project, () => updateClip(project.dir, clipId, { audio }, { token, edit: "trim" })); + results.audio = result.entry.audio ?? null; + notes = editNotes ?? notes; + } + if (json) { + out(JSON.stringify({ ok: true, clip: clipId, ...results, editNotes: notes }, null, 2)); + return 0; + } + if (results.claim) { + out(`${clipId}: claim ${JSON.stringify(results.claim)}`); + if (!results.stamps) out(` NOTE: ${results.claim.id} stamps on ${results.stampsOn} (the last clip carrying it) — these knobs are read there, not here`); + } + if ("audio" in results) out(`${clipId}: audio ${results.audio ? JSON.stringify(results.audio) : "as recorded"}`); + const n = noted(notes); + if (n) out(n); + return 0; + } catch (e) { + err(e instanceof Error ? e.message : String(e)); + return e instanceof CliError ? 2 : 1; + } +} + +const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); + +/** Set (or with null, remove) `a.b.c` in a copy of `obj`, pruning objects left empty. */ +function setPath(obj, keys, value) { + const root = structuredClone(isObj(obj) ? obj : {}); + const stack = [root]; + let at = root; + for (const k of keys.slice(0, -1)) { + if (!isObj(at[k])) at[k] = {}; + at = at[k]; + stack.push(at); + } + const last = keys[keys.length - 1]; + if (value === null) delete at[last]; + else at[last] = value; + for (let i = keys.length - 1; i > 0; i -= 1) { + if (Object.keys(stack[i]).length) break; + delete stack[i - 1][keys[i - 1]]; + } + return root; +} + +/** + * `umtool look <project> key=value …` + * @param {string[]} args the words after `look` + * @returns {Promise<number>} + */ +export async function lookCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { + const { words, flags } = splitArgs(args); + const json = flags.has("--json"); + try { + const [projectArg, ...rest] = words; + if (!projectArg || !rest.length || flags.has("--help")) { + err(LOOK_USAGE); + return 2; + } + const project = await projectOf(projectArg, root); + const pairs = parseAssignments(rest); + const fc = pairs.filter(([k]) => k.startsWith("factcheck.")); + const deck = pairs.filter(([k]) => k.startsWith("deck.")); + const variants = pairs.filter(([k]) => k === "variants"); + const look = pairs.filter(([k]) => LOOK_KEYS.includes(k)); + const unknown = pairs.filter(([k]) => !k.startsWith("factcheck.") && !k.startsWith("deck.") && k !== "variants" && !LOOK_KEYS.includes(k)); + if (unknown.length) throw new CliError(`not a knob here: ${unknown.map(([k]) => k).join(", ")}\n\n${LOOK_USAGE}`); + for (const [k] of deck) if (k !== "deck.markers" && k !== "deck.markerLayout") throw new CliError(`${k}: the deck's other settings are the On-screen form's (deck.markers and deck.markerLayout here)`); + const done = {}; + let notes = null; + const write = async (fn) => { + const token = await manifestToken(project.dir); + const { result, editNotes } = await withEditNotes(project, () => fn(token)); + notes = editNotes ?? notes; + return result; + }; + if (fc.length) { + const m = await readManifest(project.dir); + let next = m?.render?.chrome?.factcheck ?? {}; + for (const [k, v] of fc) next = setPath(next, k.split(".").slice(1), v); + const r = await write((token) => updateFactcheck(project.dir, Object.keys(next).length ? next : null, { token })); + done.factcheck = r.factcheck; + } + if (deck.length) { + const patch = {}; + for (const [k, v] of deck) patch[k.slice("deck.".length)] = v; + const r = await write((token) => updateDeckMarkers(project.dir, patch, { token })); + done.markers = r.markers; + done.markerLayout = r.markerLayout; + } + if (variants.length) { + const r = await write((token) => updateVariants(project.dir, variants[0][1], { token })); + done.variants = r.variants; + } + if (look.length) { + const r = await write((token) => updateRender(project.dir, Object.fromEntries(look), { token })); + done.look = r.look; + } + if (json) out(JSON.stringify({ ok: true, ...done, editNotes: notes }, null, 2)); + else { + for (const [k, v] of Object.entries(done)) out(`${k}: ${v === null || v === undefined ? "(default)" : JSON.stringify(v)}`); + const n = noted(notes); + if (n) out(n); + } + return 0; + } catch (e) { + err(e instanceof Error ? (e.errors ? e.errors.join("\n") : e.message) : String(e)); + return e instanceof CliError ? 2 : 1; + } +} + +const mib = (b) => (typeof b === "number" ? `${(b / 1048576).toFixed(1)} MiB` : "–"); + +function printState(s, out) { + out(`${s.take ? `take ${s.take}` : "the project's build"}: ${s.built ? `${mib(s.built.size)}, built ${new Date(s.built.mtimeMs).toISOString()}` : "NOT BUILT"}`); + out(`ladder (${s.ladderIsDefault ? "default" : "render.variants"}): ${s.ladder.map((v) => v.name).join(", ")}`); + if (s.made) { + out(`made ${s.made.at ?? ""}${s.stale ? " (from an OLDER build — make them again)" : ""}`); + for (const m of s.made.items) out(` ${m.name.padEnd(10)} ${m.width ?? "?"}x${m.height ?? "?"} ${mib(m.bytes).padStart(10)} ${m.kbps ?? "?"} kb/s${m.exists ? "" : " GONE"}`); + } + if (s.sync) { + const bad = s.sync.items.filter((x) => x.flagged); + out(`sync (${s.sync.items.length} clips, one frame = ${s.sync.frameMs} ms): ${bad.length ? `${bad.length} past a frame` : "every clip within a frame"}`); + for (const x of bad) out(` ${x.id.padEnd(10)} ${x.lagMs > 0 ? "+" : ""}${Math.round(x.lagMs)} ms → umtool set <project> ${x.id} audio.offset=…`); + } else out("sync: no report (the build writes sourced/sync.json)"); +} + +/** + * `umtool variants <project> [--take <t>] [--list] [--json]` + * @param {string[]} args the words after `variants` + * @returns {Promise<number>} + */ +export async function variantsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), env = process.env } = {}) { + const { words, flags } = splitArgs(args); + const json = flags.has("--json"); + try { + const [projectArg] = words; + if (!projectArg || flags.has("--help")) { + err("usage: umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder of a build (--list: what was made, and the sync report)"); + return 2; + } + const project = await projectOf(projectArg, root); + const manifest = await readManifest(project.dir); + if (!manifest) throw new CliError("no manifest"); + const take = typeof flags.get("--take") === "string" && flags.get("--take") ? String(flags.get("--take")) : null; + const before = await variantsState(project, manifest, take); + if (!flags.has("--list")) { + if (!before.built) throw new CliError(take ? `take ${take} has no build to make variants of` : "this cut has not been built yet — build it first"); + const [step] = variantsSteps(project, outDirOf(project, take), env); + const log = json ? (s) => err(s) : out; + log(`$ ${step.argv.join(" ")}`); + const code = await new Promise((resolve) => { + const child = spawn(process.execPath, step.argv.slice(1), { cwd: step.cwd, stdio: ["ignore", json ? "pipe" : "inherit", "inherit"] }); + if (json) child.stdout?.on("data", (b) => err(String(b).trimEnd())); + child.on("error", () => resolve(1)); + child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1))); + }); + if (code !== 0) { + err(`the encoder exited ${code}`); + return 1; + } + } + const s = await variantsState(project, manifest, take); + if (json) out(JSON.stringify(s, null, 2)); + else printState(s, out); + return 0; + } catch (e) { + err(e instanceof Error ? e.message : String(e)); + return e instanceof CliError ? 2 : 1; + } +} + +/** + * The knobs a manifest sets, for `umtool show`: per clip (claim knobs, audio), + * the fact-check's stamp, the deck's markers, the ladder. + * @param {Record<string, any>} manifest + */ +export function knobsOf(manifest) { + const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + const clips = []; + for (const e of timeline) { + if (!isObj(e)) continue; + const claim = isObj(e.claim) ? Object.fromEntries(CLAIM_KNOBS.filter((k) => e.claim[k] !== undefined).map((k) => [k, e.claim[k]])) : null; + const audio = isObj(e.audio) ? e.audio : null; + if ((claim && Object.keys(claim).length) || audio || isObj(e.claim)) { + clips.push({ + id: e.id, + ...(e.variant ? { variant: e.variant } : {}), + ...(isObj(e.claim) ? { claimId: e.claim.id, verdict: e.claim.verdict, stamps: stampingEntryId(manifest, e.claim.id) === e.id } : {}), + ...(claim && Object.keys(claim).length ? { claim } : {}), + ...(audio ? { audio } : {}), + }); + } + } + const fc = manifest?.render?.chrome?.factcheck; + const stamp = isObj(fc?.stamp) ? Object.fromEntries(Object.entries(fc.stamp).filter(([k]) => k in STAMP_KNOB_DEFAULTS)) : {}; + const stampLabels = isObj(fc?.verdicts) ? Object.fromEntries(Object.entries(fc.verdicts).filter(([, v]) => isObj(v) && typeof v.stampLabel === "string").map(([k, v]) => [k, v.stampLabel])) : {}; + const deck = manifest?.render?.chrome?.deck; + return { + clips, + stamp, + stampLabels, + markers: Array.isArray(deck?.markers) ? deck.markers : [], + markerLayout: deck?.markerLayout ?? null, + variants: variantsOf(manifest?.render), + variantsDefault: !Array.isArray(manifest?.render?.variants), + }; +} + +/** `umtool show`'s knobs block, as lines. */ +export function knobsLines(manifest) { + const k = knobsOf(manifest); + const lines = []; + for (const c of k.clips) { + const bits = []; + if (c.claimId) bits.push(`claim ${c.claimId} ${c.verdict}${c.stamps ? " (stamps here)" : ""}`); + if (c.claim) bits.push(Object.entries(c.claim).map(([a, b]) => `${a}=${JSON.stringify(b)}`).join(" ")); + if (c.audio) bits.push(`audio ${Object.entries(c.audio).map(([a, b]) => `${a}=${b}`).join(" ")}`); + lines.push(` ${String(c.id).padEnd(8)} ${bits.join(" · ")}`); + } + if (Object.keys(k.stamp).length) lines.push(` stamp ${Object.entries(k.stamp).map(([a, b]) => `${a}=${b}`).join(" ")}`); + if (Object.keys(k.stampLabels).length) lines.push(` stamp word ${Object.entries(k.stampLabels).map(([a, b]) => `${a}=${b}`).join(" ")}`); + if (k.markers.length) lines.push(` markers ${k.markers.map((m) => `${m.after}:"${m.label}"${m.align ? `(${m.align})` : ""}`).join(" ")}${k.markerLayout ? ` · layout ${k.markerLayout}` : ""}`); + lines.push(` variants ${k.variants.map((v) => v.name).join(", ")}${k.variantsDefault ? " (default)" : ""}`); + return lines; +} + +export { VARIANTS_DEFAULT }; diff --git a/umtool/lib/report/knobsCli.test.mjs b/umtool/lib/report/knobsCli.test.mjs @@ -0,0 +1,114 @@ +// `umtool set`, `umtool look`, `umtool variants` and the knobs `umtool show` +// prints (plans/video-knobs-ui.md): the same writers the UI uses, from a +// terminal; the encoder stubbed (e2e/fixtures/variants.e2e.mjs). +// +// 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"; +import { fileURLToPath } from "node:url"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-knobs-cli-")); +process.env.REPORTS_DIR = ROOT; +const { knobsLines, knobsOf, lookCommand, parseAssignments, setCommand, variantsCommand } = await import("./knobsCli.mjs"); + +const STUB = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "e2e", "fixtures", "variants.e2e.mjs"); + +const MANIFEST = { + schemaVersion: 1, + slug: "huck", + title: "Huck", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, 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 }, + ], +}; + +async function project(name) { + const dir = path.join(ROOT, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2) + "\n"); + return dir; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); +const runner = (fn) => { + const lines = []; + return { lines, run: (...args) => fn(args, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }) }; +}; + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("parseAssignments: JSON when it parses, text otherwise, empty clears", () => { + assert.deepEqual(parseAssignments(["a=2", "b=true", "c=SEIZURE", "d=", 'e=[{"x":1}]']), [["a", 2], ["b", true], ["c", "SEIZURE"], ["d", null], ["e", [{ x: 1 }]]]); + assert.throws(() => parseAssignments(["nope"]), /not key=value/); +}); + +test("umtool set: claim and audio knobs through the writers; key= clears; a bad key or value is refused", async () => { + const dir = await project("set"); + const { lines, run } = runner(setCommand); + assert.equal(await run("set", "c01", "claim.at=15.5", "claim.count=2", "claim.label=2 SEIZURES", "audio.offset=-40"), 0); + let c = (await read(dir)).timeline[0]; + assert.deepEqual(c.claim, { id: "k1", verdict: "CONTRADICTED", at: 15.5, count: 2, label: "2 SEIZURES" }); + assert.deepEqual(c.audio, { offset: -40 }); + assert.equal(await run("set", "c01", "claim.count=", "audio.offset="), 0); + c = (await read(dir)).timeline[0]; + assert.deepEqual(c.claim, { id: "k1", verdict: "CONTRADICTED", at: 15.5, label: "2 SEIZURES" }); + assert.equal("audio" in c, false); + assert.equal(await run("set", "c01", "claim.colour=1"), 2); + assert.match(lines.at(-1), /not a clip knob/); + assert.equal(await run("set", "c01", "claim.at=99"), 1); + assert.match(lines.at(-1), /must lie inside the clip's window/); + assert.equal(await run("set", "c02", "claim.count=2"), 1); + assert.match(lines.at(-1), /carries no claim/); + assert.equal(await run("set"), 2); +}); + +test("umtool look: the fact-check's stamp, a verdict's stamp word, markers, layout, the ladder, a look key", async () => { + const dir = await project("look"); + const { lines, run } = runner(lookCommand); + assert.equal(await run("look", "factcheck.stamp.scale=1.3", "factcheck.stamp.motion=pop", "factcheck.verdicts.CONTRADICTED.stampLabel=SEIZURE"), 0); + let m = await read(dir); + assert.deepEqual(m.render.chrome.factcheck, { stamp: { scale: 1.3, motion: "pop" }, verdicts: { CONTRADICTED: { stampLabel: "SEIZURE" } } }); + assert.equal(await run("look", "factcheck.stamp.scale=", "factcheck.stamp.motion="), 0); + m = await read(dir); + assert.deepEqual(m.render.chrome.factcheck, { verdicts: { CONTRADICTED: { stampLabel: "SEIZURE" } } }); + assert.equal(await run("look", 'deck.markers=[{"after":"c01","label":"Arrival","align":"left"}]', "deck.markerLayout=truncate"), 0); + m = await read(dir); + assert.deepEqual(m.render.chrome.deck, { markers: [{ after: "c01", label: "Arrival", align: "left" }], markerLayout: "truncate" }); + assert.equal(await run("look", 'variants=[{"name":"master"},{"name":"480p","height":480,"crf":26}]', "transition=0.3"), 0); + m = await read(dir); + assert.deepEqual(m.render.variants, [{ name: "master" }, { name: "480p", height: 480, crf: 26 }]); + assert.equal(m.render.transition, 0.3); + assert.equal(await run("look", "factcheck.stamp.motion=spin"), 1); + assert.match(lines.at(-1), /stamp\.motion/); + assert.equal(await run("look", "deck.height=300"), 2); + assert.equal(await run("look", "nope=1"), 2); + // what `umtool show` prints + const k = knobsOf(m); + assert.equal(k.markers.length, 1); + assert.deepEqual(k.stampLabels, { CONTRADICTED: "SEIZURE" }); + assert.ok(knobsLines(m).some((l) => /variants\s+master, 480p$/.test(l))); +}); + +test("umtool variants: refuses an unbuilt cut; makes the ladder (stub encoder) and lists it with the sync report", async () => { + const dir = await project("vars"); + const { lines, run } = runner((args, o) => variantsCommand(args, { ...o, env: { ...process.env, E2E_UMTOOL_VARIANTS_SCRIPT: STUB } })); + assert.equal(await run("vars"), 2); + assert.match(lines.at(-1), /not been built/); + await mkdir(path.join(dir, "out", "sourced"), { recursive: true }); + await writeFile(path.join(dir, "out", "huck.mp4"), Buffer.alloc(4096, 1)); + await writeFile(path.join(dir, "out", "sourced", "sync.json"), JSON.stringify({ fps: 30, items: [{ id: "c01", start: 0, lagMs: -68, peak: 0.9 }] })); + lines.length = 0; + assert.equal(await run("vars"), 0); + assert.ok(lines.some((l) => /^ {2}fit24 /.test(l)), lines.join("\n")); + assert.ok(lines.some((l) => /c01 +-68 ms/.test(l)), lines.join("\n")); + lines.length = 0; + assert.equal(await run("vars", "--list", "--json"), 0); + const s = JSON.parse(lines.join("\n")); + assert.deepEqual(s.made.items.map((i) => i.name), ["master", "1080p", "720p", "fit24"]); + assert.equal(s.sync.items[0].flagged, true); +});