commit 18238e01c7616be3ebf8283f05316b3e4aa350be
parent 6fc7b714157c22779920f428df13846be575ba6c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 00:01:10 -0500
umtool claim groups: `groups: [{id, section, claim, ids}]` beside the timeline -- runs of clips inside one section that make one claim (lib/report/claimGroups.mjs). validateGroups is one of structural()'s checks (each group's clips together, in one section, `section` the deck section they are in, a clip in at most one group); applyStructural's syncGroups keeps them through every structural edit: a removal drops the clip (reanchorAfterRemove says so; an emptied group goes), a clip moved out of its run is detached, a clip moved ALONE into the middle of a run joins it (to the run's edge joins nothing), a whole group moved into another's middle is refused, a split's second half stays in the group, `section` follows the markers; what moved is what the op says (its ids/id), else what falls out of a weighted longest common subsequence. A manifest without `groups` is never touched. Writers (manifest.mjs, each an undo point): setGroup, labelGroup, removeGroup, moveGroup (to an index among the groups, after a group, or before a row; through placeIn), promoteGroup (a level-2 marker at the group's first clip titled with its claim, at most 24), importGroups (a claim-groups file in ONE write: the cut re-ordered to it, file sections matched to deck sections by name else where most of their clips are, unnamed clips at their section's end, refused for missing ids or an emptied section unless --skip-missing / --drop-empty), orderEntries (bulk order through structural(), every clip keeping its section). `umtool timeline <p> order <file|ids…>` and `groups ls|import|set|move|label|promote|remove`; POST /api/report/timeline ops order, group-set, group-label, group-remove, group-move, group-promote and `groups` on its GET. The Cut tab draws a group bar inside its section (its claim edited in place, ⠿ drags the whole group onto a row, promote, ungroup) with its clips indented; Play's reel strip draws a group's seam lighter than a section's (seamsOf's third argument; the seams are as before without it)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
12 files changed, 1684 insertions(+), 17 deletions(-)
diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts
@@ -22,7 +22,14 @@ import {
updateSection,
updateTeaser,
upsertPost,
+ labelGroup,
+ moveGroup,
+ orderEntries,
+ promoteGroup,
+ removeGroup,
+ setGroup,
} from "@/lib/report/manifest.mjs";
+import { groupModel } from "@/lib/report/claimGroups.mjs";
import { resolveReport } from "@/lib/report/serve.mjs";
import { deckOn } from "umtool-report-to-video/deck";
import { VERDICTS, resolveFactcheck } from "umtool-report-to-video/factcheck";
@@ -58,6 +65,14 @@ export const dynamic = "force-dynamic";
// 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/patchMarkers.mjs syncSectionMarkers)
+// order { ids: [id…] } the named entries in that order, in the places they hold
+// group-set { group: gid | null, ids: [id…], claim? } a claim group is these clips (null: a new one)
+// group-label { group, claim } its claim, in words
+// group-remove { group } ungroup (its clips stay)
+// group-move { group, before: id | null } | { group, to } | { group, after: gid } the whole group
+// group-promote { group, label? } the group opens a subsection (a level-2 marker)
+// (lib/report/claimGroups.mjs: a clip moved out of its run leaves the group; moved alone into
+// the middle of one, it joins it)
//
// 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
@@ -87,6 +102,8 @@ export async function GET(request: Request) {
deckOn: deckOn(render),
// The deck's sections (its markers), for "move to section…" and the section bars.
sections: deckOn(render) ? sectionsOf(r.manifest) : [],
+ // The claim groups (lib/report/claimGroups.mjs), in cut order: the group bars.
+ groups: groupModel(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.
@@ -166,8 +183,29 @@ export async function POST(request: Request) {
return removeSection(dir, Number(body.marker), { token });
case "section-set":
return updateSection(dir, Number(body.marker), Object.fromEntries(["label", "color", "level"].filter((k) => k in body).map((k) => [k, body[k]])), { token });
+ case "order":
+ return orderEntries(dir, Array.isArray(body.ids) ? body.ids.map(String) : [], { token });
+ case "group-set":
+ return setGroup(dir, typeof body.group === "string" && body.group ? body.group : null, Array.isArray(body.ids) ? body.ids.map(String) : [], { claim: typeof body.claim === "string" ? body.claim : null }, { token });
+ case "group-label":
+ return labelGroup(dir, String(body.group ?? ""), String(body.claim ?? ""), { token });
+ case "group-remove":
+ return removeGroup(dir, String(body.group ?? ""), { token });
+ case "group-move":
+ return moveGroup(
+ dir,
+ String(body.group ?? ""),
+ "before" in body
+ ? { before: typeof body.before === "string" && body.before ? body.before : null }
+ : typeof body.after === "string" && body.after
+ ? { after: body.after }
+ : { to: Number(body.to) },
+ { token },
+ );
+ case "group-promote":
+ return promoteGroup(dir, String(body.group ?? ""), { label: typeof body.label === "string" ? body.label : null }, { token });
default:
- throw new Error("op must be move, place, remove, reject, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck, undo, section-move, section-add, section-boundary, section-remove or section-set");
+ throw new Error("op must be move, place, remove, reject, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck, undo, section-move, section-add, section-boundary, section-remove, section-set, order, group-set, group-label, group-remove, group-move or group-promote");
}
};
diff --git a/umtool/components/projects/TimelineEditor.tsx b/umtool/components/projects/TimelineEditor.tsx
@@ -22,6 +22,8 @@ import { MANIFEST_CHANGED, announceManifestChanged, refusalOf, timelineOp } from
/** One section of a deck cut (lib/report/sectionEdit.mjs), as the timeline route sends it. */
// `level` 2: a subsection (a section to every op, drawn inside `within`, its section, on the deck).
export type SectionInfo = { index: number; label: string | null; color: string | null; marker: number | null; clips: string[]; words: string; level?: number; within?: string | null };
+/** One claim group (lib/report/claimGroups.mjs groupModel), as the Cut tab draws its bar. */
+export type GroupInfo = { id: string; claim: string; ids: string[]; section: number; words: string; first: string; last: string; at: number; index: number; promoted: boolean; color?: string | null };
type Ctx = {
project: string;
@@ -30,6 +32,8 @@ type Ctx = {
dragging: React.MutableRefObject<{ id: string; at: number } | null>;
/** A section boundary being dragged (its marker), else null. */
draggingBar: React.MutableRefObject<number | null>;
+ /** A claim group being dragged (its id), else null: the whole group moves. */
+ draggingGroup: React.MutableRefObject<string | 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…". */
@@ -41,9 +45,10 @@ 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 groupBarOf = (el: EventTarget | null) => (el instanceof Element ? (el.closest("li[data-group-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 }) {
+export function TimelineList({ project, count, groupCount = 0, children }: { project: string; count: number; groupCount?: number; children: React.ReactNode }) {
const router = useRouter();
// The manifest's write token, in a ref as well as state: a key pressed before
// the first read came back must wait for it, not send no token at all.
@@ -53,6 +58,7 @@ export function TimelineList({ project, count, children }: { project: string; co
const [over, setOver] = useState<number | null>(null);
const dragging = useRef<{ id: string; at: number } | null>(null);
const draggingBar = useRef<number | null>(null);
+ const draggingGroup = useRef<string | 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[]>([]);
@@ -130,7 +136,7 @@ export function TimelineList({ project, count, children }: { project: string; co
};
return (
- <TimelineCtx.Provider value={{ project, busy, run, dragging, draggingBar, sections, selected, toggle }}>
+ <TimelineCtx.Provider value={{ project, busy, run, dragging, draggingBar, draggingGroup, 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
@@ -140,6 +146,7 @@ export function TimelineList({ project, count, children }: { project: string; co
</button>
<span className="text-[var(--color-dim)]">
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" : ""}
+ {groupCount > 0 ? "; drag a claim group's ⠿ onto a row to move the whole group before it" : ""}
</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">
@@ -182,6 +189,15 @@ export function TimelineList({ project, count, children }: { project: string; co
data-drop-at={over ?? ""}
onKeyDown={onKeyDown}
onDragOver={(e) => {
+ if (draggingGroup.current !== null) {
+ // A whole group lands before a row, or before another group's bar.
+ const gb = groupBarOf(e.target);
+ const li = rowOf(e.target);
+ if (!gb && !li) return;
+ e.preventDefault();
+ if (li) setOver(rowKey(li).at);
+ return;
+ }
if (draggingBar.current !== null) {
// A boundary goes after a CLIP.
const li = rowOf(e.target);
@@ -205,11 +221,22 @@ export function TimelineList({ project, count, children }: { project: string; co
onDrop={(e) => {
const from = dragging.current;
const marker = draggingBar.current;
+ const group = draggingGroup.current;
const li = rowOf(e.target);
const bar = barOf(e.target);
+ const gbar = groupBarOf(e.target);
dragging.current = null;
draggingBar.current = null;
+ draggingGroup.current = null;
setOver(null);
+ if (group !== null) {
+ // The whole group, its clips together, before that row (or that group's first clip).
+ const before = gbar ? (gbar.dataset.groupFirst ?? null) : li ? rowKey(li).id : null;
+ if (!before || gbar?.dataset.groupBar === group) return;
+ e.preventDefault();
+ void run("group-move", { group, before });
+ return;
+ }
if (marker !== null) {
if (!li || li.dataset.kind !== "clip") return;
e.preventDefault();
@@ -598,3 +625,136 @@ export function SectionBar({ section }: { section: SectionInfo }) {
</li>
);
}
+
+/**
+ * A claim group's bar, inside its section (lib/report/claimGroups.mjs): the
+ * claim -- click it to edit it in place (Enter saves, Escape leaves it) --,
+ * its clips, ⠿ to drag the WHOLE group onto a row (it lands before it, in that
+ * row's section), Promote (a level-2 marker at its first clip, titled with the
+ * claim: at most 24 characters) and Ungroup (its clips stay where they are).
+ */
+export function GroupBar({ group }: { group: GroupInfo }) {
+ const ctx = useContext(TimelineCtx);
+ const [editing, setEditing] = useState(false);
+ const [claim, setClaim] = useState(group.claim);
+ const [promoting, setPromoting] = useState(false);
+ const [title, setTitle] = useState(group.claim);
+ if (!ctx) return null;
+ const { busy, run, draggingGroup } = ctx;
+ const save = () => {
+ const c = claim.trim();
+ if (!c || c === group.claim) {
+ setEditing(false);
+ setClaim(group.claim);
+ return;
+ }
+ void run("group-label", { group: group.id, claim: c }).then((ok) => ok && setEditing(false));
+ };
+ const tl = [...title.trim()].length;
+ const tint = group.color ? `color-mix(in srgb, ${group.color} 55%, transparent)` : "var(--color-line)";
+ return (
+ <li
+ data-group-bar={group.id}
+ data-group-first={group.first}
+ data-group-section={group.section}
+ data-group-promoted={group.promoted ? "1" : "0"}
+ className="ml-3 flex flex-wrap items-center gap-2 rounded-sm border-l-2 border-dashed bg-[var(--color-panel)] px-2 py-0.5 text-[11px]"
+ style={{ borderLeftColor: tint }}
+ >
+ <span
+ draggable={!busy}
+ data-group-handle={group.id}
+ title="drag onto a row: the whole group moves before it"
+ onDragStart={(e) => {
+ draggingGroup.current = group.id;
+ e.dataTransfer.effectAllowed = "move";
+ e.dataTransfer.setData("text/plain", `group:${group.id}`);
+ }}
+ onDragEnd={() => (draggingGroup.current = null)}
+ className="cursor-grab select-none text-[12px] leading-none text-[var(--color-dim)]"
+ >
+ ⠿
+ </span>
+ <span className="font-mono text-[var(--color-dim)]">{group.id}</span>
+ {editing ? (
+ <input
+ autoFocus
+ data-group-claim-input={group.id}
+ value={claim}
+ maxLength={160}
+ onChange={(e) => setClaim(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") save();
+ if (e.key === "Escape") {
+ setEditing(false);
+ setClaim(group.claim);
+ }
+ }}
+ onBlur={save}
+ className="min-w-64 flex-1 rounded border border-[var(--color-sel)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[11px] text-[var(--color-text)] outline-none"
+ />
+ ) : (
+ <button
+ type="button"
+ data-group-claim={group.id}
+ disabled={busy}
+ onClick={() => (setClaim(group.claim), setEditing(true))}
+ title="the group's claim — click to edit it"
+ className="min-w-0 truncate text-left text-[var(--color-text)] hover:underline"
+ >
+ {group.claim}
+ </button>
+ )}
+ {group.promoted && (
+ <span className="micro" data-group-subsection={group.id} title="a level-2 marker opens at its first clip: the render shows it as a subsection">
+ subsection
+ </span>
+ )}
+ <span className="micro">
+ {group.ids.length} clip{group.ids.length === 1 ? "" : "s"}
+ </span>
+ {!editing && !promoting && (
+ <span className="ml-auto flex items-center gap-1">
+ {!group.promoted && (
+ <button type="button" data-group-promote={group.id} disabled={busy} onClick={() => (setTitle(group.claim), setPromoting(true))} className={buttonVariants({ variant: "quiet", size: "sm" })} title="open a subsection here, titled with the claim (a level-2 marker at its first clip)">
+ promote
+ </button>
+ )}
+ <button type="button" data-group-ungroup={group.id} disabled={busy} onClick={() => void run("group-remove", { group: group.id })} className={buttonVariants({ variant: "quiet", size: "sm" })} title="ungroup: the clips stay where they are">
+ ungroup
+ </button>
+ </span>
+ )}
+ {promoting && (
+ <span data-group-promote-form={group.id} className="ml-auto inline-flex flex-wrap items-center gap-1">
+ <input
+ autoFocus
+ data-group-promote-label={group.id}
+ value={title}
+ maxLength={60}
+ placeholder="the subsection's title"
+ onChange={(e) => setTitle(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") setPromoting(false);
+ if (e.key === "Enter" && tl > 0 && tl <= 24) void run("group-promote", { group: group.id, label: title.trim() }).then((ok) => ok && setPromoting(false));
+ }}
+ className="w-56 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 ${tl > 24 ? "text-[var(--color-bad)]" : "text-[var(--color-dim)]"}`}>{tl}/24</span>
+ <button
+ type="button"
+ data-group-promote-go={group.id}
+ disabled={busy || tl === 0 || tl > 24}
+ onClick={() => void run("group-promote", { group: group.id, label: title.trim() }).then((ok) => ok && setPromoting(false))}
+ className={buttonVariants({ variant: "go", size: "sm" })}
+ >
+ Open subsection
+ </button>
+ <button type="button" disabled={busy} onClick={() => setPromoting(false)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Cancel
+ </button>
+ </span>
+ )}
+ </li>
+ );
+}
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -16,7 +16,8 @@ import { clipRecord, storedUrlOf } from "@/lib/clips/stored";
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 { GroupBar, RowControls, RowNotes, SectionBar, TimelineList, type GroupInfo, type SectionInfo } from "../TimelineEditor";
+import { groupModel } from "@/lib/report/claimGroups.mjs";
import { Pill, TONE, hms, type ReportTabProps } from "./shared";
import VoiceMatchPanel from "./VoiceMatchPanel";
import FetchWindowsPanel from "./FetchWindowsPanel";
@@ -146,6 +147,17 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
return { opening: model.sections.length > 1 ? words(model.sections[0]) : null, after, sectionOf: model.sections.length > 1 ? (model.sectionOf as Map<string, number>) : null };
})();
+ // The claim groups (lib/report/claimGroups.mjs): a bar before each group's
+ // first clip, inside its section; its clips' rows indented under it.
+ const groupBars = (() => {
+ const model = sectionModel(m);
+ const list = (groupModel(m) as GroupInfo[]).map((g) => ({ ...g, color: (model.sections[g.section] as { color?: string | null } | undefined)?.color ?? null }));
+ const at = new Map<number, GroupInfo>(list.map((g) => [g.at, g]));
+ const of = new Map<string, string>();
+ for (const g of list) for (const id of g.ids) of.set(id, g.id);
+ return { list, at, of };
+ })();
+
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
@@ -176,16 +188,18 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
// `endsSentence === null` means the source has no punctuation to
// read, which is a different thing to say than "this cut is fine".
const midSentence = e.endsSentence === false && !e.lockEnd && !e.lock;
+ const inGroup = groupBars.of.get(e.id);
return (
<li
data-entry={e.id}
data-kind="clip"
data-at={at}
+ data-group={inGroup}
tabIndex={0}
data-cached={e.cached ? "1" : "0"}
data-fetched={e.fetched ? "1" : "0"}
data-mid-sentence={midSentence ? "1" : "0"}
- className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 outline-none focus:border-[var(--color-sel)]"
+ className={`rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 outline-none focus:border-[var(--color-sel)] ${inGroup ? "ml-6" : ""}`}
>
<div className="flex flex-wrap items-baseline gap-2 text-[12px]">
<RowControls id={e.id} at={at} kind="clip" />
@@ -423,10 +437,11 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
/>
</div>
)}
- <TimelineList project={project.id} count={entries.length}>
+ <TimelineList project={project.id} count={entries.length} groupCount={groupBars.list.length}>
{sectionBars.opening && <SectionBar section={sectionBars.opening} />}
{entries.map((e, at) => (
<Fragment key={`${e.id}@${at}`}>
+ {groupBars.at.get(at) && <GroupBar key={`g:${groupBars.at.get(at)!.id}:${groupBars.at.get(at)!.claim}`} group={groupBars.at.get(at)!} />}
{renderRow(e, at)}
{sectionBars.after.get(at) && <SectionBar section={sectionBars.after.get(at)!} />}
</Fragment>
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -130,6 +130,8 @@ export type PlayViewData = {
sectionsDiffer?: boolean;
counter: { verdicts: { id: string; label: string }[]; stamps: { landed: number; verdict: string; count: number }[] };
markers: { after: string; label: string; level?: 2 }[];
+ /** The claim groups (lib/report/claimGroups.mjs): a lighter seam before each group's first clip. */
+ groups?: { id: string; claim: string; ids: string[] }[];
leadIn: number;
transition: number;
blurRendered: boolean;
@@ -775,7 +777,7 @@ export default function PlayCut({
const placed = stamps.map((x) => ({ ...x, landed: playTimeOfChrome(plan, x.landed) }));
return ids.map((id) => ({ id, label: doc?.verdictLabels?.[id] ?? labels.get(id) ?? id, steps: counterSteps(placed, id) }));
}, [schedule, view.counter, doc?.verdictLabels, plan]);
- const seams = useMemo(() => seamsOf(view.entries.filter((e) => !skipIds.has(e.id)), view.markers), [view.entries, view.markers, skipIds]);
+ const seams = useMemo(() => seamsOf(view.entries.filter((e) => !skipIds.has(e.id)), view.markers, view.groups ?? []), [view.entries, view.markers, view.groups, skipIds]);
const pins = useMemo(() => mine.map((n) => ({ id: n.id, t: noteT(n.anchor as CutAnchor), text: n.text, open: n.status === "open" })), [mine, noteT, plan]);
const stripEntries = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]);
diff --git a/umtool/components/projects/review/ReelStrip.tsx b/umtool/components/projects/review/ReelStrip.tsx
@@ -40,7 +40,8 @@ type PlayItem = ReturnType<typeof playPlan>["items"][number];
export type StripEntry = { id: string; type: string; heading: string; dateKey?: number | null; dateLabel?: string | null; media?: unknown; rejected?: { why: string } | null };
export type StripCounter = { id: string; label: string; steps: Array<{ t: number; n: number }> };
export type StripPin = { id: string; t: number; text: string; open: boolean };
-export type StripSeam = { before: string; index: number; date: string | null; label: string | null };
+/** A seam: where a section opens, or (`kind: "group"`) a claim group -- drawn lighter. */
+export type StripSeam = { before: string; index: number; date: string | null; label: string | null; kind?: "group"; group?: string };
export type StripSection = { index: number; label: string | null; color: string | null; count?: number; level?: 2; within?: string | null };
/** A structural edit the strip asks for: a drop, an Alt+arrow, or Move to…. */
export type StripEdit =
@@ -140,6 +141,7 @@ export default function ReelStrip({
// ---- the seams' labels: "27 Feb 2025 §3 Leaves it open" where they fit ----
const seamLabels = useMemo(() => {
const list = seams
+ .filter((s) => s.kind !== "group")
.map((s) => {
const it = items[s.index];
if (!it) return null;
@@ -460,9 +462,22 @@ export default function ReelStrip({
</span>
))}
- {/* the sections' seams, in the new section's colour */}
+ {/* the sections' seams, in the new section's colour; a claim group's lighter: half the height, faint, dashed */}
{seams.map((s) => {
const it = items[s.index];
+ if (s.kind === "group") {
+ return it && inView(it.from, it.from) ? (
+ <span
+ key={`g:${s.group}:${s.before}`}
+ aria-hidden
+ data-strip-group-seam={s.before}
+ data-strip-group={s.group}
+ title={s.label ? `claim group ${s.group}: ${s.label}` : `claim group ${s.group}`}
+ className="pointer-events-none absolute bottom-0 z-[2] h-1/2 w-0 border-l border-dashed opacity-45"
+ style={{ left: pct(it.from), borderColor: named ? colorOf(secs[s.index]) : "var(--text-2)" }}
+ />
+ ) : null;
+ }
return it && inView(it.from, it.from) ? (
<span
key={s.before}
diff --git a/umtool/lib/report/claimGroups.mjs b/umtool/lib/report/claimGroups.mjs
@@ -0,0 +1,792 @@
+// CLAIM GROUPS (lane L4, 2 Nov 2026): runs of clips inside a section that make
+// ONE claim -- "One of the ladies: 'I'm not a man'" is ow1 a01 b01 -- kept in
+// the manifest beside the timeline:
+//
+// "groups": [{ "id": "g7", "section": 1, "claim": "…", "ids": ["ow1", "a01", "b01"] }]
+//
+// The rules, each refused in words (validateGroups, one of structural()'s
+// checks) rather than repaired silently:
+// - a group's clips stand together: no other clip between them (a card
+// between two of them does not break the run);
+// - it sits in ONE section -- `section` is the index of the deck section
+// its clips are in (sectionEdit.mjs sectionModel; a subsection counts as a
+// section), never spanning a boundary;
+// - a clip is in at most one group; an id names a clip of the cut.
+//
+// The render never reads them: a manifest with `groups` builds exactly as the
+// same manifest without, until a group is PROMOTED (a level-2 marker at its
+// first clip, titled with its claim). A manifest without `groups` is never
+// touched by anything here.
+//
+// How the structure edits keep them (syncGroups, run by applyStructural after
+// every structural mutation, so every writer -- the Cut tab, Play's strip, the
+// CLI, a take's walk -- keeps the same rules):
+// - a clip REMOVED from the cut leaves its group, and a group left with no
+// clip goes (reanchorAfterRemove says so);
+// - a clip MOVED out of its group's run (not landing inside or at the edge
+// of the clips of its group that stayed) is detached from the group;
+// - a clip moved ALONE into the MIDDLE of a group's run -- strictly between
+// two of its clips -- JOINS that group (it stands inside the claim now; a
+// move to the edge of a run joins nothing). We chose joining over
+// refusing: a drag into a run is the gesture for "this belongs here too",
+// and a refusal would leave no way to say it but `groups set`;
+// - a WHOLE group moved (all its clips together: `groups move`, a group
+// bar's drag) keeps its clips; landing in the middle of another group is
+// refused ("…'s clips are not together"), never a merge;
+// - `section` follows the markers after every edit.
+// What moved is what the op says it moved (its result's `ids` or `id`), else
+// what is not in the longest common subsequence of the clip order before and
+// after.
+//
+// Pure: everything here mutates the manifest it is handed and returns words.
+// manifest.mjs runs the writers inside a structural write (the lock, the token,
+// the build's checks, the undo point).
+
+import { MARKER_LIMITS } from "umtool-report-to-video/marker-limits";
+import { addSectionIn, reanchorMarkers, sectionModel, sectionWords } from "./sectionEdit.mjs";
+
+/** A claim's characters, at most (one sentence: the bar shows it whole). */
+export const GROUP_CLAIM_MAX = 160;
+/** The keys a group carries, and nothing else. */
+export const GROUP_KEYS = Object.freeze(["id", "section", "claim", "ids"]);
+const GROUP_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const isClip = (e) => !!e && (e.kind ?? e.type) === "clip";
+const quoted = (s, n = 48) => {
+ const t = String(s ?? "");
+ return `"${t.length > n ? `${t.slice(0, n - 1)}…` : t}"`;
+};
+/** `g7 ("One of the ladies…")` -- how a sentence names a group. */
+export const groupWords = (g) => `${g?.id ?? "a group"}${typeof g?.claim === "string" && g.claim ? ` (${quoted(g.claim)})` : ""}`;
+
+/** Does this manifest carry groups at all? (`[]` counts: the key is there.) */
+export const hasGroups = (m) => Array.isArray(m?.groups);
+
+/** The cut's clip ids in order, each once (a variant twin counts where it first stands, as sectionModel does). */
+export function clipOrder(m) {
+ const seen = new Set();
+ const out = [];
+ for (const e of Array.isArray(m?.timeline) ? m.timeline : []) {
+ if (!isClip(e) || typeof e.id !== "string" || seen.has(e.id)) continue;
+ seen.add(e.id);
+ out.push(e.id);
+ }
+ return out;
+}
+
+/** An id not yet a group's: `g<n>`. */
+export function freshGroupId(groups) {
+ const ids = new Set((groups ?? []).map((g) => g?.id));
+ for (let n = 1; ; n += 1) if (!ids.has(`g${n}`)) return `g${n}`;
+}
+
+/**
+ * Every reason the cut's groups are wrong, in sentences ([] without `groups`).
+ * One of structural()'s checks (manifest.mjs structureErrors): an edit is
+ * refused only for what it breaks.
+ *
+ * @param {Record<string, any>} m
+ * @returns {string[]}
+ */
+export function validateGroups(m) {
+ if (m?.groups === undefined) return [];
+ if (!Array.isArray(m.groups)) return ["groups must be a list of {id, section, claim, ids}"];
+ const errors = [];
+ const order = clipOrder(m);
+ const pos = new Map(order.map((id, k) => [id, k]));
+ const model = sectionModel(m);
+ const owner = new Map();
+ const ids = new Set();
+ m.groups.forEach((g, k) => {
+ const W = `groups[${k}]`;
+ if (!isObj(g)) {
+ errors.push(`${W} must be {id, section, claim, ids}`);
+ return;
+ }
+ const name = typeof g.id === "string" ? groupWords(g) : W;
+ const extra = Object.keys(g).filter((x) => !GROUP_KEYS.includes(x));
+ if (extra.length) errors.push(`${name}: unknown key${extra.length === 1 ? "" : "s"} ${extra.join(", ")} (a group is ${GROUP_KEYS.join(", ")})`);
+ if (typeof g.id !== "string" || !GROUP_ID_RE.test(g.id)) errors.push(`${W}.id must be letters, digits, - or _ (at most 64)`);
+ else if (ids.has(g.id)) errors.push(`group id ${g.id} is used twice`);
+ else ids.add(g.id);
+ if (typeof g.claim !== "string" || !g.claim.trim()) errors.push(`${name} needs its claim, in words`);
+ else if ([...g.claim].length > GROUP_CLAIM_MAX) errors.push(`${name}: a claim is at most ${GROUP_CLAIM_MAX} characters (this one is ${[...g.claim].length})`);
+ if (!Array.isArray(g.ids) || !g.ids.length) {
+ errors.push(`${name} needs its clips (ids, at least one)`);
+ return;
+ }
+ const mine = [];
+ for (const id of g.ids) {
+ if (typeof id !== "string" || !id) {
+ errors.push(`${name}: every id is a clip's id`);
+ continue;
+ }
+ if (!pos.has(id)) {
+ errors.push(`${name} names ${id}, which is not a clip of the cut`);
+ continue;
+ }
+ if (owner.has(id)) {
+ errors.push(`${id} is in two groups: ${owner.get(id)} and ${g.id}`);
+ continue;
+ }
+ owner.set(id, g.id);
+ mine.push(id);
+ }
+ if (!mine.length) return;
+ const at = mine.map((id) => pos.get(id)).sort((a, b) => a - b);
+ const lo = at[0];
+ const hi = at[at.length - 1];
+ if (hi - lo + 1 !== at.length) {
+ const between = order.slice(lo, hi + 1).filter((id) => !mine.includes(id));
+ errors.push(`${name}'s clips are not together: ${between.join(", ")} stand${between.length === 1 ? "s" : ""} between ${order[lo]} and ${order[hi]}`);
+ return;
+ }
+ const secs = [...new Set(mine.map((id) => model.sectionOf.get(id)))].sort((a, b) => a - b);
+ if (secs.length > 1) {
+ errors.push(`${name} spans ${secs.map((s) => sectionWords(model.sections[s])).join(" and ")}: a group never crosses a section boundary`);
+ return;
+ }
+ if (g.section !== secs[0]) {
+ errors.push(`${name}'s section is ${JSON.stringify(g.section ?? null)}, but its clips are in ${sectionWords(model.sections[secs[0]])}`);
+ }
+ });
+ return errors;
+}
+
+/**
+ * The ids that kept their order: the longest common subsequence of two id
+ * lists, a group's clip counting a little more than a loose one -- so when a
+ * loose clip and a grouped one could each be the one that moved (a swap), the
+ * loose one moved. Past ~4 million cells nothing is called moved.
+ */
+function lcsKept(a, b, member) {
+ const n = a.length;
+ const m = b.length;
+ if (n * m > 4_000_000) return new Set(a);
+ const w = (id) => (member.has(id) ? 1001 : 1000);
+ const L = Array.from({ length: n + 1 }, () => new Float64Array(m + 1));
+ for (let i = n - 1; i >= 0; i -= 1) {
+ for (let j = m - 1; j >= 0; j -= 1) L[i][j] = a[i] === b[j] ? L[i + 1][j + 1] + w(a[i]) : Math.max(L[i + 1][j], L[i][j + 1]);
+ }
+ const kept = new Set();
+ for (let i = 0, j = 0; i < n && j < m; ) {
+ if (a[i] === b[j]) {
+ kept.add(a[i]);
+ i += 1;
+ j += 1;
+ } else if (L[i + 1][j] >= L[i][j + 1]) i += 1;
+ else j += 1;
+ }
+ return kept;
+}
+
+/**
+ * After a structural edit: the groups follow the cut (the rules at the top).
+ * `before` is the clip order before the edit (clipOrder); `moved`, when the op
+ * says, the ids it moved (else the ones out of the longest common
+ * subsequence). `rebuilt`: the op wrote the groups itself (import, set, …):
+ * only `section` and the order of each group's ids are recomputed. Mutates
+ * `m`; returns one sentence per change. A manifest without `groups` is never
+ * touched.
+ *
+ * @param {Record<string, any>} m
+ * @param {string[]} before
+ * @param {{ moved?: Iterable<string> | null, rebuilt?: boolean }} [opts]
+ * @returns {string[]}
+ */
+export function syncGroups(m, before, { moved = null, rebuilt = false } = {}) {
+ if (!hasGroups(m)) return [];
+ const notes = [];
+ const order = clipOrder(m);
+ const pos = new Map(order.map((id, k) => [id, k]));
+ const valid = m.groups.filter((g) => isObj(g) && Array.isArray(g.ids));
+ if (!rebuilt) {
+ const was = new Set(before);
+ let mv;
+ if (moved) {
+ mv = new Set([...moved].filter((id) => pos.has(id)));
+ } else {
+ const member = new Set(valid.flatMap((g) => g.ids));
+ const kept = lcsKept(before.filter((id) => pos.has(id)), order.filter((id) => was.has(id)), member);
+ mv = new Set(order.filter((id) => was.has(id) && !kept.has(id)));
+ }
+ for (const id of order) if (!was.has(id)) mv.add(id);
+ // A clip that left the cut leaves its group (reanchorAfterRemove already said so for a removal).
+ for (const g of valid) {
+ const gone = g.ids.filter((id) => typeof id === "string" && !pos.has(id));
+ if (gone.length) {
+ g.ids = g.ids.filter((id) => !gone.includes(id));
+ notes.push(`group ${groupWords(g)}: ${gone.join(", ")} left the cut`);
+ }
+ }
+ const ownerOf = new Map();
+ for (const g of valid) for (const id of g.ids) ownerOf.set(id, g);
+ // A whole group moved: every clip it has moved with the edit.
+ const wholeMoved = new Set(valid.filter((g) => g.ids.length && g.ids.every((id) => mv.has(id))));
+ // JOIN: a clip moved alone that lands strictly between two clips of a group that stayed.
+ for (const id of order) {
+ if (!mv.has(id)) continue;
+ const own = ownerOf.get(id);
+ if (own && wholeMoved.has(own)) continue;
+ const p = pos.get(id);
+ for (const g of valid) {
+ if (g === own || wholeMoved.has(g)) continue;
+ const stay = g.ids.filter((x) => !mv.has(x)).map((x) => pos.get(x));
+ if (stay.length < 2 || !(Math.min(...stay) < p && p < Math.max(...stay))) continue;
+ if (own) {
+ own.ids = own.ids.filter((x) => x !== id);
+ notes.push(`${id} left group ${groupWords(own)}`);
+ }
+ g.ids.push(id);
+ ownerOf.set(id, g);
+ notes.push(`${id} joined group ${groupWords(g)}: it was moved into the middle of its run`);
+ break;
+ }
+ }
+ // DETACH: a moved clip that is no longer with the clips of its group that stayed.
+ for (const g of valid) {
+ if (!g.ids.length) continue;
+ const at = (x) => pos.get(x);
+ const stay = g.ids.filter((x) => !mv.has(x));
+ let keep;
+ if (!stay.length) {
+ // The whole group moved: its largest run of clips together is the group.
+ const runs = runsOf(g.ids.map(at).sort((a, b) => a - b));
+ keep = new Set(runs.sort((a, b) => b.length - a.length)[0].map((k) => order[k]));
+ } else {
+ const s = stay.map(at).sort((a, b) => a - b);
+ let lo = s[0];
+ let hi = s[s.length - 1];
+ const mine = new Set(g.ids.map(at));
+ // The stayed clips' span, grown by the moved ones that stand right at its edges.
+ while (mine.has(lo - 1)) lo -= 1;
+ while (mine.has(hi + 1)) hi += 1;
+ keep = new Set(g.ids.filter((x) => at(x) >= lo && at(x) <= hi));
+ }
+ const off = g.ids.filter((x) => !keep.has(x));
+ if (off.length) {
+ g.ids = g.ids.filter((x) => keep.has(x));
+ notes.push(`${off.join(", ")} ${off.length === 1 ? "was" : "were"} moved out of group ${groupWords(g)}'s run: detached from it`);
+ }
+ }
+ }
+ // An emptied group goes; each group's ids in cut order; its section from the markers.
+ const model = sectionModel(m);
+ m.groups = m.groups.filter((g) => {
+ if (!isObj(g) || !Array.isArray(g.ids)) return true;
+ if (g.ids.length) return true;
+ notes.push(`group ${groupWords(g)} dropped: no clip of it is left`);
+ return false;
+ });
+ for (const g of m.groups) {
+ if (!isObj(g) || !Array.isArray(g.ids) || !g.ids.length) continue;
+ if (g.ids.every((id) => pos.has(id))) g.ids.sort((a, b) => pos.get(a) - pos.get(b));
+ const first = g.ids.find((id) => pos.has(id));
+ const s = first === undefined ? undefined : model.sectionOf.get(first);
+ if (s !== undefined) g.section = s;
+ }
+ return notes;
+}
+
+/** Maximal runs of consecutive integers in a sorted list. */
+function runsOf(sorted) {
+ const runs = [];
+ for (const k of sorted) {
+ const r = runs[runs.length - 1];
+ if (r && r[r.length - 1] === k - 1) r.push(k);
+ else runs.push([k]);
+ }
+ return runs;
+}
+
+/**
+ * Clip `id` left the cut: it leaves its group, and a group with no clip left
+ * goes. Returns one sentence per change (reanchorAfterRemove's).
+ */
+export function dropFromGroups(m, id) {
+ if (!hasGroups(m)) return [];
+ const notes = [];
+ m.groups = m.groups.filter((g) => {
+ if (!isObj(g) || !Array.isArray(g.ids) || !g.ids.includes(id)) return true;
+ g.ids = g.ids.filter((x) => x !== id);
+ if (g.ids.length) {
+ notes.push(`group ${groupWords(g)}: ${id} dropped from it`);
+ return true;
+ }
+ notes.push(`group ${groupWords(g)} dropped: ${id} was its only clip`);
+ return false;
+ });
+ return notes;
+}
+
+/** After a split of `firstId`: the second half is in the first half's group too. */
+export function followSplitGroups(m, firstId, secondId) {
+ if (!hasGroups(m)) return [];
+ const g = m.groups.find((x) => isObj(x) && Array.isArray(x.ids) && x.ids.includes(firstId));
+ if (!g) return [];
+ g.ids.splice(g.ids.indexOf(firstId) + 1, 0, secondId);
+ return [`${secondId} is in group ${groupWords(g)}, as ${firstId} is`];
+}
+
+/**
+ * The groups as the Cut tab, the strip and `groups ls` show them, in cut
+ * order: `{ id, claim, ids, section, words (the section's), index, first,
+ * last, at (the first clip's index in the timeline), promoted }` --
+ * `promoted` when a level-2 marker opens at its first clip (its claim a
+ * subsection's title).
+ *
+ * @param {Record<string, any>} m
+ */
+export function groupModel(m) {
+ if (!hasGroups(m)) return [];
+ const model = sectionModel(m);
+ const tl = Array.isArray(m.timeline) ? m.timeline : [];
+ const at = new Map();
+ tl.forEach((e, i) => {
+ if (isClip(e) && !at.has(e.id)) at.set(e.id, i);
+ });
+ const opensAt = new Map(model.sections.filter((s) => s.marker !== null).map((s) => [s.first, s]));
+ return m.groups
+ .filter((g) => isObj(g) && Array.isArray(g.ids) && g.ids.some((id) => at.has(id)))
+ .map((g) => {
+ const ids = g.ids.filter((id) => at.has(id));
+ const first = ids.reduce((a, b) => (at.get(b) < at.get(a) ? b : a));
+ const last = ids.reduce((a, b) => (at.get(b) > at.get(a) ? b : a));
+ const s = model.sectionOf.get(first) ?? 0;
+ const opens = opensAt.get(first);
+ return {
+ id: String(g.id),
+ claim: typeof g.claim === "string" ? g.claim : "",
+ ids,
+ section: s,
+ words: sectionWords(model.sections[s] ?? model.sections[0]),
+ first,
+ last,
+ at: at.get(first),
+ promoted: !!opens && opens.level === 2 && opens.index === s,
+ };
+ })
+ .sort((a, b) => a.at - b.at)
+ .map((g, index) => ({ ...g, index }));
+}
+
+// ---- the writers (each run inside a structural write by manifest.mjs) -----
+//
+// Each returns `{ …, groupsWritten: true }` when it wrote the groups itself,
+// so syncGroups only recomputes their sections after it.
+
+function needGroup(m, gid) {
+ const g = hasGroups(m) ? m.groups.find((x) => isObj(x) && x.id === gid) : null;
+ if (!g) throw new Error(`no group ${gid}${hasGroups(m) && m.groups.length ? ` (${m.groups.map((x) => x?.id).join(", ")})` : " (the cut has no groups)"}`);
+ return g;
+}
+
+const claimOf = (v) => {
+ const c = typeof v === "string" ? v.trim().replace(/\s+/g, " ") : "";
+ if (!c) throw new Error("a group needs its claim, in words");
+ if ([...c].length > GROUP_CLAIM_MAX) throw new Error(`a claim is at most ${GROUP_CLAIM_MAX} characters (this one is ${[...c].length})`);
+ return c;
+};
+
+/**
+ * SET: group `gid` is clips `ids` now (a new group when there is none by that
+ * id, or `gid` null/"-": a fresh `g<n>`). The clips must already stand
+ * together in one section -- reorder first (`order`, `place`); a clip in
+ * another group leaves it (that group must stay together, or it is refused).
+ *
+ * @param {Record<string, any>} m
+ * @param {string | null} gid
+ * @param {string[]} ids
+ * @param {{ claim?: string | null }} [opts]
+ */
+export function setGroupIn(m, gid, ids, { claim = null } = {}) {
+ if (!hasGroups(m)) m.groups = [];
+ const want = [...new Set((Array.isArray(ids) ? ids : [ids]).map((x) => String(x ?? "").trim()).filter(Boolean))];
+ if (!want.length) throw new Error("name the group's clips");
+ const order = clipOrder(m);
+ for (const id of want) if (!order.includes(id)) throw new Error(`${id} is not a clip of the cut`);
+ const fresh = !gid || gid === "-" ? freshGroupId(m.groups) : String(gid).trim();
+ if (!GROUP_ID_RE.test(fresh)) throw new Error("a group id is letters, digits, - or _ (at most 64)");
+ let g = m.groups.find((x) => isObj(x) && x.id === fresh);
+ const created = !g;
+ if (!g) {
+ g = { id: fresh, section: 0, claim: claimOf(claim), ids: [] };
+ m.groups.push(g);
+ } else if (claim !== null && claim !== undefined) g.claim = claimOf(claim);
+ const notes = [];
+ for (const o of m.groups) {
+ if (o === g || !isObj(o) || !Array.isArray(o.ids)) continue;
+ const taken = o.ids.filter((x) => want.includes(x));
+ if (!taken.length) continue;
+ o.ids = o.ids.filter((x) => !want.includes(x));
+ notes.push(`${taken.join(", ")} left group ${groupWords(o)}`);
+ }
+ const was = g.ids.slice();
+ g.ids = want;
+ m.groups = m.groups.filter((o) => {
+ if (o === g || !isObj(o) || !Array.isArray(o.ids) || o.ids.length) return true;
+ notes.push(`group ${groupWords(o)} dropped: no clip of it is left`);
+ return false;
+ });
+ return { id: g.id, created, ids: g.ids.slice(), was, claim: g.claim, notes, groupsWritten: true };
+}
+
+/** LABEL: group `gid`'s claim. */
+export function labelGroupIn(m, gid, claim) {
+ const g = needGroup(m, gid);
+ const was = g.claim;
+ g.claim = claimOf(claim);
+ if (was === g.claim) throw new Error(`${gid}'s claim is already ${quoted(g.claim)}`);
+ return { id: g.id, claim: g.claim, was, groupsWritten: true };
+}
+
+/** REMOVE (ungroup): group `gid` goes; its clips stay where they are. */
+export function removeGroupIn(m, gid) {
+ const g = needGroup(m, gid);
+ m.groups = m.groups.filter((x) => x !== g);
+ return { id: g.id, removed: { ...g }, groupsWritten: true };
+}
+
+/**
+ * MOVE A WHOLE GROUP: its clips, together, to another place among the groups
+ * -- `to` its index among the groups AFTER the move (0 first: right before the
+ * group now at that index, in its section; the number of the others: after the
+ * last), or `after` another group (right after its last clip, in its section).
+ * The markers follow so every other clip keeps its section (sectionEdit.mjs
+ * placeIn); a section left with no clip is refused.
+ *
+ * @param {Record<string, any>} m
+ * @param {string} gid
+ * @param {{ to?: number | null, after?: string | null }} where
+ * @param {(m: Record<string, any>, ids: string[], o: { before: string | null, section: number | null }) => Record<string, any>} place sectionEdit.mjs placeIn
+ */
+export function moveGroupIn(m, gid, { to = null, after = null } = {}, place) {
+ needGroup(m, gid);
+ const all = groupModel(m);
+ const me = all.find((g) => g.id === gid);
+ if (!me) throw new Error(`group ${gid} names no clip of the cut`);
+ const others = all.filter((g) => g.id !== gid);
+ const tl = m.timeline;
+ const after1 = (clipId) => {
+ // The entry right after `clipId` that is not one of the group's own.
+ const i = tl.findIndex((e) => e?.id === clipId);
+ const next = tl.slice(i + 1).find((e) => !me.ids.includes(e?.id));
+ return next ? next.id : null;
+ };
+ let before;
+ let section;
+ let words;
+ if (after !== null && after !== undefined && after !== "") {
+ const o = others.find((g) => g.id === after);
+ if (!o) throw new Error(after === gid ? `${gid} cannot go after itself` : `no other group ${after}`);
+ before = after1(o.last);
+ section = o.section;
+ words = `after ${groupWords(o)}`;
+ } else {
+ const k = Number(to);
+ if (!Number.isInteger(k) || k < 0 || k > others.length) throw new Error(`--to is a group's place, 0–${others.length} (\`groups ls\` lists them)`);
+ if (k === others.length) {
+ const o = others[others.length - 1];
+ if (!o) throw new Error("there is no other group to move it among");
+ before = after1(o.last);
+ section = o.section;
+ words = `after ${groupWords(o)}, the last`;
+ } else {
+ const o = others[k];
+ before = o.first;
+ section = o.section;
+ words = `before ${groupWords(o)}`;
+ }
+ }
+ const r = place(m, me.ids, { before, section: deckSections(m) ? section : null });
+ return { id: gid, ids: me.ids, words, section: r.section, before: r.before, reanchored: r.reanchored ?? [], from: me.index };
+}
+
+const deckSections = (m) => isObj(m?.render?.chrome);
+
+/**
+ * PROMOTE: the group opens a SUBSECTION -- a level-2 marker right before its
+ * first clip (after the clip before it), titled with its claim (`label`, when
+ * the claim is longer than a marker's label may be). The render changes from
+ * here on: the rail gets the subsection's tick, the section title its
+ * "Section › claim". Refused when no clip comes before it, when a section
+ * already opens there, and by the deck's own checks (the cut's first marker
+ * must be a section: a group in §0 opens none).
+ *
+ * @param {Record<string, any>} m
+ * @param {string} gid
+ * @param {{ label?: string | null }} [opts]
+ */
+export function promoteGroupIn(m, gid, { label = null } = {}) {
+ const g = needGroup(m, gid);
+ const me = groupModel(m).find((x) => x.id === gid);
+ if (!me) throw new Error(`group ${gid} names no clip of the cut`);
+ const text = typeof label === "string" && label.trim() ? label.trim() : String(g.claim ?? "").trim();
+ if ([...text].length > MARKER_LIMITS.label) {
+ throw new Error(`${groupWords(g)}: a marker's label is at most ${MARKER_LIMITS.label} characters and ${label ? "this one" : "the claim"} is ${[...text].length} — give the subsection a shorter title (--label)`);
+ }
+ const tl = m.timeline;
+ const i = tl.findIndex((e) => e?.id === me.first);
+ const prev = [...tl.slice(0, i)].reverse().find(isClip);
+ if (!prev) throw new Error(`${groupWords(g)} opens the cut: no clip before it for a marker to follow`);
+ if (me.promoted) throw new Error(`${groupWords(g)} already opens a subsection`);
+ const model = sectionModel(m);
+ const opens = model.sections.find((s) => s.marker !== null && s.first === me.first);
+ if (opens) throw new Error(`${groupWords(g)} already opens ${sectionWords(opens)}: a marker is there`);
+ const r = addSectionIn(m, prev.id, { label: text, level: 2 });
+ return { id: gid, marker: r.marker, after: prev.id, label: text, opens: me.first, within: sectionWords(model.sections[me.section]) };
+}
+
+// ---- import (the shape of a claim-groups.json) and order --------------------
+
+const norm = (s) => String(s ?? "").normalize("NFKC").toLowerCase().replace(/[‐-―]/g, "-").replace(/\s+/g, " ").trim();
+
+/**
+ * A claim-groups file: `{ sections: [{ label, groups: [{ claim, ids[] }] }] }`.
+ * Checked, never repaired: the shape, every claim, every id once.
+ *
+ * @param {unknown} doc
+ * @returns {{ sections: Array<{ label: string | null, groups: Array<{ claim: string, ids: string[] }> }> }}
+ */
+export function parseGroupsDoc(doc) {
+ if (!isObj(doc) || !Array.isArray(doc.sections)) throw new Error("a groups file is {sections: [{label, groups: [{claim, ids}]}]}");
+ const seen = new Map();
+ const sections = doc.sections.map((s, k) => {
+ if (!isObj(s) || !Array.isArray(s.groups)) throw new Error(`sections[${k}] is {label, groups: [{claim, ids}]}`);
+ const label = typeof s.label === "string" && s.label.trim() ? s.label.trim() : null;
+ const groups = s.groups.map((g, j) => {
+ const W = `sections[${k}].groups[${j}]`;
+ if (!isObj(g) || !Array.isArray(g.ids) || !g.ids.length) throw new Error(`${W} is {claim, ids: [clip ids]}`);
+ let claim;
+ try {
+ claim = claimOf(g.claim);
+ } catch (e) {
+ throw new Error(`${W}: ${e instanceof Error ? e.message : e}`);
+ }
+ const ids = g.ids.map((x) => String(x ?? "").trim());
+ for (const id of ids) {
+ if (!id) throw new Error(`${W}: an empty id`);
+ if (seen.has(id)) throw new Error(`${id} is named twice in the file (${seen.get(id)} and ${W})`);
+ seen.set(id, W);
+ }
+ return { claim, ids };
+ });
+ return { label, groups };
+ });
+ return { sections };
+}
+
+/**
+ * IMPORT a claim-groups file in ONE edit: the timeline re-ordered to the
+ * file's, its groups the cut's groups (the old ones replaced), the markers
+ * re-anchored around the new order.
+ *
+ * Each of the file's sections is one of the deck's: the section of the same
+ * name (case and dashes aside), else -- a file section the deck has no name
+ * for ("As a woman" inside the opening) -- the section most of its clips are
+ * in now, kept in order between its neighbours. Several file sections may be
+ * one deck section; they never come out of order (refused). A clip the file
+ * does not name stays in its section, after the file's clips. Refused unless
+ * told otherwise: an id the cut does not have (`skipMissing`: left out, and
+ * said), a section left with no clip (`dropEmpty`: its marker removed, and
+ * said; the opening, which has no marker, is never dropped).
+ *
+ * @param {Record<string, any>} m
+ * @param {unknown} doc
+ * @param {{ skipMissing?: boolean, dropEmpty?: boolean }} [opts]
+ */
+export function importGroupsIn(m, doc, { skipMissing = false, dropEmpty = false } = {}) {
+ const file = parseGroupsDoc(doc);
+ const tl = Array.isArray(m.timeline) ? m.timeline : (m.timeline = []);
+ const present = new Set(clipOrder(m));
+ const named = file.sections.flatMap((s) => s.groups.flatMap((g) => g.ids));
+ const missing = named.filter((id) => !present.has(id));
+ if (missing.length && !skipMissing) {
+ throw new Error(`the file names ${missing.length} clip${missing.length === 1 ? "" : "s"} the cut does not have: ${missing.join(", ")} — pass --skip-missing to leave ${missing.length === 1 ? "it" : "them"} out`);
+ }
+ const notes = [];
+ if (missing.length) notes.push(`left out (not clips of the cut): ${missing.join(", ")}`);
+ const model = sectionModel(m);
+ const deck = model.sections;
+ // ---- each file section to a deck section ----
+ const live = file.sections.map((s) => ({ ...s, groups: s.groups.map((g) => ({ ...g, ids: g.ids.filter((id) => present.has(id)) })).filter((g) => g.ids.length) }));
+ const byLabel = (label, from) => (label === null ? -1 : deck.findIndex((d, k) => k >= from && d.label !== null && norm(d.label) === norm(label)));
+ const mapped = live.map(() => /** @type {number | null} */ (null));
+ let floor = 0;
+ live.forEach((s, k) => {
+ if (!s.groups.length) return;
+ const hit = byLabel(s.label, floor);
+ if (hit < 0) {
+ const earlier = byLabel(s.label, 0);
+ if (earlier < 0) return;
+ const prevK = mapped.findLastIndex((x) => x !== null && x > earlier);
+ throw new Error(`the file's sections are out of the cut's order: "${s.label}" (${sectionWords(deck[earlier])}) comes after "${live[prevK]?.label}" (${sectionWords(deck[mapped[prevK]])})`);
+ }
+ mapped[k] = hit;
+ floor = hit;
+ });
+ live.forEach((s, k) => {
+ if (!s.groups.length || mapped[k] !== null) return;
+ const lo = mapped.slice(0, k).reduce((a, x) => (x === null ? a : x), 0);
+ const hiK = mapped.findIndex((x, j) => j > k && x !== null);
+ const hi = hiK < 0 ? deck.length - 1 : mapped[hiK];
+ const count = new Map();
+ for (const g of s.groups) for (const id of g.ids) count.set(model.sectionOf.get(id), (count.get(model.sectionOf.get(id)) ?? 0) + 1);
+ const most = [...count.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0][0];
+ const at = Math.min(hi, Math.max(lo, most));
+ mapped[k] = at;
+ notes.push(`"${s.label ?? `section ${k + 1}`}" → ${sectionWords(deck[at])}: the deck has no section of that name; ${at === most ? "most of its clips are there" : "the nearest in order to where its clips are"}`);
+ });
+ // ---- each deck section's clips: the file's (in its order), then the ones it does not name ----
+ const fileIds = new Set(named.filter((id) => present.has(id)));
+ const into = deck.map(() => /** @type {string[]} */ ([]));
+ live.forEach((s, k) => {
+ for (const g of s.groups) into[mapped[k]].push(...g.ids);
+ });
+ const unnamed = clipOrder(m).filter((id) => !fileIds.has(id));
+ for (const id of unnamed) into[model.sectionOf.get(id)].push(id);
+ if (unnamed.length) notes.push(`not in the file, kept at the end of their sections: ${unnamed.join(", ")}`);
+ const empty = deck.filter((d) => !into[d.index].length);
+ if (empty.some((d) => d.index === 0)) throw new Error(`the opening (§0) would have no clip: the file's first section is ${sectionWords(deck[mapped.find((x) => x !== null) ?? 0])} — the opening has no marker to remove`);
+ if (empty.length && !dropEmpty) {
+ throw new Error(`the file leaves ${empty.map((d) => sectionWords(d)).join(", ")} with no clip (the file has no section of that name, and puts its clips in others) — pass --drop-empty to remove ${empty.length === 1 ? "its marker" : "their markers"}`);
+ }
+ // ---- the new timeline: the clips in that order, a card after the clip it followed ----
+ const newClips = into.flat();
+ const byId = new Map();
+ const cardsAfter = new Map();
+ let lead = [];
+ let lastClip = null;
+ for (const e of tl) {
+ if (isClip(e) && !byId.has(e.id)) {
+ byId.set(e.id, [e]);
+ lastClip = e.id;
+ } else if (isClip(e)) byId.get(e.id).push(e);
+ else if (lastClip === null) lead.push(e);
+ else cardsAfter.set(lastClip, [...(cardsAfter.get(lastClip) ?? []), e]);
+ }
+ const before = tl.map((e) => e?.id).join("\n");
+ const next = [...lead];
+ for (const id of newClips) next.push(...byId.get(id), ...(cardsAfter.get(id) ?? []));
+ tl.splice(0, tl.length, ...next);
+ // ---- the markers: each kept section opens after the last clip of the kept one before it ----
+ const markers = m.render?.chrome?.deck?.markers;
+ const moved = [];
+ if (Array.isArray(markers)) {
+ const kept = deck.filter((d) => into[d.index].length);
+ for (let k = 1; k < kept.length; k += 1) {
+ const mk = markers[kept[k].marker];
+ const after = into[kept[k - 1].index][into[kept[k - 1].index].length - 1];
+ if (mk.after !== after) {
+ moved.push(`marker ${kept[k].marker}${mk.label ? ` ("${mk.label}")` : ""} moved from after ${mk.after} to after ${after}`);
+ mk.after = after;
+ }
+ }
+ const drop = new Set(empty.map((d) => markers[d.marker]));
+ for (const d of empty) notes.push(`${sectionWords(d)} removed: the file has no section of that name and puts all its clips in others`);
+ m.render.chrome.deck.markers = markers.filter((mk) => !drop.has(mk));
+ }
+ // ---- the groups: the file's, in its order ----
+ const old = hasGroups(m) ? m.groups.length : 0;
+ const groups = [];
+ for (const s of live) for (const g of s.groups) groups.push({ id: `g${groups.length + 1}`, section: 0, claim: g.claim, ids: g.ids });
+ m.groups = groups;
+ const skippedGroups = file.sections.reduce((n, s) => n + s.groups.length, 0) - groups.length;
+ if (skippedGroups) notes.push(`${skippedGroups} group${skippedGroups === 1 ? "" : "s"} left out: none of ${skippedGroups === 1 ? "its" : "their"} clips is in the cut`);
+ return {
+ groups: groups.length,
+ replaced: old,
+ sections: live.map((s, k) => ({ label: s.label, section: mapped[k], groups: s.groups.length })),
+ moved: before !== tl.map((e) => e?.id).join("\n"),
+ missing,
+ dropped: empty.map((d) => ({ index: d.index, label: d.label })),
+ reanchored: moved,
+ notes,
+ groupsWritten: true,
+ };
+}
+
+/**
+ * ORDER: the named entries take the places the named entries hold now, in the
+ * order given; every other entry stays where it is (name them all for the
+ * whole order). Each clip keeps its section -- the markers are re-anchored --
+ * so an order that puts a clip among another section's is refused (move it
+ * across with `place` or `section-move`). The groups follow (syncGroups).
+ *
+ * @param {Record<string, any>} m
+ * @param {string[]} ids
+ */
+export function orderIn(m, ids) {
+ const tl = Array.isArray(m.timeline) ? m.timeline : [];
+ const want = (Array.isArray(ids) ? ids : []).map((x) => String(x ?? "").trim()).filter(Boolean);
+ if (!want.length) throw new Error("order needs the entries' ids, in their new order");
+ const seen = new Set();
+ for (const id of want) {
+ if (seen.has(id)) throw new Error(`${id} is named twice`);
+ seen.add(id);
+ const n = tl.filter((e) => e?.id === id).length;
+ if (!n) throw new Error(`no timeline entry with id ${id}`);
+ if (n > 1) throw new Error(`${id} is in the timeline ${n} times — order one twin with \`timeline move\``);
+ }
+ const slots = [];
+ tl.forEach((e, i) => {
+ if (seen.has(e?.id)) slots.push(i);
+ });
+ const byId = new Map(tl.map((e) => [e?.id, e]));
+ const before = tl.map((e) => e?.id).join("\n");
+ const next = tl.slice();
+ slots.forEach((slot, k) => {
+ next[slot] = byId.get(want[k]);
+ });
+ const model = sectionModel(m);
+ let reanchored = [];
+ if (Array.isArray(m.render?.chrome?.deck?.markers) && model.sections.length > 1) {
+ // Every clip in its own section: the sections must still follow one another.
+ let prev = 0;
+ let prevId = null;
+ for (const e of next) {
+ if (!isClip(e)) continue;
+ const s = model.sectionOf.get(e.id);
+ if (s < prev) {
+ throw new Error(`${e.id} (${sectionWords(model.sections[s])}) would stand after ${prevId} (${sectionWords(model.sections[prev])}): order keeps every clip in its section — move it across with place or section-move`);
+ }
+ prev = s;
+ prevId = e.id;
+ }
+ tl.splice(0, tl.length, ...next);
+ reanchored = reanchorMarkers(m, model, new Map(model.sectionOf));
+ } else {
+ tl.splice(0, tl.length, ...next);
+ }
+ if (before === tl.map((e) => e?.id).join("\n") && !reanchored.length) throw new Error("that is the order the cut already has");
+ // `named`, not `ids`: what moved is what the order changed (syncGroups' common subsequence), not every id named.
+ return { named: want, count: want.length, of: tl.length, reanchored };
+}
+
+/**
+ * An order as a file or the words of a command: a JSON list of ids, `{order:
+ * […]}`, `{timeline: [{id}…]}`, a claim-groups file (its ids in order), or ids
+ * separated by spaces, commas or lines.
+ *
+ * @param {string} text
+ * @returns {string[]}
+ */
+export function parseOrderText(text) {
+ const t = String(text ?? "").trim();
+ if (!t) return [];
+ if (/^[[{]/.test(t)) {
+ let j;
+ try {
+ j = JSON.parse(t);
+ } catch (e) {
+ throw new Error(`not JSON (${e instanceof Error ? e.message : e})`);
+ }
+ if (Array.isArray(j)) return j.map(String);
+ if (isObj(j) && Array.isArray(j.order)) return j.order.map(String);
+ if (isObj(j) && Array.isArray(j.timeline)) return j.timeline.map((e) => String(isObj(e) ? e.id : e));
+ if (isObj(j) && Array.isArray(j.sections)) return parseGroupsDoc(j).sections.flatMap((s) => s.groups.flatMap((g) => g.ids));
+ throw new Error("an order is a list of ids, {order: […]}, {timeline: [{id}…]} or a claim-groups file");
+ }
+ return t.split(/[\s,]+/).filter(Boolean);
+}
diff --git a/umtool/lib/report/claimGroups.test.mjs b/umtool/lib/report/claimGroups.test.mjs
@@ -0,0 +1,300 @@
+// Claim groups (claimGroups.mjs, lane L4) through umtool's writers: the
+// validator's sentences, a manifest without groups left exactly as it was,
+// every structural edit keeping the groups (a removal drops the clip, a move
+// out of the run detaches it, a move alone into the middle joins, a whole
+// group into another's middle is refused), the writers (set, label, remove,
+// move, promote, import, order), one undo point each, and the CLI.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { clipOrder, groupModel, parseOrderText, syncGroups, validateGroups } from "./claimGroups.mjs";
+import { seamsOf } from "./playCut.mjs";
+import { groupLines, groupsView, timelineCommand } from "./timelineCli.mjs";
+import {
+ MANIFEST_NAME,
+ StructureRefused,
+ importGroups,
+ labelGroup,
+ manifestToken,
+ moveEntry,
+ moveGroup,
+ moveSectionBoundary,
+ orderEntries,
+ placeEntries,
+ promoteGroup,
+ removeEntry,
+ removeGroup,
+ setGroup,
+ undoStructural,
+ addSection,
+} from "./manifest.mjs";
+
+const clip = (id, i) => ({ type: "clip", id, video: "v1", start: 10 * i, end: 10 * i + 8 });
+const IDS = ["a", "b", "c", "d", "e", "f", "g", "h"];
+/** §0 a b c d | §1 "Two" e f g h; g1 = a b c, g2 = e f. */
+const cut = ({ groups = true, markers = [{ after: "d", label: "Two", color: "#7fdc9a" }] } = {}) => ({
+ slug: "s",
+ provenance: { siteOrigin: "https://example.test", channelSlug: "chan" },
+ render: { width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck", deck: markers ? { markers } : {} } },
+ timeline: IDS.map(clip),
+ ...(groups
+ ? {
+ groups: [
+ { id: "g1", section: 0, claim: "The first claim", ids: ["a", "b", "c"] },
+ { id: "g2", section: 1, claim: "The second", ids: ["e", "f"] },
+ ],
+ }
+ : {}),
+});
+async function project(manifest) {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-groups-"));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n");
+ return dir;
+}
+const raw = (dir) => readFile(path.join(dir, MANIFEST_NAME), "utf8");
+const read = async (dir) => JSON.parse(await raw(dir));
+const order = async (dir) => (await read(dir)).timeline.map((e) => e.id).join(" ");
+const groupsOf = async (dir) => (await read(dir)).groups.map((g) => `${g.id}@${g.section}:${g.ids.join(",")}`).join(" ");
+
+test("validateGroups: none is fine; each rule a sentence", () => {
+ assert.deepEqual(validateGroups(cut({ groups: false })), []);
+ assert.deepEqual(validateGroups(cut()), []);
+ const m = cut();
+ m.groups = [
+ { id: "g1", section: 0, claim: "x", ids: ["a", "c"] },
+ { id: "g1", section: 1, claim: "", ids: ["d", "e"] },
+ { id: "g3", section: 1, claim: "y", ids: ["zz", "a"], extra: 1 },
+ { id: "g4", section: 0, claim: "z", ids: ["g"] },
+ ];
+ const errors = validateGroups(m);
+ assert.ok(errors.some((e) => /g1 \("x"\)'s clips are not together: b stands between a and c/.test(e)), errors.join("\n"));
+ assert.ok(errors.includes("group id g1 is used twice"));
+ assert.ok(errors.some((e) => /needs its claim/.test(e)));
+ assert.ok(errors.some((e) => /spans §0 \(the opening\) and §1 \(Two\): a group never crosses a section boundary/.test(e)));
+ assert.ok(errors.some((e) => /unknown key extra/.test(e)));
+ assert.ok(errors.some((e) => /names zz, which is not a clip of the cut/.test(e)));
+ assert.ok(errors.some((e) => /a is in two groups: g1 and g3/.test(e)));
+ assert.ok(errors.some((e) => /g4 \("z"\)'s section is 0, but its clips are in §1 \(Two\)/.test(e)));
+ assert.deepEqual(validateGroups({ ...cut(), groups: {} }), ["groups must be a list of {id, section, claim, ids}"]);
+});
+
+test("a manifest without groups is written as before: no groups key appears", async () => {
+ const dir = await project(cut({ groups: false }));
+ await moveEntry(dir, "b", 6);
+ await removeEntry(dir, "c");
+ const m = await read(dir);
+ assert.equal("groups" in m, false);
+ assert.equal(syncGroups(m, clipOrder(m)).length, 0);
+});
+
+test("a removal drops the clip from its group, and the group with its last clip", async () => {
+ const dir = await project(cut());
+ const r = await removeEntry(dir, "b");
+ assert.ok(r.reanchored.includes('group g1 ("The first claim"): b dropped from it'));
+ await removeEntry(dir, "e");
+ const r2 = await removeEntry(dir, "f");
+ assert.ok(r2.reanchored.includes('group g2 ("The second") dropped: f was its only clip'));
+ assert.equal(await groupsOf(dir), "g1@0:a,c");
+});
+
+test("a clip moved out of its run is detached; moved alone into the middle of one, it joins; to its edge, nothing", async () => {
+ const dir = await project(cut());
+ const r = await moveEntry(dir, "a", 7);
+ assert.equal(await order(dir), "b c d e f g h a");
+ assert.deepEqual(r.groupNotes, ['a was moved out of group g1 ("The first claim")\'s run: detached from it']);
+ assert.equal(await groupsOf(dir), "g1@0:b,c g2@1:e,f");
+ // h to the middle of g2 (between e and f): it joins.
+ const j = await moveEntry(dir, "h", 4);
+ assert.equal(await order(dir), "b c d e h f g a");
+ assert.ok(j.groupNotes.some((x) => /h joined group g2/.test(x)));
+ assert.equal(await groupsOf(dir), "g1@0:b,c g2@1:e,h,f");
+ // a right after f (the run's edge): it stays out.
+ await moveEntry(dir, "a", 6);
+ assert.equal(await order(dir), "b c d e h f a g");
+ assert.equal(await groupsOf(dir), "g1@0:b,c g2@1:e,h,f");
+ // A clip moved within its own run stays in it.
+ const w = await placeEntries(dir, ["f"], { before: "e", section: 1 });
+ assert.equal(w.groupNotes, undefined);
+ assert.equal(await groupsOf(dir), "g1@0:b,c g2@1:f,e,h");
+});
+
+test("a section boundary dragged into a group is refused in words; one at its edge is fine", async () => {
+ const dir = await project(cut());
+ const before = await raw(dir);
+ await assert.rejects(moveSectionBoundary(dir, 0, "a"), (e) => e instanceof StructureRefused && /g1 \("The first claim"\) spans §0 \(the opening\) and §1 \(Two\)/.test(e.message));
+ assert.equal(await raw(dir), before);
+ await moveSectionBoundary(dir, 0, "c");
+ // d is §1 now; the groups' sections follow the markers.
+ assert.equal(await groupsOf(dir), "g1@0:a,b,c g2@1:e,f");
+ await assert.rejects(addSection(dir, "e", { label: "Mid" }), /g2 \("The second"\) spans/);
+});
+
+test("groups move: the whole group, before a group, after one, or before a row; into another's middle is refused", async () => {
+ const dir = await project(cut());
+ const r = await moveGroup(dir, "g2", { to: 0 });
+ assert.equal(await order(dir), "e f a b c d g h");
+ assert.equal(r.words, 'before g1 ("The first claim")');
+ // The markers follow so every other clip keeps its section; g2 is in §0 now.
+ assert.equal((await read(dir)).render.chrome.deck.markers[0].after, "d");
+ assert.equal(await groupsOf(dir), "g1@0:a,b,c g2@0:e,f");
+ await moveGroup(dir, "g2", { after: "g1" });
+ assert.equal(await order(dir), "a b c e f d g h");
+ // Before a row (a bar dropped on it): in that row's section.
+ await moveGroup(dir, "g1", { before: "h" });
+ assert.equal(await order(dir), "e f d g a b c h");
+ assert.equal(await groupsOf(dir), "g1@1:a,b,c g2@0:e,f");
+ // Into the middle of another group: refused, nothing written.
+ const before = await raw(dir);
+ await assert.rejects(moveGroup(dir, "g2", { before: "b" }), (e) => e instanceof StructureRefused && /g1 \("The first claim"\)'s clips are not together/.test(e.message));
+ assert.equal(await raw(dir), before);
+});
+
+test("groups set, label, remove: a fresh id, clips taken from another group, refused when not together", async () => {
+ const dir = await project(cut());
+ await assert.rejects(setGroup(dir, null, ["g", "h"], {}), /needs its claim/);
+ const r = await setGroup(dir, null, ["g", "h"], { claim: "A third" });
+ assert.equal(r.id, "g3");
+ assert.equal(r.created, true);
+ await assert.rejects(setGroup(dir, null, ["d", "f"], { claim: "No" }), /not together/);
+ // Taking b, g1's middle clip, would leave a and c apart: refused.
+ await assert.rejects(setGroup(dir, null, ["b"], { claim: "B" }), (e) => e instanceof StructureRefused && /g1 \("The first claim"\)'s clips are not together/.test(e.message));
+ // c leaves g1 for a new group with d (g1 stays together: a b).
+ await setGroup(dir, "g9", ["c", "d"], { claim: "Two clips" });
+ assert.equal(await groupsOf(dir), "g1@0:a,b g2@1:e,f g3@1:g,h g9@0:c,d");
+ await labelGroup(dir, "g2", " The second, reworded ");
+ assert.equal((await read(dir)).groups.find((g) => g.id === "g2").claim, "The second, reworded");
+ await assert.rejects(labelGroup(dir, "g2", "x".repeat(161)), /at most 160/);
+ await removeGroup(dir, "g3");
+ assert.equal(await groupsOf(dir), "g1@0:a,b g2@1:e,f g9@0:c,d");
+ assert.equal(await order(dir), IDS.join(" "));
+});
+
+test("promote: a level-2 marker at the group's first clip, titled with its claim; the long, the opening and §0 refused", async () => {
+ const dir = await project(cut());
+ await assert.rejects(promoteGroup(dir, "g2", {}), /no clip before|already opens/);
+ await setGroup(dir, null, ["g", "h"], { claim: "Third: a claim far too long for a marker" });
+ await assert.rejects(promoteGroup(dir, "g3", {}), /a marker's label is at most 24 characters and the claim is 40 — give the subsection a shorter title \(--label\)/);
+ const r = await promoteGroup(dir, "g3", { label: "Third" });
+ assert.equal(r.after, "f");
+ assert.deepEqual((await read(dir)).render.chrome.deck.markers, [
+ { after: "d", label: "Two", color: "#7fdc9a" },
+ { after: "f", label: "Third", level: 2 },
+ ]);
+ assert.equal(await groupsOf(dir), "g1@0:a,b,c g2@1:e,f g3@2:g,h");
+ assert.equal(groupModel(await read(dir)).find((g) => g.id === "g3").promoted, true);
+ await assert.rejects(promoteGroup(dir, "g3", { label: "Again" }), /already opens a subsection/);
+ // g1 opens the cut; a group inside §0 would make the cut's first marker a subsection.
+ await assert.rejects(promoteGroup(dir, "g1", {}), /opens the cut/);
+ await setGroup(dir, "g1", ["b", "c"]);
+ await assert.rejects(promoteGroup(dir, "g1", {}), /the cut's first marker opens a section/);
+});
+
+const FILE = {
+ sections: [
+ { label: "Lead", groups: [{ claim: "Opens", ids: ["c", "a"] }, { claim: "Then", ids: ["b", "d"] }] },
+ { label: "two", groups: [{ claim: "Second section", ids: ["h", "e"] }, { claim: "Gone", ids: ["zz"] }] },
+ ],
+};
+
+test("import: the cut re-ordered to the file, its groups the cut's, in ONE undoable write", async () => {
+ const dir = await project(cut({ groups: false }));
+ const before = await raw(dir);
+ await assert.rejects(importGroups(dir, FILE), /names 1 clip the cut does not have: zz — pass --skip-missing/);
+ const r = await importGroups(dir, FILE, { skipMissing: true });
+ assert.equal(r.groups, 3);
+ // "Lead" has no deck section of its name: its clips are in the opening. "two" is "Two".
+ assert.deepEqual(r.sections.map((s) => [s.label, s.section]), [["Lead", 0], ["two", 1], ]);
+ assert.ok(r.notes.some((x) => /"Lead" → §0 \(the opening\): the deck has no section of that name; most of its clips are there/.test(x)));
+ assert.ok(r.notes.some((x) => /not in the file, kept at the end of their sections: f, g/.test(x)));
+ assert.ok(r.notes.some((x) => /1 group left out/.test(x)));
+ assert.equal(await order(dir), "c a b d h e f g");
+ assert.equal(await groupsOf(dir), "g1@0:c,a g2@0:b,d g3@1:h,e");
+ const view = groupsView(await read(dir));
+ assert.deepEqual(view.sections.map((s) => s.groups.map((g) => g.claim)), [["Opens", "Then"], ["Second section"]]);
+ assert.match(groupLines(view).join("\n"), /§1 Two\n {2}g3 {3}Second section {2}\[h e\]\n {2}ungrouped: f g\n3 groups/);
+ // Undo: the cut exactly as it was, byte for byte.
+ await undoStructural(dir);
+ assert.equal(await raw(dir), before);
+});
+
+test("import: a section the file leaves empty is refused, or its marker removed with --drop-empty; out of order refused", async () => {
+ const dir = await project(cut({ groups: false, markers: [{ after: "b", label: "Mid" }, { after: "d", label: "Two" }] }));
+ const doc = { sections: [{ label: "Open", groups: [{ claim: "x", ids: ["a", "b", "c", "d"] }] }, { label: "Two", groups: [{ claim: "y", ids: ["e", "f", "g", "h"] }] }] };
+ await assert.rejects(importGroups(dir, doc), /leaves §1 \(Mid\) with no clip .* --drop-empty/);
+ const r = await importGroups(dir, doc, { dropEmpty: true });
+ assert.deepEqual(r.dropped, [{ index: 1, label: "Mid" }]);
+ assert.deepEqual((await read(dir)).render.chrome.deck.markers, [{ after: "d", label: "Two" }]);
+ const flipped = { sections: [{ label: "Two", groups: [{ claim: "y", ids: ["e"] }] }, { label: "Mid", groups: [{ claim: "x", ids: ["a"] }] }] };
+ const dir2 = await project(cut({ groups: false, markers: [{ after: "b", label: "Mid" }, { after: "d", label: "Two" }] }));
+ await assert.rejects(importGroups(dir2, flipped), /out of the cut's order: "Mid" \(§1 \(Mid\)\) comes after "Two"/);
+ await assert.rejects(importGroups(dir2, { sections: [{ label: "x", groups: [{ claim: "y", ids: ["a", "a"] }] }] }), /a is named twice/);
+});
+
+test("order: the named entries in the places they hold; a clip across a boundary refused; the groups follow", async () => {
+ const dir = await project(cut());
+ await orderEntries(dir, ["c", "b", "a"]);
+ assert.equal(await order(dir), "c b a d e f g h");
+ assert.equal(await groupsOf(dir), "g1@0:c,b,a g2@1:e,f");
+ await assert.rejects(orderEntries(dir, ["e", "d"]), /e \(§1 \(Two\)\) would stand after|d \(§0 \(the opening\)\)|would stand after/);
+ // The whole order: g pulled between e and f joins g2 (it moved, they did not).
+ const r = await orderEntries(dir, ["c", "b", "a", "d", "e", "g", "f", "h"]);
+ assert.ok(r.groupNotes.some((x) => /g joined group g2/.test(x)));
+ assert.equal(await groupsOf(dir), "g1@0:c,b,a g2@1:e,g,f");
+ assert.equal((await read(dir)).render.chrome.deck.markers[0].after, "d");
+ assert.deepEqual(parseOrderText("a, b\nc"), ["a", "b", "c"]);
+ assert.deepEqual(parseOrderText('{"order": ["x"]}'), ["x"]);
+ assert.deepEqual(parseOrderText(JSON.stringify(FILE)), ["c", "a", "b", "d", "h", "e", "zz"]);
+});
+
+test("Play's seams: a group's lighter seam before its first clip, none where a section opens; without groups, as before", () => {
+ const m = cut();
+ const entries = m.timeline.map((e) => ({ id: e.id, type: "clip" }));
+ const markers = m.render.chrome.deck.markers;
+ assert.deepEqual(seamsOf(entries, markers), seamsOf(entries, markers, []));
+ const s = seamsOf(entries, markers, [...m.groups, { id: "g3", claim: "Late", ids: ["g", "h"] }]);
+ assert.deepEqual(s.map((x) => [x.before, x.kind ?? "section", x.label]), [
+ ["e", "section", "Two"],
+ ["g", "group", "Late"],
+ ]);
+});
+
+test("umtool timeline <p> groups: import, ls --json in the file's shape, move, promote, undo", async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "umtool-groups-cli-"));
+ const dir = path.join(root, "p");
+ await (await import("node:fs/promises")).mkdir(dir);
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify({ ...cut({ groups: false }), title: "P" }, null, 2) + "\n");
+ const file = path.join(root, "claim-groups.json");
+ await writeFile(file, JSON.stringify(FILE));
+ const out = [];
+ const err = [];
+ const run = (...args) => timelineCommand(["p", ...args], { root, out: (s) => out.push(s), err: (s) => err.push(s) });
+ assert.equal(await run("groups", "import", file), 1);
+ assert.match(err.join("\n"), /--skip-missing/);
+ assert.equal(await run("groups", "import", file, "--skip-missing"), 0, err.join("\n"));
+ assert.match(out.join("\n"), /imported 3 groups, the cut re-ordered to the file/);
+ assert.match(out.join("\n"), /undo point: revisions\/.*auto-before-groups-import/);
+ out.length = 0;
+ assert.equal(await run("groups", "ls", "--json"), 0);
+ const j = JSON.parse(out.join("\n"));
+ assert.deepEqual(j.sections.map((s) => s.groups.map((g) => [g.claim, g.ids])), [[["Opens", ["c", "a"]], ["Then", ["b", "d"]]], [["Second section", ["h", "e"]]]]);
+ out.length = 0;
+ assert.equal(await run("groups", "move", "g2", "--to", "0"), 0, err.join("\n"));
+ assert.match(out.join("\n"), /moved group g2 \(b d\) before g1/);
+ assert.equal(await run("groups", "move", "g2", "--to", "after", "g1"), 0, err.join("\n"));
+ out.length = 0;
+ assert.equal(await run("groups", "promote", "g2", "--label", "Then"), 1);
+ assert.match(err.join("\n"), /the cut's first marker opens a section/);
+ assert.equal(await run("groups", "label", "g3", "Second,", "said", "again"), 0, err.join("\n"));
+ assert.equal(await run("groups", "set", "-", "f", "g", "--claim", "Late"), 0, err.join("\n"));
+ out.length = 0;
+ assert.equal(await run("groups", "promote", "g4"), 0, err.join("\n"));
+ assert.match(out.join("\n"), /group g4 opens a subsection of §1 \(Two\): marker 1 after e, "Late"/);
+ assert.equal(await run("order", "a", "c"), 0, err.join("\n"));
+ const tok = await manifestToken(dir);
+ assert.ok(tok);
+});
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -65,6 +65,21 @@ import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs";
import { citeFollow, clockOf, qrFollowsCite } from "./citeFollow.mjs";
import { syncPatchMarkers, syncSectionMarkers } from "./patchMarkers.mjs";
import {
+ clipOrder,
+ dropFromGroups,
+ followSplitGroups,
+ hasGroups,
+ importGroupsIn,
+ labelGroupIn,
+ moveGroupIn,
+ orderIn,
+ promoteGroupIn,
+ removeGroupIn,
+ setGroupIn,
+ syncGroups,
+ validateGroups,
+} from "./claimGroups.mjs";
+import {
DRAFTED_MANIFEST_FIELDS, clearEditedDrafts, isEntryField, publishWarnings, pruneDrafted, validateDrafted, validatePublish,
} from "yt-dlp-transcript-common/lib/report/drafted.mjs";
@@ -984,6 +999,8 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no
// 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);
+ // Its claim group holds the second half too.
+ reanchored.push(...followSplitGroups(m, e.id, b.id));
return { id: e.id, second: b.id, entries: [e, b], reanchored };
}));
}
@@ -1821,6 +1838,8 @@ function structureErrors(manifest) {
...validateAssist(manifest),
// A clip inserted with a `blur` (the clip editor's New clip) is checked as the build checks it.
...validateClipBlurEntries(manifest),
+ // Claim groups (claimGroups.mjs): each one's clips together, in one section.
+ ...validateGroups(manifest),
];
}
@@ -1872,7 +1891,20 @@ export function applyStructural(manifest, mutate) {
// problem the build would name (somebody's hand edit) can still be
// re-ordered, and the problem is still the build's to report.
const already = new Set(structureErrors(manifest));
+ const order = clipOrder(manifest);
const result = mutate(manifest);
+ // The claim groups follow the edit (claimGroups.mjs syncGroups): a clip moved
+ // out of its run is detached, one moved into the middle of a run joins it,
+ // `section` follows the markers. What moved is what the op says it moved.
+ if (hasGroups(manifest)) {
+ const r = /** @type {Record<string, any>} */ (result && typeof result === "object" ? result : {});
+ const moved = Array.isArray(r.ids) ? r.ids.map(String) : typeof r.id === "string" ? [r.id] : null;
+ const notes = syncGroups(manifest, order, { moved, rebuilt: r.groupsWritten === true });
+ if (result && typeof result === "object") {
+ delete r.groupsWritten;
+ if (notes.length) r.groupNotes = [...(Array.isArray(r.groupNotes) ? r.groupNotes : []), ...notes];
+ }
+ }
const errors = structureErrors(manifest).filter((e) => !already.has(e));
if (errors.length) throw new StructureRefused(errors);
applySectionEnter(manifest.timeline);
@@ -1932,6 +1964,8 @@ export function removeIn(m, id, at = null, { reanchor = true } = {}) {
export function reanchorAfterRemove(m, removed, i) {
const id = removed?.id;
const notes = [];
+ // Its claim group (claimGroups.mjs): the clip leaves it; a group left with no clip goes.
+ if (id) notes.push(...dropFromGroups(m, id));
const chrome = m?.render?.chrome;
if (!id || !chrome || typeof chrome !== "object") return notes;
const tl = m.timeline ?? [];
@@ -2364,6 +2398,133 @@ export function sectionsOf(manifest) {
return sectionModel(manifest).sections.map((s) => ({ ...s, words: sectionWords(s) }));
}
+// ---- claim groups (claimGroups.mjs; lane L4) ---------------------------------
+//
+// Runs of clips inside a section that make one claim (`groups` beside the
+// timeline). Each writer is a structural write -- an undo point first, the
+// build's checks (validateGroups among them) -- and the ones that move clips
+// or markers go through sectionWrite, so the take patches' markers follow.
+// The render never reads `groups`; only a promote changes it (a marker).
+// `umtool timeline <p> groups …`, the Cut tab's group bars.
+
+/**
+ * SET: group `gid` is clips `ids` (a new group when there is none by that id;
+ * `gid` null or "-" makes a fresh `g<n>`, which needs its claim).
+ *
+ * @param {string} dir
+ * @param {string | null} gid
+ * @param {string[]} ids
+ * @param {{ claim?: string | null }} spec
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function setGroup(dir, gid, ids, { claim = null } = {}, { token = null } = {}) {
+ return structural(dir, "groups-set", token, (m) => setGroupIn(m, gid, ids, { claim }));
+}
+
+/**
+ * LABEL: group `gid`'s claim, in words.
+ * @param {string} dir
+ * @param {string} gid
+ * @param {string} claim
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function labelGroup(dir, gid, claim, { token = null } = {}) {
+ return structural(dir, "groups-label", token, (m) => labelGroupIn(m, gid, claim));
+}
+
+/**
+ * UNGROUP: group `gid` goes; its clips stay where they stand.
+ * @param {string} dir
+ * @param {string} gid
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function removeGroup(dir, gid, { token = null } = {}) {
+ return structural(dir, "groups-remove", token, (m) => removeGroupIn(m, gid));
+}
+
+/**
+ * MOVE A WHOLE GROUP among the groups: `to` its place after the move, or
+ * `after` another group; or `before` an entry (a group bar dropped on a row:
+ * before that entry, in its section; null: the end). Its clips go together
+ * (placeIn), every other clip keeping its section. Each move is its own undo
+ * point.
+ *
+ * @param {string} dir
+ * @param {string} gid
+ * @param {{ to?: number | null, after?: string | null, before?: string | null }} where
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function moveGroup(dir, gid, { to = null, after = null, before = undefined } = {}, { token = null } = {}) {
+ return sectionWrite(
+ dir,
+ "groups-move",
+ token,
+ (m) => {
+ if (before === undefined) return moveGroupIn(m, gid, { to, after }, placeIn);
+ const g = (Array.isArray(m.groups) ? m.groups : []).find((x) => x?.id === gid);
+ if (!g) throw new Error(`no group ${gid}`);
+ const ids = clipOrder(m).filter((id) => g.ids.includes(id));
+ const b = before === null || before === "" ? null : String(before);
+ if (b !== null && ids.includes(b)) throw new Error(`${b} is one of ${gid}'s own clips: drop the group outside its run`);
+ const tl = m.timeline;
+ const at = b === null ? tl.length : tl.findIndex((e) => e?.id === b);
+ if (at < 0) throw new Error(`no timeline entry with id ${b}`);
+ // The section of the clip it lands before (else after): where a drop on a row goes.
+ const clip = (e) => !!e && (e.kind ?? e.type) === "clip" && !ids.includes(e.id);
+ const model = sectionModel(m);
+ const next = tl.slice(at).find(clip);
+ const prev = [...tl.slice(0, at)].reverse().find(clip);
+ const s = next ? model.sectionOf.get(next.id) : prev ? model.sectionOf.get(prev.id) : null;
+ const r = placeIn(m, ids, { before: b, section: isObj(m.render?.chrome) ? s ?? null : null });
+ return { id: gid, ids, words: b ? `before ${b}` : "at the end", section: r.section, before: r.before, reanchored: r.reanchored ?? [] };
+ },
+ { snapshotEvery: 0 },
+ );
+}
+
+/**
+ * PROMOTE: the group opens a subsection, a level-2 marker at its first clip
+ * titled with its claim (`label` when the claim is longer than a marker's 24).
+ * The one group edit the render sees.
+ *
+ * @param {string} dir
+ * @param {string} gid
+ * @param {{ label?: string | null }} spec
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function promoteGroup(dir, gid, { label = null } = {}, { token = null } = {}) {
+ return sectionWrite(dir, "groups-promote", token, (m) => promoteGroupIn(m, gid, { label }), { snapshotEvery: 0 });
+}
+
+/**
+ * IMPORT a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`)
+ * in ONE write: the timeline re-ordered to it, its groups the cut's, the
+ * markers re-anchored (claimGroups.mjs importGroupsIn). One undo point of its
+ * own: `undo` puts the cut back as it was.
+ *
+ * @param {string} dir
+ * @param {unknown} doc
+ * @param {{ skipMissing?: boolean, dropEmpty?: boolean }} o
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function importGroups(dir, doc, o = {}, { token = null } = {}) {
+ return sectionWrite(dir, "groups-import", token, (m) => importGroupsIn(m, doc, o), { snapshotEvery: 0 });
+}
+
+/**
+ * ORDER (bulk): the named entries take the places the named entries hold, in
+ * the order given; every clip keeps its section (the markers re-anchored); the
+ * groups follow. Through structural(), never replaceManifest: one undo point,
+ * the build's checks.
+ *
+ * @param {string} dir
+ * @param {string[]} ids
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function orderEntries(dir, ids, { token = null } = {}) {
+ return sectionWrite(dir, "order", token, (m) => orderIn(m, ids), { snapshotEvery: 0 });
+}
+
// ---- flash-forward (UI notes 2026-10-30, item 2) ----------------------------
/**
diff --git a/umtool/lib/report/playCut.mjs b/umtool/lib/report/playCut.mjs
@@ -377,11 +377,17 @@ export function dateRamp(entries) {
* `after` clip. Each seam names the first date after it (the first dated
* clip from there on) and the marker's label when a marker made it.
*
+ * A claim group (lib/report/claimGroups.mjs) that does not open a section
+ * opens a GROUP seam before its first clip -- `kind: "group"`, its claim the
+ * label -- which the strip draws lighter than a section's. Without `groups`
+ * the seams are exactly the sections'.
+ *
* @param {Array<{ id: string, type: string, section?: unknown, dateLabel?: string | null }>} entries the cut's, in order
* @param {Array<{ after: string, label?: string }>} [markers] render.chrome.deck.markers
- * @returns {Array<{ before: string, index: number, date: string | null, label: string | null }>}
+ * @param {Array<{ id: string, claim?: string, ids: string[] }>} [groups] the manifest's claim groups
+ * @returns {Array<{ before: string, index: number, date: string | null, label: string | null, kind?: "group", group?: string }>}
*/
-export function seamsOf(entries, markers = []) {
+export function seamsOf(entries, markers = [], groups = []) {
const list = entries ?? [];
/** @type {Map<number, string | null>} */
const at = new Map();
@@ -396,14 +402,31 @@ export function seamsOf(entries, markers = []) {
const i = list.findIndex((e) => e.id === m?.after);
if (i >= 0 && i + 1 < list.length) at.set(i + 1, typeof m.label === "string" && m.label ? m.label : (at.get(i + 1) ?? null));
}
- return [...at.entries()]
+ const dateAt = (i) => list.slice(i).find((e) => e.type === "clip" && e.dateLabel)?.dateLabel ?? null;
+ const seams = [...at.entries()]
.sort((a, b) => a[0] - b[0])
.map(([i, label]) => ({
before: list[i].id,
index: i,
- date: list.slice(i).find((e) => e.type === "clip" && e.dateLabel)?.dateLabel ?? null,
+ date: dateAt(i),
label,
}));
+ if (!Array.isArray(groups) || !groups.length) return seams;
+ // A group's seam: before its first clip in the cut, where no section's is.
+ const index = new Map();
+ list.forEach((e, i) => {
+ if (!index.has(e.id)) index.set(e.id, i);
+ });
+ /** @type {Array<{ before: string, index: number, date: string | null, label: string | null, kind?: "group", group?: string }>} */
+ const out = [...seams];
+ for (const g of groups) {
+ const firsts = (Array.isArray(g?.ids) ? g.ids : []).map((id) => index.get(id)).filter((i) => i !== undefined);
+ if (!firsts.length) continue;
+ const i = Math.min(...firsts);
+ if (i === 0 || at.has(i)) continue;
+ out.push({ before: list[i].id, index: i, date: dateAt(i), label: typeof g.claim === "string" && g.claim ? g.claim : null, kind: "group", group: String(g.id) });
+ }
+ return out.sort((a, b) => a.index - b.index);
}
/**
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -155,9 +155,14 @@ export async function playView(project, { take = null, bare = false } = {}) {
index: x.index, label: x.label, color: x.color, marker: x.marker, count: x.clips.length,
...(x.level === 2 ? { level: 2, within: x.within ?? null } : {}),
}));
+ // The claim groups (lib/report/claimGroups.mjs): the strip's lighter seams, from the cut played.
+ const groups = (Array.isArray(selected.groups) ? selected.groups : [])
+ .filter((g) => g && typeof g.id === "string" && Array.isArray(g.ids))
+ .map((g) => ({ id: g.id, claim: typeof g.claim === "string" ? g.claim : "", ids: g.ids.filter((x) => typeof x === "string") }));
return {
project: project.id,
title: text(manifest.title) || project.id,
+ groups,
sections,
sectionOf: Object.fromEntries(model.sectionOf),
sectionsDiffer,
diff --git a/umtool/lib/report/sectionEdit.mjs b/umtool/lib/report/sectionEdit.mjs
@@ -128,7 +128,7 @@ export const sectionWords = (s) => {
* 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) {
+export function reanchorMarkers(m, model, membership) {
const tl = m.timeline;
const markers = deckMarkers(m) ?? [];
const lastIn = new Map();
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -24,6 +24,10 @@
// 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]
+// umtool timeline <project> order <file|@file|id…>
+// umtool timeline <project> groups [ls] | import <file> [--skip-missing] [--drop-empty]
+// | set <gid|-> <id…> [--claim C] | move <gid> (--to <index> | --to after <gid>)
+// | label <gid> <claim…> | promote <gid> [--label L] | remove <gid>
//
// An insert's attribution (--title, --date, --quote, --cite, --cite-url) is a
// second write, through updateClip -- the writer `umtool window` and the
@@ -70,6 +74,13 @@ import {
removeWrongSpeaker,
REMOVED_FILE,
removePost,
+ importGroups,
+ labelGroup,
+ moveGroup,
+ orderEntries,
+ promoteGroup,
+ removeGroup,
+ setGroup,
undoStructural,
updateClip,
updateTeaser,
@@ -77,6 +88,8 @@ import {
} from "./manifest.mjs";
import { REJECT_REASON_IDS, rejectionOf } from "./rejectReasons.mjs";
+import { groupModel, parseOrderText } from "./claimGroups.mjs";
+import { sectionModel } from "./sectionEdit.mjs";
export const TIMELINE_USAGE = [
"usage: umtool timeline <project> [ls] [--json] the cut: index, id, type, video, start–end, date title",
@@ -114,6 +127,23 @@ export const TIMELINE_USAGE = [
" 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> order <file|@file|id…> the cut's order in one write: the named entries take the",
+ " places the named entries hold, in that order (name them all for the whole order); every",
+ " clip keeps its section (an order across a boundary is refused); a JSON list, {order}, a",
+ " claim-groups file or ids by spaces, commas or lines; one undo point",
+ " umtool timeline <project> groups [ls] [--json] the claim groups, by section: id, claim, clips",
+ " umtool timeline <project> groups import <file> [--skip-missing] [--drop-empty] a claim-groups file",
+ " ({sections: [{label, groups: [{claim, ids}]}]}) in ONE write: the cut re-ordered to it, its",
+ " groups the cut's, the markers following; a file section is the deck section of its name, else",
+ " the one most of its clips are in; refused for an id the cut lacks (--skip-missing) or a section",
+ " left empty (--drop-empty removes its marker); `undo` puts the cut back",
+ " umtool timeline <project> groups set <gid|-> <id…> [--claim C] a group is these clips (already together, one",
+ " section); `-` a new g<n>. groups label <gid> <claim…> · groups remove <gid> (its clips stay)",
+ " umtool timeline <project> groups move <gid> --to <index>|--to after <gid> the whole group, its clips together,",
+ " to that place among the groups (before the group there, in its section) or after a group",
+ " umtool timeline <project> groups promote <gid> [--label L] the group opens a subsection: a level-2 marker at",
+ " its first clip titled with its claim (--label when it is over 24); the render sees only this",
+ " A clip moved out of its group's run leaves the group; moved alone into the middle of a run, it joins it",
" 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",
@@ -123,8 +153,9 @@ export const TIMELINE_USAGE = [
].join("\n");
const SECTION_VERBS = ["sections", "section-move", "section-add", "section-boundary", "section-remove", "section-set"];
-const VERBS = ["ls", "insert", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward"];
-const VALUED = new Set(["--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level"]);
+const VERBS = ["ls", "insert", "move", "place", "remove", "reject", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo", ...SECTION_VERBS, "split", "flash-forward", "order", "groups"];
+const GROUP_VERBS = ["ls", "import", "set", "move", "label", "promote", "remove"];
+const VALUED = new Set(["--after", "--before", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction", "--note", "--to-section", "--label", "--color", "--level", "--claim"]);
/** 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"];
@@ -359,7 +390,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
const { words, flags } = splitTimelineArgs(args);
const json = flags.has("--json");
try {
- const [projectArg, verb = "ls", ...rest] = words;
+ const [projectArg, verb0 = "ls", ...rest] = words;
+ let verb = verb0;
if (!projectArg || flags.has("--help")) {
err(TIMELINE_USAGE);
return 2;
@@ -381,6 +413,16 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
return 0;
}
+ if (verb === "groups" && (rest[0] ?? "ls") === "ls") {
+ const view = groupsView(manifest);
+ if (json) {
+ out(JSON.stringify({ project: project.id, token: await manifestToken(project.dir), ...view }, null, 2));
+ return 0;
+ }
+ for (const line of groupLines(view)) out(line);
+ return 0;
+ }
+
if (verb === "ls") {
const rows = timelineRows(manifest);
if (json) {
@@ -552,6 +594,68 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
({ result, editNotes } = await write(async (token) => (await runClipEditorOp(project, { op: "split", clip: id, at: second, token })).result));
break;
}
+ case "order": {
+ if (!rest.length) throw new CliError("order needs the ids in their new order, or a file of them (@file)");
+ let text = rest.join(" ");
+ if (rest.length === 1) {
+ const f = rest[0].startsWith("@") ? rest[0].slice(1) : rest[0];
+ const file = path.resolve(f);
+ const read = await readFile(file, "utf8").catch(() => null);
+ if (read !== null) text = read;
+ else if (rest[0].startsWith("@")) throw new CliError(`cannot read ${file}`);
+ }
+ let ids;
+ try {
+ ids = parseOrderText(text);
+ } catch (e) {
+ throw new CliError(`order: ${e instanceof Error ? e.message : e}`);
+ }
+ ({ result, editNotes } = await write((token) => orderEntries(project.dir, ids, { token })));
+ break;
+ }
+ case "groups": {
+ const sub = rest[0];
+ if (!GROUP_VERBS.includes(sub)) throw new CliError(`unknown: timeline groups ${sub} — ${GROUP_VERBS.join(", ")}`);
+ verb = `groups ${sub}`;
+ const args = rest.slice(1);
+ if (sub === "import") {
+ const file = need(args[0], "a claim-groups file ({sections: [{label, groups: [{claim, ids}]}]})");
+ const doc = await jsonArg(file.startsWith("@") ? file : `@${file}`, "groups import");
+ ({ result, editNotes } = await write((token) => importGroups(project.dir, doc, { skipMissing: flags.has("--skip-missing"), dropEmpty: flags.has("--drop-empty") }, { token })));
+ } else if (sub === "set") {
+ const gid = need(args[0], "a group id (`-` for a new one)");
+ const ids = args.slice(1);
+ if (!ids.length) throw new CliError("groups set needs the group's clips: groups set <gid|-> <id…> [--claim C]");
+ const claim = typeof flags.get("--claim") === "string" ? String(flags.get("--claim")) : null;
+ ({ result, editNotes } = await write((token) => setGroup(project.dir, gid === "-" ? null : gid, ids, { claim }, { token })));
+ } else if (sub === "move") {
+ const gid = need(args[0], "a group id (`groups ls` lists them)");
+ const to = flags.get("--to");
+ const afterGid = to === "after" ? args[1] : typeof flags.get("--after") === "string" ? String(flags.get("--after")) : null;
+ if (to === "after" && !afterGid) throw new CliError("groups move <gid> --to after <gid>: name the group it goes after");
+ let where;
+ if (afterGid) where = { after: afterGid };
+ else {
+ const n = Number(to);
+ if (typeof to !== "string" || to === "" || !Number.isInteger(n)) throw new CliError("groups move needs --to <index> (its place among the groups after the move) or --to after <gid>");
+ where = { to: n };
+ }
+ ({ result, editNotes } = await write((token) => moveGroup(project.dir, gid, where, { token })));
+ } else if (sub === "label") {
+ const gid = need(args[0], "a group id");
+ const claim = args.slice(1).join(" ") || (typeof flags.get("--claim") === "string" ? String(flags.get("--claim")) : "");
+ if (!claim.trim()) throw new CliError("groups label <gid> <claim…>: the claim, in words");
+ ({ result, editNotes } = await write((token) => labelGroup(project.dir, gid, claim, { token })));
+ } else if (sub === "promote") {
+ const gid = need(args[0], "a group id");
+ const label = typeof flags.get("--label") === "string" ? String(flags.get("--label")) : null;
+ ({ result, editNotes } = await write((token) => promoteGroup(project.dir, gid, { label }, { token })));
+ } else if (sub === "remove") {
+ const gid = need(args[0], "a group id");
+ ({ result, editNotes } = await write((token) => removeGroup(project.dir, gid, { token })));
+ }
+ 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"));
@@ -581,6 +685,9 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
}
out(summaryOf(verb, result, attribution));
for (const line of result.reanchored ?? []) out(` re-anchored: ${line}`);
+ // The claim groups following the edit (claimGroups.mjs syncGroups), and an import's words.
+ for (const line of result.groupNotes ?? []) out(` groups: ${line}`);
+ for (const line of result.notes ?? []) out(` ${line}`);
// The take patches beside the manifest follow the same removal (patchMarkers.mjs).
for (const p of result.patches ?? []) {
for (const line of p.notes ?? []) out(` ${p.file}: ${line}`);
@@ -668,8 +775,57 @@ export function sectionLines(sections) {
});
}
+/**
+ * The groups as `groups ls` shows them: by section, each group's id, claim and
+ * clips, and the clips no group holds.
+ *
+ * @param {Record<string, any>} manifest
+ */
+export function groupsView(manifest) {
+ const model = sectionModel(manifest);
+ const groups = groupModel(manifest);
+ const grouped = new Set(groups.flatMap((g) => g.ids));
+ const sections = model.sections.map((s) => ({
+ index: s.index,
+ label: s.label,
+ ...(s.level === 2 ? { level: 2, within: s.within ?? null } : {}),
+ groups: groups.filter((g) => g.section === s.index).map((g) => ({ id: g.id, claim: g.claim, ids: g.ids, ...(g.promoted ? { promoted: true } : {}) })),
+ ungrouped: s.clips.filter((id) => !grouped.has(id)),
+ }));
+ return { groups: groups.length, hasGroups: Array.isArray(manifest?.groups), sections };
+}
+
+/** `groups ls`, as lines. */
+export function groupLines(view) {
+ if (!view.hasGroups) return ["no claim groups yet — `groups import <file>` or `groups set - <id…> --claim C`"];
+ const lines = [];
+ for (const s of view.sections) {
+ if (!s.groups.length && !s.ungrouped.length) continue;
+ lines.push(`§${s.index} ${s.level === 2 ? "› " : ""}${s.label ?? (s.index === 0 ? "(the opening)" : "(no label)")}`);
+ for (const g of s.groups) lines.push(` ${g.id.padEnd(4)} ${g.promoted ? "▸ " : ""}${g.claim} [${g.ids.join(" ")}]`);
+ if (s.ungrouped.length) lines.push(` ungrouped: ${s.ungrouped.join(" ")}`);
+ }
+ lines.push(`${view.groups} group${view.groups === 1 ? "" : "s"}`);
+ return lines;
+}
+
function summaryOf(verb, r, attribution) {
switch (verb) {
+ case "order":
+ return `ordered ${r.count} of ${r.of} entries`;
+ case "groups import":
+ return `imported ${r.groups} group${r.groups === 1 ? "" : "s"}${r.replaced ? ` (replacing ${r.replaced})` : ""}${r.moved ? ", the cut re-ordered to the file" : ", the order unchanged"}` +
+ r.sections.map((s) => `\n ${s.label ?? "(no label)"} → §${s.section} (${s.groups} group${s.groups === 1 ? "" : "s"})`).join("");
+ case "groups set":
+ return `${r.created ? "new group" : "group"} ${r.id}: ${r.ids.join(" ")} — ${r.claim}`;
+ case "groups label":
+ return `group ${r.id}: ${r.claim}`;
+ case "groups remove":
+ return `ungrouped ${r.id} (${r.removed.ids.join(" ")} stay where they are)`;
+ case "groups move":
+ return `moved group ${r.id} (${r.ids.join(" ")}) ${r.words}${r.section !== null && r.section !== undefined ? ` in §${r.section}` : ""}`;
+ case "groups promote":
+ return `group ${r.id} opens a subsection of ${r.within}: marker ${r.marker} after ${r.after}, "${r.label}" (it opens on ${r.opens})`;
case "section-move":
return `moved ${r.ids.join(", ")} to the ${r.position} of §${r.section}${r.label ? ` (${r.label})` : ""}`;
case "section-add":