commit b45a59f0016134afa3b10140b49917e993de66b9
parent bad58d7d3f1c6a26790de3d6374c7ae0efc422a9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 1 Nov 2026 00:01:54 -0400
umtool: trailer beats writer and reader, take relabel/supersede, render-aware take delete
lib/report/trailerBeats.mjs is the one writer of promo/trailer-beats.json
(add in the cut's order, edit, move, remove, order by the cut, settings:
limit, xfade, intro), each beat checked by the trailer's own parseBeats, the
file's shape and indent kept, a .bak before each write, the mtime a token.
trailerView says before any encode: each beat's length with the clip's gaps
out, the running length against the platform limit (X 2:20 by default) with
the crossfades and the brand intro (its length from the newest built take's
schedule), beats outside their clip's window or naming a clip no longer in
the cut, and whether the beats are in the cut's order. trailerCandidatesOf:
the walk's starred clips not yet beats.
Takes: relabelTake (take.json's label, an undo point of the take's own,
refused while the take renders), setTakeSuperseded (verdicts.json, kept
beside the verdict, never on the picked take, cleared by a pick), and
takeHousekeeping.mjs renderHolds -- a take whose build lock is live, or the
base of a live build -- which planTakeDelete now refuses on.
The take-patch sync module is renamed sectionPatches.mjs (lane/ui-cut-integrity
owns patchMarkers.mjs, for removals).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
16 files changed, 1538 insertions(+), 157 deletions(-)
diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts
@@ -3,16 +3,22 @@ import { withEditNotes } from "@/lib/report/guard";
import {
StaleToken,
StructureRefused,
+ addSection,
duplicateEntry,
insertEntry,
manifestToken,
moveEntry,
+ moveSectionBoundary,
+ moveToSection,
removeEntry,
+ removeSection,
+ sectionsOf,
rejectClip,
removeWrongSpeaker,
removePost,
undoStructural,
updateFactcheck,
+ updateSection,
updateTeaser,
upsertPost,
} from "@/lib/report/manifest.mjs";
@@ -43,6 +49,12 @@ export const dynamic = "force-dynamic";
// post-remove { id }
// factcheck { factcheck: { verdicts?, stamp?, tally? } | null }
// undo {} restore the newest auto snapshot
+// section-move { ids: [id…], section, position?: "start" | "end" } clips into a section
+// section-add { afterId, label?, color? } new section here (a marker after the clip)
+// section-boundary { marker, afterId } drag a boundary (between its neighbours)
+// section-remove { marker } the section joins the one before it
+// section-set { marker, label?, color? } relabel / recolour a section
+// (each section op brings the take patches' markers along: lib/report/sectionPatches.mjs)
//
// Every op snapshots the manifest first (`revisions/<stamp>-auto-before-<op>`),
// is checked by the build's own validators, and on a GENERATED manifest leaves
@@ -70,6 +82,8 @@ export async function GET(request: Request) {
teasers,
posts: Array.isArray(r.manifest.posts) ? r.manifest.posts : [],
deckOn: deckOn(render),
+ // The deck's sections (its markers), for "move to section…" and the section bars.
+ sections: deckOn(render) ? sectionsOf(r.manifest) : [],
factcheck: (render.chrome as { factcheck?: unknown } | undefined)?.factcheck ?? null,
factcheckResolved: resolveFactcheck(render),
// The stamp's knobs (video knobs): their defaults, bounds and motions, the form's placeholders.
@@ -128,8 +142,18 @@ export async function POST(request: Request) {
return updateFactcheck(dir, (body.factcheck ?? null) as Record<string, unknown> | null, { token });
case "undo":
return undoStructural(dir, { token });
+ case "section-move":
+ return moveToSection(dir, Array.isArray(body.ids) ? body.ids.map(String) : [id], Number(body.section), { token, position: body.position === "start" ? "start" : "end" });
+ case "section-add":
+ return addSection(dir, String(body.afterId ?? id), { label: typeof body.label === "string" ? body.label : null, color: typeof body.color === "string" ? body.color : null }, { token });
+ case "section-boundary":
+ return moveSectionBoundary(dir, Number(body.marker), String(body.afterId ?? ""), { token });
+ case "section-remove":
+ return removeSection(dir, Number(body.marker), { token });
+ case "section-set":
+ return updateSection(dir, Number(body.marker), Object.fromEntries(["label", "color"].filter((k) => k in body).map((k) => [k, body[k]])), { token });
default:
- throw new Error("op must be move, remove, reject, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck or undo");
+ throw new Error("op must be move, remove, reject, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck, undo, section-move, section-add, section-boundary, section-remove or section-set");
}
};
diff --git a/umtool/components/projects/TimelineEditor.tsx b/umtool/components/projects/TimelineEditor.tsx
@@ -19,15 +19,27 @@ import { MANIFEST_CHANGED, announceManifestChanged, refusalOf, timelineOp } from
// is a structural write (POST /api/report/timeline): snapshotted first, so
// "Undo" restores the cut as it was before the last burst of edits.
+/** One section of a deck cut (lib/report/sectionEdit.mjs), as the timeline route sends it. */
+export type SectionInfo = { index: number; label: string | null; color: string | null; marker: number | null; clips: string[]; words: string };
+
type Ctx = {
project: string;
busy: boolean;
run: (op: string, args: Record<string, unknown>) => Promise<boolean>;
dragging: React.MutableRefObject<{ id: string; at: number } | null>;
+ /** A section boundary being dragged (its marker), else null. */
+ draggingBar: React.MutableRefObject<number | null>;
+ /** The deck's sections ([] without a deck): the row menu's "move to section…". */
+ sections: SectionInfo[];
+ /** Clips ticked for a multi-clip "move to section…". */
+ selected: Set<string>;
+ toggle: (id: string) => void;
};
const TimelineCtx = createContext<Ctx | null>(null);
+export const useTimeline = () => useContext(TimelineCtx);
const rowOf = (el: EventTarget | null) => (el instanceof Element ? (el.closest("li[data-entry][data-at]") as HTMLLIElement | null) : null);
+const barOf = (el: EventTarget | null) => (el instanceof Element ? (el.closest("li[data-section-bar]") as HTMLLIElement | null) : null);
const rowKey = (li: HTMLLIElement) => ({ id: li.dataset.entry ?? "", at: Number(li.dataset.at) });
export function TimelineList({ project, count, children }: { project: string; count: number; children: React.ReactNode }) {
@@ -39,9 +51,21 @@ export function TimelineList({ project, count, children }: { project: string; co
const [error, setError] = useState<string | null>(null);
const [over, setOver] = useState<number | null>(null);
const dragging = useRef<{ id: string; at: number } | null>(null);
+ const draggingBar = useRef<number | null>(null);
// The entries in order (Add clip's "after"), as the route last said.
const [entries, setEntries] = useState<{ id: string; type: string }[]>([]);
+ const [sections, setSections] = useState<SectionInfo[]>([]);
+ const [selected, setSelected] = useState<Set<string>>(() => new Set());
+ const [bulkTo, setBulkTo] = useState<string>("");
const [adding, setAdding] = useState(false);
+ const toggle = useCallback((id: string) => {
+ setSelected((cur) => {
+ const next = new Set(cur);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ });
+ }, []);
const loadToken = useCallback(async () => {
const r = await fetch(`/api/report/timeline?project=${encodeURIComponent(project)}`, { cache: "no-store" });
@@ -49,6 +73,7 @@ export function TimelineList({ project, count, children }: { project: string; co
if (r.ok) {
tokenRef.current = typeof j.token === "string" ? j.token : null;
if (Array.isArray(j.timeline)) setEntries(j.timeline);
+ setSections(Array.isArray(j.sections) ? j.sections : []);
}
return tokenRef.current;
}, [project]);
@@ -96,8 +121,15 @@ export function TimelineList({ project, count, children }: { project: string; co
});
};
+ const moveSelected = () => {
+ if (!selected.size || bulkTo === "") return;
+ void run("section-move", { ids: [...selected], section: Number(bulkTo) }).then((ok) => {
+ if (ok) setSelected(new Set());
+ });
+ };
+
return (
- <TimelineCtx.Provider value={{ project, busy, run, dragging }}>
+ <TimelineCtx.Provider value={{ project, busy, run, dragging, draggingBar, sections, selected, toggle }}>
<div className="mb-1.5 flex flex-wrap items-center gap-2 text-[11px]">
<button type="button" data-testid="timeline-undo" disabled={busy} onClick={() => void run("undo", {})} className={buttonVariants({ size: "sm" })}>
Undo last edit
@@ -106,8 +138,27 @@ export function TimelineList({ project, count, children }: { project: string; co
Add clip
</button>
<span className="text-[var(--color-dim)]">
- drag ⠿ or <kbd>alt</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd> to move
+ drag ⠿ or <kbd>alt</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd> to move{sections.length > 1 ? "; drag a section bar onto a clip to move its boundary, a clip onto a bar to move it into that section" : ""}
</span>
+ {sections.length > 0 && selected.size > 0 && (
+ <span data-testid="timeline-bulk" className="inline-flex flex-wrap items-center gap-1.5 rounded border border-[var(--color-sel)] px-1.5 py-0.5">
+ <span>{selected.size} selected</span>
+ <select data-testid="timeline-bulk-section" value={bulkTo} onChange={(e) => setBulkTo(e.target.value)} className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px]">
+ <option value="">move to section…</option>
+ {sections.map((sec) => (
+ <option key={sec.index} value={sec.index}>
+ {sec.words}
+ </option>
+ ))}
+ </select>
+ <button type="button" data-testid="timeline-bulk-move" disabled={busy || bulkTo === ""} onClick={moveSelected} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Move
+ </button>
+ <button type="button" data-testid="timeline-bulk-clear" disabled={busy} onClick={() => setSelected(new Set())} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Clear
+ </button>
+ </span>
+ )}
{busy && <span className="text-[var(--color-dim)]">saving…</span>}
{error && (
<span data-testid="timeline-error" className="text-[var(--color-bad)]">
@@ -130,7 +181,20 @@ export function TimelineList({ project, count, children }: { project: string; co
data-drop-at={over ?? ""}
onKeyDown={onKeyDown}
onDragOver={(e) => {
+ if (draggingBar.current !== null) {
+ // A boundary goes after a CLIP.
+ const li = rowOf(e.target);
+ if (!li || li.dataset.kind !== "clip") return;
+ e.preventDefault();
+ setOver(rowKey(li).at);
+ return;
+ }
if (!dragging.current) return;
+ const bar = barOf(e.target);
+ if (bar) {
+ e.preventDefault();
+ return;
+ }
const li = rowOf(e.target);
if (!li) return;
e.preventDefault();
@@ -139,9 +203,26 @@ export function TimelineList({ project, count, children }: { project: string; co
onDragLeave={() => setOver(null)}
onDrop={(e) => {
const from = dragging.current;
+ const marker = draggingBar.current;
const li = rowOf(e.target);
+ const bar = barOf(e.target);
dragging.current = null;
+ draggingBar.current = null;
setOver(null);
+ if (marker !== null) {
+ if (!li || li.dataset.kind !== "clip") return;
+ e.preventDefault();
+ void run("section-boundary", { marker, afterId: rowKey(li).id });
+ return;
+ }
+ if (from && bar) {
+ // A clip dropped on a section's bar opens that section (its start);
+ // ticked clips go with it.
+ e.preventDefault();
+ const ids = selected.has(from.id) ? [...selected] : [from.id];
+ void run("section-move", { ids, section: Number(bar.dataset.sectionBar), position: "start" }).then((ok) => ok && setSelected(new Set()));
+ return;
+ }
if (!from || !li) return;
e.preventDefault();
const to = rowKey(li).at;
@@ -277,14 +358,28 @@ export function AddClipForm({
}
/** Inside one row: the drag handle and the row's menu. */
-export function RowControls({ id, at }: { id: string; at: number }) {
+export function RowControls({ id, at, kind = "entry" }: { id: string; at: number; kind?: string }) {
const ctx = useContext(TimelineCtx);
const [menu, setMenu] = useState(false);
const [insert, setInsert] = useState<string | null>(null);
+ const [toSection, setToSection] = useState(false);
+ const [newSection, setNewSection] = useState(false);
if (!ctx) return null;
- const { busy, run, dragging } = ctx;
+ const { busy, run, dragging, sections, selected, toggle } = ctx;
+ const isClip = kind === "clip";
+ const mine = isClip ? sections.find((s) => s.clips.includes(id)) : undefined;
return (
<>
+ {isClip && sections.length > 0 && (
+ <input
+ type="checkbox"
+ data-select-clip={id}
+ aria-label={`select ${id}`}
+ checked={selected.has(id)}
+ onChange={() => toggle(id)}
+ className="accent-[var(--color-sel)]"
+ />
+ )}
<span
draggable={!busy}
data-drag-handle={id}
@@ -311,12 +406,50 @@ export function RowControls({ id, at }: { id: string; at: number }) {
<button type="button" data-row-action="insert" disabled={busy} onClick={() => (setMenu(false), setInsert(""))} className="px-1 py-0.5 text-left hover:bg-[var(--color-panel-2)]">
insert clip after
</button>
+ {isClip && sections.length > 0 && (
+ <button type="button" data-row-action="to-section" disabled={busy} onClick={() => (setMenu(false), setToSection(true))} className="px-1 py-0.5 text-left hover:bg-[var(--color-panel-2)]">
+ move to section…
+ </button>
+ )}
+ {isClip && sections.length > 0 && (
+ <button type="button" data-row-action="new-section" disabled={busy} onClick={() => (setMenu(false), setNewSection(true))} className="px-1 py-0.5 text-left hover:bg-[var(--color-panel-2)]">
+ new section here
+ </button>
+ )}
<button type="button" data-row-action="remove" disabled={busy} onClick={() => (setMenu(false), void run("remove", { id, at }))} className="px-1 py-0.5 text-left text-[var(--color-bad)] hover:bg-[var(--color-panel-2)]">
remove
</button>
</span>
)}
</span>
+ {toSection && (
+ <span data-testid={`to-section-${id}`} className="inline-flex items-center gap-1 text-[11px]">
+ <select
+ autoFocus
+ data-testid={`to-section-select-${id}`}
+ defaultValue=""
+ onChange={(e) => {
+ const v = e.target.value;
+ if (v === "") return;
+ const ids = selected.has(id) ? [...selected] : [id];
+ void run("section-move", { ids, section: Number(v) }).then((ok) => ok && setToSection(false));
+ }}
+ onKeyDown={(e) => e.key === "Escape" && setToSection(false)}
+ className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px]"
+ >
+ <option value="">move {selected.has(id) && selected.size > 1 ? `${selected.size} clips` : id} to…</option>
+ {sections.map((sec) => (
+ <option key={sec.index} value={sec.index} disabled={sec.index === mine?.index && !(selected.size > 1)}>
+ {sec.words}
+ </option>
+ ))}
+ </select>
+ <button type="button" onClick={() => setToSection(false)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ cancel
+ </button>
+ </span>
+ )}
+ {newSection && <NewSectionForm id={id} busy={busy} onCancel={() => setNewSection(false)} onAdd={(label, color) => run("section-add", { afterId: id, label, color }).then((ok) => ok && setNewSection(false))} />}
{insert !== null && (
<input
autoFocus
@@ -346,3 +479,119 @@ export function RowNotes({ id, project }: { id: string; project: string }) {
</div>
);
}
+
+/** "New section here": a label (at most 24 characters, blank for a tick) and a colour. */
+export function NewSectionForm({
+ id,
+ busy,
+ onCancel,
+ onAdd,
+ initial = { label: "", color: "#6fc3ff" },
+ verb = "Add section",
+}: {
+ id: string;
+ busy: boolean;
+ onCancel: () => void;
+ onAdd: (label: string, color: string) => void;
+ initial?: { label: string; color: string };
+ verb?: string;
+}) {
+ const [label, setLabel] = useState(initial.label);
+ const [color, setColor] = useState(initial.color);
+ const long = [...label.trim()].length > 24;
+ return (
+ <span data-testid={`new-section-${id}`} className="inline-flex flex-wrap items-center gap-1 text-[11px]">
+ <input
+ autoFocus
+ data-testid={`new-section-label-${id}`}
+ value={label}
+ maxLength={40}
+ placeholder="section label (blank: a tick)"
+ onChange={(e) => setLabel(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") onCancel();
+ if (e.key === "Enter" && !long) onAdd(label.trim(), color);
+ }}
+ className="w-48 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none focus:border-[var(--color-sel)]"
+ />
+ <span className={`num font-mono ${long ? "text-[var(--color-bad)]" : "text-[var(--color-dim)]"}`}>{[...label.trim()].length}/24</span>
+ <input type="color" data-testid={`new-section-color-${id}`} value={color} onChange={(e) => setColor(e.target.value)} className="h-5 w-7 cursor-pointer rounded border border-[var(--color-line)] bg-transparent" title="the section's colour on the rail" />
+ <button type="button" data-testid={`new-section-add-${id}`} disabled={busy || long} onClick={() => onAdd(label.trim(), color)} className={buttonVariants({ variant: "go", size: "sm" })}>
+ {verb}
+ </button>
+ <button type="button" disabled={busy} onClick={onCancel} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Cancel
+ </button>
+ </span>
+ );
+}
+
+/**
+ * A section's bar between the rows: its colour, number and label, how many
+ * clips. Dragged onto a clip, the boundary follows that clip (between its
+ * neighbours); a clip dropped on it opens the section. Edit relabels and
+ * recolours it; Remove joins it to the section before. §0 has no marker: no
+ * handle, no edit.
+ */
+export function SectionBar({ section }: { section: SectionInfo }) {
+ const ctx = useContext(TimelineCtx);
+ const [editing, setEditing] = useState(false);
+ if (!ctx) return null;
+ const { busy, run, draggingBar } = ctx;
+ const k = section.marker;
+ return (
+ <li
+ data-section-bar={section.index}
+ data-marker={k ?? ""}
+ className="flex flex-wrap items-center gap-2 rounded-sm border-l-4 bg-[var(--color-panel-2)] px-2 py-1 text-[11.5px]"
+ style={{ borderLeftColor: section.color ?? "var(--color-line)" }}
+ >
+ {k !== null ? (
+ <span
+ draggable={!busy}
+ data-bar-handle={k}
+ title="drag onto a clip: the section starts after it"
+ onDragStart={(e) => {
+ draggingBar.current = k;
+ e.dataTransfer.effectAllowed = "move";
+ e.dataTransfer.setData("text/plain", `marker:${k}`);
+ }}
+ onDragEnd={() => (draggingBar.current = null)}
+ className="cursor-grab select-none text-[13px] leading-none text-[var(--color-dim)]"
+ >
+ ⇕
+ </span>
+ ) : (
+ <span className="w-3" />
+ )}
+ <span className="inline-block h-2.5 w-2.5 rounded-full" style={{ background: section.color ?? "transparent", border: "1px solid var(--color-line)" }} />
+ <span className="font-mono text-[var(--color-dim)]">§{section.index}</span>
+ <span className="text-[var(--color-text)]" data-section-label="">
+ {section.label ?? (section.index === 0 ? "the opening" : "(no label)")}
+ </span>
+ <span className="micro">
+ {section.clips.length} clip{section.clips.length === 1 ? "" : "s"}
+ </span>
+ {k !== null && !editing && (
+ <span className="ml-auto flex items-center gap-1">
+ <button type="button" data-section-edit={k} disabled={busy} onClick={() => setEditing(true)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ edit
+ </button>
+ <button type="button" data-section-remove={k} disabled={busy} onClick={() => void run("section-remove", { marker: k })} className={buttonVariants({ variant: "quiet", size: "sm" })} title="remove this boundary: the section joins the one before it">
+ remove boundary
+ </button>
+ </span>
+ )}
+ {k !== null && editing && (
+ <NewSectionForm
+ id={`m${k}`}
+ busy={busy}
+ verb="Save"
+ initial={{ label: section.label ?? "", color: /^#[0-9a-f]{6}$/i.test(section.color ?? "") ? (section.color as string) : "#6fc3ff" }}
+ onCancel={() => setEditing(false)}
+ onAdd={(label, color) => void run("section-set", { marker: k, label, color }).then((ok) => ok && setEditing(false))}
+ />
+ )}
+ </li>
+ );
+}
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -12,7 +12,10 @@ import { clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, p
import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs";
import FetchUnfetchedButton from "../FetchUnfetchedButton";
import { clipRecord, storedUrlOf } from "@/lib/clips/stored";
-import { RowControls, RowNotes, TimelineList } from "../TimelineEditor";
+import { Fragment } from "react";
+import { deckOn } from "umtool-report-to-video/deck";
+import { sectionModel, sectionWords } from "@/lib/report/sectionEdit.mjs";
+import { RowControls, RowNotes, SectionBar, TimelineList, type SectionInfo } from "../TimelineEditor";
import { Pill, TONE, hms, type ReportTabProps } from "./shared";
import VoiceMatchPanel from "./VoiceMatchPanel";
import FetchWindowsPanel from "./FetchWindowsPanel";
@@ -128,132 +131,18 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
return `${toolsMixHref()}?${q}`;
};
- return (
- <>
- <div className="flex flex-wrap items-start gap-3">
- {/* ---- the way in ----
- Every clip row carries a bench link, which is the right control for
- "go to that one" and the wrong one for "start". Reviewing a cut is
- watching every clip in order, and the first clip is where that
- begins -- so it is a button in the title bar rather than the
- eleventh link on a page whose first screenful is decisions,
- sources and the build chain. */}
- {clips.length > 0 && (
- <div data-walk-cut="" className="flex flex-col items-start gap-1">
- {/* Where the walk STARTS is where the walk goes: the first clip
- that still needs an answer and can be played. A cut whose
- first clip is already judged (or not fetched) would otherwise
- open on a clip `n` immediately leaves. */}
- <Link
- href={clipBenchHref(project.id, walkStart)}
- data-walk-start={walkStart}
- className={buttonVariants({ variant: "go", size: "lg" })}
- >
- Walk the cut → start at {walkStart}
- </Link>
- <span className="text-[11px] text-[var(--color-dim)]" data-walk-progress="">
- <kbd>p</kbd> / <kbd>n</kbd> move between clips · {review.reviewed} of {review.total}{" "}
- reviewed{review.incorrect > 0 ? ` · ${review.incorrect} incorrect` : ""}
- {review.rejected > 0 ? ` · ${review.rejected} rejected` : ""}
- {" · "}
- <span data-ready-count="">
- ready {readiness.ready} of {readiness.needing} needing judgement
- </span>
- </span>
- {/* The bench's first-open work (a long recording's excerpt, the
- waveform), made ahead in the background (lib/report/benchPrep.mjs). */}
- <BenchPrepPanel project={project.id} />
- </div>
- )}
- {/* The whole cut played in the browser in its final look, no render (the Play view). */}
- {clips.length > 0 && (
- <Link href={playHref(project.id)} data-play-cut-link="" className={buttonVariants({ size: "lg" })} title="play the whole cut here, chrome and all, without rendering it; notes at the playhead">
- Play the cut
- </Link>
- )}
- {/* A montage's instances, ruled by ear before a render (release 34). */}
- {montage.length > 0 && (
- <Link
- href={clipDeckHref(project.id)}
- data-clip-deck-link={unruled}
- className={buttonVariants({ size: "lg" })}
- >
- Clips — {unruled ? `${unruled} of ${montage.length} to rule` : `${montage.length} ruled`}
- </Link>
- )}
- {/* Any other cut's clips -- an assistant's above all -- adjusted by a person (release 35 C2). */}
- {montage.length === 0 && clips.length > 0 && (
- <Link
- href={clipEditorHref(project.id)}
- data-clip-editor-link={assisted.length}
- className={buttonVariants({ size: "lg" })}
- >
- Clip editor — {clips.length} clip{clips.length === 1 ? "" : "s"}
- {assisted.length ? ` · ${assisted.length} by the assistant${assistedByYou ? `, ${assistedByYou} edited by you` : ""}` : ""}
- </Link>
- )}
- {/* Alternative renders of part of the cut, judged on their own page --
- where the first one is made, too (release 33's take maker). */}
- {takes.exists ? (
- <Link
- href={takesHref(project.id)}
- data-takes-link={takes.takes.length}
- className={buttonVariants({ size: "lg" })}
- >
- Takes — {takes.takes.length}
- </Link>
- ) : (
- <Link href={takesHref(project.id)} data-takes-make-link="" className={buttonVariants({ variant: "quiet", size: "sm" })}>
- Make takes
- </Link>
- )}
- {/* Walk a take: the drafts first -- a draft exists to be walked before it is rendered. */}
- {takes.takes.some((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) && (
- <span data-walk-takes="" className="flex flex-wrap items-center gap-1.5 text-[11.5px]">
- <span className="micro">walk a take</span>
- {[...takes.takes]
- .filter((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash)
- .sort((a: { draft?: boolean }, b: { draft?: boolean }) => Number(!!b.draft) - Number(!!a.draft))
- .slice(0, 6)
- .map((t: { id: string; label: string; draft?: boolean }) => (
- <Link key={t.id} href={takeWalkHref(project.id, t.id)} data-walk-take={t.id} className="ink-link" title={t.label}>
- {t.id}
- {t.draft ? " (draft)" : ""}
- </Link>
- ))}
- </span>
- )}
- {clips.length > 0 && (
- <VoiceMatchPanel
- project={project.id}
- summary={voiceMatchSummary(voices)}
- />
- )}
- {fetchBody && <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} />}
- </div>
+ // The deck's sections (its markers, lib/report/sectionEdit.mjs): a bar
+ // opens each one, after the clip its marker follows.
+ const sectionBars = (() => {
+ const after = new Map<number, SectionInfo>();
+ if (!deckOn(m?.render)) return { opening: null as SectionInfo | null, after };
+ const model = sectionModel(m);
+ const words = (s: (typeof model.sections)[number]) => ({ ...s, words: sectionWords(s) }) as SectionInfo;
+ model.placed.forEach((p: { pos: number }, i: number) => after.set(p.pos, words(model.sections[i + 1])));
+ return { opening: model.sections.length > 1 ? words(model.sections[0]) : null, after };
+ })();
- {/* --- the timeline --------------------------------------------- */}
- <section>
- <h2 className="micro mb-1.5">
- the cut — {entries.length} entries, in array order
- </h2>
- {/* The gap between "ready" and "needing", closed in one press. Every
- row below it that reads "not fetched yet" is one of these, and
- closing them one bench page at a time was the loop this replaces.
- The default pad is the fetch route's own (±20 s), so a clip
- fetched here and a clip fetched from the bench land in the same
- file. */}
- {pendingFetch.length > 0 && (
- <div className="mb-1.5">
- <FetchUnfetchedButton
- project={project.id}
- pending={pendingFetch.map((id) => ({ id, padBefore: 20, padAfter: 20 }))}
- storedUrlClips={storedPending}
- />
- </div>
- )}
- <TimelineList project={project.id} count={entries.length}>
- {entries.map((e, at) => {
+ const renderRow = (e: (typeof entries)[number], at: number) => {
// Anything that is not a CLIP renders generically. The timeline's
// vocabulary is open -- one real manifest carries `scroll` and
// `chart` beside its cards -- and a page that only knows two words
@@ -261,7 +150,6 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
if (e.kind !== "clip") {
return (
<li
- key={`${e.id}@${at}`}
data-entry={e.id}
data-kind={e.kind}
data-at={at}
@@ -286,7 +174,6 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
const midSentence = e.endsSentence === false && !e.lockEnd && !e.lock;
return (
<li
- key={`${e.id}@${at}`}
data-entry={e.id}
data-kind="clip"
data-at={at}
@@ -297,7 +184,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 outline-none focus:border-[var(--color-sel)]"
>
<div className="flex flex-wrap items-baseline gap-2 text-[12px]">
- <RowControls id={e.id} at={at} />
+ <RowControls id={e.id} at={at} kind="clip" />
<span className="font-mono text-[var(--color-text)]">{e.id}</span>
<span className="num font-mono text-[11px] text-[var(--color-dim)]">
{e.video} {hms(e.start)}–{hms(e.end)} ({(e.end - e.start).toFixed(1)}s)
@@ -400,7 +287,140 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
<RowNotes id={e.id} project={project.id} />
</li>
);
- })}
+ };
+
+ return (
+ <>
+ <div className="flex flex-wrap items-start gap-3">
+ {/* ---- the way in ----
+ Every clip row carries a bench link, which is the right control for
+ "go to that one" and the wrong one for "start". Reviewing a cut is
+ watching every clip in order, and the first clip is where that
+ begins -- so it is a button in the title bar rather than the
+ eleventh link on a page whose first screenful is decisions,
+ sources and the build chain. */}
+ {clips.length > 0 && (
+ <div data-walk-cut="" className="flex flex-col items-start gap-1">
+ {/* Where the walk STARTS is where the walk goes: the first clip
+ that still needs an answer and can be played. A cut whose
+ first clip is already judged (or not fetched) would otherwise
+ open on a clip `n` immediately leaves. */}
+ <Link
+ href={clipBenchHref(project.id, walkStart)}
+ data-walk-start={walkStart}
+ className={buttonVariants({ variant: "go", size: "lg" })}
+ >
+ Walk the cut → start at {walkStart}
+ </Link>
+ <span className="text-[11px] text-[var(--color-dim)]" data-walk-progress="">
+ <kbd>p</kbd> / <kbd>n</kbd> move between clips · {review.reviewed} of {review.total}{" "}
+ reviewed{review.incorrect > 0 ? ` · ${review.incorrect} incorrect` : ""}
+ {review.rejected > 0 ? ` · ${review.rejected} rejected` : ""}
+ {" · "}
+ <span data-ready-count="">
+ ready {readiness.ready} of {readiness.needing} needing judgement
+ </span>
+ </span>
+ {/* The bench's first-open work (a long recording's excerpt, the
+ waveform), made ahead in the background (lib/report/benchPrep.mjs). */}
+ <BenchPrepPanel project={project.id} />
+ </div>
+ )}
+ {/* The whole cut played in the browser in its final look, no render (the Play view). */}
+ {clips.length > 0 && (
+ <Link href={playHref(project.id)} data-play-cut-link="" className={buttonVariants({ size: "lg" })} title="play the whole cut here, chrome and all, without rendering it; notes at the playhead">
+ Play the cut
+ </Link>
+ )}
+ {/* A montage's instances, ruled by ear before a render (release 34). */}
+ {montage.length > 0 && (
+ <Link
+ href={clipDeckHref(project.id)}
+ data-clip-deck-link={unruled}
+ className={buttonVariants({ size: "lg" })}
+ >
+ Clips — {unruled ? `${unruled} of ${montage.length} to rule` : `${montage.length} ruled`}
+ </Link>
+ )}
+ {/* Any other cut's clips -- an assistant's above all -- adjusted by a person (release 35 C2). */}
+ {montage.length === 0 && clips.length > 0 && (
+ <Link
+ href={clipEditorHref(project.id)}
+ data-clip-editor-link={assisted.length}
+ className={buttonVariants({ size: "lg" })}
+ >
+ Clip editor — {clips.length} clip{clips.length === 1 ? "" : "s"}
+ {assisted.length ? ` · ${assisted.length} by the assistant${assistedByYou ? `, ${assistedByYou} edited by you` : ""}` : ""}
+ </Link>
+ )}
+ {/* Alternative renders of part of the cut, judged on their own page --
+ where the first one is made, too (release 33's take maker). */}
+ {takes.exists ? (
+ <Link
+ href={takesHref(project.id)}
+ data-takes-link={takes.takes.length}
+ className={buttonVariants({ size: "lg" })}
+ >
+ Takes — {takes.takes.length}
+ </Link>
+ ) : (
+ <Link href={takesHref(project.id)} data-takes-make-link="" className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Make takes
+ </Link>
+ )}
+ {/* Walk a take: the drafts first -- a draft exists to be walked before it is rendered. */}
+ {takes.takes.some((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash) && (
+ <span data-walk-takes="" className="flex flex-wrap items-center gap-1.5 text-[11.5px]">
+ <span className="micro">walk a take</span>
+ {[...takes.takes]
+ .filter((t: { draft?: boolean; baseHash?: string | null }) => t.draft || t.baseHash)
+ .sort((a: { draft?: boolean }, b: { draft?: boolean }) => Number(!!b.draft) - Number(!!a.draft))
+ .slice(0, 6)
+ .map((t: { id: string; label: string; draft?: boolean }) => (
+ <Link key={t.id} href={takeWalkHref(project.id, t.id)} data-walk-take={t.id} className="ink-link" title={t.label}>
+ {t.id}
+ {t.draft ? " (draft)" : ""}
+ </Link>
+ ))}
+ </span>
+ )}
+ {clips.length > 0 && (
+ <VoiceMatchPanel
+ project={project.id}
+ summary={voiceMatchSummary(voices)}
+ />
+ )}
+ {fetchBody && <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} />}
+ </div>
+
+ {/* --- the timeline --------------------------------------------- */}
+ <section>
+ <h2 className="micro mb-1.5">
+ the cut — {entries.length} entries, in array order
+ </h2>
+ {/* The gap between "ready" and "needing", closed in one press. Every
+ row below it that reads "not fetched yet" is one of these, and
+ closing them one bench page at a time was the loop this replaces.
+ The default pad is the fetch route's own (±20 s), so a clip
+ fetched here and a clip fetched from the bench land in the same
+ file. */}
+ {pendingFetch.length > 0 && (
+ <div className="mb-1.5">
+ <FetchUnfetchedButton
+ project={project.id}
+ pending={pendingFetch.map((id) => ({ id, padBefore: 20, padAfter: 20 }))}
+ storedUrlClips={storedPending}
+ />
+ </div>
+ )}
+ <TimelineList project={project.id} count={entries.length}>
+ {sectionBars.opening && <SectionBar section={sectionBars.opening} />}
+ {entries.map((e, at) => (
+ <Fragment key={`${e.id}@${at}`}>
+ {renderRow(e, at)}
+ {sectionBars.after.get(at) && <SectionBar section={sectionBars.after.get(at)!} />}
+ </Fragment>
+ ))}
</TimelineList>
<div className="mt-2">
<Link
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -31,6 +31,7 @@ import {
StructureRefused,
addClip,
cutOf,
+ flashForward,
manifestToken,
mergeClips,
restoreClip,
@@ -343,6 +344,10 @@ const num = (v, what) => {
* restore { clip } the assistant's version back
* split { clip, at } two clips at that second
* merge { clip } with the next clip
+ * flash-forward { clip, from, to, after? | section?, position?, move?, quote?, id? }
+ * a span copied elsewhere as a repeat (or
+ * moved out of the clip: `move`), its quote
+ * read from the words (manifest.mjs flashForward)
* add { video, channel?, cutStart, cutEnd } a selection on the strip
* bring-in { proposal } one of the clip finder's unused proposals
* ruling { clip, verdict: "keep" | "cut" | null }
@@ -413,6 +418,37 @@ export async function runClipEditorOp(project, body, { now = null } = {}) {
case "merge":
result = await mergeClips(dir, needClip().id, { token, now });
break;
+ case "flash-forward": {
+ // A span of this clip copied somewhere else in the cut (a repeat), or
+ // moved out of it (`move`): its quote read from the words, as a split's.
+ const e = needClip();
+ const a = num(body.from, "from");
+ const b = num(body.to, "to");
+ const move = body.move === true;
+ const { cutStart, cutEnd } = cutOf(e);
+ const [quote, restQuote] = await Promise.all([
+ typeof body.quote === "string" && body.quote.trim() ? body.quote : quoteFor(project, e.id, a, b),
+ move ? (Math.abs(a - cutStart) <= 0.5 ? quoteFor(project, e.id, b, cutEnd) : quoteFor(project, e.id, cutStart, a)) : Promise.resolve(""),
+ ]);
+ const section = body.section === undefined || body.section === null || body.section === "" ? null : Number(body.section);
+ result = await flashForward(
+ dir,
+ e.id,
+ {
+ from: a,
+ to: b,
+ after: typeof body.after === "string" ? body.after : null,
+ section,
+ position: body.position === "start" ? "start" : "end",
+ move,
+ ...(quote ? { quote } : {}),
+ ...(restQuote ? { restQuote } : {}),
+ ...(typeof body.id === "string" && body.id.trim() ? { id: body.id.trim() } : {}),
+ },
+ { token },
+ );
+ break;
+ }
case "add": {
const video = typeof body.video === "string" ? body.video : entry?.video;
const channel = typeof body.channel === "string" ? body.channel : entry ? channelFor(manifest, entry) : null;
@@ -546,7 +582,7 @@ export async function runClipEditorOp(project, body, { now = null } = {}) {
break;
}
default:
- throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical, room, claim, marks, audio, blur or onscreen");
+ throw new OpError("op must be trim, restore, split, merge, flash-forward, add, bring-in, ruling, role, label, vertical, room, claim, marks, audio, blur or onscreen");
}
let carried = null;
if (structural) {
@@ -560,7 +596,7 @@ export async function runClipEditorOp(project, body, { now = null } = {}) {
function summarise(r) {
if (!isObj(r)) return null;
const out = {};
- for (const k of ["id", "second", "absorbed", "at"]) if (r[k] !== undefined) out[k] = r[k];
+ for (const k of ["id", "second", "absorbed", "at", "source", "move", "rest", "section", "earlier", "reanchored", "patches", "sectionPatches", "snapshot"]) 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;
diff --git a/umtool/lib/report/delete.mjs b/umtool/lib/report/delete.mjs
@@ -29,6 +29,7 @@ import { lstat, readFile, readdir, readlink, realpath, rm, rmdir } from "node:fs
import path from "node:path";
import { MEDIA_ROOT, REPORTS_ROOT, inside } from "../paths.mjs";
import { isTakeId, takesDirOf } from "./takes.mjs";
+import { renderHolds } from "./takeHousekeeping.mjs";
const strictlyInside = (root, p) => p !== root && inside(root, p);
@@ -278,6 +279,9 @@ export async function planTakeDelete(project, takeId, opts = {}) {
const place = await placeProblem(project.dir, roots, "the project");
if (place) refusals.push({ reason: place, forceable: false });
if (opts.busyJob) refusals.push({ reason: `${opts.busyJob} is working in ${project.id}: wait for it, or cancel it`, forceable: false });
+ // What a running render names (a `umtool take` from a terminal is no job of
+ // the app's): the take rendering, or the base a render is made from.
+ for (const why of await renderHolds(project.dir, takeId)) refusals.push({ reason: `take ${takeId}: ${why}`, forceable: false });
const [mine, theirs] = await Promise.all([
readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, "video.manifest.json"), "utf8").catch(() => null),
readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), "utf8").catch(() => null),
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -42,7 +42,7 @@ import { validateRoom } from "umtool-report-to-video/room";
import { applySectionEnter } from "./sections.mjs";
import { citeUrlAt, parseClipSpec } from "./clipEditorModel.mjs";
import { addSectionIn, followSplitMarkers, moveBoundaryIn, moveToSectionIn, removeBoundaryIn, sectionModel, sectionWords, setSectionIn } from "./sectionEdit.mjs";
-import { syncPatchMarkers } from "./patchMarkers.mjs";
+import { syncSectionPatches } from "./sectionPatches.mjs";
import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck";
import { migrateManifest } from "umtool-report-to-video/modules/migrate";
import { loadPreset, resolvePresetLayers } from "umtool-report-to-video/presets";
@@ -2185,7 +2185,7 @@ export async function insertEntry(dir, afterId, spec, { token = null, at = null
// writers move clips between sections, open a section, drag or remove a
// boundary and relabel one -- each a structural write (the undo point, the
// build's checks), the markers checked by the deck's own validateChrome, and
-// then the take patches' markers brought along (patchMarkers.mjs) so the next
+// then the take patches' markers brought along (sectionPatches.mjs) so the next
// `umtool take --patch …` renders the same sections. `umtool timeline <p>
// section …`, the Cut tab's section bars and row menus.
@@ -2213,8 +2213,9 @@ async function sectionWrite(dir, op, token, mutate) {
after = clone(m.render?.chrome?.deck?.markers ?? []);
return r;
});
- const patches = await syncPatchMarkers(dir, before, after);
- return { ...res, patches };
+ // `sectionPatches`: a section edit's take-patch sync (`patches` is a removal's, patchMarkers.mjs).
+ const sectionPatches = await syncSectionPatches(dir, before, after);
+ return { ...res, sectionPatches };
}
/**
@@ -2242,17 +2243,34 @@ export async function addSection(dir, afterId, spec = {}, { token = null } = {})
return sectionWrite(dir, "section-add", token, (m) => addSectionIn(m, afterId, spec));
}
-/** Drag a boundary: marker `marker` follows clip `afterId`, between its neighbours. */
+/**
+ * Drag a boundary: marker `marker` follows clip `afterId`, between its neighbours.
+ * @param {string} dir
+ * @param {number} marker
+ * @param {string} afterId
+ * @param {{ token?: string | null }} [opts]
+ */
export async function moveSectionBoundary(dir, marker, afterId, { token = null } = {}) {
return sectionWrite(dir, "section-boundary", token, (m) => moveBoundaryIn(m, marker, afterId));
}
-/** Remove a boundary: marker `marker` goes, its section joins the one before. */
+/**
+ * Remove a boundary: marker `marker` goes, its section joins the one before.
+ * @param {string} dir
+ * @param {number} marker
+ * @param {{ token?: string | null }} [opts]
+ */
export async function removeSection(dir, marker, { token = null } = {}) {
return sectionWrite(dir, "section-remove", token, (m) => removeBoundaryIn(m, marker));
}
-/** A section's label and/or colour (its marker's). */
+/**
+ * A section's label and/or colour (its marker's).
+ * @param {string} dir
+ * @param {number} marker
+ * @param {{ label?: string | null, color?: string | null }} patch
+ * @param {{ token?: string | null }} [opts]
+ */
export async function updateSection(dir, marker, patch, { token = null } = {}) {
return sectionWrite(dir, "section-set", token, (m) => setSectionIn(m, marker, patch));
}
diff --git a/umtool/lib/report/sectionEdit.mjs b/umtool/lib/report/sectionEdit.mjs
@@ -13,7 +13,7 @@
// Everything here is PURE: each function mutates the manifest it is handed and
// returns what it did in words. manifest.mjs runs them inside a structural
// write (the lock, the token, the build's checks, the undo point), and syncs
-// the take patches' markers after (patchMarkers.mjs).
+// the take patches' markers after (sectionPatches.mjs).
//
// The rules, each refused in words rather than repaired silently:
// - a section never ends up with no clip (two markers on one boundary);
diff --git a/umtool/lib/report/sectionEdit.test.mjs b/umtool/lib/report/sectionEdit.test.mjs
@@ -11,7 +11,7 @@ import path from "node:path";
import test from "node:test";
import { addSectionIn, moveBoundaryIn, moveToSectionIn, removeBoundaryIn, sectionModel, setSectionIn } from "./sectionEdit.mjs";
-import { syncPatchMarkers } from "./patchMarkers.mjs";
+import { syncSectionPatches } from "./sectionPatches.mjs";
import {
MANIFEST_NAME,
StructureRefused,
@@ -149,13 +149,13 @@ test("the writers keep in-step take patches in step, and leave a variant alone",
});
try {
const r = await moveToSection(dir, ["a"], 1);
- assert.deepEqual(r.patches.synced, ["draft-1.patch.json"]);
- assert.deepEqual(r.patches.skipped.map((x) => x.file), ["variant.patch.json"]);
+ assert.deepEqual(r.sectionPatches.synced, ["draft-1.patch.json"]);
+ assert.deepEqual(r.sectionPatches.skipped.map((x) => x.file), ["variant.patch.json"]);
assert.deepEqual((await read(dir, "draft-1.patch.json")).render.chrome.deck.markers.map((x) => x.after), ["b", "a"]);
assert.deepEqual((await read(dir, "variant.patch.json")).render.chrome.deck.markers, [{ after: "a", label: "Other" }]);
assert.deepEqual(await read(dir, "plain.patch.json"), { title: "no markers" });
const r2 = await addSection(dir, "e", { label: "Four", color: "amber" });
- assert.deepEqual(r2.patches.synced, ["draft-1.patch.json"]);
+ assert.deepEqual(r2.sectionPatches.synced, ["draft-1.patch.json"]);
assert.equal((await read(dir, "draft-1.patch.json")).render.chrome.deck.markers.length, 3);
await moveSectionBoundary(dir, 1, "c");
await removeSection(dir, 2);
@@ -180,10 +180,10 @@ test("a marker past the deck's limits is refused in its words, nothing written",
}
});
-test("syncPatchMarkers keeps the patch's own indent", async () => {
+test("syncSectionPatches keeps the patch's own indent", async () => {
const dir = await project(deckCut(), { "one.patch.json": JSON.stringify(patchOf([{ after: "b" }]), null, 1) + "\n" });
try {
- await syncPatchMarkers(dir, [{ after: "b" }], [{ after: "c" }]);
+ await syncSectionPatches(dir, [{ after: "b" }], [{ after: "c" }]);
const text = await readFile(path.join(dir, "one.patch.json"), "utf8");
assert.match(text, /^\{\n "render"/);
assert.equal(JSON.parse(text).render.chrome.deck.markers[0].after, "c");
@@ -206,7 +206,7 @@ test("split keeps the section: a marker after the clip follows its second half;
assert.match(b2.citeUrl, /t=35$/);
assert.equal(b2.lockEnd, true);
assert.equal(b2.title, "Stream");
- assert.deepEqual(r.patches.synced, ["draft-1.patch.json"]);
+ assert.deepEqual(r.sectionPatches.synced, ["draft-1.patch.json"]);
} finally {
await rm(dir, { recursive: true, force: true });
}
diff --git a/umtool/lib/report/sectionPatches.mjs b/umtool/lib/report/sectionPatches.mjs
@@ -0,0 +1,74 @@
+// TAKE PATCHES KEEP THE CUT'S SECTIONS (UI notes 2026-10-30, item 1).
+//
+// A take patch the operator renders with (`umtool take … --patch
+// draft-1.patch.json`, a `*.patch.json` beside the manifest) may carry
+// `render.chrome.deck.markers` -- the sections -- and a patch's markers REPLACE
+// the manifest's. So a section edit in the manifest that leaves the patch alone
+// is undone at the next take, or refused (a marker naming a clip that is gone):
+// draft-9 of the Ember cut was refused exactly so.
+//
+// The rule here is deliberately narrow: a patch whose markers were IN STEP with
+// the manifest's before the edit (the same list, byte for byte) gets the new
+// list; a patch whose markers already differed is somebody's deliberate
+// variant, left as it is and named in the result, never rewritten by a guess.
+// A patch without markers, or with a timeline of its own (its markers name
+// ITS clips), is not touched. (Removals are lane/ui-cut-integrity's
+// patchMarkers.mjs: a marker after a clip that is gone re-anchored by name.) Each rewrite keeps the patch's
+// own indent (and a trailing newline) and goes through tmp + rename.
+import { readdir, readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+/** The indent a JSON file was written with (its first nested line), else 2: a rewrite keeps it. */
+export const indentOf = (text) => /^[[{]\r?\n( +)\S/.exec(String(text ?? ""))?.[1].length ?? 2;
+const markersOf = (doc) =>
+ isObj(doc) && doc.timeline === undefined && isObj(doc.render?.chrome?.deck) && Array.isArray(doc.render.chrome.deck.markers) ? doc.render.chrome.deck.markers : null;
+
+/** The project's take patches: every `*.patch.json` beside its manifest. */
+async function patchFilesOf(dir) {
+ const names = await readdir(dir).catch(() => []);
+ return names.filter((n) => /^[A-Za-z0-9][A-Za-z0-9._-]*\.patch\.json$/.test(n)).sort();
+}
+
+/**
+ * Bring every in-step patch's markers to `after` (the manifest's markers
+ * after the edit; [] or null: the patch's markers removed with them).
+ *
+ * @param {string} dir the project
+ * @param {unknown[] | null | undefined} before the manifest's markers before the edit
+ * @param {unknown[] | null | undefined} after the manifest's markers after it
+ * @returns {Promise<{ synced: string[], skipped: { file: string, why: string }[] }>}
+ */
+export async function syncSectionPatches(dir, before, after) {
+ const synced = [];
+ const skipped = [];
+ const was = JSON.stringify(before ?? []);
+ const now = JSON.stringify(after ?? []);
+ if (was === now) return { synced, skipped };
+ for (const name of await patchFilesOf(dir)) {
+ const file = path.join(dir, name);
+ let doc;
+ let text = "";
+ try {
+ text = await readFile(file, "utf8");
+ doc = JSON.parse(text);
+ } catch (e) {
+ skipped.push({ file: name, why: `does not parse (${e instanceof Error ? e.message : e}): not touched` });
+ continue;
+ }
+ const mine = markersOf(doc);
+ if (!mine) continue;
+ if (JSON.stringify(mine) !== was) {
+ skipped.push({ file: name, why: "its markers were not the manifest's before this edit (a deliberate variant?): left as they are" });
+ continue;
+ }
+ const deck = doc.render.chrome.deck;
+ if (Array.isArray(after) && after.length) deck.markers = JSON.parse(now);
+ else delete deck.markers;
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, JSON.stringify(doc, null, indentOf(text)) + "\n", "utf8");
+ await rename(tmp, file);
+ synced.push(name);
+ }
+ return { synced, skipped };
+}
diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs
@@ -221,6 +221,39 @@ export async function removeTakeEntry(projectDir, id, entryId, { token = null, a
return editTakeTimeline(projectDir, id, "remove", token, (m) => applyStructural(m, (x) => removeIn(x, entryId, at, { reanchor: false })), { now });
}
+/** A take's label: one line, at most this long. */
+export const TAKE_LABEL_MAX = 200;
+
+/**
+ * RELABEL a take (UI notes 2026-10-30, item 19: "draft 9…" on draft-10): its
+ * take.json `label`, with an undo point of the take's own first (`umtool
+ * timeline <p> --take <id> undo` takes it back). Refused while the take is
+ * rendering: the render writes take.json LAST, from the label it started
+ * with, and would put the old one back (takeHousekeeping.mjs renderHolds).
+ *
+ * @param {string} projectDir
+ * @param {string} id
+ * @param {string} label
+ * @param {{ token?: string | null, now?: Date, holds?: string[] }} [opts] `holds`: renderHolds's sentences
+ */
+export async function relabelTake(projectDir, id, label, { token = null, now = new Date(), holds = [] } = {}) {
+ const l = typeof label === "string" ? label.replace(/\s+/g, " ").trim() : "";
+ if (!l) throw new Error("a take's label is a few words, not nothing");
+ if (l.length > TAKE_LABEL_MAX) throw new Error(`a take's label is at most ${TAKE_LABEL_MAX} characters (this one is ${l.length})`);
+ if (holds.length) throw new Error(`take ${id} is not relabelled: ${holds.join("; ")}`);
+ return withTakeEditLock(async () => {
+ const current = await takeToken(projectDir, id);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const { text, doc } = await readTakeDoc(projectDir, id);
+ const was = typeof doc.label === "string" ? doc.label : "";
+ if (was === l) return { id, label: l, was, token: current, revision: null };
+ const revision = await keepRevision(projectDir, id, text, `${AUTO}relabel`, now);
+ doc.label = l;
+ const nextToken = await writeTakeAtomic(projectDir, id, doc);
+ return { id, label: l, was, token: nextToken, revision };
+ });
+}
+
/**
* Take back the take's newest edit: its newest `auto-before-<op>` revision
* restored over take.json, byte for byte (see the top of the file).
diff --git a/umtool/lib/report/takeHousekeeping.mjs b/umtool/lib/report/takeHousekeeping.mjs
@@ -0,0 +1,86 @@
+// TAKE HOUSEKEEPING (UI notes 2026-10-30, item 19): wrong labels ("draft 9…"
+// on draft-10), cancelled and superseded takes left in the list.
+//
+// relabel take.json's label takeEdit.mjs relabelTake
+// supersede verdicts.json's `superseded` takes.mjs setTakeSuperseded
+// delete takes/<id>/ whole delete.mjs planTakeDelete / deleteTake
+//
+// What a running render names is respected by all three, through one reader
+// (renderHolds): a take whose own build lock (`takes/<id>/.building.json`,
+// takePrune.mjs) is live is RENDERING -- its take.json is written last, from
+// the label it started with, and its directory is its output -- and a take
+// another live build names as its `from` is that build's base. A relabel or a
+// delete is refused for either, in words; a supersede mark (verdicts.json,
+// which no render writes) is not.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { readdir } from "node:fs/promises";
+import path from "node:path";
+import { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs";
+import { isTakeId, listTakes, readVerdicts, takesDirOf } from "./takes.mjs";
+
+/**
+ * Every reason a running render has to keep take `takeId` as it is: its own
+ * live build, and any live build made from it. [] when none.
+ *
+ * @param {string} projectDir
+ * @param {string} takeId
+ * @param {{ host?: string, alive?: (pid: number) => boolean }} [opts] for tests
+ * @returns {Promise<string[]>}
+ */
+export async function renderHolds(projectDir, takeId, opts = {}) {
+ if (!isTakeId(takeId)) return [];
+ const root = takesDirOf(projectDir);
+ const holds = [];
+ const live = (lock) => lockIsLive(lock, opts.host || opts.alive ? { ...(opts.host ? { host: opts.host } : {}), ...(opts.alive ? { alive: opts.alive } : {}) } : undefined);
+ const own = await readBuildLock(path.join(root, takeId, BUILD_LOCK));
+ if (own && live(own)) holds.push(`it is rendering now (pid ${own.pid}${own.startedAt ? `, since ${own.startedAt}` : ""}) — wait for it, or cancel it`);
+ const names = await readdir(root).catch(() => []);
+ for (const n of names) {
+ if (n === takeId || !isTakeId(n)) continue;
+ const lock = await readBuildLock(path.join(root, n, BUILD_LOCK));
+ if (lock && lock.from === takeId && live(lock)) holds.push(`take ${n} is being rendered from it (pid ${lock.pid})`);
+ }
+ return holds;
+}
+
+/**
+ * The takes as `umtool takes ls` prints them: id, label, built, picked,
+ * superseded (and by what), rendering now.
+ *
+ * @param {string} projectDir
+ */
+export async function takesOverview(projectDir) {
+ const [listing, verdicts] = await Promise.all([listTakes(projectDir), readVerdicts(projectDir)]);
+ const rows = [];
+ for (const t of listing.takes) {
+ const v = verdicts[t.id];
+ const holds = await renderHolds(projectDir, t.id);
+ rows.push({
+ id: t.id,
+ label: t.label,
+ group: t.group,
+ seconds: t.seconds,
+ builtAt: t.builtAt,
+ draft: t.draft,
+ verdict: v?.verdict ?? null,
+ picked: v?.picked === true,
+ superseded: v?.superseded ?? null,
+ rendering: holds.length > 0,
+ holds,
+ });
+ }
+ return { rows, skipped: listing.skipped };
+}
+
+/** One line of `umtool takes ls`. */
+export function takeLine(r) {
+ const marks = [
+ r.picked ? "picked" : null,
+ r.superseded ? `superseded${r.superseded.by ? ` by ${r.superseded.by}` : ""}` : null,
+ r.draft ? "draft" : null,
+ r.rendering ? "RENDERING" : null,
+ r.verdict,
+ ].filter(Boolean);
+ return `${r.id.padEnd(14)} ${typeof r.seconds === "number" ? `${r.seconds.toFixed(1)}s`.padStart(8) : " "} ${r.label}${marks.length ? ` [${marks.join(", ")}]` : ""}`;
+}
diff --git a/umtool/lib/report/takeHousekeeping.test.mjs b/umtool/lib/report/takeHousekeeping.test.mjs
@@ -0,0 +1,110 @@
+// Take housekeeping (takeHousekeeping.mjs, takeEdit.mjs relabelTake, takes.mjs
+// setTakeSuperseded, delete.mjs): relabel, supersede, delete -- and what a
+// running render names is respected.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os, { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { relabelTake } from "./takeEdit.mjs";
+import { listTakes, readVerdicts, setTakePicked, setTakeSuperseded, setTakeVerdict } from "./takes.mjs";
+import { renderHolds, takeLine, takesOverview } from "./takeHousekeeping.mjs";
+import { planTakeDelete } from "./delete.mjs";
+
+const take = (id, order, extra = {}) => ({ id, group: "takes", order, label: `${id} label`, kind: "different", summary: "", changes: [], preview: "preview.mp4", seconds: 10, builtAt: "2026-10-30T10:00:00.000Z", ...extra });
+
+async function project() {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-takes-hk-"));
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ timeline: [] }) + "\n");
+ for (const [id, order] of [["draft-9", 1], ["draft-10", 2], ["draft-11", 3]]) {
+ await mkdir(path.join(dir, "takes", id), { recursive: true });
+ await writeFile(path.join(dir, "takes", id, "take.json"), JSON.stringify(take(id, order, id === "draft-10" ? { label: "draft 9: wrong label" } : {}), null, 2) + "\n");
+ }
+ return dir;
+}
+const lock = (dir, id, doc) => writeFile(path.join(dir, "takes", id, ".building.json"), JSON.stringify({ host: os.hostname(), startedAt: "2026-10-31T23:00:00.000Z", take: id, ...doc }) + "\n");
+
+test("relabel writes take.json's label with an undo point, and is refused while the take renders", async () => {
+ const dir = await project();
+ try {
+ const r = await relabelTake(dir, "draft-10", " draft 10: the re-walk ");
+ assert.equal(r.label, "draft 10: the re-walk");
+ assert.equal(r.was, "draft 9: wrong label");
+ assert.ok(r.revision.rel.includes("auto-before-relabel"));
+ assert.equal(JSON.parse(await readFile(path.join(dir, "takes", "draft-10", "take.json"), "utf8")).label, "draft 10: the re-walk");
+ assert.equal((await readdir(path.join(dir, "takes", "draft-10", "revisions"))).length, 1);
+ await assert.rejects(relabelTake(dir, "draft-10", ""), /not nothing/);
+ await assert.rejects(relabelTake(dir, "draft-10", "x", { token: "1" }), /changed since/);
+ await lock(dir, "draft-10", { pid: process.pid });
+ const holds = await renderHolds(dir, "draft-10");
+ assert.equal(holds.length, 1);
+ assert.match(holds[0], /it is rendering now \(pid \d+/);
+ await assert.rejects(relabelTake(dir, "draft-10", "another", { holds }), /is not relabelled: it is rendering now/);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("renderHolds: a stale lock holds nothing; a live build made FROM a take holds it", async () => {
+ const dir = await project();
+ try {
+ await lock(dir, "draft-11", { pid: 2 ** 22 + 12345, from: "draft-9" });
+ assert.deepEqual(await renderHolds(dir, "draft-11", { alive: () => false }), []);
+ assert.deepEqual(await renderHolds(dir, "draft-9", { alive: () => false }), []);
+ assert.deepEqual(await renderHolds(dir, "draft-9", { alive: () => true }), ["take draft-11 is being rendered from it (pid 4206649)"]);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a take rendering, or the base of one, is not deleted", async () => {
+ const dir = await project();
+ try {
+ await lock(dir, "draft-11", { pid: process.pid, from: "draft-10" });
+ const ctx = { reportsRoot: path.dirname(dir), mediaRoot: path.dirname(dir) };
+ const p11 = await planTakeDelete({ id: path.basename(dir), dir }, "draft-11", ctx);
+ assert.ok(p11.refusals.some((r) => /draft-11: it is rendering now/.test(r.reason) && r.forceable === false));
+ const p10 = await planTakeDelete({ id: path.basename(dir), dir }, "draft-10", ctx);
+ assert.ok(p10.refusals.some((r) => /draft-11 is being rendered from it/.test(r.reason)));
+ const p9 = await planTakeDelete({ id: path.basename(dir), dir }, "draft-9", ctx);
+ assert.ok(!p9.refusals.some((r) => /render/.test(r.reason)));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("supersede: a mark in verdicts.json beside the verdict, cleared, never on the picked take", async () => {
+ const dir = await project();
+ try {
+ await setTakeVerdict(dir, "draft-9", { verdict: "maybe", note: "fine" });
+ await setTakeSuperseded(dir, "draft-9", { by: "draft-11", known: ["draft-9", "draft-10", "draft-11"] });
+ let v = await readVerdicts(dir);
+ assert.equal(v["draft-9"].superseded.by, "draft-11");
+ assert.equal(v["draft-9"].verdict, "maybe", "the verdict and note are kept");
+ // A verdict saved later keeps the mark.
+ await setTakeVerdict(dir, "draft-9", { note: "still fine" });
+ assert.equal((await readVerdicts(dir))["draft-9"].superseded.by, "draft-11");
+ await setTakeSuperseded(dir, "draft-10", {});
+ assert.deepEqual(Object.keys((await readVerdicts(dir))["draft-10"].superseded), ["by", "at"]);
+ await assert.rejects(setTakeSuperseded(dir, "draft-10", { by: "draft-10" }), /by itself/);
+ await assert.rejects(setTakeSuperseded(dir, "draft-10", { by: "draft-99", known: ["draft-9", "draft-10"] }), /no take draft-99/);
+ await setTakeSuperseded(dir, "draft-10", { clear: true });
+ assert.equal((await readVerdicts(dir))["draft-10"], undefined, "a row that says nothing is removed");
+ await setTakePicked(dir, "draft-11", ["draft-9", "draft-10", "draft-11"]);
+ await assert.rejects(setTakeSuperseded(dir, "draft-11", {}), /picked take/);
+ // Picking a superseded take clears its mark.
+ await setTakePicked(dir, "draft-9", ["draft-9", "draft-10", "draft-11"]);
+ v = await readVerdicts(dir);
+ assert.equal(v["draft-9"].superseded, undefined);
+ assert.equal(v["draft-9"].picked, true);
+ const { rows } = await takesOverview(dir);
+ assert.deepEqual(rows.map((r) => r.id), ["draft-9", "draft-10", "draft-11"]);
+ assert.match(takeLine(rows[0]), /draft-9 .*\[picked, maybe\]/);
+ assert.equal((await listTakes(dir)).takes.length, 3, "nothing deleted");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/takes.mjs b/umtool/lib/report/takes.mjs
@@ -277,12 +277,20 @@ function cleanVerdicts(raw) {
const note = typeof row.note === "string" ? row.note : "";
const at = typeof row.at === "string" ? row.at : "";
out[id] = row.picked === true ? { verdict, note, at, picked: true } : { verdict, note, at };
+ const sup = supersededOf(row.superseded);
+ if (sup) out[id].superseded = sup;
}
return out;
}
-/** A row that says nothing: no verdict, no note, not picked. */
-const emptyRow = (row) => row.verdict === null && !row.note && row.picked !== true;
+/** `superseded` as stored: `{ by: <take id> | null, at }`, else null. */
+function supersededOf(v) {
+ if (!v || typeof v !== "object" || Array.isArray(v)) return null;
+ return { by: isTakeId(v.by) ? v.by : null, at: typeof v.at === "string" ? v.at : "" };
+}
+
+/** A row that says nothing: no verdict, no note, not picked, not superseded. */
+const emptyRow = (row) => row.verdict === null && !row.note && row.picked !== true && !row.superseded;
/**
* Read verdicts.json for a write: `{}` when absent, an ERROR when present and
@@ -312,7 +320,7 @@ async function writeVerdicts(file, map) {
/**
* @param {string} projectDir
- * @returns {Promise<Record<string, { verdict: "like" | "maybe" | "no" | null, note: string, at: string, picked?: true }>>}
+ * @returns {Promise<Record<string, { verdict: "like" | "maybe" | "no" | null, note: string, at: string, picked?: true, superseded?: { by: string | null, at: string } }>>}
*/
export async function readVerdicts(projectDir) {
try {
@@ -351,6 +359,7 @@ export async function setTakeVerdict(projectDir, takeId, patch) {
at: new Date().toISOString(),
};
if (prev.picked === true) row.picked = true;
+ if (prev.superseded) row.superseded = prev.superseded;
if (emptyRow(row)) delete map[takeId];
else map[takeId] = row;
await writeVerdicts(file, map);
@@ -381,6 +390,7 @@ export async function setTakePicked(projectDir, takeId, group, { now = new Date(
else map[id] = rest;
}
const prev = map[takeId] ?? { verdict: null, note: "", at: "" };
+ // A take picked is not superseded any more.
map[takeId] = { verdict: prev.verdict, note: prev.note, at: now.toISOString(), picked: true };
await writeVerdicts(file, map);
return { entry: map[takeId], verdicts: map };
@@ -388,6 +398,42 @@ export async function setTakePicked(projectDir, takeId, group, { now = new Date(
}
/**
+ * Mark take `takeId` SUPERSEDED (UI notes 2026-10-30, item 19) -- by take
+ * `by` when one is named -- or clear the mark (`clear: true`). The operator's
+ * judgement, so it lives in verdicts.json beside the verdict and the pick (a
+ * rebuild rewrites take.json; it never touches this). A superseded take is
+ * folded away in the takes list and named in `umtool takes ls`; nothing is
+ * deleted. Picking a take clears its mark.
+ *
+ * @param {string} projectDir
+ * @param {string} takeId
+ * @param {{ by?: string | null, clear?: boolean, known?: string[] | null, now?: Date }} [opts]
+ * `known`: the project's take ids, to refuse a `by` that is not one of them
+ */
+export async function setTakeSuperseded(projectDir, takeId, { by = null, clear = false, known = null, now = new Date() } = {}) {
+ if (!isTakeId(takeId)) throw new Error("not a take id");
+ if (by !== null && !isTakeId(by)) throw new Error(`"${by}" is not a take id`);
+ if (by === takeId) throw new Error(`a take is not superseded by itself`);
+ if (by !== null && known && !known.includes(by)) throw new Error(`no take ${by} in this project`);
+ const file = verdictsFileOf(projectDir);
+ return withTakesLock(async () => {
+ const map = await readVerdictsForWrite(file);
+ const prev = map[takeId] ?? { verdict: null, note: "", at: "" };
+ /** @type {Record<string, any>} */
+ const row = { ...prev, at: now.toISOString() };
+ if (clear) delete row.superseded;
+ else {
+ if (prev.picked === true) throw new Error(`${takeId} is the picked take of its group — pick another first`);
+ row.superseded = { by, at: now.toISOString() };
+ }
+ if (emptyRow(row)) delete map[takeId];
+ else map[takeId] = row;
+ await writeVerdicts(file, map);
+ return { entry: map[takeId] ?? null, verdicts: map };
+ });
+}
+
+/**
* Every take with its verdict, for an agent reading the conversation back
* (`umtool notes`, the notes digest): label, group, summary and changes from
* take.json, and the operator's verdict and note from verdicts.json. A verdict
@@ -409,6 +455,7 @@ export async function takesWithVerdicts(projectDir) {
note: verdicts[t.id]?.note ?? "",
at: verdicts[t.id]?.at ?? "",
...(verdicts[t.id]?.picked ? { picked: /** @type {const} */ (true) } : {}),
+ ...(verdicts[t.id]?.superseded ? { superseded: verdicts[t.id].superseded } : {}),
}));
const known = new Set(out.map((t) => t.id));
for (const [id, v] of Object.entries(verdicts)) {
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -17,6 +17,12 @@
// umtool timeline <project> post <json|@file> | post-remove <id>
// umtool timeline <project> teaser <id> <patch-json|@file>
// umtool timeline <project> undo
+// umtool timeline <project> sections | section-move <id…> --to-section N [--start]
+// | section-add --after <id> [--label L] [--color C] | section-boundary <k> --after <id>
+// | section-remove <k> | section-set <k> [--label L] [--color C]
+// umtool timeline <project> split <id> <second>
+// umtool timeline <project> flash-forward <id> <from>-<to> (--after <id|-> | --to-section N [--start])
+// [--move] [--quote Q] [--id ID]
//
// An insert's attribution (--title, --date, --quote, --cite, --cite-url) is a
// second write, through updateClip -- the writer `umtool window` and the
@@ -51,8 +57,14 @@ import {
insertEntry,
manifestToken,
moveEntry,
+ moveSectionBoundary,
+ moveToSection,
+ addSection,
removeEntry,
+ removeSection,
rejectClip,
+ sectionsOf,
+ updateSection,
removeWrongSpeaker,
REMOVED_FILE,
removePost,
@@ -83,6 +95,17 @@ export const TIMELINE_USAGE = [
" umtool timeline <project> post-remove <id>",
" umtool timeline <project> teaser <id> <patch-json|@file> lines, beat, dip, tail, tailWait (null removes one)",
" umtool timeline <project> undo restore the newest automatic snapshot",
+ " umtool timeline <project> sections [--json] the deck's sections: §, label, colour, its marker, its clips",
+ " umtool timeline <project> section-move <id> [<id>…] --to-section N [--start]",
+ " clips to the end (--start: the start) of section N, every marker following",
+ " umtool timeline <project> section-add --after <id> [--label L] [--color C] new section after the clip",
+ " umtool timeline <project> section-boundary <marker> --after <id> drag a boundary (between its neighbours)",
+ " umtool timeline <project> section-remove <marker> | section-set <marker> [--label L] [--color C]",
+ " every section op brings the take patches' markers (*.patch.json in step with the manifest) along",
+ " umtool timeline <project> split <id> <second> two clips at that source second (each half's quote from the words)",
+ " umtool timeline <project> flash-forward <id> <from>-<to> (--after <id|-> | --to-section N [--start])",
+ " [--move] [--quote Q] [--id ID] a tight copy of the span elsewhere, with the clip's attribution",
+ " and locks, as repeatOf the clip (--move: the span leaves the clip, which keeps the rest)",
" umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo]",
" a take's timeline (walk a take): written into the take's patch (takes/<id>/take.json),",
" each write with an undo point of the take's own; the project's manifest is untouched",
@@ -91,8 +114,9 @@ export const TIMELINE_USAGE = [
"validators, and on a generated manifest leaves an `edit` note for its generator. The Cut tab's timeline.",
].join("\n");
-const VERBS = ["ls", "insert", "move", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo"];
-const VALUED = new Set(["--after", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note"]);
+const SECTION_VERBS = ["sections", "section-move", "section-add", "section-boundary", "section-remove", "section-set"];
+const VERBS = ["ls", "insert", "move", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward"];
+const VALUED = new Set(["--after", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color"]);
/** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */
const TAKE_VERBS = ["ls", "move", "remove", "undo"];
@@ -338,6 +362,17 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
const manifest = await readManifest(project.dir);
if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ if (verb === "sections") {
+ const sections = sectionsOf(manifest);
+ if (json) {
+ out(JSON.stringify({ project: project.id, token: await manifestToken(project.dir), sections }, null, 2));
+ return 0;
+ }
+ if (!deckOn(manifest.render)) throw new CliError(`${project.id} has no on-screen deck: its sections are not markers`);
+ for (const line of sectionLines(sections)) out(line);
+ return 0;
+ }
+
if (verb === "ls") {
const rows = timelineRows(manifest);
if (json) {
@@ -461,6 +496,67 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
({ result, editNotes } = await write((token) => undoStructural(project.dir, { token })));
break;
}
+ case "section-move": {
+ if (!rest.length) throw new CliError("section-move needs one or more clip ids");
+ const section = intFlag(flags, "--to-section");
+ if (section === null) throw new CliError("section-move needs --to-section N (`umtool timeline <project> sections` lists them)");
+ ({ result, editNotes } = await write((token) => moveToSection(project.dir, rest, section, { token, position: flags.has("--start") ? "start" : "end" })));
+ break;
+ }
+ case "section-add": {
+ const after = flags.get("--after");
+ if (typeof after !== "string" || !after) throw new CliError("section-add needs --after <clip id>");
+ const str = (k) => (typeof flags.get(k) === "string" ? String(flags.get(k)) : null);
+ ({ result, editNotes } = await write((token) => addSection(project.dir, after, { label: str("--label"), color: str("--color") }, { token })));
+ break;
+ }
+ case "section-boundary": {
+ const marker = Number(need(rest[0], "a marker's number (`sections` lists them)"));
+ const after = flags.get("--after");
+ if (typeof after !== "string" || !after) throw new CliError("section-boundary needs --after <clip id>");
+ ({ result, editNotes } = await write((token) => moveSectionBoundary(project.dir, marker, after, { token })));
+ break;
+ }
+ case "section-remove": {
+ const marker = Number(need(rest[0], "a marker's number (`sections` lists them)"));
+ ({ result, editNotes } = await write((token) => removeSection(project.dir, marker, { token })));
+ break;
+ }
+ case "section-set": {
+ const marker = Number(need(rest[0], "a marker's number (`sections` lists them)"));
+ const patch = Object.fromEntries([["--label", "label"], ["--color", "color"]].filter(([f]) => flags.has(f)).map(([f, k]) => [k, flags.get(f) === true ? "" : flags.get(f)]));
+ ({ result, editNotes } = await write((token) => updateSection(project.dir, marker, patch, { token })));
+ break;
+ }
+ case "split": {
+ const id = need(rest[0], "a clip id");
+ const second = Number(need(rest[1], "the source second to split at"));
+ if (!Number.isFinite(second)) throw new CliError("split <id> <second>: the second is a number");
+ const { runClipEditorOp } = await import("./clipEditor.mjs");
+ ({ result, editNotes } = await write(async (token) => (await runClipEditorOp(project, { op: "split", clip: id, at: second, token })).result));
+ break;
+ }
+ case "flash-forward": {
+ const id = need(rest[0], "a clip id");
+ const span = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(need(rest[1], "the span: <from>-<to> in source seconds"));
+ if (!span) throw new CliError("flash-forward <id> <from>-<to>: source seconds, e.g. 3343.6-3356.3");
+ const section = intFlag(flags, "--to-section");
+ if (section === null && !flags.has("--after")) throw new CliError("flash-forward needs --after <id> (`-`: the start) or --to-section N");
+ const afterArg = flags.has("--after") ? String(flags.get("--after")) : null;
+ const body = {
+ op: "flash-forward",
+ clip: id,
+ from: Number(span[1]),
+ to: Number(span[2]),
+ ...(section !== null ? { section, position: flags.has("--start") ? "start" : "end" } : { after: afterArg === "-" ? null : afterArg }),
+ move: flags.has("--move"),
+ ...(typeof flags.get("--quote") === "string" ? { quote: flags.get("--quote") } : {}),
+ ...(typeof flags.get("--id") === "string" ? { id: flags.get("--id") } : {}),
+ };
+ const { runClipEditorOp } = await import("./clipEditor.mjs");
+ ({ result, editNotes } = await write(async (token) => (await runClipEditorOp(project, { ...body, token })).result));
+ break;
+ }
}
if (json) {
@@ -474,6 +570,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
for (const line of p.notes ?? []) out(` ${p.file}: ${line}`);
if (p.error) out(` ${p.file}: ${p.error}`);
}
+ for (const f of result.sectionPatches?.synced ?? []) out(` patch markers synced: ${f}`);
+ for (const f of result.sectionPatches?.skipped ?? []) out(` patch NOT synced: ${f.file} — ${f.why}`);
if (result.record) out(` on record: ${REMOVED_FILE} (${result.record.reason}${result.record.correction ? `: ${result.record.correction}` : ""}${result.record.note ? `: ${result.record.note}` : ""})`);
if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel}`);
else if (result.snapshot?.error) out(` NO undo point: ${result.snapshot.error}`);
@@ -544,8 +642,30 @@ async function takeTimeline(project, take, verb, rest, flags, { out, json }) {
return 0;
}
+/** `sections`, one line each: §, its marker, colour, label, its clips. */
+export function sectionLines(sections) {
+ return sections.map((s) => {
+ const clips = s.clips.length > 6 ? `${s.clips.slice(0, 3).join(" ")} … ${s.clips.slice(-2).join(" ")}` : s.clips.join(" ");
+ return `§${String(s.index).padEnd(3)} ${s.marker === null ? " " : `m${String(s.marker).padEnd(4)} `} ${String(s.color ?? "").padEnd(8)} ${(s.label ?? (s.index === 0 ? "(the opening)" : "(no label)")).padEnd(26)} ${String(s.clips.length).padStart(3)} clip(s): ${clips}`;
+ });
+}
+
function summaryOf(verb, r, attribution) {
switch (verb) {
+ case "section-move":
+ return `moved ${r.ids.join(", ")} to the ${r.position} of §${r.section}${r.label ? ` (${r.label})` : ""}`;
+ case "section-add":
+ return `new section after ${r.after} (marker ${r.marker}${r.label ? `, "${r.label}"` : ""}${r.color ? `, ${r.color}` : ""}): it opens on ${r.opens}`;
+ case "section-boundary":
+ return `marker ${r.marker} follows ${r.after} now (was ${r.from})${r.moved.length ? `: ${r.moved.join(", ")} now in ${r.into}` : ""}`;
+ case "section-remove":
+ return `removed marker ${r.marker}${r.removed?.label ? ` ("${r.removed.label}")` : ""}: its section joins the one before it`;
+ case "section-set":
+ return `marker ${r.marker}: ${JSON.stringify(r.entry)}`;
+ case "split":
+ return `split: ${r.id} | ${r.second}`;
+ case "flash-forward":
+ return `${r.move ? "moved" : "copied"} ${r.source}'s span to ${r.id} at ${r.at}${r.section ? ` (§${r.section.index}${r.section.label ? ` ${r.section.label}` : ""})` : ""}${r.move && r.rest ? `; ${r.source} keeps ${r.rest.start}–${r.rest.end}` : r.move ? "" : ` (repeatOf ${r.source})`}`;
case "insert": {
const e = attribution ?? r.entry;
const head = `inserted ${r.id} at ${r.at}: ${e.channel ? `${e.channel}/` : ""}${e.video}@${e.start}-${e.end}`;
diff --git a/umtool/lib/report/trailerBeats.mjs b/umtool/lib/report/trailerBeats.mjs
@@ -0,0 +1,418 @@
+// THE TRAILER'S BEATS, edited (UI notes 2026-10-30, item 11).
+//
+// `umtool trailer <p> --take <t> --beats promo/trailer-beats.json` cuts a
+// trailer out of a finished master (report-to-video/trailer.mjs). The beats
+// file was hand JSON: beats went stale after tightening (five fell outside
+// their clips on the Ember cut), the X limit (under 2:20) was checked after the
+// encode, and putting the beats in the cut's order needed a script.
+//
+// This is that file's ONE writer -- the Trailer page and `umtool trailer-beats`
+// both go through it -- and its reader, which says, before any encode:
+// - each beat's length (a clip beat's gaps taken out, as the master plays it)
+// and the running length against the platform limit, with the trailer's
+// crossfades and the brand intro counted;
+// - each beat that falls outside its clip's window, or names a clip that is
+// no longer in the cut;
+// - whether the beats are in the cut's order (Order by the cut puts them so).
+//
+// The file keeps its shape: a plain array stays an array (what `--beats` has
+// always read) until a setting is saved, when it becomes `{ limit, xfade,
+// intro, beats }` -- parseBeats reads `{ beats }` too. Its indent is kept. A
+// file that does not parse is never written over. The token is its mtime.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { copyFile, mkdir, readFile, readdir, rename, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { gappedLength, gapsOf } from "umtool-report-to-video/gaps";
+import { TRAILER_XFADE_DEFAULT, TrailerError, parseBeats } from "umtool-report-to-video/trailer";
+import { indentOf } from "./sectionPatches.mjs";
+import { sectionModel, sectionWords } from "./sectionEdit.mjs";
+
+export const TRAILER_BEATS_FILE = path.join("promo", "trailer-beats.json");
+/** X's video limit is 2:20; a trailer must be UNDER it. */
+export const TRAILER_LIMIT_DEFAULT = 140;
+/** Platform limits a person picks from (seconds). */
+export const TRAILER_LIMITS = Object.freeze([
+ { id: "x", label: "X (2:20)", seconds: 140 },
+ { id: "instagram", label: "Instagram reel (1:30)", seconds: 90 },
+ { id: "shorts", label: "YouTube Short (3:00)", seconds: 180 },
+ { id: "tiktok", label: "TikTok (10:00)", seconds: 600 },
+]);
+/** A beat edge this close to its clip's edge is on it (the build records keep 3 dp). */
+const EPS = 0.02;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const r2 = (n) => Number(Number(n).toFixed(2));
+
+export class BeatsStale extends Error {
+ constructor(expected, got) {
+ super(`the trailer's beats changed since you read them (${got} vs ${expected})`);
+ this.name = "BeatsStale";
+ this.stale = true;
+ }
+}
+
+const beatsFile = (dir) => path.join(dir, TRAILER_BEATS_FILE);
+
+/** The file's mtime, the token a writer hands back; null when there is no file. */
+export async function beatsToken(dir) {
+ const st = await stat(beatsFile(dir)).catch(() => null);
+ return st ? String(Math.round(st.mtimeMs)) : null;
+}
+
+/**
+ * The beats file, read: `{ exists, shape, beats, settings, indent }`. Missing:
+ * an empty array. Not JSON, or neither an array nor `{ beats }`: an error,
+ * so nothing writes over it.
+ *
+ * @param {string} dir
+ */
+export async function readTrailerBeats(dir) {
+ let text;
+ try {
+ text = await readFile(beatsFile(dir), "utf8");
+ } catch {
+ return { exists: false, shape: /** @type {"array" | "object"} */ ("array"), beats: [], settings: {}, indent: 1, token: null };
+ }
+ let doc;
+ try {
+ doc = JSON.parse(text);
+ } catch (e) {
+ throw new Error(`${TRAILER_BEATS_FILE} does not parse; not reading or writing it (${e instanceof Error ? e.message : e})`);
+ }
+ const beats = Array.isArray(doc) ? doc : Array.isArray(doc?.beats) ? doc.beats : null;
+ if (!beats) throw new Error(`${TRAILER_BEATS_FILE} is neither a list of beats nor { "beats": [...] }`);
+ const settings = {};
+ if (isObj(doc)) {
+ if (typeof doc.limit === "number") settings.limit = doc.limit;
+ if (typeof doc.xfade === "number") settings.xfade = doc.xfade;
+ if (typeof doc.intro === "boolean") settings.intro = doc.intro;
+ }
+ return { exists: true, shape: /** @type {"array" | "object"} */ (Array.isArray(doc) ? "array" : "object"), beats, settings, indent: indentOf(text), token: await beatsToken(dir), doc };
+}
+
+/** @type {Promise<unknown>} */
+let queue = Promise.resolve();
+function withBeatsLock(fn) {
+ const run = queue.then(fn, fn);
+ queue = run.then(() => undefined, () => undefined);
+ return run;
+}
+
+/**
+ * One write: the token, the file re-read inside the lock, `mutate(beats,
+ * settings)` (which throws to refuse), every beat checked by the trailer's own
+ * parseBeats, a `.bak` of the file as it was, then tmp + rename.
+ */
+async function beatsWrite(dir, token, mutate) {
+ return withBeatsLock(async () => {
+ const current = await beatsToken(dir);
+ if (token !== null && token !== undefined && current !== token) throw new BeatsStale(token, current);
+ const read = await readTrailerBeats(dir);
+ const beats = JSON.parse(JSON.stringify(read.beats));
+ const settings = { ...read.settings };
+ const result = mutate(beats, settings);
+ if (beats.length) {
+ try {
+ parseBeats(beats);
+ } catch (e) {
+ throw new Error(e instanceof TrailerError ? e.message : String(e));
+ }
+ }
+ const hasSettings = Object.keys(settings).length > 0;
+ const out = read.shape === "array" && !hasSettings ? beats : { ...(isObj(read.doc) ? read.doc : {}), ...settings, beats };
+ if (isObj(out)) for (const k of ["limit", "xfade", "intro"]) if (!(k in settings)) delete out[k];
+ const file = beatsFile(dir);
+ await mkdir(path.dirname(file), { recursive: true });
+ if (read.exists) await copyFile(file, `${file}.bak`).catch(() => {});
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, JSON.stringify(out, null, read.indent) + "\n", "utf8");
+ await rename(tmp, file);
+ return { ...result, beats, settings, token: await beatsToken(dir) };
+ });
+}
+
+/** A beat as a person writes it: `{ id, start, end, label? }` or `{ at, dur, label? }`, rounded to 2 dp. */
+function cleanBeat(b) {
+ if (!isObj(b)) throw new Error("a beat is { id, start, end } or { at, dur }");
+ const label = typeof b.label === "string" && b.label.trim() ? { label: b.label.trim().slice(0, 120) } : {};
+ if (b.id !== undefined) return { id: String(b.id), start: r2(b.start), end: r2(b.end), ...label };
+ return { at: r2(b.at), dur: r2(b.dur), ...label };
+}
+
+const indexIn = (beats, i, what = "beat") => {
+ const n = Number(i);
+ if (!Number.isInteger(n) || n < 0 || n >= beats.length) throw new Error(`no ${what} ${Number(i) + 1} (1–${beats.length})`);
+ return n;
+};
+
+/**
+ * Add a beat at index `at` (default: where the cut's order puts it, else the end).
+ * @param {string} dir
+ * @param {Record<string, unknown>} beat
+ * @param {{ token?: string | null, at?: number | null, manifest?: Record<string, any> | null }} [opts]
+ */
+export async function addTrailerBeat(dir, beat, { token = null, at = null, manifest = null } = {}) {
+ return beatsWrite(dir, token, (beats) => {
+ const b = cleanBeat(beat);
+ let i = beats.length;
+ if (at !== null && at !== undefined) {
+ i = Number(at);
+ if (!Number.isInteger(i) || i < 0 || i > beats.length) throw new Error(`at must be 0–${beats.length}`);
+ } else if (manifest && b.id !== undefined) {
+ // In the cut's order: before the first beat whose clip comes later.
+ const order = cutOrder(manifest);
+ const mine = order.get(b.id);
+ if (mine !== undefined) {
+ const k = beats.findIndex((x) => x.id !== undefined && (order.get(x.id) ?? -1) > mine);
+ if (k >= 0) i = k;
+ }
+ }
+ beats.splice(i, 0, b);
+ return { index: i, beat: b };
+ });
+}
+
+/** Change beat `i`'s seconds or label (a key given as null removes a label). */
+export async function updateTrailerBeat(dir, i, patch, { token = null } = {}) {
+ return beatsWrite(dir, token, (beats) => {
+ const n = indexIn(beats, i);
+ if (!isObj(patch)) throw new Error("a beat patch is { start?, end?, at?, dur?, label? }");
+ const b = { ...beats[n] };
+ for (const k of ["start", "end", "at", "dur"]) if (patch[k] !== undefined) b[k] = patch[k];
+ if (patch.label !== undefined) {
+ if (patch.label === null || patch.label === "") delete b.label;
+ else b.label = patch.label;
+ }
+ beats[n] = cleanBeat(b);
+ return { index: n, beat: beats[n] };
+ });
+}
+
+/** Remove beat `i`. */
+export async function removeTrailerBeat(dir, i, { token = null } = {}) {
+ return beatsWrite(dir, token, (beats) => {
+ const n = indexIn(beats, i);
+ const [gone] = beats.splice(n, 1);
+ return { index: n, removed: gone };
+ });
+}
+
+/** Move beat `i` to index `to` (its place after the move). */
+export async function moveTrailerBeat(dir, i, to, { token = null } = {}) {
+ return beatsWrite(dir, token, (beats) => {
+ const n = indexIn(beats, i);
+ const t = Number(to);
+ if (!Number.isInteger(t) || t < 0 || t >= beats.length) throw new Error(`to must be 1–${beats.length}`);
+ const [b] = beats.splice(n, 1);
+ beats.splice(t, 0, b);
+ return { from: n, to: t };
+ });
+}
+
+/**
+ * Order the beats as the cut plays them: clip beats by their clip's place in
+ * the timeline (then by start), a raw `{ at, dur }` beat by its master second
+ * among them as best it can -- kept after the clip beat before it. A beat
+ * naming a clip no longer in the cut goes last, and is still flagged.
+ */
+export async function orderTrailerBeats(dir, manifest, { token = null } = {}) {
+ return beatsWrite(dir, token, (beats) => {
+ const order = cutOrder(manifest);
+ const keyed = beats.map((b, k) => ({ b, k, key: b.id !== undefined ? order.get(b.id) ?? Infinity : null }));
+ // A raw beat keeps its neighbour: it takes the key of the clip beat before it.
+ let last = -1;
+ for (const x of keyed) {
+ if (x.key === null) x.key = last;
+ else if (Number.isFinite(x.key)) last = x.key;
+ }
+ keyed.sort((a, b) => a.key - b.key || (a.b.id !== undefined && b.b.id !== undefined && a.b.id === b.b.id ? a.b.start - b.b.start : a.k - b.k));
+ const moved = keyed.some((x, i) => x.k !== i);
+ beats.splice(0, beats.length, ...keyed.map((x) => x.b));
+ return { moved };
+ });
+}
+
+/**
+ * The trailer's settings: `limit` (seconds, the platform's), `xfade` (the
+ * trailer's crossfade), `intro` (opens on the brand intro). null removes one
+ * (its default again).
+ */
+export async function setTrailerSettings(dir, patch, { token = null } = {}) {
+ return beatsWrite(dir, token, (_beats, settings) => {
+ if (!isObj(patch)) throw new Error("settings are { limit?, xfade?, intro? }");
+ for (const k of ["limit", "xfade"]) {
+ if (patch[k] === undefined) continue;
+ if (patch[k] === null || patch[k] === "") {
+ delete settings[k];
+ continue;
+ }
+ const v = Number(patch[k]);
+ if (!Number.isFinite(v) || v < 0 || (k === "limit" && v < 5) || (k === "xfade" && v > 3)) {
+ throw new Error(k === "limit" ? "limit is the platform's limit in seconds (5 or more)" : "xfade is the crossfade in seconds (0–3)");
+ }
+ settings[k] = r2(v);
+ }
+ if (patch.intro !== undefined) {
+ if (patch.intro === null) delete settings.intro;
+ else settings.intro = patch.intro === true;
+ }
+ return {};
+ });
+}
+
+/** Clip id → its place among the cut's clips. */
+function cutOrder(manifest) {
+ const order = new Map();
+ let n = 0;
+ for (const e of manifest?.timeline ?? []) {
+ if (e?.type !== "clip") continue;
+ if (!order.has(e.id)) order.set(e.id, n);
+ n += 1;
+ }
+ return order;
+}
+
+/** "m:ss.s" */
+export function clockOf(s) {
+ if (!Number.isFinite(s)) return "—";
+ const neg = s < 0;
+ const a = Math.abs(s);
+ const m = Math.floor(a / 60);
+ const r = a - m * 60;
+ return `${neg ? "−" : ""}${m}:${r < 10 ? "0" : ""}${r.toFixed(1)}`;
+}
+
+/**
+ * The beats against the cut, before any encode. Pure.
+ *
+ * @param {Record<string, any>} manifest the project's manifest
+ * @param {{ beats: any[], settings?: Record<string, any> }} doc readTrailerBeats's
+ * @param {{ introSeconds?: number | null }} [opts] the brand intro's length in a built take, when known
+ */
+export function trailerView(manifest, doc, { introSeconds = null } = {}) {
+ const settings = doc.settings ?? {};
+ const limit = typeof settings.limit === "number" ? settings.limit : TRAILER_LIMIT_DEFAULT;
+ const xfade = typeof settings.xfade === "number" ? settings.xfade : TRAILER_XFADE_DEFAULT;
+ const intro = settings.intro === true;
+ const tl = manifest?.timeline ?? [];
+ const order = cutOrder(manifest);
+ const model = sectionModel(manifest);
+ let sum = intro && Number.isFinite(introSeconds) ? Number(introSeconds) : 0;
+ let pieces = intro ? 1 : 0;
+ let lastKey = -1;
+ let inOrder = true;
+ const rows = (doc.beats ?? []).map((raw, i) => {
+ const problems = [];
+ let kind = "raw";
+ let seconds = 0;
+ let clip = null;
+ if (isObj(raw) && raw.id !== undefined) {
+ kind = "clip";
+ const e = tl.find((x) => x?.id === raw.id);
+ const span = Number(raw.end) - Number(raw.start);
+ if (!e) {
+ problems.push(`${raw.id} is not in the cut any more`);
+ seconds = Math.max(0, span);
+ } else if (e.type !== "clip") {
+ problems.push(`${raw.id} is a ${e.type ?? "non-clip"} entry: use { at, dur } for it`);
+ seconds = Math.max(0, span);
+ } else {
+ const lo = e.cutStart ?? e.start;
+ const hi = e.cutEnd ?? e.end;
+ if (raw.start < lo - EPS) problems.push(`starts ${(lo - raw.start).toFixed(2)} s before ${raw.id}'s window (${lo}–${hi})`);
+ if (raw.end > hi + EPS) problems.push(`ends ${(raw.end - hi).toFixed(2)} s after ${raw.id}'s window (${lo}–${hi})`);
+ const a = Math.max(raw.start, lo);
+ const b = Math.min(raw.end, hi);
+ seconds = b > a ? gappedLength(a, b, gapsOf(e)) : 0;
+ const k = order.get(raw.id);
+ if (k < lastKey) inOrder = false;
+ lastKey = Math.max(lastKey, k);
+ const sec = model.sections[model.sectionOf.get(raw.id) ?? 0];
+ clip = { start: lo, end: hi, at: k, section: model.sections.length > 1 && sec ? sectionWords(sec) : null, quote: typeof e.quote === "string" ? e.quote : null };
+ }
+ if (!(span > 0)) problems.push(`end ${raw.end} is not after start ${raw.start}`);
+ } else if (isObj(raw)) {
+ seconds = Math.max(0, Number(raw.dur) || 0);
+ }
+ pieces += 1;
+ sum += seconds;
+ const running = sum - xfade * Math.max(0, pieces - 1);
+ return {
+ n: i + 1,
+ kind,
+ ...(kind === "clip" ? { id: String(raw.id), start: raw.start, end: raw.end } : { at: raw?.at, dur: raw?.dur }),
+ label: typeof raw?.label === "string" ? raw.label : null,
+ seconds: r2(seconds),
+ running: r2(running),
+ over: running > limit,
+ clip,
+ problems,
+ };
+ });
+ const total = r2(sum - xfade * Math.max(0, pieces - 1));
+ return {
+ file: TRAILER_BEATS_FILE,
+ limit,
+ xfade,
+ intro,
+ introSeconds: intro ? (Number.isFinite(introSeconds) ? Number(introSeconds) : null) : null,
+ total,
+ remaining: r2(limit - total),
+ over: total >= limit,
+ inOrder,
+ outside: rows.filter((r) => r.problems.length).length,
+ rows,
+ };
+}
+
+/**
+ * The brand intro's length, from the newest built take whose schedule has
+ * one (`takes/<id>/out/sourced/schedule.json`, a segment of type "intro"),
+ * else null.
+ *
+ * @param {string} dir
+ * @returns {Promise<number | null>}
+ */
+export async function introSecondsOf(dir) {
+ const takes = path.join(dir, "takes");
+ const names = await readdir(takes).catch(() => []);
+ let best = null;
+ for (const n of names) {
+ const f = path.join(takes, n, "out", "sourced", "schedule.json");
+ const st = await stat(f).catch(() => null);
+ if (!st || (best && best.mtime >= st.mtimeMs)) continue;
+ try {
+ const s = JSON.parse(await readFile(f, "utf8"));
+ const seg = (s.segments ?? []).find((x) => x?.type === "intro" || x?.id === "brand-intro");
+ if (!seg) continue;
+ const len = Number.isFinite(seg.duration) ? seg.duration : Number.isFinite(seg.end) ? seg.end - seg.start : null;
+ if (Number.isFinite(len)) best = { mtime: st.mtimeMs, len };
+ } catch {
+ // a schedule that does not read says nothing about the intro
+ }
+ }
+ return best ? r2(best.len) : null;
+}
+
+/**
+ * The walk's ★ favourites not yet beats: the trailer's candidates. A starred
+ * clip (`star: true`, lane/ui-cut-integrity's walk ★) that will play, as a beat
+ * over what it plays (its cut, else its window).
+ *
+ * @param {Record<string, any>} manifest
+ * @param {any[]} beats
+ */
+export function trailerCandidatesOf(manifest, beats = []) {
+ const used = new Set(beats.filter((b) => isObj(b) && b.id !== undefined).map((b) => b.id));
+ const out = [];
+ for (const e of manifest?.timeline ?? []) {
+ if (e?.type !== "clip" || e.star !== true || used.has(e.id)) continue;
+ if (e.verdict === "incorrect" || e.verdict === "rejected") continue;
+ const start = e.cutStart ?? e.start;
+ const end = e.cutEnd ?? e.end;
+ if (!(end > start)) continue;
+ out.push({ id: String(e.id), start, end, quote: typeof e.quote === "string" ? e.quote : null, walkNote: typeof e.walkNote === "string" ? e.walkNote : null });
+ }
+ return out;
+}
diff --git a/umtool/lib/report/trailerBeats.test.mjs b/umtool/lib/report/trailerBeats.test.mjs
@@ -0,0 +1,142 @@
+// The trailer's beats (trailerBeats.mjs): the one writer of promo/trailer-beats.json,
+// and the reader that flags a beat outside its clip and keeps the running length.
+//
+// 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 {
+ BeatsStale,
+ TRAILER_BEATS_FILE,
+ addTrailerBeat,
+ beatsToken,
+ introSecondsOf,
+ moveTrailerBeat,
+ orderTrailerBeats,
+ readTrailerBeats,
+ removeTrailerBeat,
+ setTrailerSettings,
+ trailerCandidatesOf,
+ trailerView,
+ updateTrailerBeat,
+} from "./trailerBeats.mjs";
+
+const manifest = () => ({
+ timeline: [
+ { type: "clip", id: "a", video: "v", start: 10, end: 20 },
+ { type: "card", id: "k", seconds: 3 },
+ { type: "clip", id: "b", video: "v", start: 30, end: 50, gaps: [{ from: 35, to: 40 }], star: true },
+ { type: "clip", id: "c", video: "v", start: 60, end: 70, cutStart: 61, cutEnd: 69, star: true, verdict: "confirmed" },
+ ],
+});
+
+async function project(beats) {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-beats-"));
+ if (beats !== undefined) {
+ await mkdir(path.join(dir, "promo"), { recursive: true });
+ await writeFile(path.join(dir, TRAILER_BEATS_FILE), typeof beats === "string" ? beats : JSON.stringify(beats, null, 1) + "\n");
+ }
+ return dir;
+}
+const fileOf = async (dir) => readFile(path.join(dir, TRAILER_BEATS_FILE), "utf8");
+
+test("the view: each beat's length (gaps out), the running length, the limit, beats outside their clip", () => {
+ const v = trailerView(manifest(), {
+ beats: [
+ { id: "a", start: 12, end: 18 },
+ { id: "b", start: 30, end: 45 },
+ { at: 100, dur: 4 },
+ { id: "c", start: 60, end: 66 },
+ { id: "gone", start: 1, end: 3 },
+ ],
+ settings: { xfade: 0.5, intro: true, limit: 20 },
+ }, { introSeconds: 4 });
+ assert.deepEqual(v.rows.map((r) => r.seconds), [6, 10, 4, 5, 2]);
+ // 4 (intro) + 6 + 10 + 4 + 5 + 2 = 31, six pieces, five crossfades of 0.5
+ assert.equal(v.total, 28.5);
+ assert.equal(v.over, true);
+ assert.equal(v.rows[1].running, 19, "intro + a + b, two crossfades");
+ assert.equal(v.rows[1].over, false);
+ assert.equal(v.rows[2].over, true);
+ assert.deepEqual(v.rows[3].problems, ["starts 1.00 s before c's window (61–69)"]);
+ assert.deepEqual(v.rows[4].problems, ["gone is not in the cut any more"]);
+ assert.equal(v.outside, 2);
+ assert.equal(v.inOrder, true);
+});
+
+test("the view says when the beats are out of the cut's order; X's 2:20 is the default limit", () => {
+ const v = trailerView(manifest(), { beats: [{ id: "c", start: 62, end: 64 }, { id: "a", start: 12, end: 14 }] });
+ assert.equal(v.inOrder, false);
+ assert.equal(v.limit, 140);
+ assert.equal(v.total, 3.7, "two beats, one 0.3 s crossfade");
+});
+
+test("add, edit, move, remove: the file keeps its shape and indent, checked by parseBeats", async () => {
+ const dir = await project([{ id: "a", start: 12, end: 14 }]);
+ try {
+ const t0 = await beatsToken(dir);
+ const r = await addTrailerBeat(dir, { id: "c", start: 62, end: 65.555 }, { token: t0, manifest: manifest() });
+ assert.equal(r.index, 1);
+ const r2 = await addTrailerBeat(dir, { id: "b", start: 31, end: 34 }, { manifest: manifest() });
+ assert.equal(r2.index, 1, "in the cut's order: before c");
+ let text = await fileOf(dir);
+ assert.match(text, /^\[\n \{/, "still an array, still a 1-space indent");
+ assert.deepEqual(JSON.parse(text)[2], { id: "c", start: 62, end: 65.56 });
+ await updateTrailerBeat(dir, 2, { end: 64, label: "the line" });
+ await moveTrailerBeat(dir, 2, 0);
+ assert.deepEqual(JSON.parse(await fileOf(dir)).map((b) => b.id), ["c", "a", "b"]);
+ await removeTrailerBeat(dir, 1);
+ assert.deepEqual(JSON.parse(await fileOf(dir)).map((b) => b.id), ["c", "b"]);
+ await assert.rejects(updateTrailerBeat(dir, 0, { end: 50 }).then(() => updateTrailerBeat(dir, 0, { start: 60, end: 59 })), /not after start/);
+ await assert.rejects(addTrailerBeat(dir, { id: "a", start: 1, end: 2 }, { token: "1" }), (e) => e instanceof BeatsStale);
+ await orderTrailerBeats(dir, manifest());
+ assert.deepEqual(JSON.parse(await fileOf(dir)).map((b) => b.id), ["b", "c"]);
+ // A setting turns the file into { limit, …, beats }, which --beats reads too.
+ await setTrailerSettings(dir, { limit: 90, intro: true });
+ text = await fileOf(dir);
+ const doc = JSON.parse(text);
+ assert.equal(doc.limit, 90);
+ assert.equal(doc.intro, true);
+ assert.equal(doc.beats.length, 2);
+ const back = await readTrailerBeats(dir);
+ assert.equal(back.shape, "object");
+ assert.deepEqual(back.settings, { limit: 90, intro: true });
+ await setTrailerSettings(dir, { limit: null });
+ assert.equal(JSON.parse(await fileOf(dir)).limit, undefined);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a beats file that does not parse is never written over; none at all starts one", async () => {
+ const bad = await project("[{ not json");
+ const none = await project();
+ try {
+ await assert.rejects(addTrailerBeat(bad, { id: "a", start: 1, end: 2 }), /does not parse/);
+ assert.equal(await fileOf(bad), "[{ not json");
+ await addTrailerBeat(none, { id: "a", start: 12, end: 14 });
+ assert.deepEqual(JSON.parse(await fileOf(none)), [{ id: "a", start: 12, end: 14 }]);
+ } finally {
+ await rm(bad, { recursive: true, force: true });
+ await rm(none, { recursive: true, force: true });
+ }
+});
+
+test("the ★ candidates are the starred clips not yet beats, over what they play", () => {
+ assert.deepEqual(trailerCandidatesOf(manifest(), [{ id: "b", start: 31, end: 33 }]).map((c) => [c.id, c.start, c.end]), [["c", 61, 69]]);
+});
+
+test("the intro's length comes from the newest built take's schedule", async () => {
+ const dir = await project();
+ try {
+ assert.equal(await introSecondsOf(dir), null);
+ await mkdir(path.join(dir, "takes", "t1", "out", "sourced"), { recursive: true });
+ await writeFile(path.join(dir, "takes", "t1", "out", "sourced", "schedule.json"), JSON.stringify({ segments: [{ id: "brand-intro", type: "intro", start: 0, duration: 4.634 }] }));
+ assert.equal(await introSecondsOf(dir), 4.63);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});