commit bad58d7d3f1c6a26790de3d6374c7ae0efc422a9
parent 16ff0e3dd132c264eb2ae1500d3188ef8b2aec1e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 31 Oct 2026 23:51:42 -0400
umtool: sections edited as sections, flash-forward, and a split that keeps its section
Under the deck a cut's sections are its markers. New writers in
lib/report/manifest.mjs, over the pure rules in lib/report/sectionEdit.mjs:
moveToSection (clips to a section's end or start, every marker following),
addSection (new section here, label and colour), moveSectionBoundary (a
boundary dragged between its neighbours), removeSection, updateSection.
Each refuses an emptied section or crossing boundaries in words, checks the
markers with the deck's validateChrome, and then brings every take patch
whose markers were in step (*.patch.json beside the manifest) along
(lib/report/patchMarkers.mjs); a patch that already differed is left and
named.
flashForward / flashForwardIn: a tight copy of a span of a clip put after an
entry or into a section, with the clip's attribution (citeUrl moved to the new
second, cite, quote, speakers, title, date) and locks, as repeatOf the clip;
`move` takes the span out of the clip instead (it must sit at an edge).
splitClip: a marker after the clip follows its second half, and the second
half's citeUrl opens at its own second; patches synced.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
3 files changed, 785 insertions(+), 3 deletions(-)
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -40,7 +40,9 @@ import { verticalErrors } from "umtool-report-to-video/look";
import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/report/look.mjs";
import { validateRoom } from "umtool-report-to-video/room";
import { applySectionEnter } from "./sections.mjs";
-import { parseClipSpec } from "./clipEditorModel.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 { 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";
@@ -859,7 +861,7 @@ const textOr = (v, fallback) => (v === undefined ? fallback : String(v ?? "").tr
* @param {{ token?: string | null, quotes?: { first?: string, second?: string }, now?: string | null }} [opts]
*/
export async function splitClip(dir, clipId, at, { token = null, quotes = {}, now = null } = {}) {
- return prepAfter(dir, (r) => [r.id, r.second], structural(dir, "split", token, (m) => {
+ return prepAfter(dir, (r) => [r.id, r.second], sectionWrite(dir, "split", token, (m) => {
const { i, e } = clipAt(m.timeline, clipId);
const t = round2(Number(at));
const { cutStart, cutEnd } = cutOf(e);
@@ -887,6 +889,8 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no
b.start = t;
if (hasCut) b.cutStart = t;
if (typeof b.cite === "number") b.cite = t;
+ // The QR follows the clock: the second half's link opens at its own second.
+ if (typeof b.citeUrl === "string" && b.citeUrl) b.citeUrl = citeUrlAt(b.citeUrl, t);
if (b.muteFrom != null && b.muteFrom < t) delete b.muteFrom;
delete b.claim;
delete b.claims;
@@ -910,7 +914,10 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no
noteAssistEdit(b, "split", from, stamp);
}
m.timeline.splice(i + 1, 0, b);
- return { id: e.id, second: b.id, entries: [e, b] };
+ // A section boundary after the clip stays after the WHOLE of it: the
+ // marker follows the second half, or that half opens the next section.
+ const reanchored = followSplitMarkers(m, e.id, b.id);
+ return { id: e.id, second: b.id, entries: [e, b], reanchored };
}));
}
@@ -2172,6 +2179,199 @@ export async function insertEntry(dir, afterId, spec, { token = null, at = null
}));
}
+// ---- sections, edited as sections (UI notes 2026-10-30, item 1) -----------
+//
+// Under the deck a cut's sections are its markers (sectionEdit.mjs): these
+// 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
+// `umtool take --patch …` renders the same sections. `umtool timeline <p>
+// section …`, the Cut tab's section bars and row menus.
+
+/**
+ * A structural write that may change the deck's markers: the markers are
+ * checked by validateChrome (refused only for what this edit breaks), an
+ * emptied list is removed, and every take patch in step is synced after.
+ */
+async function sectionWrite(dir, op, token, mutate) {
+ let before = [];
+ let after = [];
+ const res = await structural(dir, op, token, (m) => {
+ const clone = (v) => JSON.parse(JSON.stringify(v ?? null));
+ const { chrome: c0, ...rest0 } = m.render ?? {};
+ const already = isObj(c0) ? new Set(validateChrome(clone(c0), rest0)) : new Set();
+ before = clone(m.render?.chrome?.deck?.markers ?? []);
+ const r = mutate(m);
+ const deck = m.render?.chrome?.deck;
+ if (isObj(deck) && Array.isArray(deck.markers) && !deck.markers.length) delete deck.markers;
+ const { chrome: c1, ...rest1 } = m.render ?? {};
+ if (isObj(c1)) {
+ const errors = validateChrome(c1, rest1).filter((e) => !already.has(e));
+ if (errors.length) throw new StructureRefused(errors);
+ }
+ after = clone(m.render?.chrome?.deck?.markers ?? []);
+ return r;
+ });
+ const patches = await syncPatchMarkers(dir, before, after);
+ return { ...res, patches };
+}
+
+/**
+ * Move clips `ids` to section `section` (its end; `position: "start"` its
+ * start), the markers following (sectionEdit.mjs moveToSectionIn).
+ *
+ * @param {string} dir
+ * @param {string[]} ids
+ * @param {number} section
+ * @param {{ token?: string | null, position?: "start" | "end" }} [opts]
+ */
+export async function moveToSection(dir, ids, section, { token = null, position = "end" } = {}) {
+ return sectionWrite(dir, "section-move", token, (m) => moveToSectionIn(m, ids, section, { position }));
+}
+
+/**
+ * New section here: a marker after clip `afterId`, with a label and a colour.
+ *
+ * @param {string} dir
+ * @param {string} afterId
+ * @param {{ label?: string | null, color?: string | null }} spec
+ * @param {{ token?: string | null }} [opts]
+ */
+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. */
+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. */
+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). */
+export async function updateSection(dir, marker, patch, { token = null } = {}) {
+ return sectionWrite(dir, "section-set", token, (m) => setSectionIn(m, marker, patch));
+}
+
+/** The sections a GET hands the Cut tab: index, label, colour, marker, clips. */
+export function sectionsOf(manifest) {
+ return sectionModel(manifest).sections.map((s) => ({ ...s, words: sectionWords(s) }));
+}
+
+// ---- flash-forward (UI notes 2026-10-30, item 2) ----------------------------
+
+/**
+ * FLASH-FORWARD A SPAN: a tight copy of clip `clipId`'s seconds `from`–`to`
+ * (inside its window) put somewhere else in the cut -- after entry `after`
+ * (null: at the start), or at the end (or start) of section `section` -- with
+ * the clip's attribution (title, date, channel, citeUrl moved to the new
+ * second, cite, quote or `quote` given, speakers, on-screen words, verdict)
+ * and its locks. A copy says it re-plays the clip (`repeatOf`), so the check's
+ * overlap row knows it is deliberate. `move: true` takes the span OUT of the
+ * clip instead (the v01 → v01t + the rest of v01 edit): the span must sit at
+ * one of its edges, and the clip keeps the rest (`restQuote` its words).
+ * A claim stays with the clip (one claim, one entry); so do its marks and the
+ * assistant's record. Mutates `m`.
+ *
+ * @param {Record<string, any>} m
+ * @param {string} clipId
+ * @param {{ from: number, to: number, after?: string | null, section?: number | null, position?: "start" | "end", move?: boolean, quote?: string, restQuote?: string, id?: string }} spec
+ */
+export function flashForwardIn(m, clipId, spec) {
+ if (!isObj(spec)) throw new Error("a flash-forward is { from, to, after | section }");
+ const { i, e } = clipAt(m.timeline, clipId);
+ const a = round2(Number(spec.from));
+ const b = round2(Number(spec.to));
+ if (!Number.isFinite(a) || !Number.isFinite(b)) throw new Error("from and to are source seconds");
+ if (b - a < 0.5) throw new Error(`a flash-forward is at least half a second (${a}–${b})`);
+ if (a < e.start - WIN_EPS || b > e.end + WIN_EPS) throw new Error(`${a}–${b} is not inside ${clipId}'s window ${e.start}–${e.end}`);
+ const gaps = Array.isArray(e.gaps) ? e.gaps : [];
+ for (const t of [a, b]) {
+ const g = gaps.find((x) => t > x.from && t < x.to);
+ if (g) throw new Error(`${t} is inside the gap ${g.from}–${g.to}, which never plays — start or end the span at its edge`);
+ }
+ const hasCut = e.cutStart != null && e.cutEnd != null;
+ const copy = JSON.parse(JSON.stringify(e));
+ const base = typeof spec.id === "string" && ENTRY_ID_RE.test(spec.id) ? spec.id : `${clipId}t`;
+ copy.id = freshEntryId(m.timeline, base);
+ copy.start = a;
+ copy.end = b;
+ if (hasCut) {
+ copy.cutStart = a;
+ copy.cutEnd = b;
+ }
+ if (typeof copy.cite === "number") copy.cite = Math.floor(a);
+ if (typeof copy.citeUrl === "string" && copy.citeUrl) copy.citeUrl = citeUrlAt(copy.citeUrl, a);
+ if (copy.muteFrom != null && (copy.muteFrom <= a || copy.muteFrom >= b)) delete copy.muteFrom;
+ const inside = gaps.filter((g) => g.from >= a && g.to <= b);
+ if (inside.length) copy.gaps = inside;
+ else delete copy.gaps;
+ for (const k of ["claim", "claims", "marks", "assist", "sectionEnter"]) delete copy[k];
+ const q = textOr(spec.quote, copy.quote ?? null);
+ if (q) copy.quote = q;
+ else delete copy.quote;
+ const move = spec.move === true;
+ if (move) delete copy.repeatOf;
+ else copy.repeatOf = e.id;
+ let rest = null;
+ if (move) {
+ const c = cutOf(e);
+ if (Math.abs(a - c.cutStart) <= 0.5) {
+ if (c.cutEnd - b < 0.5) throw new Error(`moving ${a}–${b} out of ${clipId} leaves less than half a second of it — move the whole clip instead`);
+ e.start = Math.max(e.start, b);
+ if (hasCut) e.cutStart = b;
+ if (typeof e.cite === "number") e.cite = Math.floor(b);
+ if (typeof e.citeUrl === "string" && e.citeUrl) e.citeUrl = citeUrlAt(e.citeUrl, b);
+ } else if (Math.abs(b - c.cutEnd) <= 0.5) {
+ if (a - c.cutStart < 0.5) throw new Error(`moving ${a}–${b} out of ${clipId} leaves less than half a second of it — move the whole clip instead`);
+ e.end = Math.min(e.end, a);
+ if (hasCut) e.cutEnd = a;
+ if (e.muteFrom != null && e.muteFrom >= a) delete e.muteFrom;
+ } else {
+ throw new Error(`${a}–${b} is in the middle of ${clipId} (${c.cutStart}–${c.cutEnd}): to move it out, split there first — or copy it (a repeat)`);
+ }
+ if (gaps.length) {
+ const keep = gaps.filter((g) => g.to <= e.end && g.from >= e.start);
+ if (keep.length) e.gaps = keep;
+ else delete e.gaps;
+ }
+ const rq = textOr(spec.restQuote, e.quote ?? null);
+ if (rq) e.quote = rq;
+ else delete e.quote;
+ rest = { start: e.start, end: e.end, ...(hasCut ? { cutStart: e.cutStart, cutEnd: e.cutEnd } : {}) };
+ }
+ // Where it goes: after an entry (null: the start), or into a section.
+ const after = spec.after === undefined || spec.after === "" ? null : spec.after;
+ let at = 0;
+ if (after !== null) at = entryIndex(m.timeline, String(after)) + 1;
+ m.timeline.splice(at, 0, copy);
+ let section = null;
+ if (spec.section !== undefined && spec.section !== null && spec.section !== "") {
+ const r = moveToSectionIn(m, [copy.id], Number(spec.section), { position: spec.position === "start" ? "start" : "end" });
+ section = { index: r.section, label: r.label, reanchored: r.reanchored };
+ at = m.timeline.findIndex((x) => x === copy);
+ }
+ const placedBefore = at <= m.timeline.indexOf(e);
+ return { id: copy.id, at, entry: copy, source: e.id, move, rest, section, earlier: placedBefore, sourceAt: i };
+}
+
+/**
+ * Flash-forward a span (flashForwardIn) as one structural write: the undo
+ * point, the build's checks, the patches' markers synced.
+ *
+ * @param {string} dir
+ * @param {string} clipId
+ * @param {Parameters<typeof flashForwardIn>[2]} spec
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function flashForward(dir, clipId, spec, { token = null } = {}) {
+ return prepAfter(dir, (r) => [r.id, r.move ? r.source : null], sectionWrite(dir, "flash-forward", token, (m) => flashForwardIn(m, clipId, spec)));
+}
+
const TEASER_PATCH_KEYS = ["lines", "beat", "dip", "tail", "tailWait"];
/**
diff --git a/umtool/lib/report/sectionEdit.mjs b/umtool/lib/report/sectionEdit.mjs
@@ -0,0 +1,316 @@
+// SECTIONS OF A DECK CUT, edited as sections (UI notes 2026-10-30, item 1).
+//
+// Under the deck a cut's sections ARE its markers (`render.chrome.deck.markers`,
+// report-to-video deck.mjs `railSections`): section 0 runs from the start to
+// the first marker's boundary, and a marker `{ after: <clip>, label?, color? }`
+// opens the next section right after that clip -- its label and colour are the
+// NEW section's. So "move this clip to section 3" is two edits that must land
+// together: the clip moves in the timeline, and every marker whose boundary the
+// move crosses follows, or the clip lands in the wrong section (or a section
+// ends up empty, or two markers cross). Doing that by `timeline move --to`
+// index arithmetic went wrong twice on the Ember cut.
+//
+// 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 rules, each refused in words rather than repaired silently:
+// - a section never ends up with no clip (two markers on one boundary);
+// - a boundary never moves past its neighbours (markers never cross);
+// - a marker never follows the last clip (a section after it is empty);
+// - markers stay within the deck's own limits (validateChrome says so).
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const isClip = (e) => !!e && (e.kind ?? e.type) === "clip";
+
+/** The deck's markers as written (an array, maybe empty), or null without a deck. */
+function deckMarkers(m) {
+ const chrome = m?.render?.chrome;
+ if (!isObj(chrome)) return null;
+ const d = isObj(chrome.deck) ? chrome.deck : null;
+ return Array.isArray(d?.markers) ? d.markers : [];
+}
+
+function needDeck(m) {
+ const chrome = m?.render?.chrome;
+ if (!isObj(chrome)) throw new Error("sections are the on-screen deck's markers, and this manifest has no deck — turn the deck on first");
+ if (!isObj(chrome.deck)) chrome.deck = {};
+ if (!Array.isArray(chrome.deck.markers)) chrome.deck.markers = [];
+ return chrome.deck.markers;
+}
+
+/**
+ * The cut's sections, read from its markers.
+ *
+ * `sections[i]`: `{ index, label, color, marker, clips, first, last }` --
+ * `marker` is the index into `deck.markers` that opens it (null for section
+ * 0), `clips` its clip ids in order, `first`/`last` its first and last clip.
+ * `sectionOf` maps a clip id to its section; `entrySection[i]` is the section
+ * of timeline entry i (a card belongs to the section it stands in). Markers
+ * naming no clip of the timeline are left out (`stray`: their indexes).
+ *
+ * @param {Record<string, any>} m
+ */
+export function sectionModel(m) {
+ const tl = Array.isArray(m?.timeline) ? m.timeline : [];
+ const markers = deckMarkers(m) ?? [];
+ const pos = new Map();
+ tl.forEach((e, i) => {
+ if (isClip(e) && !pos.has(e.id)) pos.set(e.id, i);
+ });
+ const placed = [];
+ const stray = [];
+ markers.forEach((mk, k) => {
+ const p = isObj(mk) ? pos.get(String(mk.after ?? "").trim()) : undefined;
+ if (p === undefined) stray.push(k);
+ else placed.push({ k, mk, pos: p });
+ });
+ placed.sort((a, b) => a.pos - b.pos || a.k - b.k);
+ const pal = m?.render?.palette ?? {};
+ const key = m?.render?.chrome?.deck?.pip?.sectionColor0;
+ const color0 = typeof key === "string" && /^#[0-9a-f]{3,8}$/i.test(key) ? key : (key && pal[key]) || pal.accent || null;
+ const sections = [
+ { index: 0, label: null, color: color0, marker: null, clips: [], first: null, last: null },
+ ...placed.map((p, i) => ({
+ index: i + 1,
+ label: typeof p.mk.label === "string" && p.mk.label.trim() ? p.mk.label.trim() : null,
+ color: typeof p.mk.color === "string" && p.mk.color.trim() ? p.mk.color.trim() : null,
+ marker: p.k,
+ clips: [],
+ first: null,
+ last: null,
+ })),
+ ];
+ const sectionOf = new Map();
+ const entrySection = [];
+ let s = 0;
+ let next = 0;
+ tl.forEach((e, i) => {
+ entrySection[i] = s;
+ if (isClip(e)) {
+ if (!sectionOf.has(e.id)) sectionOf.set(e.id, s);
+ sections[s].clips.push(e.id);
+ sections[s].first ??= e.id;
+ sections[s].last = e.id;
+ }
+ while (next < placed.length && placed[next].pos === i) {
+ next += 1;
+ s = next;
+ }
+ });
+ return { sections, sectionOf, entrySection, stray, placed };
+}
+
+/** "§3 (Leaves it open)" -- how a sentence names a section. */
+export const sectionWords = (s) => `§${s.index}${s.label ? ` (${s.label})` : s.index === 0 ? " (the opening)" : ""}`;
+
+/**
+ * Each marker's `after` again, from what section each clip is in: marker
+ * opening section i follows the last clip of section i-1. `membership` maps a
+ * clip id to its section; the timeline is in section order already. Refuses a
+ * section left with no clip. Returns one sentence per marker that moved.
+ */
+function reanchorMarkers(m, model, membership) {
+ const tl = m.timeline;
+ const markers = deckMarkers(m) ?? [];
+ const lastIn = new Map();
+ const count = new Map();
+ for (const e of tl) {
+ if (!isClip(e) || !membership.has(e.id)) continue;
+ const s = membership.get(e.id);
+ lastIn.set(s, e.id);
+ count.set(s, (count.get(s) ?? 0) + 1);
+ }
+ const notes = [];
+ for (const sec of model.sections) {
+ if (!count.get(sec.index)) {
+ throw new Error(`${sectionWords(sec)} would have no clip left — remove its boundary first (umtool timeline <project> section-remove ${sec.marker ?? 0}), or move a clip into it`);
+ }
+ }
+ for (const sec of model.sections.slice(1)) {
+ const mk = markers[sec.marker];
+ const after = lastIn.get(sec.index - 1);
+ if (mk.after !== after) {
+ notes.push(`marker ${sec.marker}${mk.label ? ` ("${mk.label}")` : ""} moved from after ${mk.after} to after ${after}`);
+ mk.after = after;
+ }
+ }
+ return notes;
+}
+
+/**
+ * MOVE TO SECTION: clips `ids` (in the order they stand in the cut) to the end
+ * of section `target` -- or its start with `position: "start"` -- with every
+ * marker following so each section keeps the clips it had, plus these.
+ *
+ * @param {Record<string, any>} m
+ * @param {string[]} ids
+ * @param {number} target
+ * @param {{ position?: "start" | "end" }} [opts]
+ */
+export function moveToSectionIn(m, ids, target, { position = "end" } = {}) {
+ const model = sectionModel(m);
+ if (deckMarkers(m) === null) needDeck(m);
+ const t = Number(target);
+ if (!Number.isInteger(t) || t < 0 || t >= model.sections.length) {
+ throw new Error(`section must be 0–${model.sections.length - 1} (§0 is before the first marker)`);
+ }
+ if (position !== "start" && position !== "end") throw new Error('position is "start" or "end"');
+ const want = [...new Set((Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? "").trim()).filter(Boolean))];
+ if (!want.length) throw new Error("name one or more clips to move");
+ const tl = m.timeline;
+ for (const id of want) {
+ const e = tl.find((x) => x?.id === id);
+ if (!e) throw new Error(`no timeline entry with id ${id}`);
+ if (!isClip(e)) throw new Error(`${id} is a ${e.type ?? "non-clip"} entry: a section move takes clips (a card stays where it stands)`);
+ if (tl.filter((x) => x?.id === id).length > 1) throw new Error(`${id} is in the timeline more than once — move one twin with \`timeline move\``);
+ }
+ const membership = new Map(model.sectionOf);
+ const from = new Map(want.map((id) => [id, membership.get(id)]));
+ for (const id of want) membership.set(id, t);
+ const moving = new Set(want);
+ const moved = tl.filter((e) => isClip(e) && moving.has(e.id));
+ const rest = tl.filter((e) => !(isClip(e) && moving.has(e.id)));
+ // The remaining clips are still in section order: the end of `t` is just
+ // after the last clip at or before it, its start just after the last clip
+ // before it (a card opening the next section stays after the moved clips).
+ let at = 0;
+ rest.forEach((e, i) => {
+ if (!isClip(e)) return;
+ const s = membership.get(e.id);
+ if (position === "end" ? s <= t : s < t) at = i + 1;
+ });
+ rest.splice(at, 0, ...moved);
+ const before = tl.map((e) => e?.id).join("\n");
+ m.timeline.splice(0, m.timeline.length, ...rest);
+ const reanchored = reanchorMarkers(m, model, membership);
+ const changed = before !== m.timeline.map((e) => e?.id).join("\n");
+ if (!changed && !reanchored.length) throw new Error(`${want.join(", ")} already ${want.length === 1 ? "stands" : "stand"} at the ${position} of ${sectionWords(model.sections[t])}`);
+ return {
+ ids: moved.map((e) => e.id),
+ section: t,
+ label: model.sections[t].label,
+ from: Object.fromEntries(from),
+ position,
+ reanchored,
+ };
+}
+
+/**
+ * NEW SECTION HERE: a marker right after clip `afterId`, so the clips after it
+ * (to the next boundary) are a section of their own, labelled and coloured.
+ *
+ * @param {Record<string, any>} m
+ * @param {string} afterId
+ * @param {{ label?: string | null, color?: string | null }} [spec]
+ */
+export function addSectionIn(m, afterId, { label = null, color = null } = {}) {
+ const markers = needDeck(m);
+ const model = sectionModel(m);
+ const id = String(afterId ?? "").trim();
+ const tl = m.timeline;
+ const i = tl.findIndex((e) => e?.id === id);
+ if (i < 0) throw new Error(`no timeline entry with id ${id}`);
+ if (!isClip(tl[i])) throw new Error(`${id} is a ${tl[i].type ?? "non-clip"} entry: a section boundary follows a clip`);
+ const lastClip = [...tl].reverse().find(isClip);
+ if (lastClip?.id === id) throw new Error(`${id} is the last clip: a section after it would be empty`);
+ const already = model.placed.find((p) => p.pos === i);
+ if (already) throw new Error(`a section already starts after ${id} (marker ${already.k}${already.mk.label ? `, "${already.mk.label}"` : ""}) — edit that one`);
+ const mk = { after: id };
+ const l = typeof label === "string" ? label.trim() : "";
+ if (l) mk.label = l;
+ const c = typeof color === "string" ? color.trim() : "";
+ if (c) mk.color = c;
+ // In the cut's order in the list too: the Markers editor lists them so.
+ const k = model.placed.filter((p) => p.pos < i).reduce((n, p) => Math.max(n, p.k + 1), 0);
+ markers.splice(k, 0, mk);
+ const opened = model.sections[model.entrySection[i]];
+ const nextClip = tl.slice(i + 1).find(isClip);
+ return { marker: k, after: id, label: l || null, color: c || null, opens: nextClip?.id ?? null, splitFrom: sectionWords(opened) };
+}
+
+/**
+ * DRAG A BOUNDARY: marker `k` follows clip `afterId` now -- somewhere between
+ * the boundaries either side of it, so no section empties and none cross.
+ *
+ * @param {Record<string, any>} m
+ * @param {number} k
+ * @param {string} afterId
+ */
+export function moveBoundaryIn(m, k, afterId) {
+ const markers = needDeck(m);
+ const model = sectionModel(m);
+ const n = Number(k);
+ if (!Number.isInteger(n) || !markers[n]) throw new Error(`no marker ${k} (0–${markers.length - 1})`);
+ const sec = model.sections.find((s) => s.marker === n);
+ if (!sec) throw new Error(`marker ${n} names ${markers[n]?.after ?? "nothing"}, which is not a clip of the cut`);
+ const tl = m.timeline;
+ const id = String(afterId ?? "").trim();
+ const i = tl.findIndex((e) => e?.id === id);
+ if (i < 0) throw new Error(`no timeline entry with id ${id}`);
+ if (!isClip(tl[i])) throw new Error(`${id} is a ${tl[i].type ?? "non-clip"} entry: a section boundary follows a clip`);
+ const me = model.placed.findIndex((p) => p.k === n);
+ const lo = me > 0 ? model.placed[me - 1].pos : -1;
+ const hi = me + 1 < model.placed.length ? model.placed[me + 1].pos : tl.length;
+ const clipsIn = (a, b) => tl.slice(a + 1, b + 1).filter(isClip).length;
+ if (i <= lo || clipsIn(lo, i) < 1) throw new Error(`after ${id} the boundary would cross or touch the one before it (${model.placed[me - 1]?.mk.after}): ${sectionWords(model.sections[sec.index - 1])} would have no clip`);
+ if (i >= hi || tl.slice(i + 1, hi + 1).filter(isClip).length < 1) {
+ throw new Error(`after ${id} ${sectionWords(sec)} would have no clip${hi < tl.length ? ` (the next boundary is after ${model.placed[me + 1].mk.after})` : " (it is the last clip)"}`);
+ }
+ const was = markers[n].after;
+ if (was === id) throw new Error(`marker ${n} already follows ${id}`);
+ markers[n].after = id;
+ const p0 = model.placed[me].pos;
+ const crossed = tl.slice(Math.min(p0, i) + 1, Math.max(p0, i) + 1).filter(isClip).map((e) => e.id);
+ return {
+ marker: n,
+ from: was,
+ after: id,
+ // Which clips changed section, and into which.
+ moved: crossed,
+ into: i > p0 ? sectionWords(model.sections[sec.index - 1]) : sectionWords(sec),
+ };
+}
+
+/** REMOVE A BOUNDARY: marker `k` goes, and its section joins the one before it. */
+export function removeBoundaryIn(m, k) {
+ const markers = needDeck(m);
+ const n = Number(k);
+ if (!Number.isInteger(n) || !markers[n]) throw new Error(`no marker ${k} (0–${markers.length - 1})`);
+ const [gone] = markers.splice(n, 1);
+ return { marker: n, removed: gone };
+}
+
+/** A section's label and/or colour (its marker's): null or "" removes one. */
+export function setSectionIn(m, k, patch) {
+ const markers = needDeck(m);
+ const n = Number(k);
+ if (!Number.isInteger(n) || !markers[n]) throw new Error(`no marker ${k} (0–${markers.length - 1})`);
+ if (!isObj(patch) || (!("label" in patch) && !("color" in patch))) throw new Error("send label and/or color");
+ const mk = markers[n];
+ for (const key of ["label", "color"]) {
+ if (!(key in patch)) continue;
+ const v = typeof patch[key] === "string" ? patch[key].trim() : "";
+ if (v) mk[key] = v;
+ else delete mk[key];
+ }
+ return { marker: n, entry: { ...mk } };
+}
+
+/**
+ * After clip `firstId` was split in two (the second half `secondId` right
+ * after it): a marker that followed the first half follows the second -- the
+ * same boundary, or the second half falls into the next section.
+ */
+export function followSplitMarkers(m, firstId, secondId) {
+ const markers = deckMarkers(m) ?? [];
+ const notes = [];
+ markers.forEach((mk, k) => {
+ if (isObj(mk) && String(mk.after ?? "").trim() === firstId) {
+ mk.after = secondId;
+ notes.push(`marker ${k}${mk.label ? ` ("${mk.label}")` : ""} follows ${secondId} now (the same boundary)`);
+ }
+ });
+ return notes;
+}
diff --git a/umtool/lib/report/sectionEdit.test.mjs b/umtool/lib/report/sectionEdit.test.mjs
@@ -0,0 +1,266 @@
+// Sections as sections (sectionEdit.mjs) and their writers in manifest.mjs:
+// move to section, new section here, drag / remove a boundary, the take
+// patches' markers kept in step, flash-forward a span, and a split that keeps
+// its section.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+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 {
+ MANIFEST_NAME,
+ StructureRefused,
+ addSection,
+ flashForward,
+ flashForwardIn,
+ moveSectionBoundary,
+ moveToSection,
+ removeSection,
+ splitClip,
+ undoStructural,
+} from "./manifest.mjs";
+
+const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: "v1", start, end, ...extra });
+// §0 a b | §1 "Two" c d | card k | §2 "Three" e f
+const deckCut = () => ({
+ slug: "s",
+ provenance: { siteOrigin: "https://example.test", channelSlug: "chan" },
+ render: {
+ width: 1920,
+ height: 1080,
+ chrome: {
+ engine: "hyperframes",
+ layout: "deck",
+ deck: {
+ markers: [
+ { after: "b", label: "Two", color: "#ff0000" },
+ { after: "d", label: "Three", color: "#00ff00" },
+ ],
+ },
+ },
+ },
+ timeline: [
+ clip("a", 10, 20),
+ clip("b", 30, 40),
+ clip("c", 50, 60),
+ clip("d", 70, 80),
+ { type: "card", id: "k", seconds: 3 },
+ clip("e", 90, 100),
+ clip("f", 110, 120),
+ ],
+});
+const ids = (m) => m.timeline.map((e) => e.id);
+const afters = (m) => (m.render.chrome.deck.markers ?? []).map((mk) => mk.after);
+
+test("sectionModel reads the sections off the markers", () => {
+ const { sections, sectionOf, entrySection } = sectionModel(deckCut());
+ assert.deepEqual(sections.map((s) => [s.index, s.label, s.clips]), [[0, null, ["a", "b"]], [1, "Two", ["c", "d"]], [2, "Three", ["e", "f"]]]);
+ assert.equal(sectionOf.get("e"), 2);
+ assert.equal(entrySection[4], 2, "the card after d's boundary stands in §2");
+});
+
+test("move to section: the clip lands at the section's end and the markers follow", () => {
+ const m = deckCut();
+ const r = moveToSectionIn(m, ["a"], 1);
+ assert.deepEqual(ids(m), ["b", "c", "d", "a", "k", "e", "f"]);
+ assert.deepEqual(afters(m), ["b", "a"]);
+ assert.equal(r.section, 1);
+ assert.deepEqual(r.reanchored, ['marker 1 ("Three") moved from after d to after a']);
+});
+
+test("move the clip a marker follows: the marker moves to the clip before it", () => {
+ const m = deckCut();
+ moveToSectionIn(m, ["d"], 2, { position: "start" });
+ assert.deepEqual(ids(m), ["a", "b", "c", "d", "k", "e", "f"], "d is already where §2 starts — the boundary moves instead");
+ assert.deepEqual(afters(m), ["b", "c"]);
+ const m2 = deckCut();
+ moveToSectionIn(m2, ["b", "c"], 2);
+ assert.deepEqual(ids(m2), ["a", "d", "k", "e", "f", "b", "c"]);
+ assert.deepEqual(afters(m2), ["a", "d"]);
+});
+
+test("a section left with no clip is refused, in words", () => {
+ const m = deckCut();
+ assert.throws(() => moveToSectionIn(m, ["c", "d"], 0), /§1 \(Two\) would have no clip left/);
+ assert.throws(() => moveToSectionIn(deckCut(), ["k"], 0), /a section move takes clips/);
+ assert.throws(() => moveToSectionIn(deckCut(), ["a"], 3), /section must be 0–2/);
+});
+
+test("new section here: a marker after the clip, in the cut's order, with its colour", () => {
+ const m = deckCut();
+ const r = addSectionIn(m, "e", { label: "Four", color: "#123456" });
+ assert.deepEqual(m.render.chrome.deck.markers.map((x) => [x.after, x.label ?? null]), [["b", "Two"], ["d", "Three"], ["e", "Four"]]);
+ assert.equal(r.opens, "f");
+ assert.throws(() => addSectionIn(deckCut(), "f", { label: "x" }), /the last clip/);
+ assert.throws(() => addSectionIn(deckCut(), "b", { label: "x" }), /already starts after b/);
+ const m2 = deckCut();
+ addSectionIn(m2, "a", {});
+ assert.deepEqual(afters(m2), ["a", "b", "d"], "an unlabelled one first in the list too");
+});
+
+test("drag a boundary: between its neighbours, never crossing them", () => {
+ const m = deckCut();
+ const r = moveBoundaryIn(m, 1, "c");
+ assert.deepEqual(afters(m), ["b", "c"]);
+ assert.deepEqual(r.moved, ["d"]);
+ assert.throws(() => moveBoundaryIn(deckCut(), 1, "b"), /would cross or touch/);
+ assert.throws(() => moveBoundaryIn(deckCut(), 1, "f"), /would have no clip/);
+ assert.throws(() => moveBoundaryIn(deckCut(), 0, "d"), /would have no clip/);
+ const m2 = deckCut();
+ moveBoundaryIn(m2, 1, "e");
+ assert.deepEqual(sectionModel(m2).sections[2].clips, ["f"]);
+});
+
+test("remove a boundary joins two sections; set relabels and recolours", () => {
+ const m = deckCut();
+ removeBoundaryIn(m, 0);
+ assert.deepEqual(sectionModel(m).sections.map((s) => s.clips.length), [4, 2]);
+ const m2 = deckCut();
+ setSectionIn(m2, 1, { label: "Drei", color: "" });
+ assert.deepEqual(m2.render.chrome.deck.markers[1], { after: "d", label: "Drei" });
+});
+
+test("a cut with no deck says so", () => {
+ const m = deckCut();
+ delete m.render.chrome;
+ assert.throws(() => addSectionIn(m, "a", { label: "x" }), /no deck — turn the deck on first/);
+});
+
+async function project(manifest, extra = {}) {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-sections-"));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n");
+ for (const [name, doc] of Object.entries(extra)) await writeFile(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n");
+ return dir;
+}
+const read = async (dir, name = MANIFEST_NAME) => JSON.parse(await readFile(path.join(dir, name), "utf8"));
+const patchOf = (markers) => ({ render: { chrome: { deck: { markers } } }, title: "T" });
+
+test("the writers keep in-step take patches in step, and leave a variant alone", async () => {
+ const m = deckCut();
+ const dir = await project(m, {
+ "draft-1.patch.json": patchOf(m.render.chrome.deck.markers),
+ "variant.patch.json": patchOf([{ after: "a", label: "Other" }]),
+ "plain.patch.json": { title: "no markers" },
+ });
+ 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((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.equal((await read(dir, "draft-1.patch.json")).render.chrome.deck.markers.length, 3);
+ await moveSectionBoundary(dir, 1, "c");
+ await removeSection(dir, 2);
+ const p = await read(dir, "draft-1.patch.json");
+ assert.deepEqual(p.render.chrome.deck.markers, (await read(dir)).render.chrome.deck.markers);
+ // Undo restores the manifest (the patch is the operator's to re-sync: it says so in the check).
+ await undoStructural(dir);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a marker past the deck's limits is refused in its words, nothing written", async () => {
+ const m = deckCut();
+ const dir = await project(m);
+ try {
+ const before = await readFile(path.join(dir, MANIFEST_NAME), "utf8");
+ await assert.rejects(addSection(dir, "a", { label: "a label far longer than twenty-four characters" }), (e) => e instanceof StructureRefused && /at most 24/.test(e.message));
+ assert.equal(await readFile(path.join(dir, MANIFEST_NAME), "utf8"), before);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("syncPatchMarkers 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" }]);
+ 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");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("split keeps the section: a marker after the clip follows its second half; the QR follows the second", async () => {
+ const m = deckCut();
+ m.timeline[1] = { ...m.timeline[1], cite: 30, citeUrl: "https://archive.example/?v=chan%2Fv1&t=30", lockEnd: true, title: "Stream", date: "2026-10-27" };
+ const dir = await project(m, { "draft-1.patch.json": patchOf(m.render.chrome.deck.markers) });
+ try {
+ const r = await splitClip(dir, "b", 35);
+ const after = await read(dir);
+ assert.deepEqual(ids(after), ["a", "b", "b-2", "c", "d", "k", "e", "f"]);
+ assert.deepEqual(afters(after), ["b-2", "d"]);
+ const b2 = after.timeline[2];
+ assert.equal(b2.cite, 35);
+ 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"]);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("flash-forward copies a span earlier with its attribution and locks, as a repeat", () => {
+ const m = deckCut();
+ Object.assign(m.timeline[5], {
+ channel: "chan", cite: 90, citeUrl: "https://archive.example/?v=chan%2Fv1&t=90", lock: true, title: "Stream", date: "2026-10-27",
+ quote: "the whole thing", speakers: ["Host"], claim: { id: "e", verdict: "reason" }, gaps: [{ from: 92, to: 93 }, { from: 97, to: 98 }],
+ });
+ const r = flashForwardIn(m, "e", { from: 95.5, to: 99.25, after: "a", quote: "the tight line" });
+ assert.equal(r.id, "et");
+ assert.deepEqual(ids(m), ["a", "et", "b", "c", "d", "k", "e", "f"]);
+ const c = m.timeline[1];
+ assert.equal(c.start, 95.5);
+ assert.equal(c.end, 99.25);
+ assert.equal(c.cite, 95);
+ assert.match(c.citeUrl, /t=95$/);
+ assert.equal(c.repeatOf, "e");
+ assert.equal(c.lock, true);
+ assert.equal(c.title, "Stream");
+ assert.equal(c.date, "2026-10-27");
+ assert.deepEqual(c.speakers, ["Host"]);
+ assert.equal(c.quote, "the tight line");
+ assert.equal(c.claim, undefined, "one claim, one entry");
+ assert.deepEqual(c.gaps, [{ from: 97, to: 98 }]);
+ assert.equal(r.earlier, true);
+ assert.equal(m.timeline[6].end, 100, "the clip itself is untouched");
+});
+
+test("flash-forward into a section, and a moved span takes the clip's edge with it", () => {
+ const m = deckCut();
+ m.timeline[3].cite = 70;
+ const r = flashForwardIn(m, "d", { from: 75, to: 80, section: 0, move: true, restQuote: "the first half" });
+ assert.deepEqual(ids(m), ["a", "b", "dt", "c", "d", "k", "e", "f"]);
+ assert.deepEqual(afters(m), ["dt", "d"]);
+ assert.equal(r.move, true);
+ assert.equal(m.timeline[2].repeatOf, undefined);
+ assert.deepEqual(r.rest, { start: 70, end: 75 });
+ assert.equal(m.timeline[4].quote, "the first half");
+ assert.throws(() => flashForwardIn(deckCut(), "d", { from: 72, to: 78, move: true }), /in the middle of d/);
+ assert.throws(() => flashForwardIn(deckCut(), "d", { from: 60, to: 78 }), /not inside d's window/);
+});
+
+test("flashForward writes once, with an undo point", async () => {
+ const dir = await project(deckCut());
+ try {
+ const r = await flashForward(dir, "f", { from: 111, to: 115, after: "a" });
+ assert.equal(r.id, "ft");
+ assert.ok(r.snapshot?.rel?.includes("auto-before-flash-forward"));
+ await undoStructural(dir);
+ assert.deepEqual(ids(await read(dir)), ids(deckCut()));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});