commit 415349706703163fb7a97553dfdd5f2f6bcc1841
parent 1df2a71eca6d3d883347c2a61cf158e02de04fcd
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 03:19:06 -0500
umtool: the candidates inbox (UI notes item 14) -- a sweep's proposed clips on the Cut tab, picked by a press
<project>/candidates.json (lib/report/candidates.mjs), in lib/lifecycle.mjs's store discipline:
one writer serialised in-process, whole file to a temp name and a rename, an unreadable file
never overwritten. An agent or a sweep only PROPOSES: `umtool candidates <p> import <sweep.md>`
reads the /sweep bullets (`- [verdict] [title @ time](link) (date) "quote" — why`, numbered too,
under their headings; a Top N section marks the moments it restates; a set-aside list or a
bullet with no verdict or link is skipped and said), `add <json>` an agent's; the same moment
proposed again changes nothing it holds. The parser's test keeps real-shaped, anonymised lines
(an archive link with %2F, a twitch VOD, ids with -- and a leading _, h:mm:ss, || and quotes in
titles, could-replace, a NOTE in the why, no date).
The Candidates panel: Play (the cited second from a cached window, else the archive at it),
the verdict, the sweep's rank, the place each proposes against the cut as it is now (a verdict
naming a clip proposes its section and group, else the deck section of the heading's name),
"in the cut as …", and three presses: Insert into section (its END), Insert into group (after
the group's last clip and one of its clips, so the run stays together), Not this (recorded,
hidden, never deleted). An insert undone puts its row back.
Both inserts are `timeline insert`'s writer: insertClip (timelineCli.mjs, the CLI's insert body,
now shared) and a new structural writer insertInto (manifest.mjs) -- one write, one undo point,
the marker after that last clip re-anchored after the new clip, the group set through setGroupIn
-- also `umtool timeline <p> insert --to-section N | --group G`. The window runs from the sentence
the cited second starts in to a sentence end after the quote (the recording's cues).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
15 files changed, 1829 insertions(+), 27 deletions(-)
diff --git a/umtool/app/api/report/candidates/route.ts b/umtool/app/api/report/candidates/route.ts
@@ -0,0 +1,67 @@
+import { invalidateProjects } from "@/lib/projects";
+import { StaleToken, StructureRefused, manifestToken } from "@/lib/report/manifest.mjs";
+import { CandidatesError, candidatesView, dismissCandidate, insertCandidate } from "@/lib/report/candidates.mjs";
+import { projectCache, resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+
+export const dynamic = "force-dynamic";
+
+// THE CANDIDATES INBOX (UI notes item 14): a project's proposed clips
+// (<project>/candidates.json, lib/report/candidates.mjs) for the Cut tab's
+// panel. Proposals come in from a terminal only (`umtool candidates <p>
+// import|add`); this route is the operator's two presses.
+//
+// GET ?project=<id> { …candidatesView, token, playable: { <id>: true } }
+// (playable: a cached window holds the cited second, so Play plays it here)
+// POST { project, op: "insert", id, section | group, token } through `timeline insert`'s writer
+// → { ok, inserted, clip, window, token, editNotes, attributionError? } | 409 stale
+// POST { project, op: "dismiss", id, note? } Not this: recorded, hidden, never deleted
+const headers = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers });
+ const view = await candidatesView(r.project.dir, r.manifest);
+ const playable: Record<string, boolean> = {};
+ const waiting = view.candidates.filter((c: { status: string }) => c.status === "proposed");
+ if (waiting.length) {
+ const cache = await projectCache(r.project, r.manifest).catch(() => null);
+ for (const c of waiting as { id: string; video: string; t: number }[]) {
+ const wins = cache ? (cache.windows(c.video) as { from: number; to: number }[]) : [];
+ if (wins.some((w) => w.from <= c.t && w.to >= c.t + 2)) playable[c.id] = true;
+ }
+ }
+ return Response.json({ ...view, token: await manifestToken(r.project.dir), playable }, { headers });
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/candidates");
+ if (refused) return refused;
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers });
+ const id = String(body.id ?? "");
+ try {
+ if (body.op === "dismiss") {
+ const note = typeof body.note === "string" ? body.note : null;
+ const inCut = new Set(((r.manifest.timeline ?? []) as { type?: string; id?: string }[]).filter((e) => e?.type === "clip").map((e) => String(e.id)));
+ return Response.json({ ok: true, ...(await dismissCandidate(r.project.dir, id, { note, inCut })) }, { headers });
+ }
+ if (body.op !== "insert") return Response.json({ error: 'op is "insert" or "dismiss"' }, { status: 400, headers });
+ const section = body.section === undefined || body.section === null || body.section === "" ? null : Number(body.section);
+ const group = typeof body.group === "string" && body.group ? body.group : null;
+ if (section !== null && !Number.isInteger(section)) return Response.json({ error: "section is a section's number" }, { status: 400, headers });
+ const token = body.token === undefined || body.token === null ? null : String(body.token);
+ // insertCandidate writes through `timeline insert`'s helper, which notes a generated cut's edits itself.
+ const result = await insertCandidate(r.project, id, { section, group, token });
+ invalidateProjects();
+ return Response.json({ ok: true, ...result, token: await manifestToken(r.project.dir) }, { headers });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers });
+ if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: (e as StructureRefused & { errors?: string[] }).errors }, { status: 400, headers });
+ const status = e instanceof CandidatesError ? ((e as CandidatesError & { status?: number }).status ?? 400) : 400;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+}
diff --git a/umtool/app/api/report/raw/route.ts b/umtool/app/api/report/raw/route.ts
@@ -1,8 +1,9 @@
import { stat } from "node:fs/promises";
import {
- absOf, ensureWindowFile, pickWindow, rangeResponse, resolveClaim, resolveClip, windowCacheControl, windowEtag, windowVersion, windowsFor,
+ absOf, ensureWindowFile, pickWindow, rangeResponse, resolveClaim, resolveClip, resolveReport, windowCacheControl, windowEtag, windowVersion, windowsFor,
} from "@/lib/report/serve.mjs";
import { readClaimDetail } from "@/lib/projects/report.mjs";
+import { readCandidates } from "@/lib/report/candidates.mjs";
export const dynamic = "force-dynamic";
@@ -33,7 +34,17 @@ export async function GET(request: Request) {
// root-resolution, ranges, the versioned cache header -- is the clip path's,
// unchanged: the two differ only in which list of windows they may pick from.
let windows: Array<{ name: string; from: number; to: number; path: string }>;
- if (claimId) {
+ const candidateId = url.searchParams.get("candidate");
+ if (candidateId) {
+ // A CANDIDATE (the Candidates panel's Play): a proposed moment the cut does
+ // not carry yet -- the cached windows of its recording that hold its cited second.
+ const rr = await resolveReport(projectId);
+ if ("error" in rr) return new Response(rr.error, { status: rr.status });
+ const { doc } = await readCandidates(rr.project.dir);
+ const cand = doc.candidates.find((x: { id: string }) => x.id === candidateId) as { video: string; t: number } | undefined;
+ if (!cand) return new Response("no such candidate", { status: 404 });
+ windows = await windowsFor(rr.project, { video: cand.video, start: cand.t, end: cand.t + 2 });
+ } else if (claimId) {
const c = await resolveClaim(projectId, claimId);
if ("error" in c) return new Response(c.error, { status: c.status });
const detail = await readClaimDetail(c.project.dir, claimId, { manifest: c.manifest });
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -102,6 +102,7 @@
// umtool scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--json] cuts + black spans, source seconds
// umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag …] [--thread] a post from the archive
// set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] the Posts table's writer
+// umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel
import process from "node:process";
import {
PROJECT_KINDS,
@@ -939,6 +940,9 @@ function usage() {
" refused when the post has no shot (`pnpm ops capture-posts` first); --thread: a reply drawn",
" with the post it answers above it (shot-thread.png, capture-posts \"thread\": true)",
" umtool posts set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] [--json]",
+ " umtool candidates <project> [ls] [--all] [--json] | import <sweep.md> [--dry-run] | add <json|@file>",
+ " the candidates inbox: a sweep's or an agent's proposed clips -> <project>/candidates.json;",
+ " Insert into a section or a group, and Not this, are the Cut tab's Candidates panel's",
" the Posts table's writer (updatePosts); <post> is x-<postId> or the bare <postId>",
"",
`reading ${REPORTS_ROOT} (set REPORTS_DIR to move it)`,
@@ -1021,6 +1025,8 @@ const COMMANDS = {
timeline: async () => process.exit(await settled(await (await import("../lib/report/timelineCli.mjs")).timelineCommand(argv.slice(argv.indexOf("timeline") + 1)))),
scenes: async () => process.exit(await (await import("../lib/report/scenesCli.mjs")).scenesCommand(argv.slice(argv.indexOf("scenes") + 1))),
posts: async () => process.exit(await (await import("../lib/report/postsCli.mjs")).postsCommand(argv.slice(argv.indexOf("posts") + 1))),
+ // The candidates inbox (UI notes item 14): proposals only -- lib/report/candidatesCli.mjs.
+ candidates: async () => process.exit(await (await import("../lib/report/candidatesCli.mjs")).candidatesCommand(argv.slice(argv.indexOf("candidates") + 1))),
inbox: cmdInbox,
schedule: () => tsxScript("schedule"),
refresh: () => tsxScript("refresh"),
diff --git a/umtool/components/projects/report/CandidatesPanel.tsx b/umtool/components/projects/report/CandidatesPanel.tsx
@@ -0,0 +1,321 @@
+"use client";
+
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { MANIFEST_CHANGED, announceManifestChanged } from "../timelineApi";
+
+// ---------------------------------------------------------------------------
+// THE CANDIDATES INBOX on the Cut tab (UI notes item 14). A sweep or an agent
+// PROPOSES clips (`umtool candidates <p> import <sweep.md>` / `add`, into
+// <project>/candidates.json); each row here is one cited moment -- Play, its
+// verdict, the section (and group) it proposes -- and only a press here puts
+// it in the cut: Insert into section (its end) or Insert into group (after
+// the group's last clip, one of its clips), each one write through `timeline
+// insert`'s writer with an undo point first. Not this records the row as set
+// aside and hides it; nothing is ever deleted (lib/report/candidates.mjs).
+// ---------------------------------------------------------------------------
+
+type Place = { section: number | null; group: string | null; why: string | null };
+type Candidate = {
+ id: string;
+ channel?: string;
+ video: string;
+ t: number;
+ title?: string;
+ date?: string;
+ quote?: string;
+ why?: string;
+ verdict?: string;
+ kind?: string;
+ ref?: string;
+ score?: number;
+ rank?: number;
+ top?: number;
+ heading?: string;
+ citeUrl?: string;
+ status: "proposed" | "inserted" | "dismissed";
+ inserted?: { clip: string; into: string; section?: number; group?: string };
+ dismissed?: { at: string; note?: string };
+ place: Place;
+ inCut: string | null;
+ /** Inserted once as this clip, which has since left the cut (an Undo): it waits again. */
+ left?: string;
+};
+type View = {
+ exists: boolean;
+ error: string | null;
+ candidates: Candidate[];
+ counts: { proposed: number; inserted: number; dismissed: number };
+ sections: { index: number; label: string | null; words: string }[];
+ groups: { id: string; claim: string; section: number; ids: string[] }[];
+ token: string | null;
+ playable: Record<string, boolean>;
+};
+
+const clock = (t: number) => {
+ const s = Math.floor(t);
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ return `${h ? `${h}:${String(m).padStart(2, "0")}` : m}:${String(s % 60).padStart(2, "0")}`;
+};
+
+/** The cited moment, played here from a cached window (seeked to its second). */
+function InlinePlayer({ project, c }: { project: string; c: Candidate }) {
+ const ref = useRef<HTMLVideoElement | null>(null);
+ const [from, setFrom] = useState<number | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+ const src = `/api/report/raw?project=${encodeURIComponent(project)}&candidate=${encodeURIComponent(c.id)}`;
+ useEffect(() => {
+ let live = true;
+ void fetch(src, { headers: { range: "bytes=0-0" } })
+ .then((r) => {
+ if (!live) return;
+ if (!r.ok) setErr(`HTTP ${r.status}`);
+ else setFrom(Number(r.headers.get("x-fetch-start") ?? 0));
+ })
+ .catch((e: unknown) => live && setErr(String(e)));
+ return () => {
+ live = false;
+ };
+ }, [src]);
+ if (err) return <span className="text-[11px] text-[var(--color-bad)]">could not play: {err}</span>;
+ if (from === null) return <span className="text-[11px] text-[var(--color-dim)]">opening…</span>;
+ return (
+ <video
+ ref={ref}
+ data-candidate-player={c.id}
+ src={src}
+ controls
+ autoPlay
+ preload="auto"
+ className="mt-1 w-full max-w-md rounded border border-[var(--color-line)]"
+ onLoadedMetadata={(e) => {
+ e.currentTarget.currentTime = Math.max(0, c.t - from);
+ }}
+ />
+ );
+}
+
+export default function CandidatesPanel({ project }: { project: string }) {
+ const router = useRouter();
+ const [view, setView] = useState<View | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [showDone, setShowDone] = useState(false);
+ const [playing, setPlaying] = useState<string | null>(null);
+ const [pickSection, setPickSection] = useState<Record<string, string>>({});
+ const [pickGroup, setPickGroup] = useState<Record<string, string>>({});
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/candidates?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
+ if (!r) return;
+ const j = (await r.json().catch(() => null)) as (View & { error?: string }) | null;
+ if (!r.ok || !j) {
+ setError(j?.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ setView(j);
+ }, [project]);
+ useEffect(() => {
+ void load();
+ const on = (e: Event) => {
+ if ((e as CustomEvent).detail?.project === project) void load();
+ };
+ window.addEventListener(MANIFEST_CHANGED, on);
+ return () => window.removeEventListener(MANIFEST_CHANGED, on);
+ }, [load, project]);
+
+ const post = async (id: string, body: Record<string, unknown>) => {
+ setBusy(id);
+ setError(null);
+ try {
+ const r = await fetch("/api/report/candidates", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, id, ...body }) });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
+ if (r.status === 409 && j.stale) setError(`${String(j.error ?? "the cut changed")} — reloaded; check and insert again`);
+ else if (!r.ok) setError(String(j.error ?? `HTTP ${r.status}`));
+ else if (j.attributionError) setError(`${id} is in as ${String(j.clip)}, but its header was refused: ${String(j.attributionError)}`);
+ if (r.ok && body.op === "insert") {
+ announceManifestChanged(project);
+ router.refresh();
+ }
+ return r.ok;
+ } finally {
+ setBusy(null);
+ await load();
+ }
+ };
+
+ if (!view) {
+ return error ? (
+ <section data-testid="candidates" className="mt-3 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]">
+ <p role="alert" className="m-0 text-[var(--color-bad)]">{error}</p>
+ </section>
+ ) : null;
+ }
+ const waiting = view.candidates.filter((c) => c.status === "proposed");
+ const done = view.candidates.filter((c) => c.status !== "proposed");
+ const rows = showDone ? view.candidates : waiting;
+ const sectionWords = (n: number | null | undefined) => view.sections.find((s) => s.index === n)?.words ?? (n === null || n === undefined ? "" : `§${n}`);
+
+ return (
+ <section data-testid="candidates" data-candidates-proposed={view.counts.proposed} className="mt-3 space-y-1.5 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]">
+ <div className="flex flex-wrap items-baseline gap-2">
+ <h2 className="micro m-0">candidates — {view.counts.proposed} proposed</h2>
+ <span className="text-[11px] text-[var(--color-dim)]">
+ {view.counts.inserted} inserted · {view.counts.dismissed} set aside · nothing goes in the cut until you press Insert
+ </span>
+ {done.length > 0 && (
+ <button type="button" data-candidates-show-done="" onClick={() => setShowDone((v) => !v)} className={cn(buttonVariants({ variant: "quiet", size: "sm" }), "ml-auto")}>
+ {showDone ? "hide inserted and set aside" : `show inserted and set aside (${done.length})`}
+ </button>
+ )}
+ </div>
+ {error && (
+ <p role="alert" data-testid="candidates-error" className="m-0 text-[11.5px] text-[var(--color-bad)]">
+ {error}
+ </p>
+ )}
+ {view.error && <p className="m-0 text-[11.5px] text-[var(--color-bad)]">{view.error}</p>}
+ {!view.candidates.length && (
+ <p data-candidates-empty="" className="m-0 text-[11px] text-[var(--color-dim)]">
+ No proposals. A sweep’s bullets come in with <code className="font-mono">umtool candidates {project} import <sweep.md></code>; an agent’s with{" "}
+ <code className="font-mono">umtool candidates {project} add <json></code>.
+ </p>
+ )}
+ {rows.length > 0 && (
+ <ul className="m-0 list-none space-y-1.5 p-0">
+ {rows.map((c) => {
+ const sec = pickSection[c.id] ?? (c.place.section !== null ? String(c.place.section) : "");
+ const groupsHere = view.groups;
+ const grp = pickGroup[c.id] ?? c.place.group ?? "";
+ const waitingRow = c.status === "proposed";
+ return (
+ <li
+ key={c.id}
+ data-candidate={c.id}
+ data-candidate-status={c.status}
+ data-candidate-video={c.video}
+ className={cn("rounded border border-[var(--color-line)] px-2 py-1.5", !waitingRow && "opacity-60")}
+ >
+ <div className="flex flex-wrap items-baseline gap-2">
+ <span className="font-mono text-[11px] text-[var(--color-dim)]">{c.id}</span>
+ {c.top !== undefined && <span className={badgeVariants({ variant: "state", size: "sm" })} title="the sweep's top picks across every section">#{c.top} overall</span>}
+ <span data-candidate-verdict="" className={badgeVariants({ variant: c.kind === "new claim" ? "on" : "info", size: "sm" })}>
+ {c.verdict ?? c.kind ?? "proposed"}
+ {typeof c.score === "number" ? ` · ${c.score}` : ""}
+ </span>
+ {c.rank !== undefined && <span className="micro" title="its place in the sweep's own ranking, strongest first">{c.rank}. in its section</span>}
+ <span className="text-[var(--color-text)]">{c.title ?? c.video}</span>
+ <span className="num font-mono text-[11px] text-[var(--color-dim)]">
+ {c.channel ? `${c.channel}/` : ""}
+ {c.video} @ {clock(c.t)}
+ {c.date ? ` · ${c.date}` : ""}
+ </span>
+ {c.inCut && waitingRow && (
+ <span data-candidate-in-cut={c.inCut} className={badgeVariants({ variant: "blocking", size: "sm" })} title="a clip of the cut already plays this second">
+ in the cut as {c.inCut}
+ </span>
+ )}
+ {c.left && waitingRow && (
+ <span data-candidate-left={c.left} className={badgeVariants({ variant: "state", size: "sm" })} title="its clip left the cut (an Undo or a removal): it waits again">
+ was {c.left}, no longer in the cut
+ </span>
+ )}
+ {c.status === "inserted" && <span className={badgeVariants({ variant: "on", size: "sm" })}>inserted as {c.inserted?.clip}</span>}
+ {c.status === "dismissed" && <span className={badgeVariants({ variant: "info", size: "sm" })}>not this{c.dismissed?.note ? ` — ${c.dismissed.note}` : ""}</span>}
+ </div>
+ {c.quote && <p className="m-0 mt-0.5 text-[12px] leading-snug text-[var(--color-text)]">“{c.quote}”</p>}
+ {c.why && <p className="m-0 mt-0.5 text-[11px] leading-snug text-[var(--color-dim)]">{c.why}</p>}
+ {waitingRow && (
+ <div className="mt-1 flex flex-wrap items-center gap-1.5">
+ {view.playable[c.id] ? (
+ <button type="button" data-candidate-play={c.id} onClick={() => setPlaying((p) => (p === c.id ? null : c.id))} className={buttonVariants({ size: "sm" })}>
+ {playing === c.id ? "Stop" : "Play"}
+ </button>
+ ) : c.citeUrl ? (
+ <a data-candidate-play={c.id} href={c.citeUrl} target="_blank" rel="noreferrer" className={buttonVariants({ size: "sm" })} title="no window of it is fetched: the archive plays the cited second">
+ Play ↗
+ </a>
+ ) : null}
+ <span data-candidate-place={c.place.section ?? ""} className="text-[11px] text-[var(--color-dim)]">
+ {c.place.section !== null ? `proposes ${sectionWords(c.place.section)}${c.place.group ? ` · group ${c.place.group}` : ""}${c.place.why ? ` (${c.place.why})` : ""}` : c.heading ? `under “${c.heading}” — pick a section` : "pick a section"}
+ </span>
+ {view.sections.length > 0 || view.groups.length === 0 ? (
+ <>
+ <select
+ data-candidate-section={c.id}
+ aria-label={`section for ${c.id}`}
+ value={sec}
+ onChange={(e) => setPickSection((p) => ({ ...p, [c.id]: e.target.value }))}
+ className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px] text-[var(--color-text)]"
+ >
+ <option value="">section…</option>
+ {(view.sections.length ? view.sections : [{ index: 0, label: null, words: "§0" }]).map((s) => (
+ <option key={s.index} value={String(s.index)}>
+ {s.words}
+ </option>
+ ))}
+ </select>
+ <button
+ type="button"
+ data-candidate-insert-section={c.id}
+ disabled={busy !== null || sec === ""}
+ title="at the end of that section (an undo point first)"
+ onClick={() => void post(c.id, { op: "insert", section: Number(sec), token: view.token })}
+ className={buttonVariants({ variant: "go", size: "sm" })}
+ >
+ Insert into section
+ </button>
+ </>
+ ) : null}
+ {groupsHere.length > 0 && (
+ <>
+ <select
+ data-candidate-group={c.id}
+ aria-label={`group for ${c.id}`}
+ value={grp}
+ onChange={(e) => setPickGroup((p) => ({ ...p, [c.id]: e.target.value }))}
+ className="max-w-56 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px] text-[var(--color-text)]"
+ >
+ <option value="">group…</option>
+ {groupsHere.map((g) => (
+ <option key={g.id} value={g.id}>
+ {g.id} §{g.section} — {g.claim.slice(0, 48)}
+ </option>
+ ))}
+ </select>
+ <button
+ type="button"
+ data-candidate-insert-group={c.id}
+ disabled={busy !== null || grp === ""}
+ title="after the group's last clip, one of its clips (an undo point first)"
+ onClick={() => void post(c.id, { op: "insert", group: grp, token: view.token })}
+ className={buttonVariants({ variant: "go", size: "sm" })}
+ >
+ Insert into group
+ </button>
+ </>
+ )}
+ <button
+ type="button"
+ data-candidate-dismiss={c.id}
+ disabled={busy !== null}
+ title="set it aside: recorded and hidden, never deleted"
+ onClick={() => void post(c.id, { op: "dismiss" })}
+ className={buttonVariants({ variant: "quiet", size: "sm" })}
+ >
+ Not this
+ </button>
+ </div>
+ )}
+ {playing === c.id && <InlinePlayer project={project} c={c} />}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -22,6 +22,7 @@ import { Pill, TONE, hms, type ReportTabProps } from "./shared";
import VoiceMatchPanel from "./VoiceMatchPanel";
import FetchWindowsPanel from "./FetchWindowsPanel";
import GroupProposalsPanel from "./GroupProposalsPanel";
+import CandidatesPanel from "./CandidatesPanel";
import BenchPrepPanel from "./BenchPrepPanel";
import { lastStartedRun, projectFetchBody, readFetchRuns } from "@/lib/report/fetchWindows.mjs";
import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
@@ -458,6 +459,8 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
</div>
</section>
+ {/* The candidates inbox: a sweep's proposed clips, each inserted only by a press (UI notes item 14). */}
+ <CandidatesPanel project={project.id} />
{clips.length > 0 && <GroupProposalsPanel project={project.id} />}
{/* --- the walk's ★ clips: the trailer's candidates ------------------- */}
{candidates.length > 0 && (
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -68,6 +68,8 @@ Inbox cannot disagree about what is wrong with one.
| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) |
| `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) |
| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) |
+| `timeline <project> insert (--to-section N \| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` | a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) |
+| `candidates <project> [ls] [--all] [--json]` · `candidates <project> import <sweep.md> [--dry-run] [--json]` · `candidates <project> add <json\|@file> [--json]` | the **candidates inbox** (`<project>/candidates.json`): proposals only — `import` reads a sweep's bullets (`- [verdict] [title @ time](link) (date) "quote" — why`, under their headings; a Top N section marks what it restates; a bullet with no verdict or link is skipped and said), `add` an agent's (`{channel?, video, t, quote?, why?, verdict?, score?, section?}` or `{link, …}`); the same moment again changes nothing it holds. Insert and Not this are the Cut tab's Candidates panel's ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) |
| `timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\|@file\|id…>` | **claim groups** (`groups` beside the timeline; the Cut tab's group bars): runs of clips inside one section making one claim — `ls` by section, each group's id, claim and clips (`--json` with the token); `import` 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; **exit 1** for an id the cut lacks (`--skip-missing`) or a section left with no clip (`--drop-empty` removes its marker); `set` (the clips already together), `label`, `remove` (ungroup), `move` the whole group (before the group at that index, or after one, in its section), `promote` (a level-2 marker at its first clip titled with its claim — the one group edit the render sees; `--label` when the claim is over 24); `order` the named entries in the places they hold (every clip keeping its section). A clip moved out of its group's run leaves it; moved alone into the middle of one, it joins. Every write an undo point (`undo`) ([knobs.md](knobs.md#claim-groups-runs-of-clips-that-make-one-claim)) |
| `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it |
| `timeline <project> sections [--json]` · `section-move <id>… --to-section N [--start]` · `section-add --after <id> [--label L] [--color C]` · `section-boundary <marker> --after <id>` · `section-remove <marker>` · `section-set <marker> [--label L] [--color C]` · `split <id> <second>` · `flash-forward <id> <from>-<to> (--after <id\|-> \| --to-section N [--start]) [--move] [--quote Q] [--id ID]` | **sections as sections** (the deck's markers; the Cut tab's section bars and row menus): clips moved to a section with every marker following, a section opened, a boundary moved, relabelled, removed — no section emptied, no boundary crossed (**exit 1**) — and every take patch in step synced; **split** (each half's quote from the words, the second half's cite and QR at its second, a marker after the clip following its second half); **flash-forward** a tight copy of a span elsewhere with the clip's attribution and locks, as `repeatOf` the clip (`--move`: out of the clip) ([knobs.md](knobs.md#sections-split-and-flash-forward-editing-the-cut)) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -302,6 +302,32 @@ into a group is refused. Each write is an undo point (**Undo last edit**, `umtoo
| the cut's order in one write | — | `umtool timeline <p> order <file\|@file\|id…>` — 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: `place`, `section-move`); a JSON list, `{order}`, a claim-groups file or ids by spaces, commas or lines; one undo point | `{op: "order", ids}` |
| propose groups | the Cut tab's **Propose groups**: the proposals, each **Accept** / **Reject** — never applied without a press | `pnpm ops report-draft --json '{"task":"propose-groups","project":"/abs/project/dir","request":"…"}'` (`request` optional; routed by `settings.generation`, `propose-groups`; proposals land in `<project>/group-proposals.json`, contiguous runs in one section, none over a grouped clip; Accept writes through `groups set`) | `POST /api/report/group-proposals` |
+## The candidates inbox (proposed clips, picked by a press)
+
+`<project>/candidates.json` (`lib/report/candidates.mjs`): the clips a sweep or an agent proposes, each a cited moment --
+the recording and second, its verdict (`strengthens fb1`, `new claim`, `could replace s01`, a score when it has one),
+the quote, why, and the heading the sweep put it under. **Proposing never touches the cut**; only the operator's
+press on the Cut tab's **Candidates** panel inserts. The place a row proposes is worked out against the cut as it is
+now: a verdict naming a clip of the cut proposes that clip's section and group, else a deck section with the
+sweep's heading as its name; else the operator picks. A row whose second a clip already plays says "in the cut as …".
+
+| | In umtool | From a terminal | Route |
+|---|---|---|---|
+| the rows | the Cut tab's **Candidates** panel: verdict, `#N overall` (a sweep's Top N), its rank in its section, title, recording @ time, date, quote, why, the proposed place; **show inserted and set aside** | `umtool candidates <p> [ls] [--all] [--json]` | `GET /api/report/candidates` |
+| import a sweep | — | `umtool candidates <p> import <sweep.md> [--dry-run]` -- every bullet `- [verdict] [title @ time](link) (date) "quote" — why` (numbered too), under its heading (a numbered heading's number dropped); a **Top N** section marks the moments it restates; a bullet with no verdict or link, or under a set-aside heading, is skipped and said | — |
+| an agent's proposal | — | `umtool candidates <p> add <json\|@file>` -- `{channel?, video, t, quote?, why?, verdict?, score?, section?, title?, date?}` or `{link, …}`, one or a list | — |
+| Play | **Play**: the cited second in the page when a cached window holds it, else **Play ↗** opens the archive at it | — | `GET /api/report/raw?candidate=<id>` |
+| Insert into section | the row's section (the proposed one preselected) and **Insert into section**: at the END of that section, the marker after its last clip re-anchored after the new one -- one write, an undo point | `umtool timeline <p> insert --to-section N <channel>/<video>@<start>-<end> [--title …]` | `POST /api/report/candidates {op: "insert", id, section, token}` |
+| Insert into group | the row's group (the proposed one preselected) and **Insert into group**: after the group's last clip and one of its clips, so the run stays together -- one write | `umtool timeline <p> insert --group G <spec> […]` | `{op: "insert", id, group, token}` |
+| Not this | **Not this**: the row set aside, recorded with when, hidden, never deleted; the same moment proposed again stays set aside | — | `{op: "dismiss", id, note?}` |
+| an Insert undone | the cut's **Undo last edit** (or the clip removed): the row waits again, "was <clip>, no longer in the cut" | `umtool timeline <p> undo` | — |
+
+An Insert's window runs from the sentence the cited second starts in (a sentence start at most 6 s before it) to the
+first sentence end after the quote has been said (~2.6 words a second, 4–40 s), from the recording's cues; with no
+cues, from the cited second for the quote's length. Its header is the row's: the stream title, the date, the quote,
+the cite second, in the manifest's convention (`timeline insert`'s). The same moment is the same recording and whole
+second (`<channel>/<video>@<s>`). A file that does not parse is never overwritten: every write refuses until it is fixed.
+
## The finale (the timeline in primary view)
The cut's last clips with the footer's rail redrawn large across the top (every pip lit, the markers flagged,
diff --git a/umtool/e2e/candidates.spec.ts b/umtool/e2e/candidates.spec.ts
@@ -0,0 +1,167 @@
+import { test, expect, type Page } from "@playwright/test";
+import { execFileSync } from "node:child_process";
+import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The candidates inbox on the Cut tab (UI notes item 14, lib/report/candidates.mjs):
+//
+// candidates-fixture the deck on: §0 c01 c02 | §1 "As a streamer" c03 c04 |
+// §2 "Looks" c05 c06, g1 c03 c04; sweep.md beside it in the
+// /sweep shape. WRITES its manifest, revisions/ and
+// candidates.json; every test starts from the fixture's.
+//
+// A sweep imported from a terminal (`umtool candidates <p> import`), its rows on
+// the panel with the verdict and the place each proposes; Play in the page from
+// a cached window; Insert into section (its end, the marker after the new clip);
+// Insert into group (after the group's last clip, one of its clips); Not this
+// (recorded, hidden, kept); nothing in the cut until a press.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, ".e2e-song");
+const DIR = path.join(FIXTURE, "reports", "candidates-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const STORE = path.join(DIR, "candidates.json");
+const PROJECT = "reports/candidates-fixture";
+const SHOTS = process.env.U4_SHOTS ?? null;
+
+type Manifest = { timeline: { id: string; quote?: string; video?: string }[]; groups?: { id: string; ids: string[] }[]; render: { chrome: { deck: { markers?: { after: string }[] } } } };
+const read = () => JSON.parse(readFileSync(MANIFEST, "utf8")) as Manifest;
+const order = () => read().timeline.map((e) => e.id).join(" ");
+const store = () => JSON.parse(readFileSync(STORE, "utf8")) as { candidates: { id: string; video: string; status: string; inserted?: { clip: string }; dismissed?: { at: string } }[] };
+
+function importSweep() {
+ return execFileSync("node", ["bin/umtool.mjs", "candidates", PROJECT, "import", path.join(DIR, "sweep.md")], {
+ cwd: path.join(HERE, ".."),
+ encoding: "utf8",
+ env: { ...process.env, REPORTS_DIR: FIXTURE, CHANNELS_DIR: path.join(FIXTURE, "channels"), UMTOOL_CACHE_DIR: path.join(FIXTURE, "cache"), UMTOOL_MEDIA_DIR: "" },
+ });
+}
+
+test.beforeAll(() => {
+ if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
+});
+test.beforeEach(() => {
+ test.setTimeout(90_000);
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+ rmSync(STORE, { force: true });
+});
+
+async function open(page: Page) {
+ await page.goto(urls.section(PROJECT, "timeline"));
+ await expect(page.getByTestId("candidates")).toBeVisible({ timeout: 20_000 });
+}
+const row = (page: Page, video: string) => page.locator(`[data-candidate-video='${video}']`);
+const idOf = (video: string) => store().candidates.find((c) => c.video === video)!.id;
+
+test("empty, the panel says how proposals come in; an import lands them proposed, the cut untouched", async ({ page }) => {
+ await open(page);
+ await expect(page.locator("[data-candidates-empty]")).toContainText(`umtool candidates ${PROJECT} import`);
+ const before = order();
+ const out = importSweep();
+ expect(out).toMatch(/4 added/);
+ // A re-import changes nothing it holds.
+ expect(importSweep()).toMatch(/0 added, 4 already there/);
+ expect(order()).toBe(before);
+ await page.reload();
+ await expect(page.getByTestId("candidates")).toHaveAttribute("data-candidates-proposed", "4");
+ // The Top 5's first leads the list.
+ await expect(page.locator("[data-candidate]").first()).toHaveAttribute("data-candidate-video", "v1234567");
+ await expect(row(page, "v1234567")).toContainText("#1 overall");
+ await expect(row(page, "vid2")).toContainText("strengthens c04");
+ await expect(row(page, "vid2").locator("[data-candidate-place]")).toContainText("§1 (As a streamer) · group g1 (c04's group (g1))");
+ await expect(row(page, "W4pgGUq5ygQ").locator("[data-candidate-place]")).toContainText("§2 (Looks)");
+ await expect(row(page, "W4pgGUq5ygQ")).toContainText("“I respect that looks sell.”");
+ await expect(row(page, "v1234567").locator("[data-candidate-place]")).toContainText("pick a section");
+ // The proposed place is preselected.
+ await expect(page.locator(`[data-candidate-section='${idOf("W4pgGUq5ygQ")}']`)).toHaveValue("2");
+ await expect(page.locator(`[data-candidate-group='${idOf("vid2")}']`)).toHaveValue("g1");
+ if (SHOTS) {
+ await page.setViewportSize({ width: 1366, height: 1100 });
+ await page.getByTestId("candidates").scrollIntoViewIfNeeded();
+ await page.getByTestId("candidates").screenshot({ path: path.join(SHOTS, "14-candidates-imported.png") });
+ }
+});
+
+test("Play: a cached window plays the cited second here; one with none opens the archive at it", async ({ page }) => {
+ importSweep();
+ await open(page);
+ const id = idOf("vid2");
+ await page.locator(`button[data-candidate-play='${id}']`).click();
+ const player = page.locator(`[data-candidate-player='${id}']`);
+ await expect(player).toBeVisible();
+ await expect.poll(() => player.evaluate((v: HTMLVideoElement) => v.currentTime), { timeout: 15_000 }).toBeGreaterThanOrEqual(2.9);
+ const far = page.locator(`a[data-candidate-play='${idOf("W4pgGUq5ygQ")}']`);
+ await expect(far).toHaveAttribute("href", "https://archive.example/?v=testchan%2FW4pgGUq5ygQ&t=284");
+ await expect(far).toHaveAttribute("target", "_blank");
+});
+
+test("Insert into section: at its end, the next marker after the new clip; Insert into group: after its last clip, one of its clips", async ({ page }) => {
+ importSweep();
+ await open(page);
+ const looks = idOf("W4pgGUq5ygQ");
+ await page.locator(`[data-candidate-insert-section='${looks}']`).click();
+ await expect(row(page, "W4pgGUq5ygQ")).toHaveCount(0);
+ await expect.poll(order).toBe("c01 c02 c03 c04 c05 c06 W4pgGUq5ygQ-284");
+ const e = read().timeline.at(-1)!;
+ expect(e.quote).toBe("I respect that looks sell.");
+ expect(store().candidates.find((c) => c.id === looks)!.inserted!.clip).toBe("W4pgGUq5ygQ-284");
+ // The Cut tab's list has it, in §2.
+ await expect(page.locator("li[data-entry='W4pgGUq5ygQ-284'] [data-row-section]")).toHaveAttribute("data-row-section", "2");
+
+ // A section that is not the last: §0's marker moves after the new clip.
+ const voice = idOf("v1234567");
+ await page.locator(`[data-candidate-section='${voice}']`).selectOption("0");
+ await page.locator(`[data-candidate-insert-section='${voice}']`).click();
+ await expect.poll(order).toBe("c01 c02 v1234567-3766 c03 c04 c05 c06 W4pgGUq5ygQ-284");
+ expect(read().render.chrome.deck.markers![0].after).toBe("v1234567-3766");
+
+ const grp = idOf("vid2");
+ await page.locator(`[data-candidate-insert-group='${grp}']`).click();
+ await expect.poll(() => store().candidates.find((c) => c.id === grp)!.status).toBe("inserted");
+ // Its id is the recording and its start: the window starts where the sentence does (vid2's cues).
+ const gid = store().candidates.find((c) => c.id === grp)!.inserted!.clip;
+ expect(gid).toMatch(/^vid2-\d+$/);
+ await expect.poll(order).toBe(`c01 c02 v1234567-3766 c03 c04 ${gid} c05 c06 W4pgGUq5ygQ-284`);
+ expect(read().groups!.find((g) => g.id === "g1")!.ids).toEqual(["c03", "c04", gid]);
+ expect(read().render.chrome.deck.markers![1].after).toBe(gid);
+ await expect(page.locator(`li[data-entry='${gid}'][data-kind]`)).toHaveAttribute("data-group", "g1");
+ // Each insert an undo point.
+ await page.getByTestId("timeline-undo").click();
+ await expect.poll(order).toBe("c01 c02 v1234567-3766 c03 c04 c05 c06 W4pgGUq5ygQ-284");
+ // Undone, the candidate waits again and says what it was.
+ await expect(row(page, "vid2").locator("[data-candidate-left]")).toHaveAttribute("data-candidate-left", gid);
+ await expect(row(page, "vid2")).toHaveAttribute("data-candidate-status", "proposed");
+ if (SHOTS) {
+ await page.reload();
+ await page.locator("[data-candidates-show-done]").click();
+ await page.setViewportSize({ width: 1366, height: 1300 });
+ await page.screenshot({ path: path.join(SHOTS, "14-candidates-inserted.png"), fullPage: true });
+ }
+});
+
+test("Not this: recorded and hidden, never deleted; shown again with the done rows", async ({ page }) => {
+ importSweep();
+ await open(page);
+ const id = idOf("XCERAAfIePY");
+ const before = order();
+ await page.locator(`[data-candidate-dismiss='${id}']`).click();
+ await expect(row(page, "XCERAAfIePY")).toHaveCount(0);
+ await expect(page.getByTestId("candidates")).toHaveAttribute("data-candidates-proposed", "3");
+ const r = store().candidates.find((c) => c.id === id)!;
+ expect(r.status).toBe("dismissed");
+ expect(r.dismissed!.at).toBeTruthy();
+ expect(store().candidates).toHaveLength(4);
+ expect(order()).toBe(before);
+ // Importing the sweep again does not bring it back.
+ importSweep();
+ await page.reload();
+ await expect(page.getByTestId("candidates")).toHaveAttribute("data-candidates-proposed", "3");
+ await page.locator("[data-candidates-show-done]").click();
+ await expect(row(page, "XCERAAfIePY")).toHaveAttribute("data-candidate-status", "dismissed");
+ await expect(row(page, "XCERAAfIePY")).toContainText("not this");
+});
diff --git a/umtool/e2e/fixtures/intake-fixture.mjs b/umtool/e2e/fixtures/intake-fixture.mjs
@@ -0,0 +1,76 @@
+// What the intake specs act on (UI notes 2026-10-30, items 13, 14, 16), each
+// its own project, written by its spec alone:
+//
+// candidates-fixture the deck on: §0 c01 c02 | §1 "As a streamer" c03 c04 |
+// §2 "Looks" c05 c06, group g1 c03 c04; sweep.md beside
+// it in the /sweep bullet shape (anonymised), imported by
+// the spec through `umtool candidates … import`; a
+// cached window of vid2 (0–9 s), so a candidate on it
+// plays here (candidates.spec.ts)
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+const json = (doc) => JSON.stringify(doc, null, 2) + "\n";
+const write = (dir, name, text) => {
+ mkdirSync(path.dirname(path.join(dir, name)), { recursive: true });
+ writeFileSync(path.join(dir, name), text);
+};
+
+const clips = (ids) =>
+ ids.map((id, i) => ({
+ type: "clip",
+ id,
+ channel: "testchan",
+ video: "vid1",
+ start: 0.5 + i,
+ end: 1.4 + i,
+ cite: 0.5 + i,
+ lock: true,
+ title: "The Fixture Stream",
+ date: "2026-10-27",
+ quote: `the words of ${id}`,
+ }));
+
+export const CANDIDATES_SWEEP = `# Re-sweep: newer transcripts against the cut
+
+- Format of each bullet: \`[verdict] [title @ time](link) (upload date) "quote" — why\`.
+
+## 1. As a streamer
+
+- [strengthens c04] [An older stream || Some react @ 0:03](https://archive.example/?v=testchan%2Fvid2&t=3) (2025-07-18) "I'm a streamer who reacts to stuff a lot." — the same self-introduction c04 gives, a year before; a stock phrase
+- [new claim] [Working my way back to "normal" @ 1:02:46](https://archive.example/?v=testchan-twitch%2Fv1234567&t=3766) (2026-10-29) "I didn't want my voice on stream." — a new window, in no clip
+
+## 2. Looks
+
+- [new claim] [The not-so-fabulous history || Liquid react @ 4:44](https://archive.example/?v=testchan%2FW4pgGUq5ygQ&t=284) (2025-08-03) "I respect that looks sell." — she accepts the trade outright
+- [could replace c06] [It's pretty clear by now... @ 30:45](https://archive.example/?v=testchan%2FXCERAAfIePY&t=1845) (2025-08-27) "It is one of the big reasons." — earlier than c06 by 13 months
+
+## Top 5 across all sections
+
+1. [new claim] [Working my way back to "normal" @ 1:02:46](https://archive.example/?v=testchan-twitch%2Fv1234567&t=3766) (2026-10-29) "I didn't want my voice on stream."
+
+## Read and set aside (not hers)
+
+- \`zISdc4EwxJ4\` @ 15:29 ("I'm a host"): someone else.
+`;
+
+/**
+ * @param {{ reports: string, deckManifest: Function, cachedWindow: string }} o
+ */
+export function makeIntakeFixture({ reports, deckManifest, cachedWindow }) {
+ const cands = path.join(reports, "candidates-fixture");
+ const m = deckManifest("candidates-fixture", "The Candidates Fixture", clips(["c01", "c02", "c03", "c04", "c05", "c06"]));
+ m.render.chrome.deck.markers = [
+ { after: "c02", label: "As a streamer", color: "#ff5a5a" },
+ { after: "c04", label: "Looks", color: "#4fbf6a" },
+ ];
+ m.groups = [{ id: "g1", section: 1, claim: "Says she streams", ids: ["c03", "c04"] }];
+ write(cands, "video.manifest.json", json(m));
+ write(cands, "sweep.md", CANDIDATES_SWEEP);
+ mkdirSync(path.join(cands, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(cands, "out", "clips-raw", "vid1_0.00-9.00.mp4"));
+ copyFileSync(cachedWindow, path.join(cands, "out", "clips-raw", "vid2_0.00-9.00.mp4"));
+ return { cands };
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -48,6 +48,7 @@ import { makeMarksFixture } from "./marks-fixture.mjs";
import { makeLivePreviewFixture } from "./live-preview-fixture.mjs";
import { makePlayCutFixture } from "./play-cut-fixture.mjs";
import { makeCutEditingFixture } from "./cut-editing-fixture.mjs";
+import { makeIntakeFixture } from "./intake-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -1874,6 +1875,8 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out
// Editing the cut (UI notes 2026-10-30): sections, flash-forward, the trailer's beats, take housekeeping
// (cut-sections, cut-flash, trailer-beats and take-housekeeping specs).
makeCutEditingFixture({ reports, manifest, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 });
+// The intake (UI notes 2026-10-30, items 13, 14, 16): the candidates inbox, the source backlog, Add post (intake specs).
+makeIntakeFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Gaps inside a clip and the bench waveform's zoom (gaps-zoom.spec.ts), which WRITES (gaps cut,
// undone, put back): its own project on gapvid, a recording id of its own (the fixture's vid1
// window -- tone, silences at 2.9-3.1 and 5.9-6.1 -- so nothing another spec fetches moves it).
diff --git a/umtool/lib/report/candidates.mjs b/umtool/lib/report/candidates.mjs
@@ -0,0 +1,604 @@
+// THE CANDIDATES INBOX (UI notes 2026-10-30, item 14): a project's proposed
+// clips -- what a sweep or an agent found, each a cited moment with its
+// verdict, its quote, why, and the section the sweep put it under -- waiting
+// for the operator's pick on the Cut tab.
+//
+// <project>/candidates.json
+// { format: "umtool-candidates", version: 1,
+// candidates: [{ id: "k1", key: "<channel>/<video>@<second>",
+// channel, video, t, title?, date?, quote?, why?,
+// verdict?, kind, ref?, score?, rank?, top?, heading?, citeUrl?,
+// source: { file?, line?, by }, addedAt,
+// status: "proposed" | "inserted" | "dismissed",
+// inserted?: { clip, into: "section" | "group", section, group?, at },
+// dismissed?: { at, note? } }] }
+//
+// WHO WRITES WHAT. An agent or a sweep only PROPOSES (`umtool candidates <p>
+// import <md>` / `add <json>`, addCandidates): rows land `proposed`, never in
+// the cut. Only the operator's press on the Candidates panel inserts
+// (insertCandidate, through `timeline insert`'s own writer, timelineCli.mjs
+// insertClip) or sets one aside (dismissCandidate: "Not this", recorded and
+// hidden, never deleted). Proposing the same moment again (the same key)
+// changes nothing about it, so a re-imported sweep never revives a row the
+// operator set aside.
+//
+// THE STORE, in lib/lifecycle.mjs's discipline: one writer, serialised
+// in-process, every write a whole file to a temp name and a rename. A file that
+// does not parse is never overwritten -- a write refuses (CandidatesUnreadable,
+// 409) until somebody fixes it; a read is empty with `error`.
+//
+// THE PLACE a row proposes is worked out against the cut as it is now
+// (candidatesView), never stored: a verdict naming a clip ("strengthens fb1",
+// "could replace s01") proposes that clip's section and its group; else the
+// sweep's heading, when a deck section has that name.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { deckOn } from "umtool-report-to-video/deck";
+import { readManifest } from "../projects/report.mjs";
+import { groupModel } from "./claimGroups.mjs";
+import { sectionModel, sectionWords } from "./sectionEdit.mjs";
+import { sentenceBoundaries } from "./sentenceEdges.mjs";
+
+export const CANDIDATES_FILE = "candidates.json";
+export const CANDIDATES_FORMAT = "umtool-candidates";
+export const CANDIDATES_VERSION = 1;
+export const CANDIDATE_STATUSES = Object.freeze(["proposed", "inserted", "dismissed"]);
+/** At most this many rows in one file (a sweep is tens). */
+export const CANDIDATES_MAX = 2000;
+const TEXT_MAX = 2000;
+const NAME_RE = /^[A-Za-z0-9._-]{1,128}$/;
+const ID_RE = /^k\d{1,5}$/;
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+export class CandidatesError extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.name = "CandidatesError";
+ this.status = status;
+ }
+}
+
+export const candidatesFile = (dir) => path.join(/* turbopackIgnore: true */ dir, CANDIDATES_FILE);
+
+/** The key a moment is known by: the same recording, the same whole second. */
+export const candidateKey = (c) => `${c.channel ?? ""}/${c.video}@${Math.floor(Number(c.t))}`;
+
+const text = (v, max = TEXT_MAX) => {
+ if (typeof v !== "string") return null;
+ const s = v.replace(/\s+/g, " ").trim();
+ return s ? [...s].slice(0, max).join("") : null;
+};
+
+/** "1:19:13" / "4:44" / "284" → seconds, or null. */
+export function clockSeconds(s) {
+ const m = /^\s*(?:(\d+):)?(\d{1,2}):(\d{2})(?:\.\d+)?\s*$/.exec(String(s ?? ""));
+ if (m) return (Number(m[1] ?? 0) * 3600) + Number(m[2]) * 60 + Number(m[3]);
+ const n = Number(s);
+ return Number.isFinite(n) && n >= 0 ? n : null;
+}
+
+/** A `t=` value: "2085", "2085s", "34m45s", "1h2m3s". */
+function tParam(v) {
+ if (v === null || v === undefined || v === "") return null;
+ const s = String(v).trim();
+ if (/^\d+(\.\d+)?s?$/.test(s)) return Number(s.replace(/s$/, ""));
+ const m = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(s);
+ if (m && (m[1] || m[2] || m[3])) return Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0);
+ return null;
+}
+
+/**
+ * The recording and second a citation link names: an archive's
+ * `?v=<channel>/<video>&t=<s>` (the /sweep shape, `%2F` or not), or YouTube's
+ * `watch?v=<id>&t=…` / `youtu.be/<id>?t=…` (no channel: the cut's own).
+ *
+ * @param {string} href
+ * @returns {{ channel: string | null, video: string, t: number | null } | null}
+ */
+export function parseCiteLink(href) {
+ let u;
+ try {
+ u = new URL(href);
+ } catch {
+ return null;
+ }
+ const t = tParam(u.searchParams.get("t"));
+ const host = u.hostname.replace(/^www\.|^m\./, "");
+ if (host === "youtu.be") {
+ const video = u.pathname.slice(1).split("/")[0];
+ return NAME_RE.test(video) ? { channel: null, video, t } : null;
+ }
+ const v = u.searchParams.get("v");
+ if (!v) return null;
+ const parts = v.split("/");
+ if (parts.length === 2 && NAME_RE.test(parts[0]) && NAME_RE.test(parts[1])) return { channel: parts[0], video: parts[1], t };
+ if (parts.length === 1 && NAME_RE.test(parts[0])) return { channel: null, video: parts[0], t };
+ return null;
+}
+
+/**
+ * What a verdict says: `strengthens fb1` → { kind: "strengthens", ref: "fb1" },
+ * `could replace s01` → { kind: "could replace", ref: "s01" }, `new claim`
+ * → { kind: "new claim" }; a number in it is its score (`0.91`, `score 0.91`,
+ * `91%`).
+ *
+ * @param {string} verdict
+ */
+export function parseVerdict(verdict) {
+ let v = text(verdict, 120) ?? "";
+ let score = null;
+ const sm = /(?:^|\s)(?:score\s*[:=]?\s*)?(\d+(?:\.\d+)?)(%)?(?=\s|$|,|;)/i.exec(v);
+ if (sm) {
+ const n = Number(sm[1]) / (sm[2] ? 100 : 1);
+ if (Number.isFinite(n) && n >= 0 && n <= 100) {
+ score = n;
+ v = (v.slice(0, sm.index) + v.slice(sm.index + sm[0].length)).replace(/\s*[,;]\s*/g, " ").trim();
+ }
+ }
+ const rm = /^(.*?\b(?:strengthens|supports|extends|replaces|replace|counters|answers|pairs with|beside|after|before|joins))\s+([A-Za-z][A-Za-z0-9_-]{0,63})\b(.*)$/i.exec(v);
+ if (rm) return { kind: `${rm[1]}${rm[3]}`.replace(/\s+/g, " ").trim().toLowerCase(), ref: rm[2], score };
+ return { kind: v.toLowerCase() || "proposed", ref: null, score };
+}
+
+// `- [verdict] [title @ time](link) (date) "quote" — why`, also numbered (`1. …`).
+const BULLET_RE = /^\s*(?:[-*+]|\d{1,3}[.)])\s+\[([^\]]{1,120})\]\s+\[(.+?)\]\((https?:\/\/[^)\s]+)\)\s*(.*)$/;
+const DATE_RE = /^\((\d{4}-\d{2}-\d{2})\)\s*/;
+const HEADING_RE = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
+/** Headings whose bullets restate the sections' (a "Top 5"), or are not proposals. */
+const TOP_RE = /^top\s+\d+\b/i;
+const ASIDE_RE = /\b(set aside|not hers|dropped|rejected|not safe)\b/i;
+
+/** `"quote" — why` (straight or curly quotes, an em/en dash or ` - `), or the why alone. */
+function quoteAndWhy(rest) {
+ const s = rest.trim();
+ if (!s) return { quote: null, why: null };
+ const open = s[0];
+ if (open === '"' || open === "“") {
+ const close = open === "“" ? "[”\"]" : "[\"”]";
+ const m = new RegExp(`^.(.*?)${close}\\s+(?:—|–|--|-)\\s+(.*)$`, "s").exec(s);
+ if (m) return { quote: m[1].trim() || null, why: m[2].trim() || null };
+ const q = new RegExp(`^.(.*)${close}\\s*$`, "s").exec(s);
+ if (q) return { quote: q[1].trim() || null, why: null };
+ }
+ const d = /^(?:—|–|--|-)\s+(.*)$/.exec(s);
+ return { quote: null, why: (d ? d[1] : s).trim() || null };
+}
+
+/**
+ * A sweep's markdown, read for its proposals: every bullet in the /sweep shape
+ * `- [verdict] [title @ time](link) (date) "quote" — why`, under the heading it
+ * stands under (a numbered heading's number dropped: `## 2. Sex appeal` is
+ * "Sex appeal"), ranked in the order the section lists them. A "Top N"
+ * section's bullets restate the others': each marks its moment's `top`
+ * instead of adding a row. A bullet with no verdict or no citation link is not
+ * a proposal (a "read and set aside" list) and is skipped, never an error.
+ *
+ * @param {string} md
+ * @param {{ file?: string | null }} [o]
+ * @returns {{ candidates: Array<Record<string, any>>, skipped: Array<{ line: number, why: string }> }}
+ */
+export function parseSweepMarkdown(md, { file = null } = {}) {
+ const lines = String(md ?? "").split(/\r?\n/);
+ const out = [];
+ const byKey = new Map();
+ const skipped = [];
+ let heading = null;
+ let top = false;
+ let aside = false;
+ let rank = 0;
+ lines.forEach((raw, i) => {
+ const h = HEADING_RE.exec(raw);
+ if (h) {
+ if (h[1].length === 1) return; // the document's title
+ const words = h[2].replace(/^\d+[.)]\s*/, "").trim();
+ top = TOP_RE.test(words);
+ aside = !top && ASIDE_RE.test(words);
+ heading = top || aside ? heading : words || null;
+ rank = 0;
+ return;
+ }
+ if (!/^\s*(?:[-*+]|\d{1,3}[.)])\s+\[/.test(raw)) return;
+ const b = BULLET_RE.exec(raw);
+ if (!b) {
+ skipped.push({ line: i + 1, why: "not `[verdict] [title @ time](link)`" });
+ return;
+ }
+ const [, verdictRaw, titleAt, href, after] = b;
+ const link = parseCiteLink(href);
+ if (!link) {
+ skipped.push({ line: i + 1, why: `the link names no recording: ${href}` });
+ return;
+ }
+ const at = /^(.*)\s+@\s+([\d:.]+)\s*$/.exec(titleAt);
+ const t = link.t ?? (at ? clockSeconds(at[2]) : null);
+ if (t === null || !Number.isFinite(t)) {
+ skipped.push({ line: i + 1, why: "no second: the link has no t= and the title no @ time" });
+ return;
+ }
+ let rest = after;
+ const d = DATE_RE.exec(rest);
+ const date = d ? d[1] : null;
+ if (d) rest = rest.slice(d[0].length);
+ const { quote, why } = quoteAndWhy(rest);
+ const v = parseVerdict(verdictRaw);
+ const c = {
+ channel: link.channel,
+ video: link.video,
+ t,
+ title: text(at ? at[1] : titleAt, 300),
+ date,
+ quote: text(quote),
+ why: text(why),
+ verdict: text(verdictRaw, 120),
+ kind: v.kind,
+ ref: v.ref,
+ score: v.score,
+ heading: top ? null : heading,
+ citeUrl: href,
+ source: { file, line: i + 1 },
+ };
+ const key = candidateKey(c);
+ if (top) {
+ const n = /^\s*(\d{1,3})[.)]/.exec(raw);
+ const topRank = n ? Number(n[1]) : (rank += 1);
+ const seen = byKey.get(key);
+ if (seen) {
+ seen.top ??= topRank;
+ return;
+ }
+ c.top = topRank;
+ } else if (aside) {
+ skipped.push({ line: i + 1, why: "under a set-aside heading" });
+ return;
+ } else {
+ rank += 1;
+ c.rank = rank;
+ }
+ if (byKey.has(key)) {
+ skipped.push({ line: i + 1, why: `the same moment as line ${byKey.get(key).source.line}` });
+ return;
+ }
+ byKey.set(key, c);
+ out.push(c);
+ });
+ return { candidates: out, skipped };
+}
+
+/**
+ * One proposal from an agent (`umtool candidates <p> add <json>`), judged:
+ * `{ channel?, video, t, quote?, why?, verdict?, score?, section? (a heading),
+ * title?, date?, citeUrl?, ref? }` -- or `{ link }` for the cite link alone.
+ */
+export function normalizeProposal(p, { file = null } = {}) {
+ if (!isObj(p)) throw new CandidatesError("a proposal is an object: { channel?, video, t, quote?, why?, verdict?, score?, section? }");
+ let { channel = null, video, t } = p;
+ const link = typeof p.citeUrl === "string" ? parseCiteLink(p.citeUrl) : typeof p.link === "string" ? parseCiteLink(p.link) : null;
+ if (link) {
+ channel ??= link.channel;
+ video ??= link.video;
+ t ??= link.t;
+ }
+ if (typeof video !== "string" || !NAME_RE.test(video)) throw new CandidatesError(`a proposal needs its video id (got ${JSON.stringify(video)})`);
+ if (channel !== null && (typeof channel !== "string" || !NAME_RE.test(channel))) throw new CandidatesError(`not a channel slug: ${JSON.stringify(channel)}`);
+ const sec = typeof t === "string" ? clockSeconds(t) : Number(t);
+ if (sec === null || !Number.isFinite(sec) || sec < 0) throw new CandidatesError(`a proposal needs its second, t ≥ 0 (got ${JSON.stringify(t)})`);
+ if (p.date !== undefined && p.date !== null && !/^\d{4}-\d{2}-\d{2}$/.test(String(p.date))) throw new CandidatesError(`date is YYYY-MM-DD (got ${JSON.stringify(p.date)})`);
+ const v = parseVerdict(typeof p.verdict === "string" ? p.verdict : "");
+ const score = p.score === undefined || p.score === null ? v.score : Number(p.score);
+ if (score !== null && !Number.isFinite(score)) throw new CandidatesError("score is a number");
+ return {
+ channel,
+ video,
+ t: Math.round(sec * 100) / 100,
+ title: text(p.title, 300),
+ date: p.date ?? null,
+ quote: text(p.quote),
+ why: text(p.why),
+ verdict: text(p.verdict, 120),
+ kind: v.kind,
+ ref: typeof p.ref === "string" && p.ref ? p.ref : v.ref,
+ score,
+ heading: text(p.section ?? p.heading, 200),
+ citeUrl: typeof p.citeUrl === "string" ? p.citeUrl : typeof p.link === "string" ? p.link : null,
+ source: { file, line: null },
+ };
+}
+
+// ---- the store ----------------------------------------------------------------
+
+const clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== null && v !== undefined));
+
+/** One stored row, judged on read (a bad row is skipped, never fatal). */
+function rowOf(r) {
+ if (!isObj(r) || typeof r.id !== "string" || !ID_RE.test(r.id)) return null;
+ if (typeof r.video !== "string" || !NAME_RE.test(r.video) || !Number.isFinite(Number(r.t))) return null;
+ if (!CANDIDATE_STATUSES.includes(r.status)) return null;
+ return { ...r, t: Number(r.t), key: candidateKey(r) };
+}
+
+/**
+ * Every row: `{ doc: { format, version, candidates }, error? }`. A missing file
+ * is empty; an unreadable one is empty with `error`.
+ *
+ * @param {string} dir
+ */
+export async function readCandidates(dir) {
+ const empty = () => ({ format: CANDIDATES_FORMAT, version: CANDIDATES_VERSION, candidates: [] });
+ let raw;
+ try {
+ raw = await readFile(/* turbopackIgnore: true */ candidatesFile(dir), "utf8");
+ } catch (err) {
+ if (err?.code === "ENOENT") return { doc: empty(), exists: false };
+ return { doc: empty(), exists: true, error: `${CANDIDATES_FILE} cannot be read: ${err?.message ?? err}` };
+ }
+ let j;
+ try {
+ j = JSON.parse(raw);
+ } catch (err) {
+ return { doc: empty(), exists: true, error: `${CANDIDATES_FILE} is not JSON: ${err.message}` };
+ }
+ if (!isObj(j) || j.format !== CANDIDATES_FORMAT || !Array.isArray(j.candidates)) {
+ return { doc: empty(), exists: true, error: `${CANDIDATES_FILE} is not a ${CANDIDATES_FORMAT} file` };
+ }
+ return { doc: { format: CANDIDATES_FORMAT, version: CANDIDATES_VERSION, candidates: j.candidates.map(rowOf).filter(Boolean) }, exists: true };
+}
+
+let chain = Promise.resolve();
+
+/** The one writer: `mutate(doc)` on the file as it is, then the whole file written. */
+function writeCandidates(dir, mutate) {
+ const run = chain.then(async () => {
+ const file = candidatesFile(dir);
+ const read = await readCandidates(dir);
+ if (read.error) throw new CandidatesError(`${read.error}; fix or remove ${file} first`, 409);
+ const doc = read.doc;
+ const result = await mutate(doc);
+ const out = {
+ format: CANDIDATES_FORMAT,
+ version: CANDIDATES_VERSION,
+ candidates: doc.candidates.map(({ key: _k, ...r }) => ({ id: r.id, key: candidateKey(r), ...r })),
+ };
+ await mkdir(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
+ try {
+ await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(out, null, 2)}\n`);
+ await rename(/* turbopackIgnore: true */ tmp, file);
+ } catch (err) {
+ await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {});
+ throw err;
+ }
+ return result;
+ });
+ // The next write waits for this one, whether it failed or not.
+ chain = run.catch(() => {});
+ return run;
+}
+
+const nextId = (rows) => `k${rows.reduce((n, r) => Math.max(n, Number(r.id.slice(1)) || 0), 0) + 1}`;
+
+/**
+ * PROPOSE: rows added `proposed`. A moment already in the file (its key) is
+ * left exactly as it is -- inserted, set aside or waiting -- except that a
+ * "Top N" mark it lacked is added. Answers `{ added, kept, ids }`.
+ *
+ * @param {string} dir
+ * @param {Array<Record<string, any>>} list parseSweepMarkdown's or normalizeProposal's rows
+ * @param {{ by?: string, now?: string | null }} [o]
+ */
+export function addCandidates(dir, list, { by = "agent", now = null } = {}) {
+ const stamp = now ?? new Date().toISOString();
+ return writeCandidates(dir, (doc) => {
+ const byKey = new Map(doc.candidates.map((r) => [candidateKey(r), r]));
+ const added = [];
+ const kept = [];
+ for (const c of list) {
+ const key = candidateKey(c);
+ const seen = byKey.get(key);
+ if (seen) {
+ if (c.top && !seen.top) seen.top = c.top;
+ kept.push(seen.id);
+ continue;
+ }
+ if (doc.candidates.length >= CANDIDATES_MAX) throw new CandidatesError(`a project holds at most ${CANDIDATES_MAX} candidates`);
+ const row = clean({ id: nextId(doc.candidates), ...c, source: clean({ ...(c.source ?? {}), by }), addedAt: stamp, status: "proposed" });
+ doc.candidates.push(row);
+ byKey.set(key, row);
+ added.push(row.id);
+ }
+ return { added, kept };
+ });
+}
+
+/**
+ * A waiting row by id, or a refusal in words. `inCut` (the clip ids the cut
+ * holds now) lets an INSERTED row whose clip has since left the cut (an
+ * Undo, a removal) wait again.
+ */
+function waitingRow(doc, id, inCut = null) {
+ if (typeof id !== "string" || !ID_RE.test(id)) throw new CandidatesError("id is a candidate's id (k1, k2, …)");
+ const r = doc.candidates.find((x) => x.id === id);
+ if (!r) throw new CandidatesError(`no candidate ${id}`, 404);
+ if (r.status === "inserted" && inCut && !inCut.has(r.inserted?.clip)) return r;
+ if (r.status !== "proposed") throw new CandidatesError(`${id} is ${r.status === "inserted" ? `in the cut already (${r.inserted?.clip ?? "?"})` : "set aside (Not this)"}`, 409);
+ return r;
+}
+
+/** An inserted row whose clip is no longer in the cut (undone, removed): it waits again. */
+const goneFrom = (r, inCut) => r.status === "inserted" && !inCut.has(r.inserted?.clip);
+
+/**
+ * NOT THIS: the row set aside -- recorded with when (and a note), hidden from
+ * the panel's list, never deleted; proposing the moment again does not bring
+ * it back.
+ *
+ * @param {string} dir
+ * @param {string} id
+ * @param {{ note?: string | null, now?: string | null, inCut?: Set<string> | null }} [o] `inCut`: the cut's clip ids (an undone insert may be set aside)
+ */
+export function dismissCandidate(dir, id, { note = null, now = null, inCut = null } = {}) {
+ return writeCandidates(dir, (doc) => {
+ const r = waitingRow(doc, id, inCut);
+ r.status = "dismissed";
+ r.dismissed = clean({ at: now ?? new Date().toISOString(), note: text(note, 500) });
+ return { dismissed: id, row: { ...r } };
+ });
+}
+
+/** Mark a row inserted (after the clip landed). */
+function markInserted(dir, id, inserted, inCut) {
+ return writeCandidates(dir, (doc) => {
+ const r = waitingRow(doc, id, inCut);
+ r.status = "inserted";
+ r.inserted = clean(inserted);
+ return { ...r };
+ });
+}
+
+// ---- the place, the window, the view ------------------------------------------
+
+const norm = (s) => String(s ?? "").normalize("NFKC").toLowerCase().replace(/[‐-―]/g, "-").replace(/[^a-z0-9]+/g, " ").trim();
+
+/**
+ * Where a row proposes to go in the cut as it is: `{ section, group, why }`
+ * (section null: nothing to go on, the operator picks). A verdict naming a
+ * clip of the cut proposes that clip's section and group; else the heading,
+ * when a section has that name (or one contains the other).
+ */
+export function placeOf(c, manifest, { model = sectionModel(manifest), groups = groupModel(manifest) } = {}) {
+ const clips = (manifest?.timeline ?? []).filter((e) => e?.type === "clip");
+ const deck = deckOn(manifest?.render);
+ const sectionOfClip = (id) => (deck ? model.sectionOf.get(id) : (clips.find((e) => e.id === id)?.section ?? 0));
+ if (c.ref && clips.some((e) => e.id === c.ref)) {
+ const g = groups.find((x) => x.ids.includes(c.ref)) ?? null;
+ return { section: sectionOfClip(c.ref) ?? 0, group: g ? g.id : null, why: `${c.ref}'s ${g ? `group (${g.id})` : "section"}` };
+ }
+ if (c.heading && deck) {
+ const h = norm(c.heading);
+ const named = model.sections.filter((s) => s.label);
+ const s = named.find((x) => norm(x.label) === h) ?? named.find((x) => h && (norm(x.label).includes(h) || h.includes(norm(x.label))));
+ if (s) return { section: s.index, group: null, why: "the sweep's heading" };
+ }
+ return { section: null, group: null, why: c.ref ? `${c.ref} is not in the cut` : null };
+}
+
+/** The clip of the cut that already plays this moment (the same recording, within a second of its window), or null. */
+export function inCutAs(c, manifest) {
+ const t = Number(c.t);
+ const hit = (manifest?.timeline ?? []).find(
+ (e) => e?.type === "clip" && e.video === c.video && (!c.channel || !e.channel || e.channel === c.channel) && Number(e.start) - 1 <= t && t <= Number(e.end) + 1,
+ );
+ return hit ? hit.id : null;
+}
+
+/** How long a quote takes to say: ~2.6 words a second, 4–40 s. */
+export const quoteSeconds = (quote) => {
+ const words = String(quote ?? "").split(/\s+/).filter(Boolean).length;
+ return Math.min(40, Math.max(4, words / 2.6));
+};
+
+/**
+ * The window an Insert gives the moment: from the sentence it starts in (a
+ * sentence start at most 6 s before the cited second) to the first sentence
+ * end after the quote has been said (at most 15 s past it). With no cues,
+ * the cited second to the quote's length. The bench trims it from there.
+ *
+ * @param {number} t
+ * @param {string | null} quote
+ * @param {Array<{ start: number, end: number, text: string }> | null} cues
+ */
+export function candidateWindow(t, quote, cues) {
+ const dur = quoteSeconds(quote);
+ const r2 = (n) => Math.round(n * 100) / 100;
+ if (!Array.isArray(cues) || !cues.length) return { start: r2(t), end: r2(t + dur), from: "the quote's length (no cues)" };
+ const { starts, ends } = sentenceBoundaries(cues);
+ const start = [...starts].reverse().find((s) => s <= t + 0.5 && s >= t - 6) ?? t;
+ const end = ends.find((e) => e >= start + dur - 0.5 && e <= start + dur + 15) ?? start + dur;
+ return { start: r2(start), end: r2(Math.max(end, start + 1)), from: "the sentences around it" };
+}
+
+/**
+ * The panel's rows, in order (the proposed first: a Top N mark, then the sweep's
+ * own order), each with its place in the cut as it is now and the clip already
+ * playing it; with the sections and groups to pick from.
+ *
+ * @param {string} dir
+ * @param {Record<string, any> | null} [manifest]
+ */
+export async function candidatesView(dir, manifest = null) {
+ const m = manifest ?? (await readManifest(dir)) ?? {};
+ const { doc, error, exists } = await readCandidates(dir);
+ const model = sectionModel(m);
+ const groups = groupModel(m);
+ const deck = deckOn(m?.render);
+ const clipIds = new Set((m.timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id));
+ // An inserted row whose clip has left the cut (an Undo, a removal) waits again, and says so.
+ const rows = doc.candidates.map((c) => {
+ const back = goneFrom(c, clipIds);
+ const status = back ? "proposed" : c.status;
+ return { ...c, status, ...(back ? { left: c.inserted?.clip } : {}), place: placeOf(c, m, { model, groups }), inCut: status === "proposed" ? inCutAs(c, m) : null };
+ });
+ const order = { proposed: 0, inserted: 1, dismissed: 2 };
+ rows.sort((a, b) => order[a.status] - order[b.status] || (a.top ?? 1e9) - (b.top ?? 1e9) || Number(a.id.slice(1)) - Number(b.id.slice(1)));
+ const count = (s) => rows.filter((r) => r.status === s).length;
+ return {
+ file: CANDIDATES_FILE,
+ exists: !!exists,
+ error: error ?? null,
+ candidates: rows,
+ counts: { proposed: count("proposed"), inserted: count("inserted"), dismissed: count("dismissed") },
+ sections: deck ? model.sections.filter((s) => s.clips.length).map((s) => ({ index: s.index, label: s.label, level: s.level, words: sectionWords(s) })) : [],
+ groups: groups.map((g) => ({ id: g.id, claim: g.claim, section: g.section, ids: g.ids })),
+ };
+}
+
+/**
+ * INSERT (the operator's press, never an agent's): candidate `id` into
+ * section `section` (its end) or group `group` (after its last clip, one of
+ * its clips) through `timeline insert`'s own writer (timelineCli.mjs
+ * insertClip: the entry, then its attribution through updateClip -- the
+ * stream title, the date, the quote, the cite second), its window from the
+ * sentences around the cited second (candidateWindow). The row is marked
+ * inserted with the clip's id. `token` is the manifest's as the page read it.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} id
+ * @param {{ section?: number | null, group?: string | null, token?: string | null, cues?: Array<any> | null, now?: string | null }} o
+ */
+export async function insertCandidate(project, id, { section = null, group = null, token = null, cues = undefined, now = null } = {}) {
+ const { doc, error } = await readCandidates(project.dir);
+ if (error) throw new CandidatesError(error, 409);
+ if ((section === null) === (group === null)) throw new CandidatesError("insert into a section or into a group: name one");
+ const { insertClip, attributionPatch, insertConvention } = await import("./timelineCli.mjs");
+ const { StaleToken, manifestToken } = await import("./manifest.mjs");
+ const cur = await manifestToken(project.dir);
+ if (token !== null && token !== cur) throw new StaleToken(token, cur);
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CandidatesError(`${project.id} has no manifest`, 404);
+ const clipIds = (m) => new Set((m?.timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id));
+ const c = waitingRow(doc, id, clipIds(manifest));
+ let cueList = cues;
+ if (cueList === undefined) {
+ const { cuesForSource } = await import("../projects/report.mjs");
+ const got = await cuesForSource(project.dir, { video: c.video, ...(c.channel ? { channel: c.channel } : {}) }, c.t - 10, c.t + 60).catch(() => null);
+ cueList = got?.cues ?? null;
+ }
+ const win = candidateWindow(c.t, c.quote ?? null, cueList);
+ const flags = new Map();
+ if (c.title) flags.set("--stream-title", c.title);
+ if (c.date) flags.set("--date", c.date);
+ if (c.quote) flags.set("--quote", c.quote);
+ flags.set("--cite", String(Math.floor(c.t)));
+ const patch = attributionPatch(flags, insertConvention(manifest));
+ const clip = { ...(c.channel ? { channel: c.channel } : {}), video: c.video, start: win.start, end: win.end };
+ const done = await insertClip(project, manifest, clip, { toSection: section, group, patch });
+ const row = await markInserted(project.dir, id, {
+ clip: done.result.id,
+ into: group !== null ? "group" : "section",
+ section: done.result.section ?? null,
+ group: group ?? null,
+ at: now ?? new Date().toISOString(),
+ }, clipIds(manifest)); // the cut as it was before this insert: a re-insert may take the same id
+ return { inserted: id, clip: done.result.id, window: win, result: done.result, editNotes: done.editNotes, attributionError: done.attributionError, row };
+}
diff --git a/umtool/lib/report/candidates.test.mjs b/umtool/lib/report/candidates.test.mjs
@@ -0,0 +1,245 @@
+// The candidates inbox (UI notes item 14): a sweep's markdown read for its
+// proposals (real-shaped, anonymised lines in the /sweep bullet shape), the
+// store's one writer (a re-import changes nothing it holds; an unreadable file
+// is never overwritten), the place a row proposes, and Insert into a section
+// or a group through `timeline insert`'s writer -- one undo point, the marker
+// re-anchored, the group contiguous -- and Not this (recorded, hidden, kept).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, readdir, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ CANDIDATES_FILE,
+ addCandidates,
+ candidateWindow,
+ candidatesView,
+ dismissCandidate,
+ insertCandidate,
+ normalizeProposal,
+ parseCiteLink,
+ parseSweepMarkdown,
+ parseVerdict,
+ readCandidates,
+} from "./candidates.mjs";
+import { MANIFEST_NAME, insertIntoIn, manifestToken, removeEntry } from "./manifest.mjs";
+import { sectionModel } from "./sectionEdit.mjs";
+
+// The shapes the re-sweep files carry, anonymised: an archive link with %2F,
+// a twitch VOD id, ids with -- and a leading _, h:mm:ss, a title with ||, ?!?
+// and quotes in it, a "could replace", a NOTE in the why, a numbered Top 5
+// restating bullets, a bullet with no date, and a set-aside list.
+const SWEEP = `# Re-sweep, Nov 2026: newer transcripts against the cut
+
+- Date: 1 Nov 2026. Notes for the operator; nothing in the project was edited.
+- Format of each bullet: \`[verdict] [title @ time](link) (upload date) "quote" — why\`.
+
+## 1. As a streamer
+
+**As a host:** nothing found that is clearly her own first-person statement.
+
+- [strengthens fb1] [It's not the size, but how you use it... right guys?!? || Some Channel react @ 34:45](https://example-archive.pages.dev/?v=somestreamer%2FkHsAbcd3e0&t=2085) (2025-07-18) "I'm Sam. I'm a redhead who reacts to stuff a lot of times." — the same self-introduction fb1 gives ("the fiery redhead"), fifteen months before; a stock phrase
+- [strengthens j01] [The fight has begun! || Another react @ 43:14](https://example-archive.pages.dev/?v=somestreamer%2FFZvoVxld6Ts&t=2594) (2025-07-23) "I am just a simple country gamer." — same downplay again
+
+## 2. Looks
+
+- [new claim] [The not-so-fabulous history of a streamer || Liquid react @ 4:44](https://example-archive.pages.dev/?v=somestreamer%2FW4pgGUq5ygQ&t=284) (2025-08-03) "I respect that looks sell." — she accepts the trade outright, then draws the line at 5:00-5:13
+- [could replace s01] [It's pretty clear by now... @ 30:45](https://example-archive.pages.dev/?v=somestreamer%2FXCERAAfIePY&t=1845) (2025-08-27) "It's one of the big reasons why I use it is I need to protect my privacy." — earlier than s01 by 13 months; start the clip at 30:43 and stop at 30:57
+
+## 4. Why the voice
+
+- [new claim] [Working my way back to "normal" @ 5:02:46](https://example-archive.pages.dev/?v=somestreamer-twitch%2Fv2914211236&t=18166) (2026-10-29) "I didn't want my voice to be on stream so I got the changer" — a new window between cc1 and os1; NOTE: the transcript garbles a word, say it from the audio
+- [strengthens n02] [Looking back on my first year @ 10:16](https://example-archive.pages.dev/?v=somestreamer%2FoRsQnRc--aQ&t=616) "from day one I've used it and I've been open about it from day one" — no date on this one
+- [new claim] [Who wants to try? || Some react @ 6:48](https://example-archive.pages.dev/?v=somestreamer%2F_BjBoBICHaE&t=408) (2025-12-27) "maybe some of the other voices that I have might work well" — she keeps several
+
+## Top 5 across all sections
+
+1. [new claim] [Working my way back to "normal" @ 5:02:46](https://example-archive.pages.dev/?v=somestreamer-twitch%2Fv2914211236&t=18166) (2026-10-29) "I didn't want my voice to be on stream so I got the changer"
+2. [strengthens fb1] [It's not the size, but how you use it... right guys?!? || Some Channel react @ 34:45](https://example-archive.pages.dev/?v=somestreamer%2FkHsAbcd3e0&t=2085) (2025-07-18) "I'm Sam."
+
+## Read and set aside (not hers, or not safe to use)
+
+- \`zISdc4EwxJ4\` @ 15:29 ("I'm a host"): a child in her hypothetical about someone else.
+- [dropped] [A quoted tweet @ 1:00](https://example-archive.pages.dev/?v=somestreamer%2Fqmac00000&t=60) "read aloud" — a commenter she is quoting
+`;
+
+test("a sweep's bullets: verdict, ref, the recording and second, the date, the quote and why, the heading, the rank", () => {
+ const { candidates: c, skipped } = parseSweepMarkdown(SWEEP, { file: "RESWEEP.md" });
+ assert.equal(c.length, 7);
+ assert.deepEqual(
+ c.map((x) => [x.channel, x.video, x.t]),
+ [
+ ["somestreamer", "kHsAbcd3e0", 2085],
+ ["somestreamer", "FZvoVxld6Ts", 2594],
+ ["somestreamer", "W4pgGUq5ygQ", 284],
+ ["somestreamer", "XCERAAfIePY", 1845],
+ ["somestreamer-twitch", "v2914211236", 18166],
+ ["somestreamer", "oRsQnRc--aQ", 616],
+ ["somestreamer", "_BjBoBICHaE", 408],
+ ],
+ );
+ const [a, , n, r, tw, nd] = c;
+ assert.equal(a.kind, "strengthens");
+ assert.equal(a.ref, "fb1");
+ assert.equal(a.title, "It's not the size, but how you use it... right guys?!? || Some Channel react");
+ assert.equal(a.date, "2025-07-18");
+ assert.equal(a.quote, "I'm Sam. I'm a redhead who reacts to stuff a lot of times.");
+ assert.match(a.why, /^the same self-introduction fb1 gives \("the fiery redhead"\)/);
+ assert.equal(a.heading, "As a streamer");
+ assert.equal(a.rank, 1);
+ assert.equal(a.top, 2, "the Top 5 restating it marks it, adds nothing");
+ assert.equal(n.kind, "new claim");
+ assert.equal(n.ref, null);
+ assert.equal(n.heading, "Looks");
+ assert.equal(r.kind, "could replace");
+ assert.equal(r.ref, "s01");
+ assert.equal(tw.title, 'Working my way back to "normal"');
+ assert.equal(tw.top, 1);
+ assert.match(tw.why, /NOTE: the transcript garbles a word/);
+ assert.equal(tw.heading, "Why the voice");
+ assert.equal(nd.date, null);
+ assert.equal(nd.quote, "from day one I've used it and I've been open about it from day one");
+ assert.equal(nd.rank, 2);
+ assert.ok(skipped.some((s) => /set-aside/.test(s.why)), "a bullet under a set-aside heading is not a proposal");
+ assert.ok(!c.some((x) => x.video === "zISdc4EwxJ4" || x.video === "qmac00000"));
+});
+
+test("cite links, verdicts and an agent's proposal", () => {
+ assert.deepEqual(parseCiteLink("https://x.pages.dev/?v=chan/vid-1&t=90"), { channel: "chan", video: "vid-1", t: 90 });
+ assert.deepEqual(parseCiteLink("https://www.youtube.com/watch?v=abcDEF12345&t=1m30s"), { channel: null, video: "abcDEF12345", t: 90 });
+ assert.deepEqual(parseCiteLink("https://youtu.be/abcDEF12345?t=42"), { channel: null, video: "abcDEF12345", t: 42 });
+ assert.equal(parseCiteLink("not a link"), null);
+ assert.deepEqual(parseVerdict("0.91 strengthens ow2"), { kind: "strengthens", ref: "ow2", score: 0.91 });
+ assert.deepEqual(parseVerdict("new claim"), { kind: "new claim", ref: null, score: null });
+ const p = normalizeProposal({ link: "https://x.pages.dev/?v=chan%2Fvid&t=12", quote: " hello there ", verdict: "strengthens c01", section: "Two" });
+ assert.equal(p.channel, "chan");
+ assert.equal(p.t, 12);
+ assert.equal(p.quote, "hello there");
+ assert.equal(p.ref, "c01");
+ assert.equal(p.heading, "Two");
+ assert.throws(() => normalizeProposal({ video: "v" }), /second/);
+ assert.throws(() => normalizeProposal({ video: "v", t: 3, date: "3 May" }), /YYYY-MM-DD/);
+});
+
+test("the window: from the sentence it starts in to a sentence end after the quote; no cues, the quote's length", () => {
+ const cues = [
+ { start: 98, end: 100, text: "Before that." },
+ { start: 100, end: 103, text: "I respect that" },
+ { start: 103, end: 106, text: "looks sell." },
+ { start: 106, end: 110, text: "And then more words here." },
+ ];
+ assert.deepEqual(candidateWindow(101, "I respect that looks sell.", cues), { start: 100, end: 106, from: "the sentences around it" });
+ assert.deepEqual(candidateWindow(50, "a b c d", null), { start: 50, end: 54, from: "the quote's length (no cues)" });
+});
+
+const clip = (id, i, video = "v1") => ({ type: "clip", id, video, start: 10 * i, end: 10 * i + 8 });
+const cut = () => ({
+ slug: "s",
+ provenance: { channelSlug: "somestreamer" },
+ render: { width: 1920, height: 1080, chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "fb1", label: "As a streamer" }, { after: "j01", label: "Looks" }] } } },
+ timeline: [clip("c01", 0), clip("fb1", 1), clip("ow1", 2), clip("j01", 3), clip("s01", 4), clip("t01", 5)],
+ groups: [{ id: "g1", section: 1, claim: "One claim", ids: ["ow1", "j01"] }],
+});
+async function project() {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-candidates-"));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(cut(), null, 2) + "\n");
+ return { id: "cands", dir };
+}
+const manifest = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8"));
+
+test("insert into a section lands at its END, the marker re-anchored; into a group after its last clip, one of its clips", () => {
+ const m = cut();
+ const r = insertIntoIn(m, "somestreamer/new1@100-105", { section: 0 });
+ assert.equal(r.after, "fb1");
+ assert.deepEqual(m.timeline.map((e) => e.id), ["c01", "fb1", "new1-100", "ow1", "j01", "s01", "t01"]);
+ assert.equal(m.render.chrome.deck.markers[0].after, "new1-100", "the section's marker follows the new clip");
+ assert.equal(sectionModel(m).sectionOf.get("new1-100"), 0);
+ const m2 = cut();
+ const g = insertIntoIn(m2, "somestreamer/new2@200-205", { group: "g1" });
+ assert.deepEqual(m2.timeline.map((e) => e.id), ["c01", "fb1", "ow1", "j01", "new2-200", "s01", "t01"]);
+ assert.equal(m2.render.chrome.deck.markers[1].after, "new2-200");
+ assert.deepEqual(m2.groups[0].ids, ["ow1", "j01", "new2-200"]);
+ assert.equal(g.groupsWritten, true);
+ assert.throws(() => insertIntoIn(cut(), "a/b@1-3", { section: 9 }), /section must be 0–2/);
+ assert.throws(() => insertIntoIn(cut(), "a/b@1-3", { group: "g9" }), /no group g9 \(g1\)/);
+ assert.throws(() => insertIntoIn(cut(), "a/b@1-3", {}), /name one of them/);
+});
+
+test("the store: import, a re-import changes nothing, the place each proposes, Insert into a section and a group, Not this", async () => {
+ const p = await project();
+ const parsed = parseSweepMarkdown(SWEEP, { file: "RESWEEP.md" }).candidates;
+ const r1 = await addCandidates(p.dir, parsed, { by: "sweep", now: "2026-11-02T00:00:00.000Z" });
+ assert.equal(r1.added.length, 7);
+ const r2 = await addCandidates(p.dir, parsed, { by: "sweep" });
+ assert.equal(r2.added.length, 0);
+ assert.equal(r2.kept.length, 7);
+
+ const view = await candidatesView(p.dir);
+ assert.deepEqual(view.counts, { proposed: 7, inserted: 0, dismissed: 0 });
+ assert.equal(view.candidates[0].top, 1, "the Top 5's first leads the list");
+ const byVideo = (v) => view.candidates.find((c) => c.video === v);
+ assert.deepEqual(byVideo("kHsAbcd3e0").place, { section: 0, group: null, why: "fb1's section" });
+ assert.deepEqual(byVideo("FZvoVxld6Ts").place, { section: 1, group: "g1", why: "j01's group (g1)" });
+ assert.deepEqual(byVideo("W4pgGUq5ygQ").place, { section: 2, group: null, why: "the sweep's heading" });
+ assert.equal(byVideo("v2914211236").place.section, null);
+ assert.deepEqual(view.sections.map((s) => s.label), [null, "As a streamer", "Looks"]);
+
+ const a = byVideo("W4pgGUq5ygQ");
+ const token = await manifestToken(p.dir);
+ const ins = await insertCandidate(p, a.id, { section: 2, token, cues: null });
+ assert.equal(ins.clip, "W4pgGUq5ygQ-284");
+ const m = await manifest(p.dir);
+ assert.equal(m.timeline.at(-1).id, "W4pgGUq5ygQ-284", "the end of the last section");
+ const e = m.timeline.at(-1);
+ assert.equal(e.channel, "somestreamer");
+ assert.equal(e.quote, "I respect that looks sell.");
+ assert.equal(e.date, "2025-08-03");
+ assert.equal(e.cite, 284);
+ assert.ok((await readdir(path.join(p.dir, "revisions"))).some((n) => n.includes("auto-before-insert")), "an undo point");
+
+ const b = byVideo("FZvoVxld6Ts");
+ await insertCandidate(p, b.id, { group: "g1", cues: null });
+ const m2 = await manifest(p.dir);
+ assert.deepEqual(m2.groups[0].ids, ["ow1", "j01", "FZvoVxld6Ts-2594"]);
+ assert.equal(m2.timeline[m2.timeline.findIndex((x) => x.id === "j01") + 1].id, "FZvoVxld6Ts-2594");
+
+ const d = byVideo("_BjBoBICHaE");
+ await dismissCandidate(p.dir, d.id, { note: "not her voice" });
+ await assert.rejects(insertCandidate(p, d.id, { section: 0, cues: null }), /set aside/);
+ await assert.rejects(insertCandidate(p, a.id, { section: 0, cues: null }), /in the cut already/);
+ await assert.rejects(insertCandidate(p, byVideo("oRsQnRc--aQ").id, { section: 0, token: "stale", cues: null }), /changed/i);
+
+ const after = await readCandidates(p.dir);
+ assert.equal(after.doc.candidates.length, 7, "nothing is ever deleted");
+ assert.equal(after.doc.candidates.find((x) => x.id === d.id).status, "dismissed");
+ assert.equal(after.doc.candidates.find((x) => x.id === d.id).dismissed.note, "not her voice");
+ assert.equal(after.doc.candidates.find((x) => x.id === a.id).inserted.clip, "W4pgGUq5ygQ-284");
+ // Proposing the set-aside moment again does not bring it back.
+ await addCandidates(p.dir, [parsed.find((x) => x.video === "_BjBoBICHaE")]);
+ assert.equal((await readCandidates(p.dir)).doc.candidates.find((x) => x.id === d.id).status, "dismissed");
+ const v2 = await candidatesView(p.dir);
+ assert.deepEqual(v2.counts, { proposed: 4, inserted: 2, dismissed: 1 });
+
+ // Its clip taken out of the cut again (an Undo, a removal): the row waits again, and says what it was.
+ await removeEntry(p.dir, "W4pgGUq5ygQ-284");
+ const v3 = await candidatesView(p.dir);
+ const back = v3.candidates.find((x) => x.id === a.id);
+ assert.equal(back.status, "proposed");
+ assert.equal(back.left, "W4pgGUq5ygQ-284");
+ assert.deepEqual(v3.counts, { proposed: 5, inserted: 1, dismissed: 1 });
+ const again = await insertCandidate(p, a.id, { section: 1, cues: null });
+ assert.equal((await readCandidates(p.dir)).doc.candidates.find((x) => x.id === a.id).inserted.clip, again.clip);
+});
+
+test("an unreadable file is never overwritten: a write refuses, a read is empty with the reason", async () => {
+ const p = await project();
+ await writeFile(path.join(p.dir, CANDIDATES_FILE), "{ not json");
+ const r = await readCandidates(p.dir);
+ assert.equal(r.doc.candidates.length, 0);
+ assert.match(r.error, /not JSON/);
+ await assert.rejects(addCandidates(p.dir, [normalizeProposal({ video: "v", t: 1 })]), (e) => e.status === 409);
+ assert.equal(await readFile(path.join(p.dir, CANDIDATES_FILE), "utf8"), "{ not json");
+});
diff --git a/umtool/lib/report/candidatesCli.mjs b/umtool/lib/report/candidatesCli.mjs
@@ -0,0 +1,123 @@
+// `umtool candidates` (UI notes item 14): the candidates inbox from a
+// terminal -- what an agent or a sweep PROPOSES. It never inserts and never
+// sets a row aside: those are the operator's presses on the Cut tab's
+// Candidates panel (lib/report/candidates.mjs).
+//
+// umtool candidates <project> [ls] [--all] [--json] the waiting rows (--all: inserted and set aside too)
+// umtool candidates <project> import <sweep.md> [--dry-run] [--json]
+// umtool candidates <project> add <json|@file> [--json] one proposal or a list
+//
+// Plain ESM: the CLI runs under bare node.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { CANDIDATES_FILE, addCandidates, candidatesView, normalizeProposal, parseSweepMarkdown } from "./candidates.mjs";
+
+export const CANDIDATES_USAGE = [
+ "usage: umtool candidates <project> [ls] [--all] [--json] the proposed clips waiting on the Cut tab's Candidates panel",
+ " (--all: the inserted and the set-aside too): id, verdict, recording @ second, the place it proposes",
+ " umtool candidates <project> import <sweep.md> [--dry-run] [--json] a sweep's bullets",
+ " `- [verdict] [title @ time](link) (date) \"quote\" — why`, under their headings; a Top N",
+ " section marks the moments it restates; a bullet with no verdict or link is skipped and said",
+ " umtool candidates <project> add <json|@file> [--json] an agent's proposal(s): {channel?, video, t, quote?, why?,",
+ " verdict?, score?, section?, title?, date?} or {link, …}, one or a list",
+ "",
+ `Proposals only: rows land in <project>/${CANDIDATES_FILE} as proposed. Insert into a section or a group, and`,
+ "Not this, are the operator's presses on the panel. The same moment proposed again changes nothing it holds.",
+].join("\n");
+
+class CliError extends Error {}
+
+/**
+ * @param {string[]} args the words after `candidates`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, by?: string }} [opts]
+ * @returns {Promise<number>}
+ */
+export async function candidatesCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), by = "cli" } = {}) {
+ const words = args.filter((a) => !a.startsWith("--"));
+ const flags = new Set(args.filter((a) => a.startsWith("--")));
+ const json = flags.has("--json");
+ try {
+ const [projectArg, verb = "ls", arg] = words;
+ if (!projectArg || flags.has("--help")) {
+ err(CANDIDATES_USAGE);
+ return 2;
+ }
+ const r = await resolveProject(projectArg, root);
+ if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${projectArg}"`);
+ const project = r.project;
+
+ if (verb === "ls") {
+ const view = await candidatesView(project.dir);
+ const rows = flags.has("--all") ? view.candidates : view.candidates.filter((c) => c.status === "proposed");
+ if (json) {
+ out(JSON.stringify({ project: project.id, ...view, candidates: rows }, null, 2));
+ return view.error ? 1 : 0;
+ }
+ if (view.error) err(view.error);
+ for (const c of rows) out(candidateLine(c));
+ out(`${view.counts.proposed} proposed, ${view.counts.inserted} inserted, ${view.counts.dismissed} set aside — ${project.id}/${CANDIDATES_FILE}`);
+ return view.error ? 1 : 0;
+ }
+
+ if (verb === "import") {
+ if (!arg) throw new CliError("import needs a sweep's markdown file");
+ const file = path.resolve(arg);
+ const md = await readFile(file, "utf8");
+ const { candidates, skipped } = parseSweepMarkdown(md, { file: path.basename(file) });
+ if (flags.has("--dry-run")) {
+ if (json) out(JSON.stringify({ project: project.id, dryRun: true, candidates, skipped }, null, 2));
+ else {
+ for (const c of candidates) out(candidateLine({ ...c, id: "--", status: "proposed" }));
+ for (const s of skipped) out(` skipped line ${s.line}: ${s.why}`);
+ out(`${candidates.length} proposal(s), ${skipped.length} skipped — nothing written (--dry-run)`);
+ }
+ return 0;
+ }
+ const res = await addCandidates(project.dir, candidates, { by });
+ if (json) out(JSON.stringify({ project: project.id, ...res, skipped }, null, 2));
+ else {
+ for (const s of skipped) out(` skipped line ${s.line}: ${s.why}`);
+ out(`${res.added.length} added${res.kept.length ? `, ${res.kept.length} already there (unchanged)` : ""} — the Cut tab's Candidates panel`);
+ }
+ return 0;
+ }
+
+ if (verb === "add") {
+ if (!arg) throw new CliError("add needs a JSON proposal (or @file)");
+ const raw = arg.startsWith("@") ? await readFile(path.resolve(arg.slice(1)), "utf8") : arg;
+ let v;
+ try {
+ v = JSON.parse(raw);
+ } catch (e) {
+ throw new CliError(`add: not JSON (${e instanceof Error ? e.message : e})`);
+ }
+ const list = (Array.isArray(v) ? v : Array.isArray(v?.candidates) ? v.candidates : [v]).map((p) => normalizeProposal(p));
+ const res = await addCandidates(project.dir, list, { by });
+ if (json) out(JSON.stringify({ project: project.id, ...res }, null, 2));
+ else out(`${res.added.length} added${res.kept.length ? `, ${res.kept.length} already there (unchanged)` : ""}`);
+ return 0;
+ }
+ throw new CliError(`unknown: candidates ${verb} — ls, import, add`);
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ if (json) out(JSON.stringify({ ok: false, error: msg }, null, 2));
+ else err(`umtool candidates: ${msg}`);
+ return 1;
+ }
+}
+
+const clock = (t) => {
+ const s = Math.floor(t);
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ return `${h ? `${h}:${String(m).padStart(2, "0")}` : m}:${String(s % 60).padStart(2, "0")}`;
+};
+
+export function candidateLine(c) {
+ const where = c.place?.section !== null && c.place?.section !== undefined ? ` → §${c.place.section}${c.place.group ? ` ${c.place.group}` : ""} (${c.place.why})` : c.heading ? ` (${c.heading})` : "";
+ const state = c.status === "inserted" ? ` [inserted as ${c.inserted?.clip}]` : c.status === "dismissed" ? " [not this]" : c.left ? ` [was ${c.left}, no longer in the cut]` : c.inCut ? ` [in the cut as ${c.inCut}]` : "";
+ const rank = c.top ? `#${c.top} ` : "";
+ return `${String(c.id).padEnd(5)} ${rank}[${c.verdict ?? c.kind}] ${c.channel ? `${c.channel}/` : ""}${c.video} @ ${clock(c.t)}${c.date ? ` ${c.date}` : ""}${where}${state}${c.quote ? `\n "${c.quote.slice(0, 110)}${c.quote.length > 110 ? "…" : ""}"` : ""}`;
+}
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -41,7 +41,7 @@ import { LOOK_KEYS, applyLookPatch, lookOf } from "yt-dlp-transcript-common/lib/
import { validateRoom } from "umtool-report-to-video/room";
import { applySectionEnter } from "./sections.mjs";
import { citeUrlAt, parseClipSpec } from "./clipEditorModel.mjs";
-import { addSectionIn, followSplitMarkers, moveBoundaryIn, moveToSectionIn, placeIn, removeBoundaryIn, sectionModel, sectionWords, setSectionIn } from "./sectionEdit.mjs";
+import { addSectionIn, followSplitMarkers, moveBoundaryIn, moveToSectionIn, placeIn, reanchorMarkers, removeBoundaryIn, sectionModel, sectionWords, setSectionIn } from "./sectionEdit.mjs";
import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck";
import { migrateManifest } from "umtool-report-to-video/modules/migrate";
import { loadPreset, resolvePresetLayers } from "umtool-report-to-video/presets";
@@ -2288,6 +2288,98 @@ export async function insertEntry(dir, afterId, spec, { token = null, at = null
}));
}
+/**
+ * INSERT INTO A SECTION OR A GROUP, in memory (UI notes 2026-10-30, item 14:
+ * the candidates inbox's Insert; `umtool timeline <p> insert --to-section N`
+ * / `--group G`). The clip goes in at the END of deck section `section` --
+ * right after its last clip -- or right after the last clip of group `group`,
+ * and becomes one of that group's clips (claimGroups.mjs setGroupIn), so the
+ * run stays contiguous. A marker that followed that last clip is re-anchored
+ * after the new one (sectionEdit.mjs reanchorMarkers), so the clip lands IN
+ * the section, not at the start of the next, and every other clip keeps its
+ * section. Without a deck a section is the clips' `section` field: the clip
+ * goes after the last clip carrying it and carries it too.
+ *
+ * Exactly one of `section` / `group`. Mutates `m`; returns
+ * `{ id, at, entry, section, group, reanchored, groupsWritten? }`.
+ *
+ * @param {Record<string, any>} m
+ * @param {unknown} spec a clip spec string or a clip entry (entryFromSpec)
+ * @param {{ section?: number | null, group?: string | null }} where
+ */
+export function insertIntoIn(m, spec, { section = null, group = null } = {}) {
+ if ((section === null || section === undefined) === (group === null || group === undefined)) {
+ throw new Error("insert into a section or into a group: name one of them");
+ }
+ if (!Array.isArray(m.timeline)) m.timeline = [];
+ const tl = m.timeline;
+ const entry = entryFromSpec(tl, spec);
+ if (entry.type !== "clip") throw new Error("only a clip goes into a section or a group");
+ const hasDeck = isObj(m?.render?.chrome);
+ const model = sectionModel(m);
+ const at = (id) => tl.findIndex((e) => e?.type === "clip" && e.id === id);
+ let target;
+ let after;
+ let g = null;
+ if (group !== null && group !== undefined) {
+ const groups = Array.isArray(m.groups) ? m.groups : [];
+ g = groups.find((x) => isObj(x) && x.id === group) ?? null;
+ if (!g || !Array.isArray(g.ids) || !g.ids.length) {
+ const ids = groups.map((x) => x?.id).filter(Boolean);
+ throw new Error(`no group ${group}${ids.length ? ` (${ids.join(", ")})` : " (the cut has no groups)"}`);
+ }
+ const placed = g.ids.filter((id) => at(id) >= 0);
+ if (!placed.length) throw new Error(`group ${group} has no clip in the cut`);
+ after = placed.reduce((a, b) => (at(b) > at(a) ? b : a));
+ const last = tl[at(after)];
+ target = hasDeck ? (model.sectionOf.get(after) ?? 0) : Number.isInteger(last?.section) ? last.section : null;
+ } else {
+ const t = Number(section);
+ if (hasDeck) {
+ if (!Number.isInteger(t) || t < 0 || t >= model.sections.length) {
+ throw new Error(`section must be 0–${model.sections.length - 1} (§0 is before the first marker)`);
+ }
+ after = model.sections[t].last;
+ if (!after) throw new Error(`${sectionWords(model.sections[t])} has no clip to go after`);
+ } else {
+ if (!Number.isInteger(t) || t < 0) throw new Error("section is a section's number, 0 or more");
+ const last = [...tl].reverse().find((e) => e?.type === "clip" && (Number.isInteger(e.section) ? e.section : 0) === t);
+ if (!last) throw new Error(`no clip of the cut is in section ${t} (this cut has no deck: its sections are the clips' \`section\` field)`);
+ after = last.id;
+ }
+ target = t;
+ }
+ const i = at(after) + 1;
+ if (!hasDeck && Number.isInteger(target)) entry.section = target;
+ tl.splice(i, 0, entry);
+ let reanchored = [];
+ if (hasDeck) {
+ const membership = new Map(model.sectionOf);
+ membership.set(entry.id, target);
+ reanchored = reanchorMarkers(m, model, membership);
+ }
+ const out = { id: entry.id, at: i, entry, after, section: target, group: g ? g.id : null, reanchored };
+ if (g) {
+ const r = setGroupIn(m, g.id, [...g.ids, entry.id]);
+ return { ...out, groupNotes: [`${entry.id} joined group ${g.id}${g.claim ? ` ("${g.claim}")` : ""}, after ${after}`, ...r.notes], groupsWritten: true };
+ }
+ return out;
+}
+
+/**
+ * Insert a clip into a section or a group (insertIntoIn): ONE structural
+ * write -- one undo point -- the markers checked by the deck's own validator
+ * and the take patches' markers brought along (sectionWrite).
+ *
+ * @param {string} dir
+ * @param {unknown} spec
+ * @param {{ section?: number | null, group?: string | null }} where
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function insertInto(dir, spec, where, { token = null } = {}) {
+ return prepAfter(dir, clipIdOf, sectionWrite(dir, "insert", token, (m) => insertIntoIn(m, spec, where)));
+}
+
// ---- sections, edited as sections (UI notes 2026-10-30, item 1) -----------
//
// Under the deck a cut's sections are its markers (sectionEdit.mjs): these
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -12,6 +12,7 @@
// umtool timeline <project> insert --after <id|-> <channel>/<video>@<start>-<end>
// [--id ID] [--section N] [--lock] [--lock-end]
// [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]
+// umtool timeline <project> insert (--to-section N | --group G) <channel>/<video>@<start>-<end> [same flags]
// umtool timeline <project> move <id> --to <index>
// umtool timeline <project> place <id…> --before <id|-> [--section N]
// umtool timeline <project> remove <id> | duplicate <id>
@@ -60,6 +61,7 @@ import {
StructureRefused,
duplicateEntry,
insertEntry,
+ insertInto,
manifestToken,
moveEntry,
placeEntries,
@@ -99,6 +101,10 @@ export const TIMELINE_USAGE = [
" a clip after <id> (`-`: at the start); the attribution through `umtool window`'s writer.",
" Under the deck --title is the deck's title (onscreen.title); a cut whose deck titles",
" are dates gets --date as one too. The section is <id>'s unless --section says",
+ " umtool timeline <project> insert (--to-section N | --group G) <channel>/<video>@<start>-<end> [same flags]",
+ " at the END of section N, or after group G's last clip and one of its clips (the run stays",
+ " together): one write, the marker after that clip re-anchored after the new one; the",
+ " candidates inbox's Insert (umtool candidates) is this",
" umtool timeline <project> move <id> --to <index> <index> is its place AFTER the move (0 first)",
" umtool timeline <project> place <id> [<id>…] --before <id|-> [--section N] Play's drag on the reel strip:",
" before that entry (`-`: at the end), the clips joining section N (default: the section",
@@ -155,7 +161,7 @@ export const TIMELINE_USAGE = [
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", "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"]);
+const VALUED = new Set(["--group", "--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"];
@@ -382,6 +388,55 @@ export function attributionPatch(flags, convention = { deck: false, dateTitles:
}
/**
+ * INSERT ONE CLIP, as `timeline insert` does it: the entry (insertedClip, the
+ * clip it goes after lending its section, deck title and citation), written
+ * after `after` (insertEntry) -- or at the end of section `toSection` / after
+ * the last clip of group `group`, joining it (insertInto: one structural
+ * write, the markers re-anchored) -- then its attribution `patch`
+ * (attributionPatch's) as a second write through updateClip. The candidates
+ * inbox's Insert (candidates.mjs) runs exactly this. A refused attribution
+ * leaves the clip in and answers `attributionError`.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} manifest as read just now
+ * @param {{ channel?: string, video: string, start: number, end: number }} clip
+ * @param {{ after?: string | null, at?: number | null, toSection?: number | null, group?: string | null, id?: string | null,
+ * section?: number | null, lock?: boolean, lockEnd?: boolean, patch?: Record<string, any> }} o
+ */
+export async function insertClip(project, manifest, clip, { after = null, at = null, toSection = null, group = null, id = null, section = null, lock = false, lockEnd = false, patch = {} } = {}) {
+ const write = async (fn) => withEditNotes(project, async () => fn(await manifestToken(project.dir)));
+ const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ let like;
+ if (group !== null) {
+ const g = groupModel(manifest).find((x) => x.id === group);
+ like = g ? tl.find((e) => e?.type === "clip" && e.id === g.last) ?? null : null;
+ } else if (toSection !== null) {
+ const s = sectionModel(manifest).sections[toSection];
+ like = s?.last ? tl.find((e) => e?.type === "clip" && e.id === s.last) ?? null : null;
+ } else like = insertNeighbour(tl, after, at);
+ // Into a section or a group the place names the section (the clip it goes after lends its field).
+ const entry = insertedClip(clip, like, { id, section: group !== null || toSection !== null ? null : section, lock, lockEnd });
+ const p = { ...patch };
+ // A deck title the clip already took from the clip before it is not a change to write.
+ if (p.onscreen !== undefined && JSON.stringify(p.onscreen) === JSON.stringify(entry.onscreen ?? null)) delete p.onscreen;
+ const where = group !== null ? { group } : toSection !== null ? { section: toSection } : null;
+ const { result, editNotes: notes0 } = await write((token) => (where ? insertInto(project.dir, entry, where, { token }) : insertEntry(project.dir, after, entry, { token, at })));
+ let editNotes = notes0;
+ if (id && result.id !== id) result.idTaken = id;
+ let attribution = null;
+ if (Object.keys(p).length) {
+ try {
+ const done = await write((token) => updateClip(project.dir, result.id, p, { token }));
+ attribution = done.result.entry;
+ editNotes = done.editNotes ?? editNotes;
+ } catch (e) {
+ return { result, editNotes, attribution: null, attributionError: e instanceof Error ? e.message : String(e) };
+ }
+ }
+ return { result, editNotes, attribution, attributionError: null };
+}
+
+/**
* @param {string[]} args the words after `timeline`
* @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
* @returns {Promise<number>} the exit code
@@ -457,40 +512,41 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
let attribution = null;
switch (verb) {
case "insert": {
- if (!flags.has("--after")) throw new CliError("insert needs --after <id> (or --after - for the start)");
- const afterArg = String(flags.get("--after"));
+ const toSection = intFlag(flags, "--to-section");
+ const group = flags.has("--group") ? String(flags.get("--group")) : null;
+ if (toSection !== null && group !== null) throw new CliError("insert goes --to-section N or --group G, not both");
+ if (!flags.has("--after") && toSection === null && group === null) {
+ throw new CliError("insert needs --after <id> (or --after - for the start), --to-section N (its end) or --group G (after its last clip)");
+ }
+ if (flags.has("--after") && (toSection !== null || group !== null)) throw new CliError("insert takes --after, or --to-section / --group, not both");
+ const afterArg = flags.has("--after") ? String(flags.get("--after")) : "";
const after = afterArg === "-" || afterArg === "" ? null : afterArg;
const spec = need(rest[0], "a clip: <channel>/<video>@<start>-<end>");
- const convention = insertConvention(manifest);
- const patch = attributionPatch(flags, convention);
const c = parseClipSpec(spec);
if (!c) throw new Error("a clip is <channel>/<video>@<start>-<end> in seconds");
const section = intFlag(flags, "--section");
if (section !== null && section < 0) throw new CliError("--section is a section's number, 0 or more");
- const entry = insertedClip(c, insertNeighbour(manifest.timeline, after, at), {
+ const patch = attributionPatch(flags, insertConvention(manifest));
+ const done = await insertClip(project, manifest, c, {
+ after,
+ at,
+ toSection,
+ group,
id: flags.has("--id") ? String(flags.get("--id")) : null,
section,
lock: flags.has("--lock"),
lockEnd: flags.has("--lock-end"),
+ patch,
});
- // A deck title the clip already took from the clip before it is not a change to write.
- if (patch.onscreen !== undefined && JSON.stringify(patch.onscreen) === JSON.stringify(entry.onscreen ?? null)) delete patch.onscreen;
- ({ result, editNotes } = await write((token) => insertEntry(project.dir, after, entry, { token, at })));
- if (flags.has("--id") && result.id !== flags.get("--id")) {
- result.idTaken = String(flags.get("--id"));
- }
- if (Object.keys(patch).length) {
- try {
- const done = await write((token) => updateClip(project.dir, result.id, patch, { token }));
- attribution = done.result.entry;
- editNotes = done.editNotes ?? editNotes;
- } catch (e) {
- // The clip is in; only its header failed. Say both, and how to finish.
- const msg = e instanceof Error ? e.message : String(e);
- if (json) out(JSON.stringify({ ok: false, inserted: result, attributionError: msg, editNotes }, null, 2));
- else err(`inserted ${result.id} at ${result.at}, but its attribution was refused: ${msg}\n finish with: umtool window ${project.id} ${result.id} …`);
- return 1;
- }
+ result = done.result;
+ editNotes = done.editNotes;
+ attribution = done.attribution;
+ if (done.attributionError) {
+ // The clip is in; only its header failed. Say both, and how to finish.
+ const msg = done.attributionError;
+ if (json) out(JSON.stringify({ ok: false, inserted: result, attributionError: msg, editNotes }, null, 2));
+ else err(`inserted ${result.id} at ${result.at}, but its attribution was refused: ${msg}\n finish with: umtool window ${project.id} ${result.id} …`);
+ return 1;
}
break;
}