// `umtool trailer-beats` (UI notes 2026-10-30, item 11): the project's trailer
// beats (promo/trailer-beats.json) from a terminal -- the same writer and the
// same reader as the Trailer page (lib/report/trailerBeats.mjs), so the running
// length, the platform limit and the beats outside their clips are said here
// before any encode. `umtool trailer
--take --beats
// /promo/trailer-beats.json` cuts the trailer from them.
//
// Beats are numbered from 1, as `umtool trailer`'s refusals number them.
//
// Plain ESM: the CLI runs under bare node.
import { editGaps } from "umtool-report-to-video/gaps";
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { clampPatch } from "./reelAnchor.mjs";
import { readReelHistory } from "./reelHistory.mjs";
import { anchorContextOf, reelPlayView } from "./reelPlay.mjs";
import { readManifest } from "../projects/report.mjs";
import {
BEAT_VERDICTS,
BeatsStale,
DEFAULT_REEL,
TRAILER_LIMITS,
addTrailerBeat,
anchorTrailerBeats,
beatsToken,
clockOf,
createReel,
introSecondsOf,
isReelId,
listReels,
readReelUndo,
reelFileOf,
moveTrailerBeat,
orderTrailerBeats,
readTrailerBeats,
removeTrailerBeat,
setTrailerSettings,
trailerCandidatesOf,
trailerView,
undoTrailerBeats,
updateTrailerBeat,
} from "./trailerBeats.mjs";
export const TRAILER_BEATS_USAGE = [
"usage: umtool trailer-beats [ls] [--json] the beats: length, running length against the limit,",
" beats outside their clip, the cut's order",
" umtool trailer-beats add [-] [--at N] [--label L]",
" a clip beat (default: the clip's whole cut), in the cut's order unless --at N",
" umtool trailer-beats add-raw [--at N] [--label L] master seconds",
" umtool trailer-beats set - [--label L] beat n's source seconds",
" umtool trailer-beats gap add - | remove | clear",
" seconds cut out of beat n's middle (a clip's gap rule): it plays as one beat of jump cuts",
" umtool trailer-beats remove | move --to | order (the cut's order)",
` umtool trailer-beats limit l.id).join("|")}> | xfade | intro on|off|''`,
" intro on: the master's brand intro (one rendered for the reel when the master has none);",
" a JSON intro ({\"style\":\"boot-dark\",\"mark\":\"chime\",\"site\":\"anilyzer\"}): the reel's own, rendered for it",
" umtool trailer-beats outro on|off|none|'{\"title\":…,\"text\":…,\"image\":\"promo/x.jpg\",\"seconds\":3.5}'",
" the card the reel ends on: the title (default the reel's title, else the project's), the call",
" to action (default \"Full video on the channel\"), an image of the project's under it, its seconds",
" (3.5, the fade in from the last beat included); a JSON key null drops it; none removes the outro",
" umtool trailer-beats candidates [--add] the walk's ★ clips not yet beats (--add: all of them)",
` umtool trailer-beats verdict ${BEAT_VERDICTS.join("|")}|clear the walk's word on beat n`,
" umtool trailer-beats title |none | take |none the reel's name, the take it is cut from",
" umtool trailer-beats undo the reel as it was before its last write (each write is an undo point)",
" umtool trailer-beats status [--take ] [--json] each beat against the take the reel plays now:",
" unchanged, rerendered, edges, look, clipped, orphan, unanchored (what it was cut against)",
" umtool trailer-beats anchor […] --take anchor beats (all, or n…) to that take's master",
" umtool trailer-beats clamp [--take ] | repoint [--take ]",
" a clipped beat pulled inside its clip's new limits; an orphan's seconds on another clip",
" umtool trailer-beats history [--json] every write to the reel: what moved, old and new",
" umtool trailer-beats reels [--json] the project's reels",
" umtool trailer-beats new-reel [--from ] [--title T] a new reel (empty, or a copy)",
"",
"--reel on any of these: that reel (promo/-beats.json); the default is `trailer`, promo/trailer-beats.json.",
"--take on an edit: the take it is made against -- the beat is anchored to that take's master.",
"`umtool trailer --reel [--take ]` cuts it.",
].join("\n");
class CliError extends Error {}
function parse(args) {
const valued = new Set(["--at", "--to", "--label", "--reel", "--from", "--title", "--take"]);
/** @type {Record} */
const flags = {};
const positional = [];
for (let i = 0; i < args.length; i += 1) {
const a = args[i];
if (a.startsWith("--")) {
if (valued.has(a)) {
if (i + 1 >= args.length) throw new CliError(`${a} needs a value`);
flags[a] = args[++i];
} else if (["--json", "--help", "--add"].includes(a)) flags[a] = "";
else throw new CliError(`unknown flag ${a}`);
} else positional.push(a);
}
return { flags, positional, has: (n) => n in flags };
}
const spanOf = (s) => {
const m = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(String(s ?? ""));
if (!m) throw new CliError(`a span is - in source seconds (got ${s})`);
return { start: Number(m[1]), end: Number(m[2]) };
};
const beatNo = (s, what = "beat") => {
const n = Number(s);
if (!Number.isInteger(n) || n < 1) throw new CliError(`${what} is a beat's number, from 1 (\`umtool trailer-beats \` lists them)`);
return n - 1;
};
/** seconds, m:ss(.s), or a platform's id. */
export function limitOf(s) {
const p = TRAILER_LIMITS.find((l) => l.id === String(s).toLowerCase());
if (p) return p.seconds;
const m = /^(\d+):(\d{1,2}(?:\.\d+)?)$/.exec(String(s));
if (m) return Number(m[1]) * 60 + Number(m[2]);
const n = Number(s);
if (!Number.isFinite(n)) throw new CliError(`limit is seconds, m:ss, or one of ${TRAILER_LIMITS.map((l) => l.id).join(", ")}`);
return n;
}
/** The view as lines. */
export function viewLines(v) {
const lines = [];
for (const r of v.rows) {
const what = r.kind === "clip" ? `${r.id.padEnd(8)} ${String(r.start).padStart(9)}–${String(r.end).padEnd(9)}` : `(master) at ${r.at} for ${r.dur}`.padEnd(29);
const gaps = r.gaps?.length ? ` gaps ${r.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : "";
const flag = r.problems.length ? ` ! ${r.problems.join("; ")}` : "";
lines.push(`${String(r.n).padStart(3)} ${what} ${`${r.seconds.toFixed(2)}s`.padStart(8)} ${clockOf(r.running).padStart(7)}${r.over ? " OVER" : ""}${r.verdict ? ` [${r.verdict}]` : ""}${r.clip?.section ? ` ${r.clip.section}` : ""}${r.label ? ` "${r.label}"` : ""}${gaps}${flag}`);
}
if (v.outro) lines.push(` + outro card ${`${Number(v.outro.seconds).toFixed(2)}s`.padStart(8)} "${v.outro.title || "(no title)"}" · "${v.outro.text}"${v.outro.image ? ` · over ${v.outro.image}` : ""}`);
else if (v.outroSetting) lines.push(" outro off (its words kept: `outro on`)");
lines.push(
`${v.rows.length} beat(s): ${clockOf(v.total)} of ${clockOf(v.limit)}${v.over ? ` — OVER by ${(v.total - v.limit).toFixed(1)} s` : ` (${v.remaining.toFixed(1)} s to spare)`}` +
` · crossfade ${v.xfade} s${v.intro ? ` · intro ${v.introSeconds ?? "?"} s${v.introSeconds === null ? " (unknown until a take is built)" : ""}${v.introOwn ? " (the reel's own)" : ""}` : ""}` +
`${v.outro ? ` · outro ${v.outro.seconds} s` : ""}` +
`${v.outside ? ` · ${v.outside} beat(s) to fix` : ""}${v.inOrder ? "" : " · not in the cut's order (`order`)"}`,
);
return lines;
}
/**
* @param {string[]} args the words after `trailer-beats`
* @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
*/
export async function trailerBeatsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
try {
const p = parse(args);
const [projectArg, verb = "ls", ...rest] = p.positional;
if (!projectArg || p.has("--help")) {
err(TRAILER_BEATS_USAGE);
return p.has("--help") ? 0 : 2;
}
const r = await resolveProject(projectArg, root);
if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
if (!r.project) throw new CliError(`no project matches "${projectArg}"`);
const project = r.project;
const manifest = await readManifest(project.dir);
if (!manifest) throw new CliError(`${project.id} has no manifest`);
let reel = p.has("--reel") ? p.flags["--reel"] : DEFAULT_REEL;
if (!isReelId(reel)) throw new CliError(`--reel ${reel}: a reel name (lower case, digits and dashes)`);
const token = await beatsToken(project.dir, reel);
const label = p.has("--label") ? p.flags["--label"] : undefined;
const at = p.has("--at") ? beatNo(p.flags["--at"], "--at") : null;
let did = null;
// An edit made against a take (--take): the beats written are anchored to it (reelAnchor.mjs).
const anchorTake = p.has("--take") ? p.flags["--take"] : null;
const ctx = anchorTake && verb !== "status" ? await anchorContextOf(project.dir, anchorTake) : null;
if (anchorTake && verb !== "status" && !ctx) throw new CliError(`--take ${anchorTake}: no finished master to anchor to`);
const anchorFor = ctx?.anchorFor ?? null;
switch (verb) {
case "ls":
break;
case "add": {
const id = rest[0];
if (!id) throw new CliError("add [-]");
const e = (manifest.timeline ?? []).find((x) => x?.id === id && x.type === "clip");
if (!e) throw new CliError(`no clip ${id} in the cut`);
const span = rest[1] ? spanOf(rest[1]) : { start: e.cutStart ?? e.start, end: e.cutEnd ?? e.end };
const res = await addTrailerBeat(project.dir, { id, ...span, ...(label ? { label } : {}) }, { token, at, manifest, reel, anchorFor });
did = `added beat ${res.index + 1}: ${id} ${res.beat.start}–${res.beat.end}`;
break;
}
case "add-raw": {
const a = Number(rest[0]);
const d = Number(rest[1]);
if (!Number.isFinite(a) || !Number.isFinite(d)) throw new CliError("add-raw : master seconds");
const res = await addTrailerBeat(project.dir, { at: a, dur: d, ...(label ? { label } : {}) }, { token, at, reel });
did = `added beat ${res.index + 1}: master ${a} for ${d} s`;
break;
}
case "set": {
const i = beatNo(rest[0]);
const patch = { ...(rest[1] ? spanOf(rest[1]) : {}), ...(label !== undefined ? { label } : {}) };
if (!Object.keys(patch).length) throw new CliError("set - [--label L]");
const res = await updateTrailerBeat(project.dir, i, patch, { token, reel, anchorFor });
const { anchor: _a, ...shown } = res.beat;
did = `beat ${i + 1}: ${JSON.stringify(shown)}`;
break;
}
case "gap": {
const i = beatNo(rest[0]);
const op = rest[1];
const doc = await readTrailerBeats(project.dir, { reel });
const b = doc.beats[i];
if (!b) throw new CliError(`no beat ${i + 1}`);
if (b.id === undefined) throw new CliError(`beat ${i + 1} is master seconds ({ at, dur }): only a clip beat has gaps`);
let next;
if (op === "add") {
const sp = spanOf(rest[2]);
next = editGaps(b.gaps ?? [], { add: { from: sp.start, to: sp.end } });
} else if (op === "remove") {
const t = Number(rest[2]);
if (!Number.isFinite(t)) throw new CliError("gap remove : a source second inside (or at) the gap");
next = editGaps(b.gaps ?? [], { remove: t });
} else if (op === "clear") next = [];
else throw new CliError("gap add - | remove | clear");
const res = await updateTrailerBeat(project.dir, i, { gaps: next }, { token, reel, anchorFor });
did = `beat ${i + 1}: ${(res.beat.gaps ?? []).length ? `gaps ${res.beat.gaps.map((g) => `${g.from}–${g.to}`).join(", ")}` : "no gaps"}`;
break;
}
case "remove": {
const i = beatNo(rest[0]);
const res = await removeTrailerBeat(project.dir, i, { token, reel });
did = `removed beat ${i + 1} (${res.removed.id ?? `master ${res.removed.at}`})`;
break;
}
case "move": {
const i = beatNo(rest[0]);
if (!p.has("--to")) throw new CliError("move --to ");
const to = beatNo(p.flags["--to"], "--to");
await moveTrailerBeat(project.dir, i, to, { token, reel });
did = `moved beat ${i + 1} to ${to + 1}`;
break;
}
case "order": {
const res = await orderTrailerBeats(project.dir, manifest, { token, reel });
did = res.moved ? "the beats are in the cut's order now" : "the beats were already in the cut's order";
break;
}
case "limit":
await setTrailerSettings(project.dir, { limit: rest[0] === "default" ? null : limitOf(rest[0]) }, { token, reel });
did = "limit set";
break;
case "xfade":
await setTrailerSettings(project.dir, { xfade: rest[0] === "default" ? null : Number(rest[0]) }, { token, reel });
did = "crossfade set";
break;
case "intro": {
const arg = rest.join(" ").trim();
if (arg.startsWith("{")) {
let spec;
try {
spec = JSON.parse(arg);
} catch (e) {
throw new CliError(`intro '': ${e instanceof Error ? e.message : e}`);
}
await setTrailerSettings(project.dir, { intro: spec }, { token, reel });
did = `intro: the reel's own (${spec.style ?? "?"}${spec.site ? `, site ${typeof spec.site === "string" ? spec.site : spec.site?.name}` : ""})`;
break;
}
if (!["on", "off"].includes(arg)) throw new CliError("intro on|off|''");
await setTrailerSettings(project.dir, { intro: arg === "on" }, { token, reel });
did = `intro ${arg}`;
break;
}
case "outro": {
const arg = rest.join(" ").trim();
let patch;
if (arg === "on" || arg === "off") patch = arg === "on";
else if (arg === "none") patch = null;
else if (arg.startsWith("{")) {
try {
patch = JSON.parse(arg);
} catch (e) {
throw new CliError(`outro '': ${e instanceof Error ? e.message : e}`);
}
} else throw new CliError("outro on|off|none|'{\"title\":…,\"text\":…,\"image\":…,\"seconds\":…}'");
await setTrailerSettings(project.dir, { outro: patch }, { token, reel });
did = patch === null ? "outro removed" : patch === false ? "outro off" : "outro on";
break;
}
case "title": {
const t = rest.join(" ").trim();
if (!t) throw new CliError("title |none");
await setTrailerSettings(project.dir, { title: t === "none" ? null : t }, { token, reel });
did = t === "none" ? "title cleared" : `title: ${t}`;
break;
}
case "take": {
const t = rest[0];
if (!t) throw new CliError("take |none: the take the reel is cut from (none: the last cut, else the latest master)");
await setTrailerSettings(project.dir, { take: t === "none" ? null : t }, { token, reel });
did = t === "none" ? "take unpinned" : `pinned to take ${t}`;
break;
}
case "verdict": {
const i = beatNo(rest[0]);
const v = rest[1];
if (v !== "clear" && !BEAT_VERDICTS.includes(v)) throw new CliError(`verdict ${BEAT_VERDICTS.join("|")}|clear`);
await updateTrailerBeat(project.dir, i, { verdict: v === "clear" ? null : v }, { token, reel });
did = `beat ${i + 1}: ${v === "clear" ? "verdict cleared" : v}`;
break;
}
case "status": {
const v = await reelPlayView(project, { reel, take: anchorTake });
if (!v.status) throw new CliError(v.noMaster?.why ?? "no take to classify the beats against");
const rows = (v.rows ?? []).map((r) => ({ n: r.n, id: r.id, beat: r.beat, state: r.status?.state ?? null, why: r.status?.why ?? null, was: r.status?.was ?? null, now: r.status?.now ?? null }));
if (p.has("--json")) out(JSON.stringify({ project: project.id, reel, take: v.take?.id ?? null, ...v.status, rows }, null, 2));
else {
out(`reel ${reel} on take ${v.take?.id} (${v.take?.why}): ${v.status.line}`);
for (const r of rows) out(`${String(r.n).padStart(3)} ${(r.id ?? "(master)").padEnd(10)} ${(r.state ?? "?").padEnd(11)} ${r.why ?? ""}`);
}
return 0;
}
case "anchor": {
if (!anchorFor) throw new CliError("anchor […] --take : the take whose master the beats are anchored to");
const only = rest.length ? rest.map((x) => beatNo(x)) : null;
await anchorTrailerBeats(project.dir, anchorFor, { token, reel, only, take: anchorTake ?? "" });
did = `anchored ${only ? `beat${only.length === 1 ? "" : "s"} ${only.map((k) => k + 1).join(", ")}` : "every beat"} to take ${anchorTake}`;
break;
}
case "clamp":
case "repoint": {
const i = beatNo(rest[0]);
const v = await reelPlayView(project, { reel, take: anchorTake });
const row = (v.rows ?? [])[i];
const doc = await readTrailerBeats(project.dir, { reel });
const b = doc.beats[i];
if (!row || !b) throw new CliError(`no beat ${i + 1}`);
const useFor = anchorFor ?? (v.take ? (await anchorContextOf(project.dir, v.take.id))?.anchorFor ?? null : null);
if (verb === "clamp") {
if (row.status?.state !== "clipped" || !row.status.now) throw new CliError(`beat ${i + 1} is ${row.status?.state ?? "not classified"}: only a clipped beat is clamped`);
const patch = clampPatch(b, { clip: row.status.now });
if (!patch) throw new CliError(`beat ${i + 1}: nothing of it is left inside ${b.id}'s new limits — re-place it (set) or remove it`);
await updateTrailerBeat(project.dir, i, patch, { token, reel, anchorFor: useFor });
did = `beat ${i + 1}: clamped to ${patch.start}–${patch.end}`;
} else {
const id = rest[1];
if (!id) throw new CliError("repoint ");
if (!(manifest.timeline ?? []).some((x) => x?.id === id && x.type === "clip")) throw new CliError(`no clip ${id} in the cut`);
await updateTrailerBeat(project.dir, i, { id }, { token, reel, anchorFor: useFor });
did = `beat ${i + 1}: re-pointed to ${id}`;
}
break;
}
case "history": {
const h = await readReelHistory(project.dir, reelFileOf(reel));
if (p.has("--json")) out(JSON.stringify({ project: project.id, reel, entries: h }, null, 2));
else if (!h.length) out(`no history for the reel ${reel} yet (it starts with the next write)`);
else for (const e of h) out(`${e.at} ${e.what}${e.take ? ` (take ${e.take})` : ""}${e.changes?.length ? `: ${e.changes.map((c) => (c.op ? `${c.op}${c.n ? ` ${c.n}` : ""}` : `${c.n}.${c.field} ${JSON.stringify(c.old)} → ${JSON.stringify(c.new)}`)).join("; ")}` : ""}`);
return 0;
}
case "undo": {
const u = await undoTrailerBeats(project.dir, { token, reel });
did = `undone: ${u.undone} (${u.left} undo point${u.left === 1 ? "" : "s"} left)`;
break;
}
case "reels": {
const reels = await listReels(project.dir);
if (p.has("--json")) out(JSON.stringify({ project: project.id, reels }, null, 2));
else for (const x of reels) out(`${x.name.padEnd(16)} ${x.file.padEnd(32)} ${x.exists ? `${x.beats} beat(s)` : "(no file yet)"}${x.title ? ` "${x.title}"` : ""}${x.take ? ` take ${x.take}` : ""}${x.error ? ` ! ${x.error}` : ""}`);
return 0;
}
case "new-reel": {
const name = rest[0];
if (!name) throw new CliError("new-reel [--from ] [--title T]");
await createReel(project.dir, name, { from: p.has("--from") ? p.flags["--from"] : null, title: p.has("--title") ? p.flags["--title"] : null });
did = `made the reel ${name} (${reelFileOf(name)})${p.has("--from") ? `, a copy of ${p.flags["--from"]}` : ""}`;
reel = name;
break;
}
case "candidates": {
const doc = await readTrailerBeats(project.dir, { reel });
const cands = trailerCandidatesOf(manifest, doc.beats);
if (!p.has("--add")) {
if (p.has("--json")) out(JSON.stringify({ project: project.id, candidates: cands }, null, 2));
else if (!cands.length) out("no ★ clips that are not beats already (star a clip on the walk)");
else for (const c of cands) out(`★ ${c.id.padEnd(8)} ${c.start}–${c.end}${c.walkNote ? ` — ${c.walkNote}` : ""}${c.quote ? ` "${c.quote.slice(0, 90)}${c.quote.length > 90 ? "…" : ""}"` : ""}`);
return 0;
}
let tok = token;
for (const c of cands) tok = (await addTrailerBeat(project.dir, { id: c.id, start: c.start, end: c.end }, { token: tok, manifest, reel })).token;
did = `added ${cands.length} ★ beat(s)`;
break;
}
default:
throw new CliError(`unknown: trailer-beats ${verb}\n${TRAILER_BEATS_USAGE}`);
}
const doc = await readTrailerBeats(project.dir, { reel });
const view = trailerView(manifest, doc, { introSeconds: doc.settings?.intro ? await introSecondsOf(project.dir) : null, reel });
const undo = await readReelUndo(project.dir, { reel });
if (p.has("--json")) {
out(JSON.stringify({ ok: true, project: project.id, ...(did ? { did } : {}), token: await beatsToken(project.dir, reel), ...view, undo: undo.length }, null, 2));
return 0;
}
if (did) out(did);
if (reel !== DEFAULT_REEL || view.title) out(`reel ${reel}${view.title ? ` "${view.title}"` : ""} (${view.file})${view.take ? ` · cut from take ${view.take}` : ""}`);
for (const line of viewLines(view)) out(line);
return 0;
} catch (e) {
if (e instanceof BeatsStale) {
err(`umtool trailer-beats: ${e.message} — somebody else wrote it; run it again`);
return 1;
}
err(`umtool trailer-beats: ${e instanceof Error ? e.message : String(e)}`);
return e instanceof CliError ? 2 : 1;
}
}