commit fe819bb9e450462fc7bbc77d69f2af2fd9823cbd
parent cdd3e016b8bcd7c0e4d8167f340d9f8f256d1632
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 06:27:55 -0500
Merge main (a31fe3df: lane A, U4 lane/ui-intake) into r38/case-verify-leads
Conflicts: editor/CHANGELOG.md (both sides' bullets kept) and umtool/e2e/fixtures/editor-stub.mjs
(both route sets kept: U4's intakeRoute, then lane C's caseStagesRoute).
Both stubs answered POST /api/ops/capture-posts. One handler now serves both: U4's
(editor-stub-intake.mjs, job cp-<n>, records {route: "capture-posts", ...body}, writes
posts-media/<id>/shot.png + capture.json) also writes each attachment the post names
(media[].name, read from the channel's posts/*.jsonl), which a research case's forum evidence
needs; lane C's stub drops its own copy. The case-stages unit test mounts the intake stub for it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
46 files changed, 3856 insertions(+), 130 deletions(-)
diff --git a/editor/app/api/ops/channel/[slug]/route.ts b/editor/app/api/ops/channel/[slug]/route.ts
@@ -114,6 +114,10 @@ export async function GET(
generatedAt: snapshot.generatedAt,
totals: snapshot.totals,
buckets,
+ // Listed and not on disk (the download lane's backlog): top-level in
+ // the snapshot, not a bucket, so said here as a count. `totals.videos`
+ // + this is what the channel lists (umtool's source backlog line).
+ undownloaded: Array.isArray(snapshot.undownloadedIds) ? snapshot.undownloadedIds.length : null,
}
: null,
});
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/post-cards/route.ts b/umtool/app/api/report/post-cards/route.ts
@@ -0,0 +1,124 @@
+import { askEditor, EditorError, readDraftJob } from "@/lib/articles/generation";
+import { channelsDirFor } from "@/lib/projects/report.mjs";
+import { PostsRefused, StaleToken, manifestToken, updatePosts } from "@/lib/report/manifest.mjs";
+import { postChannels, postWarnings, searchPostArchive } from "@/lib/report/postCards.mjs";
+import { addPostFromArchive, findPostId, findPostRow } from "@/lib/report/postsCli.mjs";
+import { citedChannels } from "@/lib/report/sourceBacklog.mjs";
+import { withEditNotes } from "@/lib/report/guard";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+
+export const dynamic = "force-dynamic";
+
+// ADD POST, from Play the cut (UI notes item 13; lib/report/postCards.mjs,
+// postsCli.mjs addPostFromArchive). The chain it replaces -- `pnpm ops
+// capture-posts` → `umtool posts add` → `umtool look deck.posts` -- in one panel:
+//
+// GET ?project=<id> { channels, posts: [the cut's posts, each with its warnings], token }
+// GET ?project=<id>&channel=<slug>&q=<words> { hits: [{ id, date, text, warnings, captured, inCut, … }], total }
+// GET ?project=<id>&job=<jobId> a capture's job (the editor's)
+// POST { project, op: "capture", channel, ids } the editor's capture-posts (paced there, on the
+// platform's own queue) → { jobId }
+// POST { project, op: "add", channel, id, attach?, crop? } the card, through `posts add`'s write
+// POST { project, op: "crop", post, crop, token? } the post's own crop (shotMaxHeight; null: none)
+const headers = { "cache-control": "no-store" };
+const SLUG_RE = /^[A-Za-z0-9._-]+$/;
+const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+
+/** The archive channel and native id a manifest post came from, when it says. */
+function sourceOf(p: Record<string, unknown>): { slug: string; id: string } | null {
+ const shot = typeof p.shot === "string" ? /^posts-media\/([^/]+)\/([^/]+)\//.exec(p.shot) : null;
+ const slug = typeof p.siteChannel === "string" ? p.siteChannel : shot?.[1];
+ const id = typeof p.postId === "string" ? p.postId : shot?.[2] ?? (typeof p.id === "string" ? p.id.replace(/^(x|bsky|post)-/, "") : null);
+ return slug && id && SLUG_RE.test(slug) && ID_RE.test(id) ? { slug, id } : null;
+}
+
+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 m = r.manifest as Record<string, unknown>;
+ const channelsDir = channelsDirFor(r.project.dir, m) as string | null;
+ if (!channelsDir) return Response.json({ error: "this project reads no corpus (no channels directory)" }, { status: 400, headers });
+ const job = url.searchParams.get("job");
+ try {
+ if (job) {
+ const j = await readDraftJob(job, 6);
+ return Response.json({ ...j, ended: ["done", "failed", "cancelled", "error"].includes(j.status) }, { headers });
+ }
+ const channel = url.searchParams.get("channel");
+ if (channel) {
+ if (!SLUG_RE.test(channel)) return Response.json({ error: "not a channel slug" }, { status: 400, headers });
+ return Response.json(await searchPostArchive(channelsDir, channel, url.searchParams.get("q") ?? "", { manifest: m }), { headers });
+ }
+ const cited = (citedChannels(m) as { slug: string }[]).map((c) => c.slug);
+ const posts = await Promise.all(
+ ((Array.isArray(m.posts) ? m.posts : []) as Record<string, unknown>[]).map(async (p) => {
+ const src = sourceOf(p);
+ const row = src ? (await findPostRow(channelsDir, src.slug, src.id).catch(() => null))?.row ?? null : null;
+ return {
+ id: String(p.id ?? ""),
+ date: typeof p.date === "string" ? p.date : null,
+ text: typeof p.text === "string" ? p.text : "",
+ attachTo: typeof p.attachTo === "string" ? p.attachTo : null,
+ shot: typeof p.shot === "string" ? p.shot : null,
+ shotMaxHeight: Number.isInteger(p.shotMaxHeight) ? (p.shotMaxHeight as number) : null,
+ hide: p.hide === true,
+ source: src,
+ warnings: postWarnings(row),
+ };
+ }),
+ );
+ return Response.json({ channels: await postChannels(channelsDir, m, cited), posts, token: await manifestToken(r.project.dir) }, { headers });
+ } catch (e) {
+ const status = e instanceof EditorError ? e.status : 400;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/post-cards");
+ 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 });
+ try {
+ if (body.op === "capture") {
+ const slug = String(body.channel ?? "");
+ const ids = Array.isArray(body.ids) ? body.ids.map(String).filter((x) => ID_RE.test(x)) : [];
+ if (!SLUG_RE.test(slug) || !ids.length) return Response.json({ error: "a capture names a channel and its post ids" }, { status: 400, headers });
+ // The editor's own capture: paced there (a pause before every contact
+ // after the first), on the platform's download queue, refused for an id
+ // not in the channel's archive.
+ const answer = await askEditor<{ jobId?: string }>("/api/ops/capture-posts", { method: "POST", body: { slug, ids } });
+ return Response.json({ ok: true, jobId: answer.jobId ?? null }, { headers });
+ }
+ if (body.op === "add") {
+ const crop = body.crop === undefined || body.crop === null || body.crop === "" ? null : Number(body.crop);
+ if (crop !== null && !Number.isInteger(crop)) return Response.json({ error: "crop is a whole number of pixels" }, { status: 400, headers });
+ const out = await addPostFromArchive(r.project, {
+ slug: String(body.channel ?? ""),
+ postId: String(body.id ?? ""),
+ attach: typeof body.attach === "string" && body.attach ? body.attach : null,
+ crop,
+ });
+ return Response.json({ ok: true, post: out.result.post, created: out.result.created, warnings: out.warnings, copied: out.copied, editNotes: out.editNotes, token: await manifestToken(r.project.dir) }, { headers });
+ }
+ if (body.op === "crop") {
+ const found = findPostId(r.manifest, String(body.post ?? ""));
+ const id = found === null ? null : String(found);
+ if (!id) return Response.json({ error: `no post ${String(body.post ?? "")} in the cut` }, { status: 404, headers });
+ const crop = body.crop === undefined || body.crop === null || body.crop === "" ? null : Number(body.crop);
+ const token = typeof body.token === "string" ? body.token : await manifestToken(r.project.dir);
+ const { result, editNotes } = await withEditNotes(r.project, () => updatePosts(r.project.dir, { [id]: { shotMaxHeight: crop } }, { token }));
+ return Response.json({ ok: true, id, post: (result as { posts: Record<string, unknown> }).posts[id], token: (result as { token: string }).token, editNotes }, { headers });
+ }
+ return Response.json({ error: 'op is "capture", "add" or "crop"' }, { status: 400, headers });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers });
+ if (e instanceof PostsRefused) return Response.json({ error: e.message, errors: (e as PostsRefused & { errors: string[] }).errors }, { status: 400, headers });
+ const status = e instanceof EditorError ? e.status : 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/app/api/report/source-backlog/route.ts b/umtool/app/api/report/source-backlog/route.ts
@@ -0,0 +1,54 @@
+import { EditorError } from "@/lib/articles/generation";
+import { armSourceWatch, citedChannels, clearSourceWatch, SourceWatchError } from "@/lib/report/sourceBacklog.mjs";
+import { prioritize, readBacklog } from "@/lib/report/sourceBacklog";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+
+export const dynamic = "force-dynamic";
+
+// THE SOURCE BACKLOG of a report video (UI notes item 16, lib/report/sourceBacklog.*):
+//
+// GET ?project=<id> { channels: [{ slug, listed, held, transcribed, done, focused, … }],
+// focus, editorError, watch, fired } (the read is recorded: a watch may fire)
+// POST { project, op: "prioritize", slugs? } the editor's focus gains them (default: every cited channel),
+// through its POST /api/ops/channel-priority -- never settings directly
+// POST { project, op: "watch" } Re-sweep when complete: the Inbox says so once every cited channel the
+// editor archives is done (one it does not is left out: `left`)
+// POST { project, op: "unwatch" }
+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 });
+ return Response.json(await readBacklog(r.project.dir, r.manifest), { headers });
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/source-backlog");
+ 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 cited = (citedChannels(r.manifest) as { slug: string }[]).map((c) => c.slug);
+ try {
+ if (body.op === "prioritize") {
+ const slugs = Array.isArray(body.slugs) ? body.slugs.map(String).filter((s) => cited.includes(s)) : cited;
+ return Response.json({ ok: true, ...(await prioritize(slugs)) }, { headers });
+ }
+ if (body.op === "watch") {
+ // Only what the editor archives can ever be complete: a channel it does not answer for is left out, and said.
+ const now = await readBacklog(r.project.dir, r.manifest);
+ if (now.editorError) return Response.json({ error: `the editor did not answer: ${now.editorError}` }, { status: 502, headers });
+ const slugs = now.channels.filter((c) => !c.error).map((c) => c.slug);
+ const left = now.channels.filter((c) => c.error).map((c) => c.slug);
+ return Response.json({ ok: true, ...(await armSourceWatch(r.project.dir, slugs)), ...(left.length ? { left } : {}) }, { headers });
+ }
+ if (body.op === "unwatch") return Response.json({ ok: true, ...(await clearSourceWatch(r.project.dir)) }, { headers });
+ return Response.json({ error: 'op is "prioritize", "watch" or "unwatch"' }, { status: 400, headers });
+ } catch (e) {
+ const status = e instanceof EditorError ? e.status : e instanceof SourceWatchError ? ((e as SourceWatchError & { status?: number }).status ?? 400) : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -108,6 +108,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,
@@ -1007,6 +1008,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)`,
@@ -1095,6 +1099,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
@@ -23,6 +23,8 @@ 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 { readCandidates } from "@/lib/report/candidates.mjs";
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";
@@ -69,6 +71,9 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
).filter(Boolean).length;
const walkStart = (readiness.readyIds[0] as string | undefined) ?? clips[0]?.id;
const showAll = search.all === "1";
+ // The candidates inbox (UI notes item 14): its panel once a sweep has proposed something; until
+ // then one line in the timeline's heading says how proposals come in (no panel, no height).
+ const hasCandidates = (await readCandidates(project.dir)).exists === true;
const takes = await listTakes(project.dir);
// The trailer's beats (promo/trailer-beats.json): how many, for the Trailer link.
const trailerBeats = await readTrailerBeats(project.dir).then((d) => d.beats.length, () => null);
@@ -425,6 +430,11 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
<section>
<h2 className="micro mb-1.5">
the cut — {entries.length} entries, in array order
+ {!hasCandidates && (
+ <span data-candidates-empty="" className="ml-2 normal-case tracking-normal text-[var(--color-dim)]" title="a sweep's proposed clips land in the Candidates panel, inserted only by your press">
+ · no candidates: <code className="font-mono">umtool candidates {project.id} import <sweep.md></code>
+ </span>
+ )}
</h2>
{/* The gap between "ready" and "needing", closed in one press. Every
row below it that reads "not fetched yet" is one of these, and
@@ -461,6 +471,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). */}
+ {hasCandidates && <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/components/projects/report/OverviewTab.tsx b/umtool/components/projects/report/OverviewTab.tsx
@@ -15,6 +15,7 @@ import type { Decision } from "@/lib/decisions";
import type { PieceFrame } from "@/lib/pieces/frame";
import { TONE, hms, type ReportTabProps } from "./shared";
import DecisionSettle from "./DecisionSettle";
+import SourceBacklog from "./SourceBacklog";
import ProjectSites from "./ProjectSites";
import LinkPolicyPanel from "./LinkPolicyPanel";
import { manifestToken } from "@/lib/report/manifest.mjs";
@@ -119,6 +120,8 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP
</ul>
</section>
+ {/* How much of each cited channel the archive holds and has transcribed (UI notes item 16). */}
+ {clips.length > 0 && <SourceBacklog project={project.id} />}
<ProjectSites project={project} detail={detail} />
<LinkPolicyPanel project={project.id} />
diff --git a/umtool/components/projects/report/SourceBacklog.tsx b/umtool/components/projects/report/SourceBacklog.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+
+// ---------------------------------------------------------------------------
+// THE SOURCE BACKLOG on a report video's page (UI notes item 16): for each
+// channel the cut cites, "<channel> transcribed/listed · held · Prioritize",
+// from the editor's own snapshot counts (GET /api/report/source-backlog).
+// Prioritize puts the channel in the editor's focus through its ops action;
+// "Re-sweep when complete" arms a watch the Inbox fires once the backlog of
+// every cited channel is done (lib/report/sourceBacklog.mjs).
+// ---------------------------------------------------------------------------
+
+type Row = {
+ slug: string;
+ listed: number | null;
+ held: number | null;
+ transcribed: number | null;
+ undownloaded: number | null;
+ untranscribed: number | null;
+ done: boolean;
+ focused: boolean;
+ clips: number;
+ tier: string | null;
+ error?: string;
+};
+type View = {
+ channels: Row[];
+ editorError: string | null;
+ watch: { slugs: string[]; armedAt: string; firedAt?: string } | null;
+ watchError: string | null;
+};
+
+const n = (v: number | null) => (v === null ? "?" : v.toLocaleString("en-US"));
+const day = (iso: string) => new Date(iso).toLocaleDateString("en-GB", { day: "numeric", month: "short" });
+
+export default function SourceBacklog({ project }: { project: string }) {
+ const [view, setView] = useState<View | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [said, setSaid] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/source-backlog?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
+ const j = r ? ((await r.json().catch(() => null)) as (View & { error?: string }) | null) : null;
+ if (!r?.ok || !j) {
+ setError(j?.error ?? "the backlog could not be read");
+ return;
+ }
+ setView(j);
+ }, [project]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+ const post = async (body: Record<string, unknown>) => {
+ setBusy(true);
+ setError(null);
+ setSaid(null);
+ try {
+ const r = await fetch("/api/report/source-backlog", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, ...body }) });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
+ if (!r.ok) setError(String(j.error ?? `HTTP ${r.status}`));
+ return r.ok ? j : null;
+ } finally {
+ setBusy(false);
+ await load();
+ }
+ };
+ if (!view) return error ? <p className="m-0 text-[11px] text-[var(--color-dim)]">sources: {error}</p> : null;
+ if (!view.channels.length) return null;
+ // What the editor archives decides it: a channel it does not answer for is never "done".
+ const allDone = view.channels.filter((c) => !c.error).every((c) => c.done);
+ const w = view.watch;
+ return (
+ <section data-testid="source-backlog" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]">
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
+ <h2 className="micro m-0">sources</h2>
+ {view.channels.map((c) => (
+ <span key={c.slug} data-backlog-channel={c.slug} data-backlog-done={c.done ? "1" : "0"} className="flex flex-wrap items-baseline gap-1.5">
+ <span className="font-mono text-[var(--color-text)]">{c.slug}</span>
+ {c.error ? (
+ <span className="text-[11px] text-[var(--color-dim)]">{c.error}</span>
+ ) : c.held === null ? (
+ <span className="text-[11px] text-[var(--color-dim)]">no report yet</span>
+ ) : (
+ <span className="num" data-backlog-line={c.slug} title={`${n(c.undownloaded)} listed and not downloaded · ${n(c.untranscribed)} held and not transcribed`}>
+ {n(c.transcribed)}/{n(c.listed)} transcribed · {n(c.held)} held
+ </span>
+ )}
+ {c.done && <span className={badgeVariants({ variant: "on", size: "sm" })}>complete</span>}
+ {!c.done && !c.error && c.focused && <span className={badgeVariants({ variant: "state", size: "sm" })}>in focus</span>}
+ {!c.done && !c.error && !c.focused && (
+ <button
+ type="button"
+ data-backlog-prioritize={c.slug}
+ disabled={busy || !!view.editorError}
+ title="put it in the editor's focus: its downloads and transcriptions lead every lane (the editor's channel-priority)"
+ onClick={async () => {
+ const j = await post({ op: "prioritize", slugs: [c.slug] });
+ if (j) setSaid(`${c.slug} is in the editor's focus`);
+ }}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ >
+ Prioritize
+ </button>
+ )}
+ </span>
+ ))}
+ <span className="ml-auto flex flex-wrap items-baseline gap-1.5">
+ {w?.firedAt ? (
+ <span data-backlog-watch="fired" className="text-[11px] text-kept-text">complete since {day(w.firedAt)} — re-sweep (the Inbox says so)</span>
+ ) : w ? (
+ <span data-backlog-watch="armed" className="text-[11px] text-[var(--color-dim)]">re-sweep when complete · watching since {day(w.armedAt)}</span>
+ ) : null}
+ {w ? (
+ <button type="button" data-backlog-unwatch="" disabled={busy} onClick={() => void post({ op: "unwatch" })} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ {w.firedAt ? "Clear" : "Stop watching"}
+ </button>
+ ) : (
+ !allDone && (
+ <button
+ type="button"
+ data-backlog-watch-arm=""
+ disabled={busy}
+ title="an Inbox card (Re-sweep) once every cited channel has nothing left to download or transcribe"
+ onClick={async () => {
+ const j = await post({ op: "watch" });
+ if (j) setSaid("watching: the Inbox says when the backlog is done");
+ }}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ >
+ Re-sweep when complete
+ </button>
+ )
+ )}
+ </span>
+ </div>
+ {view.editorError && <p className="m-0 mt-1 text-[11px] text-[var(--color-dim)]">the editor did not answer: {view.editorError}</p>}
+ {view.watchError && <p className="m-0 mt-1 text-[11px] text-[var(--color-bad)]">{view.watchError}</p>}
+ {error && (
+ <p role="alert" className="m-0 mt-1 text-[11px] text-[var(--color-bad)]">
+ {error}
+ </p>
+ )}
+ {said && <p data-backlog-said="" className="m-0 mt-1 text-[11px] text-[var(--color-dim)]">{said}</p>}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/review/AddPost.tsx b/umtool/components/projects/review/AddPost.tsx
@@ -0,0 +1,288 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// ADD POST in Play the cut (UI notes item 13): the chain `pnpm ops
+// capture-posts` → `umtool posts add` → `umtool look deck.posts` in one
+// panel (/api/report/post-cards). Search a channel's posts archive; Capture
+// one through the EDITOR's capture-posts (paced there); Add it to the clip on
+// screen (`posts add`'s own write) and see its card on that clip as the cut
+// plays. Each post's WARNING comes from its own data -- a quoted post, a
+// repost, media -- since its screenshot shows them; the cure is a CROP (the
+// post's own shotMaxHeight: its top that tall, never panned).
+// ---------------------------------------------------------------------------
+
+type Hit = {
+ id: string;
+ date: string | null;
+ author: string | null;
+ text: string;
+ url: string | null;
+ warnings: string[];
+ captured: boolean;
+ inCut: boolean;
+};
+type CutPost = { id: string; date: string | null; text: string; attachTo: string | null; shotMaxHeight: number | null; hide: boolean; warnings: string[] };
+type Base = { channels: { slug: string; suggested: boolean }[]; posts: CutPost[]; token: string | null };
+
+async function postJson(body: Record<string, unknown>) {
+ const r = await fetch("/api/report/post-cards", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
+ return { ok: r.ok, status: r.status, json: j };
+}
+
+export default function AddPost({
+ project,
+ clip,
+ onAdded,
+}: {
+ project: string;
+ /** The clip on screen: what Add attaches the post to (null: a card is on screen). */
+ clip: string | null;
+ /** A post was added or cropped: the view is read again, the deck recomposed, the card shown on its clip. */
+ onAdded: (post: { id: string; attachTo: string | null }) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [base, setBase] = useState<Base | null>(null);
+ const [channel, setChannel] = useState("");
+ const [q, setQ] = useState("");
+ const [hits, setHits] = useState<Hit[] | null>(null);
+ const [total, setTotal] = useState(0);
+ const [busy, setBusy] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [said, setSaid] = useState<string | null>(null);
+ const [crop, setCrop] = useState<Record<string, string>>({});
+ const [capturing, setCapturing] = useState<{ jobId: string; id: string; line: string } | null>(null);
+
+ const loadBase = useCallback(async () => {
+ const r = await fetch(`/api/report/post-cards?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
+ const j = r ? ((await r.json().catch(() => null)) as (Base & { error?: string }) | null) : null;
+ if (!r?.ok || !j) {
+ setError(j?.error ?? "the posts could not be read");
+ return;
+ }
+ setBase(j);
+ setChannel((c) => c || j.channels[0]?.slug || "");
+ }, [project]);
+ useEffect(() => {
+ if (open && !base) void loadBase();
+ }, [open, base, loadBase]);
+
+ const search = useCallback(async () => {
+ if (!channel) return;
+ setBusy("search");
+ setError(null);
+ try {
+ const r = await fetch(`/api/report/post-cards?project=${encodeURIComponent(project)}&channel=${encodeURIComponent(channel)}&q=${encodeURIComponent(q)}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => ({}))) as { hits?: Hit[]; total?: number; archive?: boolean; error?: string };
+ if (!r.ok) setError(j.error ?? `HTTP ${r.status}`);
+ else if (j.archive === false) setError(`${channel} has no posts archive`);
+ setHits(j.hits ?? []);
+ setTotal(j.total ?? 0);
+ } finally {
+ setBusy(null);
+ }
+ }, [channel, project, q]);
+
+ // A capture in flight: the editor's job, followed until it ends; then the search again (its shot is there).
+ useEffect(() => {
+ if (!capturing) return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/post-cards?project=${encodeURIComponent(project)}&job=${encodeURIComponent(capturing.jobId)}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as { status: string; ended: boolean; tail: string[] };
+ setCapturing((c) => (c ? { ...c, line: `${j.status}${j.tail.length ? ` — ${j.tail[j.tail.length - 1]}` : ""}` } : c));
+ if (j.ended) {
+ setSaid(`capture of ${capturing.id}: ${j.status}${j.tail.length ? ` — ${j.tail[j.tail.length - 1]}` : ""}`);
+ setCapturing(null);
+ await search();
+ }
+ }, 1000);
+ return () => clearInterval(t);
+ }, [capturing, project, search]);
+
+ const capture = async (id: string) => {
+ setBusy(id);
+ setError(null);
+ try {
+ const r = await postJson({ project, op: "capture", channel, ids: [id] });
+ if (!r.ok || !r.json.jobId) setError(String(r.json.error ?? `HTTP ${r.status}`));
+ else setCapturing({ jobId: String(r.json.jobId), id, line: "queued" });
+ } finally {
+ setBusy(null);
+ }
+ };
+ const add = async (h: Hit) => {
+ setBusy(h.id);
+ setError(null);
+ setSaid(null);
+ try {
+ const c = crop[h.id]?.trim();
+ const r = await postJson({ project, op: "add", channel, id: h.id, ...(clip ? { attach: clip } : {}), ...(c ? { crop: Number(c) } : {}) });
+ if (!r.ok) {
+ setError(String(r.json.error ?? `HTTP ${r.status}`));
+ return;
+ }
+ const post = r.json.post as { id: string; attachTo?: string };
+ setSaid(`${r.json.created ? "added" : "replaced"} ${post.id}${post.attachTo ? ` on ${post.attachTo}` : ""} — its card plays at the clip's end`);
+ await loadBase();
+ await search();
+ onAdded({ id: post.id, attachTo: post.attachTo ?? null });
+ } finally {
+ setBusy(null);
+ }
+ };
+ const saveCrop = async (p: CutPost) => {
+ setBusy(p.id);
+ setError(null);
+ try {
+ const v = (crop[`cut:${p.id}`] ?? (p.shotMaxHeight ? String(p.shotMaxHeight) : "")).trim();
+ const r = await postJson({ project, op: "crop", post: p.id, crop: v ? Number(v) : null, token: base?.token ?? null });
+ if (!r.ok) {
+ setError(String(r.json.error ?? `HTTP ${r.status}`));
+ return;
+ }
+ setSaid(v ? `${p.id} cropped to its top ${v} px` : `${p.id} uncropped`);
+ await loadBase();
+ onAdded({ id: p.id, attachTo: p.attachTo });
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ return (
+ <div data-play-add-post="" className="text-[12px]">
+ <button type="button" data-play-add-post-open="" onClick={() => setOpen((v) => !v)} className={buttonVariants({ variant: open ? "outline" : "quiet", size: "sm" })} title="a post card from the channel's posts archive, on the clip on screen">
+ {open ? "Close Add post" : "Add post"}
+ </button>
+ {open && (
+ <div data-testid="add-post" className="mt-1.5 space-y-1.5 rounded border border-seam bg-panel px-3 py-2">
+ <div className="flex flex-wrap items-center gap-1.5">
+ <select data-add-post-channel="" aria-label="posts channel" value={channel} onChange={(e) => setChannel(e.target.value)} className="rounded border border-seam-2 bg-ground px-1 py-0.5 text-[11.5px] text-text">
+ {!base?.channels.length && <option value="">no posts archive</option>}
+ {base?.channels.map((c) => (
+ <option key={c.slug} value={c.slug}>
+ {c.slug}
+ </option>
+ ))}
+ </select>
+ <input
+ data-add-post-q=""
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") void search();
+ }}
+ placeholder="words in the post (empty: the newest)"
+ className="min-w-48 flex-1 rounded border border-seam-2 bg-ground px-1.5 py-0.5 text-[11.5px] text-text"
+ />
+ <button type="button" data-add-post-search="" disabled={!channel || busy !== null} onClick={() => void search()} className={buttonVariants({ size: "sm" })}>
+ Search
+ </button>
+ <span className="text-[11px] text-muted">{clip ? `adds to ${clip}, the clip on screen` : "a card is on screen: the post rides on the clip its date picks"}</span>
+ </div>
+ {error && (
+ <p role="alert" data-add-post-error="" className="m-0 text-[11.5px] text-reject-text">
+ {error}
+ </p>
+ )}
+ {said && <p data-add-post-said="" className="m-0 text-[11.5px] text-text-2">{said}</p>}
+ {capturing && <p data-add-post-capturing={capturing.id} className="m-0 text-[11.5px] text-muted">capturing {capturing.id} through the editor (paced): {capturing.line}</p>}
+ {hits && (
+ <>
+ <p className="m-0 text-[11px] text-muted">
+ {total} post{total === 1 ? "" : "s"} in {channel}
+ {total > hits.length ? `, the newest ${hits.length} shown` : ""}
+ </p>
+ <ul className="m-0 max-h-80 list-none space-y-1 overflow-y-auto p-0">
+ {hits.map((h) => (
+ <li key={h.id} data-add-post-hit={h.id} data-add-post-captured={h.captured ? "1" : "0"} className="rounded border border-seam px-2 py-1">
+ <div className="flex flex-wrap items-baseline gap-1.5">
+ <span className="font-mono text-[11px] text-muted">{h.date?.slice(0, 10)}</span>
+ {h.author && <span className="text-text-2">@{h.author.replace(/^@/, "")}</span>}
+ {h.inCut && <span className={badgeVariants({ variant: "on", size: "sm" })}>in the cut</span>}
+ <span className={badgeVariants({ variant: h.captured ? "info" : "state", size: "sm" })}>{h.captured ? "captured" : "no screenshot yet"}</span>
+ {h.url && (
+ <a href={h.url} target="_blank" rel="noreferrer" className="ink-link text-[11px]">
+ the post ↗
+ </a>
+ )}
+ </div>
+ <p className="m-0 mt-0.5 line-clamp-3 text-[12px] leading-snug text-text">{h.text}</p>
+ {h.warnings.map((w, i) => (
+ <p key={i} role="note" data-add-post-warning={h.id} className="m-0 mt-0.5 text-[11.5px] text-reject-text">
+ ⚠ {w}
+ </p>
+ ))}
+ <div className="mt-1 flex flex-wrap items-center gap-1.5">
+ {!h.captured ? (
+ <button type="button" data-add-post-capture={h.id} disabled={busy !== null || !!capturing} onClick={() => void capture(h.id)} className={buttonVariants({ variant: "outline", size: "sm" })} title="the editor's capture-posts: a screenshot of the post, paced">
+ Capture
+ </button>
+ ) : (
+ <>
+ <label className="flex items-center gap-1 text-[11px] text-muted">
+ crop
+ <input
+ data-add-post-crop={h.id}
+ inputMode="numeric"
+ value={crop[h.id] ?? ""}
+ onChange={(e) => setCrop((c) => ({ ...c, [h.id]: e.target.value }))}
+ placeholder={h.warnings.length ? "px — keep its top" : "px"}
+ className="w-20 rounded border border-seam-2 bg-ground px-1 py-0.5 font-mono text-[11px] text-text"
+ />
+ </label>
+ <button type="button" data-add-post-add={h.id} disabled={busy !== null} onClick={() => void add(h)} className={buttonVariants({ variant: "go", size: "sm" })}>
+ {h.inCut ? "Replace in the cut" : clip ? `Add to ${clip}` : "Add"}
+ </button>
+ </>
+ )}
+ </div>
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ {base && base.posts.length > 0 && (
+ <div data-add-post-cut="" className="space-y-1 border-t border-seam pt-1.5">
+ <p className="micro m-0">posts in the cut — {base.posts.length}</p>
+ <ul className="m-0 list-none space-y-1 p-0">
+ {base.posts.map((p) => (
+ <li key={p.id} data-add-post-in-cut={p.id} className={cn("flex flex-wrap items-baseline gap-1.5", p.hide && "opacity-60")}>
+ <span className="font-mono text-[11px] text-text">{p.id}</span>
+ <span className="text-[11px] text-muted">{p.attachTo ? `on ${p.attachTo}` : "on the clip its date picks"}</span>
+ <span className="min-w-0 max-w-[24rem] truncate text-[11.5px] text-text-2">{p.text}</span>
+ <label className="flex items-center gap-1 text-[11px] text-muted">
+ crop
+ <input
+ data-add-post-cut-crop={p.id}
+ inputMode="numeric"
+ value={crop[`cut:${p.id}`] ?? (p.shotMaxHeight ? String(p.shotMaxHeight) : "")}
+ onChange={(e) => setCrop((c) => ({ ...c, [`cut:${p.id}`]: e.target.value }))}
+ placeholder="px"
+ className="w-20 rounded border border-seam-2 bg-ground px-1 py-0.5 font-mono text-[11px] text-text"
+ />
+ </label>
+ <button type="button" data-add-post-cut-crop-save={p.id} disabled={busy !== null} onClick={() => void saveCrop(p)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Save crop
+ </button>
+ {p.warnings.map((w, i) => (
+ <span key={i} role="note" data-add-post-cut-warning={p.id} className="basis-full pl-4 text-[11px] text-reject-text">
+ ⚠ {w}
+ {p.shotMaxHeight ? ` (cropped to ${p.shotMaxHeight} px)` : ""}
+ </span>
+ ))}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -26,6 +26,7 @@ import RejectClip from "./RejectClip";
import WhatPlays, { type WorkingCut } from "./WhatPlays";
import { useCutApp } from "../cutApp/CutApp";
import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport";
+import AddPost from "./AddPost";
// ---------------------------------------------------------------------------
// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The
@@ -1061,6 +1062,20 @@ export default function PlayCut({
/>
<ClipExportStatus exp={clipExport} />
</div>
+ {/* Add post (UI notes item 13): a card from the channel's posts archive, captured through the editor, on the clip on screen. */}
+ {editable && (
+ <AddPost
+ project={project}
+ clip={item?.clip ? item.id : null}
+ onAdded={(p) => {
+ setPlaying(false);
+ // Its card plays at the end of the clip it rides on: the playhead goes there, the deck recomposed.
+ const it = planRef.current.items.find((x) => x.id === (p.attachTo ?? item?.id));
+ void reloadView();
+ if (it) seekTo(Math.max(it.from, it.to - 1));
+ }}
+ />
+ )}
{/* Reject ▾ (x): the clip on screen out of the cut for a reason, on record, with an undo (the project's cut: not on a take). */}
{editable && (
<RejectClip
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -73,12 +73,14 @@ Inbox cannot disagree about what is wrong with one.
| `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) |
| `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)) |
| `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) |
-| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key. Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** |
-| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run) |
+| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** |
+| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) |
| `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) |
| `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project>` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build ([knobs.md](knobs.md#look-presets)) |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -292,6 +292,7 @@ that mentions the seizure in question and one before it. The Marks box is on eve
| `render.chrome.deck.markerLayout` — `stagger` or `truncate` when labels crowd (default: stagger only when a label would truncate) | markers, **layout** | `deck.markerLayout=truncate` | `PUT /api/report/chrome {project, token, markerLayout}` |
| `render.chrome.deck.claims[]` — his explicit claims drawn against the record on the rail, at most 6: a `count` or a `goalpost` ([below](#claim-checks-on-the-rail)) | On-screen, **claim checks**: add a count / a goalpost, the clip picker, **use the playhead**, his words, the window's dates, the record's verdict, per, the claim; a goalpost's steps (**add a step**), each its from date and due durations; remove — the build's validator under each as it is typed | `umtool look <p> deck.claims='[…]'` (`deck.claims=` none) | `PUT /api/report/chrome {project, token, claims}` |
| `posts[].thread` — `true`: a reply drawn with the post it answers above it — the capture's `shot-thread.png` beside the post's `shot` (taken by `pnpm ops capture-posts --json '{"slug":…,"ids":[…],"thread":true}'`, the replied-to author's avatar, name and handle blurred unless gold- or grey-checked or the reply's own; `"threadRedact": false` takes it unblurred), the post's own shot while there is none; needs a `shot`. In the feed a thread shot is drawn whole: the card under it leaves rather than the reply being squeezed, and one taller than the column is scaled to fit, never cut; the popup posts pan through it as through any tall shot | Media, On-screen **Posts** table: **thread** (shown once a thread shot is on disk) | `umtool posts set <p> <post> thread=on` (`thread=off` clears it) · on add: `umtool posts add <p> <channel>/<postId> --thread` | `PUT /api/report/posts {project, token, posts: {<id>: {thread}}}` |
+| `posts[].shotMaxHeight` — the post's OWN **crop** of its screenshot, 120–1080 px: its top that tall, the rest cut off and **never panned to** (the deck-wide `deck.posts.shotMaxHeight` caps the viewport and a taller shot pans through it; this one does not) — what keeps a quoted post or a media thumbnail under the post's words off the screen; needs a `shot` | Play the cut, **Add post**: a hit's **crop** before Add, or a post in the cut's **crop** + **Save crop** (empty: none) | `umtool posts set <p> <post> crop=420` (`crop=off` clears it) · on add: `umtool posts add <p> <channel>/<postId> --crop 420` | `POST /api/report/post-cards {project, op: "crop", post, crop}` · `PUT /api/report/posts {…, posts: {<id>: {shotMaxHeight}}}` |
| `render.blur` — `off`: every clip's picture as recorded, no caption (the uncensored variant); `on` (the default) blurs the clips that ask | Build, **Look**: **Blurred clips** | `umtool look <p> blur=off` · a take: `umtool take <p> --id uncensored --set render.blur=off` | `PUT /api/report/render {project, token, patch: {blur}}` |
| `render.intro` — the brand sting the cut opens with: a style (`boot` `boot-wipe` `boot-dark` `boot-cascade` `boot-mark`) or `{style, ground?, mark?, sound?, seconds?, site?, swap?, url?, urlPlace?}`; absent is none ([report-video.md](report-video.md#the-brand-intro-renderintro)) | Build, **Look**: **Intro** | `umtool look <p> intro=boot-dark` (`intro=` none) · a take: `umtool take <p> --id intro-wipe --set render.intro=boot-wipe` | `PUT /api/report/render {project, token, patch: {intro}}` |
| `render.intro.site` — on the chime, "Archi" becomes the cited site's name ("Jera"), "lyzer" stays, the colours go to its accent: `auto` (the site whose `siteUrl` is `provenance.siteOrigin`; none found, no swap), a site id, `{name, lead?, accent?, url?}`, or `none`/absent (the plain intro, byte for byte). `render.intro.swap` `swipe-down` (default) \| `roll` \| `wipe`; `render.intro.url` `both` (default: the site's, then archilyzer.pages.dev) \| `site` \| `project` \| `false`; `render.intro.urlPlace` `under` (default: one row under MEDIA) \| `replace` (MEDIA's place) | — (manifest or a take) | a take: `umtool take <p> --id intro-jera --set render.intro.style=boot-dark --set render.intro.mark=chime --set render.intro.site=auto` (`--set render.intro.swap=roll`, `--set render.intro.url=false`, `--set render.intro.urlPlace=replace`) · standalone: `node umtool/report-to-video/intro.mjs render --style boot-dark --mark chime --site auto --site-origin https://jeralyzer.pages.dev --swap wipe --out x.mp4` | `PUT /api/report/render {project, token, patch: {intro: {…, site}}}` |
@@ -360,6 +361,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, once a sweep has proposed (until then one line in the timeline's heading, "no candidates: umtool candidates … import"): 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, its own undo point (never coalesced with the last edit) | `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,
@@ -591,6 +618,34 @@ it replies on the note as the agent; with no route the button says why, and the
Then the cut: the Build tab's **final** preset (a full build, about an hour for a 36-clip cut), and Deliver's
**Make variants**.
+## Add post (a post card from Play the cut)
+
+The chain `pnpm ops capture-posts` → `umtool posts add` → `umtool look deck.posts` in one panel: Play the cut's **Add
+post** (`components/projects/review/AddPost.tsx`, `/api/report/post-cards`, `lib/report/postCards.mjs`).
+
+| | In umtool | From a terminal | Route |
+|---|---|---|---|
+| the archive | **Add post** → a posts channel (those the cut's posts come from first, then those named like a cited channel, `<channel>-x`) and words: every word in the post's text or handle, any case, newest first (40 shown); empty, the newest | — (the archive is `channels/<slug>/posts/*.jsonl`) | `GET /api/report/post-cards?project&channel&q` |
+| the WARNING | each hit, and each post in the cut: **⚠** when the post's OWN data says its screenshot shows more than its words — it quotes a post (`quoted`), it is a repost (`repostOf`), it carries media (`mediaCount`, a forum's `media`): somebody else's words or video, or a thumbnail. Decided from the record, never from the picture | `umtool posts add` prints `WARNING: …` (`--json`: `warnings`) | the hits' `warnings` |
+| capture | a hit with no screenshot: **Capture** — the EDITOR's capture-posts (paced there: a pause before every contact after the first; the platform's own queue; an id not in the channel's archive refused), followed until it ends, then the search again | `pnpm ops capture-posts --json '{"slug":…,"ids":[…]}'` | `POST {op: "capture", channel, ids}` → `{jobId}` · `GET ?job=` |
+| add | a captured hit: **crop** (optional, px) and **Add to <clip>** — the clip on screen (a card on screen: the clip its date picks) — through `posts add`'s own write (`addPostFromArchive`: the capture copied into `posts-media/<slug>/<postId>/`, `upsertPost`, an undo point); the playhead goes to the clip's end and the deck is composed again, so the card shows on its clip | `umtool posts add <p> <slug>/<postId> --attach <clip> [--crop <px>]` | `POST {op: "add", channel, id, attach?, crop?}` |
+| crop a post in the cut | **posts in the cut**: **crop** + **Save crop** (`posts[].shotMaxHeight`, above) | `umtool posts set <p> <post> crop=<px>\|off` | `POST {op: "crop", post, crop}` |
+
+## The source backlog (Sources · Prioritize · Re-sweep when complete)
+
+The Overview tab's **sources** line (`components/projects/report/SourceBacklog.tsx`, `lib/report/sourceBacklog.*`): for each
+channel the cut cites (a clip's `siteChannel`, else its channel, else the cut's provenance channel; a clip with its own
+`src` cites none), `<channel> <transcribed>/<listed> transcribed · <held> held` from the EDITOR's snapshot counts
+(`GET /api/ops/channel/<slug>`: `totals`, `buckets.downloadedNoTranscript`, `undownloaded`; listed = held + not yet
+downloaded), never a walk of the disk. A channel is **complete** when nothing listed is left to download and nothing held is
+left to transcribe.
+
+| | In umtool | From a terminal | Route |
+|---|---|---|---|
+| the line | the Overview tab, above the decisions; `in focus` / `complete` / "the editor does not archive it" | `pnpm ops get channel <slug>` | `GET /api/report/source-backlog?project` |
+| Prioritize | a channel's **Prioritize**: the editor's focus (every lane leads with it) gains the channel, the ones in focus kept — through the editor's own `POST /api/ops/channel-priority {focus: {kind: "channels", slugs}}`, never settings; a site focus is the editor's to change (refused, said). Focus never starts a stopped lane or lifts a held one | `pnpm ops channel-priority --json '{"focus":{"kind":"channels","slugs":["<slug>"]}}'` | `POST {op: "prioritize", slugs?}` |
+| Re-sweep when complete | **Re-sweep when complete**: a watch (`<project>/source-watch.json`, one writer) over the cited channels the editor archives; every read of the backlog — this page's, and the Inbox's background check, at most hourly — records what it saw, and the first read with every watched channel complete FIRES it, once: an Inbox **sources-complete** card (Review, **Re-sweep**) until **Clear** | — | `POST {op: "watch"}` · `{op: "unwatch"}` |
+
## Export one clip
A clean mp4 of ONE clip, to post or hand on, with none of the deck — no rail, subtitles, QR, cards or stamps — written
diff --git a/umtool/e2e/add-post.spec.ts b/umtool/e2e/add-post.spec.ts
@@ -0,0 +1,133 @@
+import { test, expect, type Page } from "@playwright/test";
+import { copyFileSync, existsSync, readFileSync, rmSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+import { POST_IDS } from "./fixtures/intake-fixture.mjs";
+
+// ---------------------------------------------------------------------------
+// Add post in Play the cut (UI notes item 13; lib/report/postCards.mjs,
+// postsCli.mjs addPostFromArchive, /api/report/post-cards):
+//
+// add-post-fixture play-cut-fixture's cut, no posts; the corpus's testchan-x
+// posts archive: a plain post (captured), one QUOTING
+// another account (not captured) and one with a picture
+// (captured). WRITES its manifest, posts-media/ and the
+// corpus's testchan-x/posts-media/<quoting>/ (the stub's
+// capture); every test starts from the fixture's.
+//
+// The archive searched from Play; each post's warning from its own data;
+// Capture through the editor's capture-posts (the stub's job); Add to the clip
+// on screen with a crop -- the card on that clip in the live preview, its shot
+// cropped (data-crop, never panned) -- and the crop changed on a post in the cut.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const DIR = path.join(FIXTURE, "reports", "add-post-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const PROJECT = "reports/add-post-fixture";
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const QUOTING_SHOT = path.join(FIXTURE, "channels", "testchan-x", "posts-media", POST_IDS.quoting);
+const SHOTS = process.env.U4_SHOTS ?? null;
+
+type Post = { id: string; attachTo?: string; shot?: string; shotMaxHeight?: number };
+const posts = () => ((JSON.parse(readFileSync(MANIFEST, "utf8")) as { posts?: Post[] }).posts ?? []);
+const stubLog = () => {
+ try {
+ return JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route: string; slug?: string; ids?: string[] }[];
+ } catch {
+ return [];
+ }
+};
+
+test.beforeAll(() => {
+ if (!existsSync(`${MANIFEST}.pristine`)) copyFileSync(MANIFEST, `${MANIFEST}.pristine`);
+});
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+ rmSync(path.join(DIR, "posts-media"), { recursive: true, force: true });
+ rmSync(QUOTING_SHOT, { recursive: true, force: true });
+});
+
+const root = (page: Page) => page.locator("[data-play-cut]");
+async function open(page: Page) {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.playHref(PROJECT));
+ await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+ await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 });
+ await page.locator("[data-play-add-post-open]").click();
+ await expect(page.getByTestId("add-post")).toBeVisible();
+ await expect(page.locator("[data-add-post-channel]")).toHaveValue("testchan-x");
+}
+async function search(page: Page, q: string) {
+ await page.locator("[data-add-post-q]").fill(q);
+ await page.locator("[data-add-post-search]").click();
+ await expect(page.locator("[data-add-post-hit]").first()).toBeVisible();
+}
+const hit = (page: Page, id: string) => page.locator(`[data-add-post-hit='${id}']`);
+
+test("the archive searched from Play; each post's warning from its own data: a quoted post, a picture, none", async ({ page }) => {
+ await open(page);
+ await search(page, "voice");
+ await expect(page.locator("[data-add-post-hit]")).toHaveCount(3);
+ await expect(hit(page, POST_IDS.quoting).locator("[data-add-post-warning]")).toContainText("quotes a post by @someoneelse");
+ await expect(hit(page, POST_IDS.media).locator("[data-add-post-warning]")).toContainText("a picture or video");
+ await expect(hit(page, POST_IDS.plain).locator("[data-add-post-warning]")).toHaveCount(0);
+ await expect(hit(page, POST_IDS.quoting)).toHaveAttribute("data-add-post-captured", "0");
+ await expect(hit(page, POST_IDS.plain)).toHaveAttribute("data-add-post-captured", "1");
+ await search(page, "pictured");
+ await expect(page.locator("[data-add-post-hit]")).toHaveCount(1);
+});
+
+test("Capture through the editor, Add to the clip on screen with a crop: the card on that clip in the preview, cropped", async ({ page }) => {
+ await open(page);
+ await search(page, "voice");
+ const before = stubLog().length;
+ await page.locator(`[data-add-post-capture='${POST_IDS.quoting}']`).click();
+ await expect(page.locator("[data-add-post-said]")).toContainText(`capture of ${POST_IDS.quoting}: done`, { timeout: 20_000 });
+ const asked = stubLog().slice(before).filter((r) => r.route === "capture-posts");
+ expect(asked).toEqual([expect.objectContaining({ slug: "testchan-x", ids: [POST_IDS.quoting] })]);
+ await expect(hit(page, POST_IDS.quoting)).toHaveAttribute("data-add-post-captured", "1");
+ // The clip on screen is c01: the post goes on it, cropped to its own words.
+ await expect(page.locator(`[data-add-post-add='${POST_IDS.quoting}']`)).toHaveText("Add to c01");
+ await page.locator(`[data-add-post-crop='${POST_IDS.quoting}']`).fill("300");
+ await page.locator(`[data-add-post-add='${POST_IDS.quoting}']`).click();
+ await expect(page.locator("[data-add-post-said]")).toContainText(`added x-${POST_IDS.quoting} on c01`);
+ await expect.poll(() => posts().map((p) => `${p.id}:${p.attachTo}:${p.shotMaxHeight}`)).toEqual([`x-${POST_IDS.quoting}:c01:300`]);
+ expect(existsSync(path.join(DIR, "posts-media", "testchan-x", POST_IDS.quoting, "shot.png"))).toBe(true);
+ // The card on c01, in the live preview: its shot cropped (data-crop), never panned.
+ const preview = page.locator("[data-testid=onscreen-posts-preview][data-segment='c01']");
+ await expect(preview).toHaveAttribute("data-posts-ready", "1", { timeout: 60_000 });
+ const frame = page.frameLocator("[data-testid=onscreen-posts-preview-iframe]");
+ await expect(frame.locator(".shot-view[data-crop='300']")).toHaveCount(1);
+ // In the cut, the post still says what its screenshot carries.
+ await expect(page.locator(`[data-add-post-cut-warning='x-${POST_IDS.quoting}']`)).toContainText("cropped to 300 px");
+ if (SHOTS) {
+ await page.waitForTimeout(800);
+ await page.screenshot({ path: path.join(SHOTS, "13-add-post-card-on-clip.png") });
+ }
+});
+
+test("a post in the cut: Save crop changes its own shotMaxHeight; empty takes the crop off", async ({ page }) => {
+ await open(page);
+ await search(page, "pictured");
+ await page.locator(`[data-add-post-add='${POST_IDS.media}']`).click();
+ await expect.poll(() => posts().map((p) => p.id)).toEqual([`x-${POST_IDS.media}`]);
+ const crop = page.locator(`[data-add-post-cut-crop='x-${POST_IDS.media}']`);
+ await crop.fill("420");
+ await page.locator(`[data-add-post-cut-crop-save='x-${POST_IDS.media}']`).click();
+ await expect.poll(() => posts()[0].shotMaxHeight).toBe(420);
+ if (SHOTS) {
+ await page.getByTestId("add-post").screenshot({ path: path.join(SHOTS, "13-add-post-panel-warnings.png") });
+ }
+ await crop.fill("");
+ await page.locator(`[data-add-post-cut-crop-save='x-${POST_IDS.media}']`).click();
+ await expect.poll(() => "shotMaxHeight" in posts()[0]).toBe(false);
+ // A crop out of range is refused in the build's words.
+ await crop.fill("50");
+ await page.locator(`[data-add-post-cut-crop-save='x-${POST_IDS.media}']`).click();
+ await expect(page.locator("[data-add-post-error]")).toContainText("from 120 to 1080");
+});
diff --git a/umtool/e2e/candidates.spec.ts b/umtool/e2e/candidates.spec.ts
@@ -0,0 +1,177 @@
+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 });
+}
+/** The Cut tab, with no candidates file yet: no panel, one line in the timeline's heading. */
+async function openEmpty(page: Page) {
+ await page.goto(urls.section(PROJECT, "timeline"));
+ await expect(page.locator("[data-candidates-empty]")).toBeVisible({ timeout: 20_000 });
+ await expect(page.getByTestId("candidates")).toHaveCount(0);
+}
+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 openEmpty(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 open(page);
+ 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.”");
+ // A new claim names no clip: its place is the deck section of the heading it stands under.
+ await expect(row(page, "v1234567").locator("[data-candidate-place]")).toContainText("§1 (As a streamer) (the sweep's heading)");
+ // 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");
+ // An undo point is named by its second (lib/report/snapshots.mjs): two writes inside one second
+ // share one. A person's presses are seconds apart; the spec's are not, so it waits one out.
+ await page.waitForTimeout(1100);
+ 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/cut-integrity.spec.ts b/umtool/e2e/cut-integrity.spec.ts
@@ -208,8 +208,10 @@ test("#6 removing a clip re-anchors the take patch's markers; the hand-made one
await page.locator('[data-row-menu="c04"]').click();
await page.locator('[data-entry="c04"] [data-row-action="remove"]').click();
await expect.poll(() => entries().map((e) => e.id)).toEqual(["c01", "c03", "c02"]);
- const patch = JSON.parse(readFileSync(path.join(DIR, "draft-1.patch.json"), "utf8")) as { render: { chrome: { deck: { markers: { after: string; label: string }[] } } } };
- expect(patch.render.chrome.deck.markers).toEqual([{ after: "c02", label: "After four" }, { after: "gone", label: "Hand-made" }]);
+ // The patch is synced just after the manifest: poll it too (a single read raced it under load).
+ const patchMarkers = () =>
+ (JSON.parse(readFileSync(path.join(DIR, "draft-1.patch.json"), "utf8")) as { render: { chrome: { deck: { markers: { after: string; label: string }[] } } } }).render.chrome.deck.markers;
+ await expect.poll(patchMarkers).toEqual([{ after: "c02", label: "After four" }, { after: "gone", label: "Hand-made" }]);
await page.goto(urls.projectHref(PROJECT));
await expect(row(page, "patch-markers-stale", "draft-1.patch.json")).toContainText('"Hand-made" after gone — a take made with --patch draft-1.patch.json is refused');
await expect(row(page, "patch-markers-stale", "draft-1.patch.json")).not.toContainText("After four");
diff --git a/umtool/e2e/fixtures/editor-stub-case-stages.mjs b/umtool/e2e/fixtures/editor-stub-case-stages.mjs
@@ -6,27 +6,21 @@
// `@@transcribe-result {…}` -- the text the fixture's HEARD
// POST /api/ops/wayback-lookup {url}
// 403 {refusal: "excluded"} for the fixture's EXCLUDED_URL, else two captures
-// POST /api/ops/capture-posts {slug, ids}
-// job; when done, posts-media/<id>/shot.png and the post's attachment
-// written into the fixture corpus
// POST /api/ops/fetch-posts {slug, …}
// job, done after 0.6 s
// GET /api/ops/job/cs-<n>?tail=N
//
-// (create-channel and import-page are editor-stub-import-page.mjs's.) Never a
+// (create-channel and import-page are editor-stub-import-page.mjs's;
+// capture-posts is editor-stub-intake.mjs's, shared with U4's Add post.) Never a
// worker, the Wayback Machine or a forum. Every request is recorded by the
// main stub's `record`.
-import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { EXCLUDED_URL, HEARD } from "./case-stages-fixture.mjs";
const jobs = new Map();
let next = 1;
-// A 1×1 PNG.
-const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");
-
function job(kind, log, onDone, ms = 600) {
const id = `cs-${next++}`;
const j = { id, kind, status: "queued", log: [...log] };
@@ -86,23 +80,6 @@ export function caseStagesRoute(req, res, url, ctx) {
)
return true;
if (
- post("/api/ops/capture-posts", (body) => {
- const ids = Array.isArray(body.ids) ? body.ids.map(String) : [];
- if (!body.slug || !ids.length) return json(res, 400, { ok: false, error: "name a channel and its posts" });
- const id = job("capture-posts", [`Capture ${ids.length} post(s) of ${body.slug}`], () => {
- for (const pid of ids) {
- const dir = path.join(ctx.channels, body.slug, "posts-media", pid);
- mkdirSync(dir, { recursive: true });
- writeFileSync(path.join(dir, "shot.png"), PNG);
- writeFileSync(path.join(dir, "minutes.png"), PNG);
- writeFileSync(path.join(dir, "capture.json"), JSON.stringify({ id: pid, shot: "shot.png", media: ["minutes.png"] }));
- }
- });
- json(res, 200, { ok: true, jobId: id });
- })
- )
- return true;
- if (
post("/api/ops/fetch-posts", (body) => {
if (!body.slug) return json(res, 400, { ok: false, error: "name a channel" });
json(res, 200, { ok: true, jobId: job("fetch-posts", [`Fetch ${body.older ? "older " : ""}posts of ${body.slug}`]) });
diff --git a/umtool/e2e/fixtures/editor-stub-intake.mjs b/umtool/e2e/fixtures/editor-stub-intake.mjs
@@ -0,0 +1,138 @@
+// The editor's doors the intake specs knock on (UI notes 2026-10-30, items 13
+// and 16), stubbed beside editor-stub.mjs:
+//
+// GET /api/ops/channel/<slug> a channel's snapshot counts (testchan: a backlog,
+// 1,454/2,798 transcribed; backlog-done: nothing left;
+// any other: 404 "Channel … not found")
+// GET /api/ops/settings?key=channelPriority { value: { focus, channels } }
+// POST /api/ops/channel-priority {focus} the focus replaced, recorded
+// POST /api/ops/capture-posts {slug, ids} job cp-<n>: running at once, done after ~1 s, when it
+// has written posts-media/<id>/shot.png + capture.json, and
+// each attachment the post names (media[].name) -- shared by
+// Add post and a research case's forum evidence (lane C)
+// GET /api/ops/job/cp-<n> that job
+// POST /__stub/channel-counts {slug, totals?, undownloaded?, untranscribed?} (no token) a spec's
+// counts for a channel; {} resets
+import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { postShotPng } from "./intake-fixture.mjs";
+
+const DEFAULT_COUNTS = () => ({
+ testchan: { totals: { videos: 2751, transcribed: 1454, downloaded: 2700 }, undownloaded: 47, untranscribed: 1297 },
+ "backlog-done": { totals: { videos: 120, transcribed: 120, downloaded: 120 }, undownloaded: 0, untranscribed: 0 },
+});
+let counts = DEFAULT_COUNTS();
+const priority = { focus: { kind: "none" }, channels: {} };
+const jobs = new Map();
+
+/** The file names of a post's named attachments, read from the channel's posts/*.jsonl (none when unreadable). */
+function attachmentNames(channels, slug, id) {
+ const dir = path.join(channels, slug, "posts");
+ let files = [];
+ try {
+ files = readdirSync(dir).filter((f) => f.endsWith(".jsonl"));
+ } catch {
+ return [];
+ }
+ for (const f of files) {
+ for (const line of readFileSync(path.join(dir, f), "utf8").split("\n")) {
+ if (!line.includes(`"id":"${id}"`)) continue;
+ try {
+ const p = JSON.parse(line);
+ if (p.id === id) return (p.media ?? []).map((m) => m?.name).filter((n) => typeof n === "string" && /^[A-Za-z0-9._-]+$/.test(n));
+ } catch {
+ /* not a post */
+ }
+ }
+ }
+ return [];
+}
+let nextJob = 1;
+
+/** The control door (before the token check). Answers true when it handled the request. */
+export function intakeControl(req, res, url, { json, readBody }) {
+ if (req.method === "POST" && url.pathname === "/__stub/channel-counts") {
+ readBody(req, (body) => {
+ if (!body?.slug) {
+ counts = DEFAULT_COUNTS();
+ priority.focus = { kind: "none" };
+ } else counts[body.slug] = { totals: body.totals ?? counts[body.slug]?.totals ?? { videos: 0, transcribed: 0, downloaded: 0 }, undownloaded: body.undownloaded ?? 0, untranscribed: body.untranscribed ?? 0 };
+ json(res, 200, { ok: true, counts });
+ });
+ return true;
+ }
+ return false;
+}
+
+/** The token-gated doors. Answers true when it handled the request. */
+export function intakeRoute(req, res, url, { json, readBody, push, channels }) {
+ const ch = /^\/api\/ops\/channel\/([^/]+)$/.exec(url.pathname);
+ if (req.method === "GET" && ch) {
+ req.resume();
+ const slug = decodeURIComponent(ch[1]);
+ const c = counts[slug];
+ if (!c) {
+ json(res, 404, { ok: false, error: `Channel "${slug}" not found` });
+ return true;
+ }
+ json(res, 200, {
+ ok: true,
+ slug,
+ config: { name: slug },
+ priority: { tier: "normal", overrides: {}, rank: null },
+ counts: null,
+ media: { status: "ok" },
+ report: { generatedAt: "2026-11-01T00:00:00.000Z", totals: c.totals, buckets: { downloadedNoTranscript: c.untranscribed, noTranscript: c.untranscribed }, undownloaded: c.undownloaded },
+ });
+ return true;
+ }
+ if (req.method === "GET" && url.pathname === "/api/ops/settings" && url.searchParams.get("key") === "channelPriority") {
+ req.resume();
+ json(res, 200, { ok: true, key: "channelPriority", value: priority });
+ return true;
+ }
+ if (req.method === "POST" && url.pathname === "/api/ops/channel-priority") {
+ readBody(req, (body) => {
+ push({ route: "channel-priority", ...(body ?? {}) });
+ if (!body?.focus || Object.keys(body).length !== 1) return json(res, 400, { ok: false, error: "the stub takes a focus body alone" });
+ priority.focus = body.focus;
+ json(res, 200, { ok: true });
+ });
+ return true;
+ }
+ if (req.method === "POST" && url.pathname === "/api/ops/capture-posts") {
+ readBody(req, (body) => {
+ push({ route: "capture-posts", ...(body ?? {}) });
+ const slug = String(body?.slug ?? "");
+ const ids = Array.isArray(body?.ids) ? body.ids.map(String) : [];
+ if (!/^[A-Za-z0-9._-]+$/.test(slug) || !ids.length) return json(res, 400, { ok: false, error: '"slug" and "ids"' });
+ const id = `cp-${nextJob++}`;
+ const job = { id, kind: "capture-posts", status: "running", tail: [`capturing ${ids.length} post(s) of ${slug}`] };
+ jobs.set(id, job);
+ setTimeout(() => {
+ for (const pid of ids) {
+ const d = path.join(channels, slug, "posts-media", pid);
+ mkdirSync(d, { recursive: true });
+ writeFileSync(path.join(d, "shot.png"), postShotPng());
+ // The post's named attachments (release 38 lane C's forum post, case-stages.spec), as the real
+ // capture saves its media beside the shot.
+ for (const name of attachmentNames(channels, slug, pid)) writeFileSync(path.join(d, name), postShotPng());
+ writeFileSync(path.join(d, "capture.json"), JSON.stringify({ version: 1, id: pid, url: `https://x.com/i/status/${pid}`, capturedAt: new Date().toISOString(), state: "captured", mediaState: "skipped", media: [] }) + "\n");
+ }
+ job.status = "done";
+ job.tail.push(`Done: ${ids.length} captured, 0 deleted, 0 unavailable, 0 failed.`);
+ }, 1000);
+ json(res, 200, { ok: true, jobId: id });
+ });
+ return true;
+ }
+ const jm = /^\/api\/ops\/job\/(cp-\d+)$/.exec(url.pathname);
+ if (req.method === "GET" && jm) {
+ req.resume();
+ const job = jobs.get(jm[1]);
+ if (!job) json(res, 404, { ok: false, error: "no such job" });
+ else json(res, 200, { ok: true, job: { id: job.id, kind: job.kind, status: job.status }, tail: job.tail });
+ return true;
+ }
+ return false;
+}
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -15,6 +15,7 @@
// Modelled on e2e/fixtures/ollama-stub.mjs in the editor: a second webServer
// entry, ready when its own endpoint answers.
+import { intakeControl, intakeRoute } from "./editor-stub-intake.mjs";
import http from "node:http";
import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs";
@@ -1233,6 +1234,8 @@ const server = http.createServer((req, res) => {
return json(res, 200, { ok: true, ...scheduleClock });
});
}
+ // The intake specs' counts (editor-stub-intake.mjs).
+ if (intakeControl(req, res, url, { json, readBody })) return;
if (req.method === "POST" && url.pathname === "/__stub/ops-jobs") {
return readBody(req, (body) => {
const mode = body?.mode ?? "ok";
@@ -1250,6 +1253,8 @@ const server = http.createServer((req, res) => {
return json(res, 401, { error: "missing bearer token" });
}
+ // UI notes items 13 and 16: a channel's counts, the focus, capture-posts (editor-stub-intake.mjs).
+ if (intakeRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push({ ...r, authorization: auth }), record()) })) return;
// Release 38 lane C: a research case's verify, leads and evidence stages (editor-stub-case-stages.mjs).
if (caseStagesRoute(req, res, url, { channels: CHANNELS, json, readBody, push: (r) => (requests.push(r), record()) })) return;
// Release 37 S4: Import this capture (editor-stub-import-page.mjs).
diff --git a/umtool/e2e/fixtures/intake-fixture.mjs b/umtool/e2e/fixtures/intake-fixture.mjs
@@ -0,0 +1,178 @@
+// 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)
+// source-backlog-fixture a deck cut citing two channels: testchan (the editor
+// stub answers it with a backlog: 1,454/2,798 transcribed)
+// and backlog-done (the stub's: nothing left), and a third
+// the stub does not archive (source-backlog.spec.ts)
+// add-post-fixture play-cut-fixture's cut (play-cut-fixture.mjs) with no posts;
+// the social channel testchan-x beside it in the corpus:
+// posts/2026-10.jsonl -- 1910000000000000001 plain words,
+// captured; ...002 QUOTING another account, not captured
+// (the stub's capture-posts takes it); ...003 with a picture,
+// captured -- each captured shot a tall 500x900 png
+// (add-post.spec.ts)
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { deflateSync } from "node:zlib";
+import { makePlayCutFixture } from "./play-cut-fixture.mjs";
+
+const CRC = (() => {
+ const t = new Uint32Array(256);
+ for (let n = 0; n < 256; n += 1) {
+ let c = n;
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ t[n] = c >>> 0;
+ }
+ return t;
+})();
+const crc32 = (buf) => {
+ let c = 0xffffffff;
+ for (const b of buf) c = CRC[(c ^ b) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+};
+const chunk = (type, data) => {
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(data.length);
+ const td = Buffer.concat([Buffer.from(type, "ascii"), data]);
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(td));
+ return Buffer.concat([len, td, crc]);
+};
+/**
+ * A post's screenshot, drawn: a light card -- the post's own words as dark bars
+ * in its top 300 px -- and, below, a grey box standing for a quoted post or a
+ * media thumbnail (what a crop keeps off the screen).
+ */
+export function postShotPng(w = 500, h = 900) {
+ const raw = Buffer.alloc((w * 3 + 1) * h);
+ for (let y = 0; y < h; y += 1) {
+ const row = y * (w * 3 + 1);
+ raw[row] = 0;
+ for (let x = 0; x < w; x += 1) {
+ let v = 245;
+ if (y < 300 && y % 40 > 24 && x > 24 && x < w - 24 - (y % 80 > 40 ? 120 : 0)) v = 40; // the words
+ if (y >= 340 && y < h - 30 && x > 24 && x < w - 24) v = y % 60 < 4 || x < 30 || x > w - 30 ? 120 : 190; // the quoted box
+ const i = row + 1 + x * 3;
+ raw[i] = v;
+ raw[i + 1] = v;
+ raw[i + 2] = v + (y >= 340 ? 10 : 0) > 255 ? 255 : v + (y >= 340 ? 10 : 0);
+ }
+ }
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(w, 0);
+ ihdr.writeUInt32BE(h, 4);
+ ihdr[8] = 8;
+ ihdr[9] = 2;
+ return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]);
+}
+
+export const POST_IDS = { plain: "1910000000000000001", quoting: "1910000000000000002", media: "1910000000000000003" };
+
+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, channels, 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"));
+
+ // ---- the source backlog (item 16) ----------------------------------------------
+ const backlog = path.join(reports, "source-backlog-fixture");
+ const bm = deckManifest("source-backlog-fixture", "The Source Backlog Fixture", [
+ ...clips(["c01", "c02", "c03"]),
+ { ...clips(["c04"])[0], channel: "backlog-done" },
+ { ...clips(["c05"])[0], channel: "not-archived" },
+ ]);
+ write(backlog, "video.manifest.json", json(bm));
+
+ // ---- Add post (item 13) -----------------------------------------------------------
+ makePlayCutFixture({ reports, deckManifest, cachedWindow, name: "add-post-fixture", title: "The Add Post Fixture" });
+ // With a post drawn the tally's cell is narrower: a word that fits it (the build refuses "Seizures" there).
+ const apFile = path.join(reports, "add-post-fixture", "video.manifest.json");
+ const ap = JSON.parse(readFileSync(apFile, "utf8"));
+ ap.render.chrome.factcheck.verdicts.CORROBORATED.tallyLabel = "Fits";
+ writeFileSync(apFile, json(ap));
+ const x = path.join(channels, "testchan-x");
+ const row = (id, date, text, extra = {}) =>
+ JSON.stringify({ id, slug: "testchan-x", channelSlug: "testchan-x", author: "teststreamer", authorName: "Test Streamer", createdAt: `${date}T15:00:00.000Z`, uploadDate: date.replace(/-/g, ""), text, url: `https://x.com/teststreamer/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], ...extra });
+ write(x, "config.json", json({ name: "Test Streamer (X)", kind: "social", platform: "x" }));
+ write(
+ x,
+ "posts/2026-10.jsonl",
+ [
+ row(POST_IDS.plain, "2026-10-20", "The voice is a setting, nothing more."),
+ row(POST_IDS.quoting, "2026-10-21", "About that voice clip going round:", { quoted: { platform: "twitter", id: "1900000000000000009", author: "someoneelse", url: "https://x.com/someoneelse/status/1900000000000000009" } }),
+ row(POST_IDS.media, "2026-10-22", "The voice setup, pictured.", { mediaCount: 1 }),
+ ].join("\n") + "\n",
+ );
+ write(x, "posts-archive", Object.values(POST_IDS).map((id) => `twitter ${id}`).join("\n") + "\n");
+ for (const id of [POST_IDS.plain, POST_IDS.media]) {
+ const d = path.join(x, "posts-media", id);
+ mkdirSync(d, { recursive: true });
+ writeFileSync(path.join(d, "shot.png"), postShotPng());
+ writeFileSync(path.join(d, "capture.json"), json({ version: 1, id, url: `https://x.com/teststreamer/status/${id}`, capturedAt: "2026-10-30T00:00:00.000Z", state: "captured", mediaState: "skipped", media: [] }));
+ }
+ return { cands, backlog };
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -51,6 +51,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"));
@@ -1898,6 +1899,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, channels: CHANNELS, 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/e2e/source-backlog.spec.ts b/umtool/e2e/source-backlog.spec.ts
@@ -0,0 +1,108 @@
+import { test, expect, type Page } from "@playwright/test";
+import { readFileSync, rmSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs";
+
+// ---------------------------------------------------------------------------
+// The source backlog on a report video's page (UI notes item 16,
+// lib/report/sourceBacklog.*):
+//
+// source-backlog-fixture a deck cut citing testchan (the editor stub's
+// backlog: 1,454/2,798 transcribed, 2,751 held),
+// backlog-done (nothing left) and not-archived (the
+// stub's 404). WRITES source-watch.json, removed after.
+//
+// The line per channel from the editor's snapshot counts; Prioritize through
+// the editor's channel-priority (the focus body, never settings); Re-sweep
+// when complete armed, then FIRED by a read once every channel is done, and
+// the Inbox's sources-complete card (Re-sweep).
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const DIR = path.join(FIXTURE, "reports", "source-backlog-fixture");
+const PROJECT = "reports/source-backlog-fixture";
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const STUB = `http://127.0.0.1:${portFor("EDITOR_STUB_PORT")}`;
+const SHOTS = process.env.U4_SHOTS ?? null;
+
+const stubLog = () => {
+ try {
+ return JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route: string; focus?: { kind: string; slugs?: string[] } }[];
+ } catch {
+ return [];
+ }
+};
+const counts = (page: Page, body: Record<string, unknown>) => page.request.post(`${STUB}/__stub/channel-counts`, { data: body });
+
+test.beforeEach(async ({ page }) => {
+ test.setTimeout(90_000);
+ rmSync(path.join(DIR, "source-watch.json"), { force: true });
+ await counts(page, {});
+});
+test.afterAll(async ({ request }) => {
+ rmSync(path.join(DIR, "source-watch.json"), { force: true });
+ await request.post(`${STUB}/__stub/channel-counts`, { data: {} });
+});
+
+async function open(page: Page) {
+ await page.goto(urls.projectHref(PROJECT));
+ await expect(page.getByTestId("source-backlog")).toBeVisible({ timeout: 20_000 });
+}
+
+test("each cited channel: transcribed/listed and held from the editor; complete; one the editor does not archive", async ({ page }) => {
+ await open(page);
+ const box = page.getByTestId("source-backlog");
+ await expect(box.locator("[data-backlog-line='testchan']")).toHaveText("1,454/2,798 transcribed · 2,751 held");
+ await expect(box.locator("[data-backlog-channel='testchan']")).toHaveAttribute("data-backlog-done", "0");
+ await expect(box.locator("[data-backlog-channel='backlog-done']")).toContainText("complete");
+ await expect(box.locator("[data-backlog-channel='not-archived']")).toContainText("the editor does not archive it");
+ await expect(box.locator("[data-backlog-prioritize='testchan']")).toBeVisible();
+ await expect(box.locator("[data-backlog-prioritize='backlog-done']")).toHaveCount(0);
+ if (SHOTS) {
+ await page.setViewportSize({ width: 1366, height: 900 });
+ await page.screenshot({ path: path.join(SHOTS, "16-source-backlog.png") });
+ }
+});
+
+test("Prioritize asks the editor's channel-priority for its focus; the line says in focus", async ({ page }) => {
+ await open(page);
+ const before = stubLog().length;
+ await page.locator("[data-backlog-prioritize='testchan']").click();
+ await expect(page.locator("[data-backlog-said]")).toContainText("testchan is in the editor's focus");
+ const asked = stubLog().slice(before).filter((r) => r.route === "channel-priority");
+ expect(asked).toHaveLength(1);
+ expect(asked[0].focus).toEqual({ kind: "channels", slugs: ["testchan"] });
+ await expect(page.locator("[data-backlog-channel='testchan']")).toContainText("in focus");
+ await expect(page.locator("[data-backlog-prioritize='testchan']")).toHaveCount(0);
+});
+
+test("Re-sweep when complete: armed; fired once every channel is done; the Inbox's card says Re-sweep", async ({ page }) => {
+ await open(page);
+ await page.locator("[data-backlog-watch-arm]").click();
+ await expect(page.locator("[data-backlog-watch='armed']")).toContainText("re-sweep when complete");
+ const armed = JSON.parse(readFileSync(path.join(DIR, "source-watch.json"), "utf8"));
+ // A channel the editor does not archive can never be complete: the watch is for the ones it answers.
+ expect(armed.watch.slugs.sort()).toEqual(["backlog-done", "testchan"]);
+ // A reload before the backlog is done fires nothing.
+ await page.reload();
+ await expect(page.locator("[data-backlog-watch='armed']")).toBeVisible({ timeout: 20_000 });
+ await counts(page, { slug: "testchan", totals: { videos: 2798, transcribed: 2798, downloaded: 2798 }, undownloaded: 0, untranscribed: 0 });
+ await page.reload();
+ await expect(page.locator("[data-backlog-watch='fired']")).toContainText("complete since", { timeout: 20_000 });
+ const fired = JSON.parse(readFileSync(path.join(DIR, "source-watch.json"), "utf8"));
+ expect(fired.watch.firedAt).toBeTruthy();
+ await page.goto(urls.homeHref());
+ const card = page.locator(`[data-lit-line][data-piece='p:${PROJECT}'][data-card='sources-complete']`);
+ await expect(card).toBeVisible({ timeout: 20_000 });
+ await expect(card).toContainText("Re-sweep");
+ if (SHOTS) await card.screenshot({ path: path.join(SHOTS, "16-inbox-resweep.png") });
+ // Cleared, the card goes.
+ await open(page);
+ await page.locator("[data-backlog-unwatch]").click();
+ await expect(page.locator("[data-backlog-watch]")).toHaveCount(0);
+ await page.goto(urls.homeHref());
+ await expect(card).toHaveCount(0);
+});
diff --git a/umtool/lib/inbox.ts b/umtool/lib/inbox.ts
@@ -26,6 +26,7 @@ import { scheduleDecisions } from "./inbox/schedules.mjs";
import { readSchedules } from "./schedules";
import type { ScheduleView } from "./schedule-types";
import { refreshDecisions } from "./inbox/refresh";
+import { sourceWatchDecisions } from "./inbox/sourceWatch";
// ---------------------------------------------------------------------------
// THE INBOX, AS DATA: every open decision (lib/projects.ts openDecisions: the
@@ -389,7 +390,9 @@ export async function diskDecisions(graph: PieceGraph, life: LifecycleRead): Pro
const refresh = await readMutes()
.then((mutes) => refreshDecisions(graph, life, mutes))
.catch(() => [] as Decision[]);
- return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...proposals, ...refresh, ...recurring];
+ // Re-sweep when complete (UI notes item 16): a report video's source watch that fired.
+ const sources = await sourceWatchDecisions().catch(() => [] as Decision[]);
+ return [...perArticle.flat(), ...pieceDecisions(graph, life), ...drafts, ...proposals, ...refresh, ...recurring, ...sources];
}
/**
diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs
@@ -64,6 +64,9 @@ const KIND_CATEGORY = {
// recordings since the current report are something to review.
"refresh-held": "spend",
"refresh-available": "review",
+ // UI notes item 16: a report video's cited channels are all downloaded and
+ // transcribed -- a re-sweep to review (lib/inbox/sourceWatch.ts).
+ "sources-complete": "review",
// Release 29 M8: a model's proposed verdicts for a fact-check's unruled
// claims, each waiting on the operator's approve or reject.
"verdict-proposed": "review",
@@ -96,7 +99,7 @@ export function groupOf(d) {
// Within a group: the brief's order first (proposals before failed runs), then
// everything else as equals.
-const KIND_RANK = { "worth-researching": 0, "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "tick-partial": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "verdict-proposed": 1, "unreadable-notes": 0, "unreadable-proposals": 0, "refresh-held": 2, "refresh-available": 2 };
+const KIND_RANK = { "worth-researching": 0, "research-proposal": 0, "iteration-failed": 1, "tick-held": 2, "tick-failed": 2, "tick-partial": 2, "iteration-ready": 0, "edition-ready": 0, "drafts-unreviewed": 1, "verdict-proposed": 1, "unreadable-notes": 0, "unreadable-proposals": 0, "refresh-held": 2, "refresh-available": 2, "sources-complete": 2 };
const SEVERITY_RANK = { blocking: 0, open: 1, info: 2 };
// ONE primary action per decision, its button copy naming the result.
@@ -155,6 +158,7 @@ const ACTION_LABEL = {
"ambiguous-project": "Fix the project's files",
"refresh-held": "Refresh",
"refresh-available": "Refresh",
+ "sources-complete": "Re-sweep",
};
const CATEGORY_LABEL = { fix: "Fix it", choose: "Decide", info: "Open", spend: "Decide", review: "Review", note: "Answer note", finish: "Mark done" };
diff --git a/umtool/lib/inbox/sourceWatch.ts b/umtool/lib/inbox/sourceWatch.ts
@@ -0,0 +1,81 @@
+import { stat } from "node:fs/promises";
+import path from "node:path";
+import type { Decision } from "@/lib/decisions";
+import { projectHref } from "@/lib/hrefs";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { projectRefs } from "@/lib/projects";
+import { SOURCE_WATCH_FILE, backlogWords, readSourceWatch } from "@/lib/report/sourceBacklog.mjs";
+import { readBacklog } from "@/lib/report/sourceBacklog";
+
+// ---------------------------------------------------------------------------
+// "RE-SWEEP WHEN COMPLETE" (UI notes item 16), the Inbox's half -- one kind:
+//
+// sources-complete a report video's source watch (<project>/source-watch.json,
+// lib/report/sourceBacklog.mjs) has fired: every channel the
+// cut cites has nothing left to download or transcribe. Review,
+// action Re-sweep (the project's page, the backlog line);
+// gone when the operator clears or re-arms the watch.
+//
+// The check is the refresh check's pattern (lib/inbox/refresh.ts): the Inbox
+// only READS the watch files; an armed watch whose last read is over an hour
+// old is read again in the background (the editor's snapshot counts, one
+// project at a time, never twice at once), in the app's server only and not
+// where UMTOOL_SOURCE_WATCH=0. The project page's own read records too, so
+// opening the project fires it as well. SERVER-ONLY.
+// ---------------------------------------------------------------------------
+
+export const SOURCES_COMPLETE = "sources-complete";
+export const SOURCE_WATCH_EVERY_MS = 60 * 60 * 1000;
+
+type Watched = { id: string; dir: string; title: string; watch: { slugs: string[]; armedAt: string; firedAt?: string; fired?: Record<string, unknown>[] }; checkedAt: string | null };
+
+async function watched(): Promise<Watched[]> {
+ const refs = (await projectRefs()).filter((p) => kindMakesTakes(p.kind));
+ const out: Watched[] = [];
+ for (const p of refs) {
+ const has = await stat(path.join(/* turbopackIgnore: true */ p.dir, SOURCE_WATCH_FILE)).then(() => true, () => false);
+ if (!has) continue;
+ const { doc } = await readSourceWatch(p.dir);
+ if (!doc.watch) continue;
+ out.push({ id: p.id, dir: p.dir, title: p.name, watch: doc.watch, checkedAt: doc.last?.checkedAt ?? null });
+ }
+ return out;
+}
+
+const g = globalThis as typeof globalThis & { __umtoolSourceWatch?: Promise<unknown> | null };
+
+/** Read the stale armed watches' backlogs in the background (a page never waits on it). */
+export function kickSourceWatches(list: Watched[], now = Date.now()): void {
+ if (g.__umtoolSourceWatch) return;
+ const stale = list.filter((w) => !w.watch.firedAt && (!w.checkedAt || now - Date.parse(w.checkedAt) >= SOURCE_WATCH_EVERY_MS));
+ if (!stale.length) return;
+ g.__umtoolSourceWatch = (async () => {
+ for (const w of stale) await readBacklog(w.dir).catch(() => null);
+ })()
+ .catch(() => null)
+ .finally(() => {
+ g.__umtoolSourceWatch = null;
+ });
+}
+
+/** The Inbox's `sources-complete` cards (and the stale watches read in the background). */
+export async function sourceWatchDecisions(o: { background?: boolean } = {}): Promise<Decision[]> {
+ const list = await watched();
+ if (o.background !== false && process.env.NEXT_RUNTIME && process.env.UMTOOL_SOURCE_WATCH !== "0") kickSourceWatches(list);
+ return list
+ .filter((w) => w.watch.firedAt)
+ .map(
+ (w) =>
+ ({
+ project: w.id,
+ projectTitle: w.title,
+ piece: `p:${w.id}`,
+ kind: SOURCES_COMPLETE,
+ target: w.watch.slugs.join(", "),
+ why: `the backlog is done — ${(w.watch.fired ?? []).map((r) => backlogWords(r)).join("; ") || w.watch.slugs.join(", ")}: re-sweep the cut's sources`,
+ href: projectHref(w.id, { tab: "overview" }),
+ severity: "open",
+ at: Date.parse(w.watch.firedAt!) || 0,
+ }) as Decision,
+ );
+}
diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs
@@ -21,6 +21,7 @@ export const WHAT = {
"worth-researching": "worth researching",
"refresh-available": "new recordings match",
"refresh-held": "refresh held by the cap",
+ "sources-complete": "sources complete: re-sweep",
"claim-unadjudicated": "claims never ruled",
"claim-incoherent": "claims that don't hold together",
"clip-no-cues": "clips with no cues",
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";
@@ -1560,7 +1560,7 @@ export async function updateRender(dir, patch, { token = null } = {}) {
// into the manifest, and this writer refuses to be a second way to do that.
// ---------------------------------------------------------------------------
-const POST_PATCH_KEYS = ["attachTo", "hide", "thread"];
+const POST_PATCH_KEYS = ["attachTo", "hide", "thread", "shotMaxHeight"];
/**
* A batch of post patches, checked for shape before anything is read: post id
@@ -1568,7 +1568,7 @@ const POST_PATCH_KEYS = ["attachTo", "hide", "thread"];
* `attachTo: ""` is the same as null (a select's "auto").
*
* @param {unknown} posts
- * @returns {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean }>}
+ * @returns {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }>}
*/
export function normalizePostPatches(posts) {
if (!posts || typeof posts !== "object" || Array.isArray(posts)) {
@@ -1576,7 +1576,7 @@ export function normalizePostPatches(posts) {
}
const ids = Object.keys(posts);
if (!ids.length) throw new Error("nothing to change");
- /** @type {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean }>} */
+ /** @type {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }>} */
const out = {};
for (const id of ids) {
const v = /** @type {Record<string, unknown>} */ (posts)[id];
@@ -1585,10 +1585,10 @@ export function normalizePostPatches(posts) {
}
for (const k of Object.keys(v)) {
if (!POST_PATCH_KEYS.includes(k)) {
- throw new Error(`${id}: ${k} is not something this writer changes (only attachTo, hide and thread)`);
+ throw new Error(`${id}: ${k} is not something this writer changes (only attachTo, hide, thread and shotMaxHeight)`);
}
}
- /** @type {{ attachTo?: string | null, hide?: boolean, thread?: boolean }} */
+ /** @type {{ attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }} */
const p = {};
if ("attachTo" in v) {
const a = /** @type {Record<string, unknown>} */ (v).attachTo;
@@ -1606,6 +1606,13 @@ export function normalizePostPatches(posts) {
if (typeof t !== "boolean") throw new Error(`${id}: thread must be true or false`);
p.thread = t;
}
+ // The post's own crop of its screenshot (UI notes item 13): px, or null for none.
+ if ("shotMaxHeight" in v) {
+ const c = /** @type {Record<string, unknown>} */ (v).shotMaxHeight;
+ if (c === null || c === "" || c === undefined) p.shotMaxHeight = null;
+ else if (typeof c === "number" && Number.isInteger(c)) p.shotMaxHeight = c;
+ else throw new Error(`${id}: shotMaxHeight must be a whole number of pixels, or null for no crop`);
+ }
out[id] = p;
}
return out;
@@ -1625,9 +1632,9 @@ export function normalizePostPatches(posts) {
* build's own check, so a manifest this accepts is one the build accepts.
*
* @param {string} dir
- * @param {Record<string, { attachTo?: string | null, hide?: boolean }>} posts
+ * @param {Record<string, { attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }>} posts
* @param {{ token?: string | null }} [opts]
- * @returns {Promise<{ posts: Record<string, { attachTo: string | null, hide: boolean }>, token: string | null }>}
+ * @returns {Promise<{ posts: Record<string, { attachTo: string | null, hide: boolean, thread: boolean, shotMaxHeight: number | null }>, token: string | null }>}
*/
export async function updatePosts(dir, posts, { token = null } = {}) {
const next = normalizePostPatches(posts);
@@ -1660,16 +1667,20 @@ export async function updatePosts(dir, posts, { token = null } = {}) {
if (p.thread) post.thread = true;
else delete post.thread;
}
+ if ("shotMaxHeight" in p) {
+ if (p.shotMaxHeight !== null && p.shotMaxHeight !== undefined) post.shotMaxHeight = p.shotMaxHeight;
+ else delete post.shotMaxHeight;
+ }
}
const errors = validatePosts(manifest.posts, manifest.timeline ?? [], manifest.render);
if (errors.length) throw new PostsRefused(errors);
const nextToken = await writeManifestAtomic(dir, manifest);
- /** @type {Record<string, { attachTo: string | null, hide: boolean, thread: boolean }>} */
+ /** @type {Record<string, { attachTo: string | null, hide: boolean, thread: boolean, shotMaxHeight: number | null }>} */
const saved = {};
for (const id of ids) {
const post = byId.get(id);
- saved[id] = { attachTo: post.attachTo ?? null, hide: post.hide === true, thread: post.thread === true };
+ saved[id] = { attachTo: post.attachTo ?? null, hide: post.hide === true, thread: post.thread === true, shotMaxHeight: Number.isInteger(post.shotMaxHeight) ? post.shotMaxHeight : null };
}
return { posts: saved, token: nextToken };
});
@@ -2354,6 +2365,99 @@ export async function updateLinkPolicy(dir, policy, { token = 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 -- its own undo point, never coalesced -- 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 } = {}) {
+ // EVERY insert its own undo point (no 2-minute coalescing, as Play's place): each is a press.
+ return prepAfter(dir, clipIdOf, sectionWrite(dir, "insert", token, (m) => insertIntoIn(m, spec, where), { snapshotEvery: 0 }));
+}
+
// ---- sections, edited as sections (UI notes 2026-10-30, item 1) -----------
//
// Under the deck a cut's sections are its markers (sectionEdit.mjs): these
@@ -2869,7 +2973,7 @@ export async function writeDraftedField(dir, { entry = null, field, value }, { t
});
}
-const POST_TEXT_KEYS = ["platform", "author", "handle", "date", "text", "url", "shot", "flag", "accent", "logo", "siteChannel", "siteUrl", "postId", "variant"];
+const POST_TEXT_KEYS = ["platform", "author", "handle", "date", "text", "url", "shot", "flag", "accent", "logo", "siteChannel", "siteUrl", "postId", "variant", "shotMaxHeight"];
/**
* Add a post, or replace the one with its id. The value is the post as it
diff --git a/umtool/lib/report/manifest.test.mjs b/umtool/lib/report/manifest.test.mjs
@@ -400,7 +400,7 @@ test("updatePosts: attachTo and hide round trip; null and false delete the key;
try {
const token = await manifestToken(dir);
const res = await updatePosts(dir, { p1: { attachTo: "c02", hide: true }, p2: { attachTo: null, hide: false } }, { token });
- assert.deepEqual(res.posts, { p1: { attachTo: "c02", hide: true, thread: false }, p2: { attachTo: null, hide: false, thread: false } });
+ assert.deepEqual(res.posts, { p1: { attachTo: "c02", hide: true, thread: false, shotMaxHeight: null }, p2: { attachTo: null, hide: false, thread: false, shotMaxHeight: null } });
assert.equal(res.token, await manifestToken(dir));
const raw = await readRaw(dir);
assert.ok(raw.startsWith('{\n "slug"') && raw.endsWith("}\n"), "the CLI's formatting kept");
@@ -429,7 +429,7 @@ test("updatePosts: thread round trips on a post with a shot (false deletes it);
const dir = await project(m0);
try {
const res = await updatePosts(dir, { p1: { thread: true } });
- assert.deepEqual(res.posts.p1, { attachTo: null, hide: false, thread: true });
+ assert.deepEqual(res.posts.p1, { attachTo: null, hide: false, thread: true, shotMaxHeight: null });
assert.equal(post(await read(dir), "p1").thread, true);
// Replaced by a writer that does not name it: kept, as attachTo is.
await upsertPost(dir, { ...m0.posts[0], text: "one, again" });
diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs
@@ -312,6 +312,11 @@ export function applyPostsDraft(posts, draft = {}) {
if (d.thread) out.thread = true;
else delete out.thread;
}
+ // A crop being tried (the Add post panel's), previewed before it is saved.
+ if ("shotMaxHeight" in d) {
+ if (Number.isInteger(d.shotMaxHeight)) out.shotMaxHeight = d.shotMaxHeight;
+ else delete out.shotMaxHeight;
+ }
return out;
});
}
diff --git a/umtool/lib/report/onscreen.test.mjs b/umtool/lib/report/onscreen.test.mjs
@@ -229,7 +229,7 @@ test("applyPostsDraft: the writer's rule, on a copy", () => {
assert.equal(applyPostsDraft(posts, {}), posts);
assert.deepEqual(normalizePostsDraft(undefined), {});
assert.deepEqual(normalizePostsDraft({}), {});
- assert.throws(() => normalizePostsDraft({ p1: { text: "x" } }), /only attachTo, hide and thread/);
+ assert.throws(() => normalizePostsDraft({ p1: { text: "x" } }), /only attachTo, hide, thread and shotMaxHeight/);
});
test("postRows: the automatic clip, the effective one, and the slot in the schedule", () => {
diff --git a/umtool/lib/report/postCards.mjs b/umtool/lib/report/postCards.mjs
@@ -0,0 +1,141 @@
+// POST CARDS FROM PLAY THE CUT (UI notes 2026-10-30, item 13): what the Add
+// post panel reads -- a channel's posts archive searched, each post's
+// warnings from its OWN data -- beside postsCli.mjs's addPostFromArchive (the
+// one write) and the editor's capture-posts (the one capture, paced there).
+//
+// The archive is `channels/<slug>/posts/YYYY-MM.jsonl` (common/lib/posts-server.ts,
+// read only here) and its captures `channels/<slug>/posts-media/<id>/`.
+//
+// THE WARNING is decided from the post's record, never from the picture: a
+// post that QUOTES another (`quoted`), REPOSTS one (`repostOf`) or carries
+// MEDIA (`mediaCount`, a forum's `media`) has a screenshot that shows them --
+// somebody else's words or footage, or a thumbnail -- below its own words.
+// The cure is a crop (`shotMaxHeight` on the post) or another post.
+//
+// Plain ESM.
+import { readFile, readdir, stat } from "node:fs/promises";
+import path from "node:path";
+
+const SLUG_RE = /^[A-Za-z0-9._-]+$/;
+const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+export const POST_SEARCH_MAX = 40;
+
+const who = (ref) => (ref && typeof ref.author === "string" && ref.author ? `@${ref.author.replace(/^@/, "")}` : "another account");
+
+/**
+ * What the post's screenshot carries besides its own words, as sentences
+ * (empty: nothing). From the record only.
+ *
+ * @param {Record<string, any> | null} row an archive row (common/lib/posts.ts Post)
+ * @returns {string[]}
+ */
+export function postWarnings(row) {
+ if (!row || typeof row !== "object") return [];
+ const out = [];
+ if (row.quoted && typeof row.quoted === "object") {
+ out.push(`it quotes a post by ${who(row.quoted)}: the screenshot carries that post (someone else's words, or their video) — crop it to the post's own words, or pick another`);
+ }
+ if (row.repostOf && typeof row.repostOf === "object") {
+ out.push(`it is a repost of ${who(row.repostOf)}: the screenshot is someone else's post`);
+ }
+ const media = Number.isInteger(row.mediaCount) && row.mediaCount > 0 ? row.mediaCount : Array.isArray(row.media) ? row.media.filter((m) => m && m.kind !== "link-card").length : 0;
+ if (media > 0) out.push(`it carries ${media === 1 ? "a picture or video" : `${media} pictures or videos`}: the screenshot shows ${media === 1 ? "its thumbnail" : "their thumbnails"} — crop it if they are not the point`);
+ return out;
+}
+
+/** The date a row was posted, `YYYY-MM-DD…`, or null. */
+const dateOf = (row) =>
+ typeof row?.createdAt === "string" && row.createdAt
+ ? row.createdAt
+ : /^\d{8}$/.test(String(row?.uploadDate ?? ""))
+ ? `${row.uploadDate.slice(0, 4)}-${row.uploadDate.slice(4, 6)}-${row.uploadDate.slice(6, 8)}`
+ : null;
+
+/**
+ * Search channel `slug`'s posts archive: every word of `q` in the post's words
+ * or handle (any case), newest first, at most `limit`; an empty `q` is the
+ * newest posts. Each hit with its warnings, whether its screenshot is captured,
+ * and whether the cut carries it already.
+ *
+ * @param {string} channelsDir
+ * @param {string} slug
+ * @param {string} q
+ * @param {{ limit?: number, manifest?: Record<string, any> | null }} [o]
+ */
+export async function searchPostArchive(channelsDir, slug, q, { limit = POST_SEARCH_MAX, manifest = null } = {}) {
+ if (!SLUG_RE.test(slug)) throw new Error(`not a channel slug: ${slug}`);
+ const dir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "posts");
+ const names = (await readdir(dir).catch(() => null))?.filter((n) => /^\d{4}-\d{2}\.jsonl$/.test(n)).sort().reverse() ?? null;
+ if (names === null) return { slug, archive: false, hits: [], total: 0 };
+ const words = String(q ?? "").toLowerCase().split(/\s+/).filter(Boolean);
+ const byId = new Map();
+ for (const name of names) {
+ const text = await readFile(path.join(dir, name), "utf8").catch(() => "");
+ for (const line of text.split("\n")) {
+ if (!line.trim()) continue;
+ let row;
+ try {
+ row = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (!row || !POST_ID_RE.test(String(row.id ?? ""))) continue;
+ byId.set(String(row.id), row); // a re-fetch appends: the last line wins
+ }
+ }
+ const hay = (row) => `${row.text ?? ""} ${row.author ?? ""} ${row.authorName ?? ""}`.toLowerCase();
+ const matched = [...byId.values()].filter((row) => !row.isDeleted && words.every((w) => hay(row).includes(w)));
+ matched.sort((a, b) => String(dateOf(b) ?? "").localeCompare(String(dateOf(a) ?? "")));
+ const inCut = new Set(
+ (Array.isArray(manifest?.posts) ? manifest.posts : []).flatMap((p) => [p?.postId, typeof p?.id === "string" ? p.id.replace(/^(x|bsky|post)-/, "") : null]).filter(Boolean),
+ );
+ const media = path.join(/* turbopackIgnore: true */ channelsDir, slug, "posts-media");
+ const hits = await Promise.all(
+ matched.slice(0, limit).map(async (row) => {
+ const id = String(row.id);
+ const shot = await stat(path.join(media, id, "shot.png")).then(() => true, () => false);
+ return {
+ id,
+ date: dateOf(row),
+ author: typeof row.author === "string" ? row.author : null,
+ authorName: typeof row.authorName === "string" ? row.authorName : null,
+ text: typeof row.text === "string" ? row.text : "",
+ url: typeof row.url === "string" ? row.url : null,
+ platform: typeof row.platform === "string" ? row.platform : null,
+ quoted: row.quoted && typeof row.quoted === "object" ? { author: row.quoted.author ?? null, url: row.quoted.url ?? null } : null,
+ mediaCount: Number.isInteger(row.mediaCount) ? row.mediaCount : Array.isArray(row.media) ? row.media.length : 0,
+ warnings: postWarnings(row),
+ captured: shot,
+ inCut: inCut.has(id),
+ };
+ }),
+ );
+ return { slug, archive: true, hits, total: matched.length };
+}
+
+/**
+ * The channels with a posts archive, the ones this cut is likeliest to want
+ * first: those its posts already come from (`siteChannel`, a shot's
+ * `posts-media/<slug>/`), then those named like a channel it cites
+ * (`emberparadox-x` for `emberparadox`), then the rest by name.
+ *
+ * @param {string} channelsDir
+ * @param {Record<string, any> | null} manifest
+ * @param {string[]} cited the channels the cut's clips cite
+ */
+export async function postChannels(channelsDir, manifest, cited = []) {
+ const dirs = await readdir(/* turbopackIgnore: true */ channelsDir, { withFileTypes: true }).catch(() => []);
+ const have = [];
+ for (const d of dirs) {
+ if (!d.isDirectory() || !SLUG_RE.test(d.name)) continue;
+ if (await stat(path.join(/* turbopackIgnore: true */ channelsDir, d.name, "posts")).then((s) => s.isDirectory(), () => false)) have.push(d.name);
+ }
+ const used = new Set(
+ (Array.isArray(manifest?.posts) ? manifest.posts : []).flatMap((p) => [
+ typeof p?.siteChannel === "string" ? p.siteChannel : null,
+ typeof p?.shot === "string" ? (/^posts-media\/([^/]+)\//.exec(p.shot)?.[1] ?? null) : null,
+ ]),
+ );
+ const rank = (s) => (used.has(s) ? 0 : cited.some((c) => s.startsWith(`${c}-`) || s === c) ? 1 : 2);
+ return have.sort((a, b) => rank(a) - rank(b) || a.localeCompare(b)).map((slug) => ({ slug, suggested: rank(slug) < 2 }));
+}
diff --git a/umtool/lib/report/postCards.test.mjs b/umtool/lib/report/postCards.test.mjs
@@ -0,0 +1,78 @@
+// Post cards from Play the cut (UI notes item 13): the WARNING from a post's
+// own data (a quoted post, a repost, media), the archive searched (every word,
+// newest first, the last line of a re-fetch winning, captured and in-the-cut
+// said), the channels offered, and a post's own crop -- `posts set crop=`, the
+// writer, the build's check and the card's drawing (its top, never panned).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { validatePosts } from "umtool-report-to-video/deck";
+import { postChannels, postWarnings, searchPostArchive } from "./postCards.mjs";
+import { postPatchOf } from "./postsCli.mjs";
+import { MANIFEST_NAME, normalizePostPatches, updatePosts } from "./manifest.mjs";
+import { readFile } from "node:fs/promises";
+
+const row = (id, text, extra = {}) => ({ id, slug: "chan-x", channelSlug: "chan-x", author: "somebody", createdAt: `2026-10-${String(10 + Number(id.slice(-1))).padStart(2, "0")}T12:00:00Z`, text, url: `https://x.com/somebody/status/${id}`, platform: "twitter", isReply: false, isRepost: false, links: [], ...extra });
+
+test("the warning is the post's own data: a quoted post, a repost, media; none for words alone", () => {
+ assert.deepEqual(postWarnings(row("1001", "just words")), []);
+ const q = postWarnings(row("1002", "look at this", { quoted: { platform: "twitter", id: "9", author: "other" } }));
+ assert.equal(q.length, 1);
+ assert.match(q[0], /quotes a post by @other/);
+ assert.match(postWarnings(row("1003", "pic", { mediaCount: 2 }))[0], /2 pictures or videos/);
+ assert.match(postWarnings(row("1004", "rt", { repostOf: { platform: "twitter", id: "8", author: "x" } }))[0], /repost of @x/);
+ assert.deepEqual(postWarnings(null), []);
+});
+
+async function corpus() {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-posts-"));
+ const posts = path.join(dir, "chan-x", "posts");
+ await mkdir(posts, { recursive: true });
+ await writeFile(
+ path.join(posts, "2026-10.jsonl"),
+ [row("1001", "the voice changer again"), row("1002", "Voice reveal soon", { quoted: { platform: "twitter", id: "9", author: "other" } }), row("1003", "pictures", { mediaCount: 1 }), row("1001", "the voice changer again (edited)")].map((r) => JSON.stringify(r)).join("\n") + "\n{torn",
+ );
+ await mkdir(path.join(dir, "chan-x", "posts-media", "1002"), { recursive: true });
+ await writeFile(path.join(dir, "chan-x", "posts-media", "1002", "shot.png"), "png");
+ await mkdir(path.join(dir, "chan"), { recursive: true });
+ await mkdir(path.join(dir, "zeta-x", "posts"), { recursive: true });
+ return dir;
+}
+
+test("the archive searched: every word, any case, newest first; captured and in-the-cut said; the last line wins", async () => {
+ const dir = await corpus();
+ const r = await searchPostArchive(dir, "chan-x", "VOICE", { manifest: { posts: [{ id: "x-1002" }] } });
+ assert.deepEqual(r.hits.map((h) => h.id), ["1002", "1001"]);
+ assert.equal(r.hits[0].captured, true);
+ assert.equal(r.hits[0].inCut, true);
+ assert.equal(r.hits[0].warnings.length, 1);
+ assert.equal(r.hits[1].text, "the voice changer again (edited)");
+ assert.equal(r.hits[1].captured, false);
+ assert.equal((await searchPostArchive(dir, "chan-x", "")).total, 3);
+ assert.equal((await searchPostArchive(dir, "chan", "")).archive, false);
+ assert.deepEqual(await postChannels(dir, { posts: [] }, ["chan"]), [{ slug: "chan-x", suggested: true }, { slug: "zeta-x", suggested: false }]);
+});
+
+test("a post's own crop: posts set crop=, the patch writer, the build's check (a shot needed, 120–1080)", async () => {
+ assert.deepEqual(postPatchOf(["crop=420"]), { shotMaxHeight: 420 });
+ assert.deepEqual(postPatchOf(["crop=off"]), { shotMaxHeight: null });
+ assert.throws(() => postPatchOf(["crop=big"]), /whole number/);
+ assert.deepEqual(normalizePostPatches({ a: { shotMaxHeight: 300 } }), { a: { shotMaxHeight: 300 } });
+ assert.throws(() => normalizePostPatches({ a: { shotMaxHeight: "300" } }), /whole number/);
+ const post = { id: "x-1", platform: "x", date: "2026-10-01", text: "t", url: "https://x.com/a/status/1", shot: "posts-media/c/1/shot.png" };
+ assert.deepEqual(validatePosts([{ ...post, shotMaxHeight: 400 }], []), []);
+ assert.match(validatePosts([{ ...post, shotMaxHeight: 50 }], []).join(), /120 to 1080/);
+ assert.match(validatePosts([{ ...post, shot: undefined, shotMaxHeight: 400 }], []).join(), /has no shot/);
+
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-crop-"));
+ await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify({ slug: "s", timeline: [{ type: "clip", id: "c1", video: "v", start: 0, end: 2 }], posts: [post] }));
+ const r = await updatePosts(dir, { "x-1": { shotMaxHeight: 360 } });
+ assert.equal(r.posts["x-1"].shotMaxHeight, 360);
+ assert.equal(JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")).posts[0].shotMaxHeight, 360);
+ await updatePosts(dir, { "x-1": { shotMaxHeight: null } });
+ assert.equal("shotMaxHeight" in JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")).posts[0], false, "null removes the key");
+});
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -34,11 +34,12 @@ import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { channelsDirFor, readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
import { PostsRefused, StaleToken, StructureRefused, manifestToken, updatePosts, upsertPost } from "./manifest.mjs";
+import { postWarnings } from "./postCards.mjs";
export const POSTS_USAGE = [
"usage: umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID]",
- " [--thread] [--dry-run] [--json]",
- " umtool posts set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] [--json]",
+ " [--thread] [--crop <px>] [--dry-run] [--json]",
+ " umtool posts set <project> <post> thread=on|off [hide=on|off] [attach=<clipId>|auto] [crop=<px>|off] [--json]",
" a post card from the corpus's posts archive (channels/<slug>/posts/*.jsonl): its words, date, link and handle,",
" and its screenshot (channels/<slug>/posts-media/<postId>/shot.png) copied into the project's posts-media/.",
" The id is x-<postId> (bsky-, post-) unless --id; --attach pins it to a clip; --author overrides the name",
@@ -47,9 +48,11 @@ export const POSTS_USAGE = [
" --thread (or `set … thread=on`): a reply drawn with the post it answers above it -- the capture's",
" shot-thread.png beside shot.png (capture-posts with \"thread\": true takes it); its own shot while there is none.",
" set: <post> is the manifest's post id (x-<postId>) or the bare <postId>; the Posts table's writer.",
+ " --crop / crop=<px>: the post's own crop of its screenshot (shotMaxHeight, 120-1080): its top that tall, never panned.",
+ " A post that quotes another or carries media is added with a WARNING: its screenshot shows them (the post's own data says so).",
].join("\n");
-const VALUED = new Set(["--attach", "--flag", "--author", "--id"]);
+const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -144,10 +147,10 @@ const OFF = new Set(["off", "false", "no", "0"]);
* `hide=on|off`, `attach=<clipId>|auto`. Throws on anything else.
*
* @param {string[]} pairs
- * @returns {{ attachTo?: string | null, hide?: boolean, thread?: boolean }}
+ * @returns {{ attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }}
*/
export function postPatchOf(pairs) {
- /** @type {{ attachTo?: string | null, hide?: boolean, thread?: boolean }} */
+ /** @type {{ attachTo?: string | null, hide?: boolean, thread?: boolean, shotMaxHeight?: number | null }} */
const out = {};
for (const pair of pairs) {
const eq = pair.indexOf("=");
@@ -157,12 +160,17 @@ export function postPatchOf(pairs) {
if (ON.has(v)) out[k] = true;
else if (OFF.has(v)) out[k] = false;
else throw new CliError(`${k}= takes on or off, not ${JSON.stringify(v)}`);
+ } else if (k === "crop") {
+ // The post's own crop of its screenshot: its top that many px, never panned.
+ if (OFF.has(v) || v === "none") out.shotMaxHeight = null;
+ else if (/^\d+$/.test(v)) out.shotMaxHeight = Number(v);
+ else throw new CliError(`crop= takes a whole number of pixels, or off (got ${JSON.stringify(v)})`);
} else if (k === "attach") {
if (!v) throw new CliError("attach= takes a clip id, or auto");
out.attachTo = v === "auto" ? null : pair.slice(eq + 1);
- } else throw new CliError(`${pair}: not a post knob (thread=, hide=, attach=)`);
+ } else throw new CliError(`${pair}: not a post knob (thread=, hide=, attach=, crop=)`);
}
- if (!Object.keys(out).length) throw new CliError("nothing to set: thread=on|off, hide=on|off or attach=<clipId>|auto");
+ if (!Object.keys(out).length) throw new CliError("nothing to set: thread=on|off, hide=on|off, attach=<clipId>|auto or crop=<px>|off");
return out;
}
@@ -229,6 +237,63 @@ const sameFile = async (a, b) => {
};
/**
+ * ADD A POST CARD from the archive -- `posts add`'s whole write, which the
+ * Add post panel (Play the cut, /api/report/post-cards) runs too: the archive's
+ * row, its screenshot required, the entry (postEntryOf, `crop` its
+ * shotMaxHeight), the capture copied into the project (never through a link
+ * out of it), then upsertPost under the generated-manifest guard. Answers what
+ * was written and the WARNINGS the post's own data gives (postWarnings: a
+ * quoted post, a media thumbnail in the screenshot). `dryRun`: nothing written.
+ *
+ * @param {{ id: string, dir: string, kind?: string }} project
+ * @param {{ slug: string, postId: string, attach?: string | null, flag?: string | null, author?: string | null, id?: string | null, thread?: boolean, crop?: number | null, dryRun?: boolean }} o
+ */
+export async function addPostFromArchive(project, { slug, postId, attach = null, flag = null, author = null, id = null, thread = false, crop = null, dryRun = false }) {
+ if (!SLUG_RE.test(slug) || !POST_ID_RE.test(postId)) throw new CliError(`not <archive-channel>/<postId>: ${slug}/${postId}`);
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ // The corpus the project reads (provenance.channelsDir), else the global one.
+ const channelsDir = channelsDirFor(project.dir, manifest);
+ const found = await findPostRow(channelsDir, slug, postId);
+ if (!found.row) {
+ throw new Error(
+ found.shards
+ ? `${slug} has no post ${postId} in its archive (${found.shards} shard(s) read under ${path.join(channelsDir, slug, "posts")})`
+ : `${slug} has no posts archive under ${channelsDir} — is it a social channel?`,
+ );
+ }
+ const shotFrom = path.join(channelsDir, slug, "posts-media", postId, "shot.png");
+ if (!(await stat(shotFrom).catch(() => null))) {
+ throw new Error(
+ `${slug}/${postId} has no screenshot (${shotFrom}) — capture it first:\n` +
+ ` pnpm ops capture-posts --json '${JSON.stringify({ slug, ids: [postId] })}'`,
+ );
+ }
+ if (attach && !(manifest.timeline ?? []).some((e) => e?.type === "clip" && e.id === attach)) {
+ throw new CliError(`--attach ${attach}: no clip with that id in ${project.id}`);
+ }
+ const post = postEntryOf(found.row, { slug, postId, manifest, attach, flag, author, id, thread });
+ if (crop !== null && crop !== undefined) post.shotMaxHeight = crop;
+ const warnings = postWarnings(found.row);
+ // A thread shot asked for and not taken: the card draws its own shot until a capture takes one.
+ const threadFrom = path.join(path.dirname(shotFrom), "shot-thread.png");
+ const threadMissing = thread && !(await stat(threadFrom).catch(() => null));
+ const shotTo = path.join(project.dir, ...post.shot.split("/"));
+ if (dryRun) return { post, shard: found.shard, shotFrom, shotTo, warnings, found };
+ // The pictures first: a post whose `shot` names a file not there would build a broken card.
+ // Never THROUGH a link out of the project: a cut whose posts-media/<slug> links the
+ // channel's own captures (the Huck cut's do) already has them, and a link anywhere
+ // else would make this copy a write into somebody else's tree.
+ const where = await shotHome(project.dir, path.dirname(shotTo), path.dirname(path.dirname(shotFrom)));
+ if (where === "elsewhere") {
+ throw new Error(`${path.relative(project.dir, path.dirname(shotTo))} leads out of ${project.id} (a link) — not copying through it`);
+ }
+ const copied = where === "linked" ? [] : await copyCapture(path.dirname(shotFrom), path.dirname(shotTo));
+ const { result, editNotes } = await withEditNotes(project, async () => upsertPost(project.dir, post, { token: await manifestToken(project.dir) }));
+ return { post, result, editNotes, found, shotFrom, shotTo, where, copied, threadMissing, warnings };
+}
+
+/**
* @param {string[]} args the words after `posts`
* @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
* @returns {Promise<number>} the exit code
@@ -267,58 +332,35 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
if (!r.project) throw new CliError(`no project matches "${projectArg}"`);
const project = r.project;
- const manifest = await readManifest(project.dir);
- if (!manifest) throw new CliError(`${project.id} has no manifest`);
- // The corpus the project reads (provenance.channelsDir), else the global one.
- const channelsDir = channelsDirFor(project.dir, manifest);
- const found = await findPostRow(channelsDir, slug, postId);
- if (!found.row) {
- throw new Error(
- found.shards
- ? `${slug} has no post ${postId} in its archive (${found.shards} shard(s) read under ${path.join(channelsDir, slug, "posts")})`
- : `${slug} has no posts archive under ${channelsDir} — is it a social channel?`,
- );
- }
- const shotFrom = path.join(channelsDir, slug, "posts-media", postId, "shot.png");
- if (!(await stat(shotFrom).catch(() => null))) {
- throw new Error(
- `${slug}/${postId} has no screenshot (${shotFrom}) — capture it first:\n` +
- ` pnpm ops capture-posts --json '${JSON.stringify({ slug, ids: [postId] })}'`,
- );
- }
- const attach = str("--attach");
- if (attach && !(manifest.timeline ?? []).some((e) => e?.type === "clip" && e.id === attach)) {
- throw new CliError(`--attach ${attach}: no clip with that id in ${project.id}`);
- }
const thread = flags.has("--thread");
- const post = postEntryOf(found.row, { slug, postId, manifest, attach, flag: str("--flag"), author: str("--author"), id: str("--id"), thread });
- // A thread shot asked for and not taken: the card draws its own shot until a capture takes one.
- const threadFrom = path.join(path.dirname(shotFrom), "shot-thread.png");
- const threadMissing = thread && !(await stat(threadFrom).catch(() => null));
- const shotTo = path.join(project.dir, ...post.shot.split("/"));
+ const cropRaw = str("--crop");
+ const crop = cropRaw === null ? null : Number(cropRaw);
+ if (cropRaw !== null && !Number.isInteger(crop)) throw new CliError(`--crop takes a whole number of pixels (got ${cropRaw})`);
+ const added = await addPostFromArchive(project, {
+ slug,
+ postId,
+ attach: str("--attach"),
+ flag: str("--flag"),
+ author: str("--author"),
+ id: str("--id"),
+ thread,
+ crop,
+ dryRun,
+ });
if (dryRun) {
- out(json ? JSON.stringify({ ok: true, dryRun: true, post, shard: found.shard, shotFrom, shotTo }, null, 2) : `would add ${post.id} (${found.shard}):\n${JSON.stringify(post, null, 2)}\n shot ${shotFrom} -> ${shotTo}`);
+ const { post, shard, shotFrom, shotTo } = added;
+ out(json ? JSON.stringify({ ok: true, dryRun: true, post, shard, shotFrom, shotTo, warnings: added.warnings }, null, 2) : `would add ${post.id} (${shard}):\n${JSON.stringify(post, null, 2)}\n shot ${shotFrom} -> ${shotTo}${added.warnings.map((w) => `\n WARNING: ${w}`).join("")}`);
return 0;
}
- // The pictures first: a post whose `shot` names a file not there would build a broken card.
- // Never THROUGH a link out of the project: a cut whose posts-media/<slug> links the
- // channel's own captures (the Huck cut's do) already has them, and a link anywhere
- // else would make this copy a write into somebody else's tree.
- const where = await shotHome(project.dir, path.dirname(shotTo), path.dirname(path.dirname(shotFrom)));
- if (where === "elsewhere") {
- throw new Error(`${path.relative(project.dir, path.dirname(shotTo))} leads out of ${project.id} (a link) — not copying through it`);
- }
- const copied = where === "linked" ? [] : await copyCapture(path.dirname(shotFrom), path.dirname(shotTo));
- const { result, editNotes } = await withEditNotes(project, async () =>
- upsertPost(project.dir, post, { token: await manifestToken(project.dir) }),
- );
+ const { result, editNotes, found, shotFrom, shotTo, where, copied, threadMissing, warnings } = added;
if (json) {
- out(JSON.stringify({ ok: true, ...result, shard: found.shard, shot: { from: shotFrom, to: shotTo, via: where }, copied, ...(thread ? { threadShot: !threadMissing } : {}), editNotes }, null, 2));
+ out(JSON.stringify({ ok: true, ...result, shard: found.shard, shot: { from: shotFrom, to: shotTo, via: where }, copied, ...(thread ? { threadShot: !threadMissing } : {}), warnings, editNotes }, null, 2));
return 0;
}
out(`${result.created ? "added" : "replaced"} post ${result.post.id}${result.post.attachTo ? ` -> ${result.post.attachTo}` : ""} ${result.post.date}`);
out(` ${result.post.author ?? ""}${result.post.handle ? ` @${result.post.handle}` : ""}: ${result.post.text.split("\n")[0].slice(0, 100)}`);
- out(` shot ${result.post.shot}${where === "linked" ? " (posts-media links the channel's captures)" : copied.length ? ` (copied: ${copied.join(", ")})` : " (already there)"}`);
+ out(` shot ${result.post.shot}${where === "linked" ? " (posts-media links the channel's captures)" : copied.length ? ` (copied: ${copied.join(", ")})` : " (already there)"}${result.post.shotMaxHeight ? `, cropped to its top ${result.post.shotMaxHeight} px` : ""}`);
+ for (const w of warnings) out(` WARNING: ${w}`);
if (threadMissing) {
out(
` thread: no shot-thread.png yet -- its own shot is drawn until one is taken:\n` +
@@ -377,7 +419,7 @@ async function setCommand(projectArg, ref, pairs, { root, json, out }) {
out(JSON.stringify({ ok: true, id, post: saved, ...(threadThere === null ? {} : { threadShot: threadThere }), token: result.token, editNotes }, null, 2));
return 0;
}
- out(`set ${id}: thread ${saved.thread ? "on" : "off"}, ${saved.hide ? "hidden" : "shown"}, rides on ${saved.attachTo ?? "auto"}`);
+ out(`set ${id}: thread ${saved.thread ? "on" : "off"}, ${saved.hide ? "hidden" : "shown"}, rides on ${saved.attachTo ?? "auto"}${saved.shotMaxHeight ? `, cropped to its top ${saved.shotMaxHeight} px` : ""}`);
if (threadThere === false) out(" no shot-thread.png beside its shot yet -- its own shot is drawn (capture-posts with \"thread\": true)");
if (editNotes) out(` edit noted for ${editNotes.generatedBy}`);
return 0;
diff --git a/umtool/lib/report/postsCli.test.mjs b/umtool/lib/report/postsCli.test.mjs
@@ -207,7 +207,7 @@ test("posts set: the Posts table's writer -- thread on/off by the post's id or i
assert.equal(await run("set", "set", XID, "thread=on", "--json"), 0);
const on = JSON.parse(lines.at(-1));
assert.equal(on.id, `x-${XID}`);
- assert.deepEqual(on.post, { attachTo: null, hide: false, thread: true });
+ assert.deepEqual(on.post, { attachTo: null, hide: false, thread: true, shotMaxHeight: null });
assert.equal(on.threadShot, false, "no thread shot beside its shot: its own is drawn");
assert.equal((await read(dir)).posts.find((p) => p.id === `x-${XID}`).thread, true);
assert.equal(await run("set", "set", `x-${XID}`, "thread=off", "hide=on", "attach=c01"), 0);
diff --git a/umtool/lib/report/sourceBacklog.mjs b/umtool/lib/report/sourceBacklog.mjs
@@ -0,0 +1,239 @@
+// THE SOURCE BACKLOG on a report video's page (UI notes 2026-10-30, item 16):
+// for each channel the cut cites, how much of it the archive holds and has
+// transcribed -- "Sources: emberparadox 1,454/2,798 transcribed · Prioritize"
+// -- read from the EDITOR (`GET /api/ops/channel/<slug>`: its snapshot's
+// totals and bucket sizes, never a walk of the disk), and a watch that tells
+// the operator when that backlog is done ("Re-sweep when complete").
+//
+// PRIORITIZE never writes settings: it asks the editor's own
+// `POST /api/ops/channel-priority {focus: {kind: "channels", slugs}}` -- the
+// focus every lane leads with -- with the channels already in focus kept
+// (the focus is ONE list; a site focus is not replaced from here).
+//
+// THE WATCH, umtool's own state beside the project, in lib/lifecycle.mjs's
+// discipline (one writer serialised in-process, whole file temp + rename, an
+// unreadable file never overwritten):
+//
+// <project>/source-watch.json
+// { format: "umtool-source-watch", version: 1,
+// watch: { slugs, armedAt, firedAt?, fired?: [rows] } | null,
+// last?: { checkedAt, rows: [{ slug, listed, held, transcribed, undownloaded, untranscribed, done }] } }
+//
+// While a watch is armed, every read of the backlog (the page's, and the
+// Inbox's background check, lib/inbox/sourceWatch.ts) records what it saw
+// (no file is made for a project with no watch); the first read in which
+// every watched channel is done FIRES the watch, once: the Inbox raises a
+// `sources-complete` card (Re-sweep) until the operator clears or re-arms it.
+//
+// Plain ESM.
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { channelFor, clipsOf } from "../projects/report.mjs";
+
+export const SOURCE_WATCH_FILE = "source-watch.json";
+export const SOURCE_WATCH_FORMAT = "umtool-source-watch";
+const SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/i;
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+
+export class SourceWatchError extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.name = "SourceWatchError";
+ this.status = status;
+ }
+}
+
+/**
+ * The channels the cut cites, as the editor knows them (a clip's
+ * `siteChannel` -- the archive's slug, the Rumble case -- else its channel,
+ * else the cut's provenance channel), with how many clips cite each. Clips
+ * that carry their own media (`src`) cite no channel.
+ *
+ * @param {Record<string, any>} manifest
+ * @returns {Array<{ slug: string, clips: number }>}
+ */
+export function citedChannels(manifest) {
+ const n = new Map();
+ for (const e of clipsOf(manifest)) {
+ if (e.src != null) continue;
+ const slug = typeof e.siteChannel === "string" && e.siteChannel ? e.siteChannel : channelFor(manifest, e);
+ if (typeof slug !== "string" || !SLUG_RE.test(slug)) continue;
+ n.set(slug, (n.get(slug) ?? 0) + 1);
+ }
+ return [...n.entries()].map(([slug, clips]) => ({ slug, clips })).sort((a, b) => b.clips - a.clips || a.slug.localeCompare(b.slug));
+}
+
+const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : null);
+
+/**
+ * One channel's backlog from the editor's `GET /api/ops/channel/<slug>`
+ * answer: `listed` (on disk + not yet), `held` (a video directory),
+ * `downloaded` (its media), `transcribed`, the two backlogs, and `done` --
+ * nothing listed left to download and nothing held left to transcribe. A
+ * channel the editor has no report for answers nulls and is never `done`.
+ *
+ * @param {string} slug
+ * @param {any} r the route's JSON
+ */
+export function backlogOf(slug, r) {
+ const rep = isObj(r?.report) ? r.report : null;
+ const totals = isObj(rep?.totals) ? rep.totals : {};
+ const held = num(totals.videos);
+ const transcribed = num(totals.transcribed);
+ const downloaded = num(totals.downloaded);
+ const undownloaded = num(rep?.undownloaded);
+ const untranscribed = num(rep?.buckets?.downloadedNoTranscript);
+ const listed = held !== null && undownloaded !== null ? held + undownloaded : num(r?.counts?.playlistCount);
+ const done = held !== null && undownloaded === 0 && untranscribed === 0;
+ return {
+ slug,
+ name: typeof r?.config?.name === "string" ? r.config.name : null,
+ listed,
+ held,
+ downloaded,
+ transcribed,
+ undownloaded,
+ untranscribed,
+ done,
+ tier: typeof r?.priority?.tier === "string" ? r.priority.tier : null,
+ generatedAt: typeof rep?.generatedAt === "string" ? rep.generatedAt : null,
+ mediaStatus: typeof r?.media?.status === "string" ? r.media.status : null,
+ };
+}
+
+/**
+ * The focus body that adds `slugs` to what is in focus now (`focus` as
+ * `settings.channelPriority.focus` reads), or a refusal in words: a site's
+ * focus is the editor's to change.
+ *
+ * @param {any} focus
+ * @param {string[]} slugs
+ */
+export function focusBodyFor(focus, slugs) {
+ const want = [...new Set(slugs.filter((s) => typeof s === "string" && SLUG_RE.test(s)))];
+ if (!want.length) throw new SourceWatchError("name the channels to prioritize");
+ if (isObj(focus) && focus.kind === "site") {
+ throw new SourceWatchError(`the editor's focus is the site "${focus.siteId}" — change it on the editor's Channels page; Prioritize adds channels to a channel focus`, 409);
+ }
+ const had = isObj(focus) && focus.kind === "channels" && Array.isArray(focus.slugs) ? focus.slugs.filter((s) => typeof s === "string") : [];
+ const slugsOut = [...new Set([...had, ...want])];
+ return { body: { focus: { kind: "channels", slugs: slugsOut } }, added: want.filter((s) => !had.includes(s)), already: want.filter((s) => had.includes(s)) };
+}
+
+/** Which slugs are in focus now. */
+export const focusedOf = (focus) => (isObj(focus) && focus.kind === "channels" && Array.isArray(focus.slugs) ? focus.slugs.filter((s) => typeof s === "string") : []);
+
+// ---- the watch ----------------------------------------------------------------
+
+export const sourceWatchFile = (dir) => path.join(/* turbopackIgnore: true */ dir, SOURCE_WATCH_FILE);
+
+const rowOf = (r) =>
+ isObj(r) && typeof r.slug === "string"
+ ? { slug: r.slug, listed: num(r.listed), held: num(r.held), transcribed: num(r.transcribed), undownloaded: num(r.undownloaded), untranscribed: num(r.untranscribed), done: r.done === true }
+ : null;
+
+/** `{ doc: { watch, last }, error? }` -- missing is empty; unreadable is empty with `error`. */
+export async function readSourceWatch(dir) {
+ const empty = { watch: null, last: null };
+ let raw;
+ try {
+ raw = await readFile(/* turbopackIgnore: true */ sourceWatchFile(dir), "utf8");
+ } catch (err) {
+ if (err?.code === "ENOENT") return { doc: empty };
+ return { doc: empty, error: `${SOURCE_WATCH_FILE} cannot be read: ${err?.message ?? err}` };
+ }
+ let j;
+ try {
+ j = JSON.parse(raw);
+ } catch (err) {
+ return { doc: empty, error: `${SOURCE_WATCH_FILE} is not JSON: ${err.message}` };
+ }
+ if (!isObj(j) || j.format !== SOURCE_WATCH_FORMAT) return { doc: empty, error: `${SOURCE_WATCH_FILE} is not a ${SOURCE_WATCH_FORMAT} file` };
+ const w = isObj(j.watch) && Array.isArray(j.watch.slugs) ? j.watch : null;
+ const watch = w
+ ? {
+ slugs: w.slugs.filter((s) => typeof s === "string"),
+ armedAt: typeof w.armedAt === "string" ? w.armedAt : "",
+ ...(typeof w.firedAt === "string" ? { firedAt: w.firedAt, fired: Array.isArray(w.fired) ? w.fired.map(rowOf).filter(Boolean) : [] } : {}),
+ }
+ : null;
+ const last = isObj(j.last) && typeof j.last.checkedAt === "string" && Array.isArray(j.last.rows) ? { checkedAt: j.last.checkedAt, rows: j.last.rows.map(rowOf).filter(Boolean) } : null;
+ return { doc: { watch, last } };
+}
+
+let chain = Promise.resolve();
+
+function writeSourceWatch(dir, mutate) {
+ const run = chain.then(async () => {
+ const file = sourceWatchFile(dir);
+ const read = await readSourceWatch(dir);
+ if (read.error) throw new SourceWatchError(`${read.error}; fix or remove ${file} first`, 409);
+ const doc = read.doc;
+ const result = mutate(doc);
+ const out = { format: SOURCE_WATCH_FORMAT, version: 1, watch: doc.watch, ...(doc.last ? { last: doc.last } : {}) };
+ 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, doc: out };
+ });
+ chain = run.catch(() => {});
+ return run;
+}
+
+/** ARM: tell me when these channels' backlog is done (a new watch replaces the old, fired or not). */
+export function armSourceWatch(dir, slugs, { now = null } = {}) {
+ const want = [...new Set((slugs ?? []).filter((s) => typeof s === "string" && SLUG_RE.test(s)))];
+ if (!want.length) return Promise.reject(new SourceWatchError("the cut cites no channel to watch"));
+ return writeSourceWatch(dir, (doc) => {
+ doc.watch = { slugs: want, armedAt: now ?? new Date().toISOString() };
+ return { armed: want };
+ });
+}
+
+/** CLEAR: no watch (the card goes); what was last seen stays. */
+export function clearSourceWatch(dir) {
+ return writeSourceWatch(dir, (doc) => {
+ const had = doc.watch;
+ doc.watch = null;
+ return { cleared: !!had };
+ });
+}
+
+/**
+ * RECORD what a read of the backlog saw. A watch not yet fired FIRES when
+ * every one of its channels was read and is done -- once; answers `{ fired }`.
+ *
+ * @param {string} dir
+ * @param {ReturnType<typeof backlogOf>[]} rows
+ */
+export function recordSourceCheck(dir, rows, { now = null } = {}) {
+ const stamp = now ?? new Date().toISOString();
+ return writeSourceWatch(dir, (doc) => {
+ const kept = rows.map(rowOf).filter(Boolean);
+ doc.last = { checkedAt: stamp, rows: kept };
+ const w = doc.watch;
+ if (!w || w.firedAt) return { fired: false };
+ const by = new Map(kept.map((r) => [r.slug, r]));
+ const all = w.slugs.length > 0 && w.slugs.every((s) => by.get(s)?.done === true);
+ if (!all) return { fired: false };
+ w.firedAt = stamp;
+ w.fired = w.slugs.map((s) => by.get(s));
+ return { fired: true };
+ });
+}
+
+/** "1,454" */
+export const thousands = (n) => (typeof n === "number" ? n.toLocaleString("en-US") : "?");
+
+/** The line for one channel: `emberparadox 1,454/2,798 transcribed · 2,751 held`. */
+export function backlogWords(r) {
+ if (r.error) return `${r.slug}: ${r.error}`;
+ if (r.held === null) return `${r.slug}: no report yet`;
+ return `${r.slug} ${thousands(r.transcribed)}/${thousands(r.listed ?? r.held)} transcribed · ${thousands(r.held)} held${r.done ? " · complete" : ""}`;
+}
diff --git a/umtool/lib/report/sourceBacklog.test.mjs b/umtool/lib/report/sourceBacklog.test.mjs
@@ -0,0 +1,78 @@
+// The source backlog (UI notes item 16): the channels a cut cites (the
+// archive's slug first), one channel's counts from the editor's snapshot
+// answer, Prioritize's focus body (the channels in focus kept; a site focus
+// refused), and the watch -- armed, recorded, FIRED once when every watched
+// channel is done, an unreadable file never overwritten.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { SOURCE_WATCH_FILE, armSourceWatch, backlogOf, backlogWords, citedChannels, clearSourceWatch, focusBodyFor, readSourceWatch, recordSourceCheck } from "./sourceBacklog.mjs";
+
+const answer = ({ videos = 2751, transcribed = 1454, downloaded = 2700, undownloaded = 47, untranscribed = 1297 } = {}) => ({
+ ok: true,
+ config: { name: "Some Streamer" },
+ priority: { tier: "normal" },
+ report: { generatedAt: "2026-11-01T00:00:00Z", totals: { videos, transcribed, downloaded }, buckets: { downloadedNoTranscript: untranscribed }, undownloaded },
+});
+
+test("the cited channels: siteChannel first, else the clip's channel, else the provenance's; own-media clips cite none", () => {
+ const m = {
+ provenance: { channelSlug: "main" },
+ timeline: [
+ { type: "clip", id: "a", video: "v1" },
+ { type: "clip", id: "b", video: "v2", channel: "other" },
+ { type: "clip", id: "c", video: "v3", channel: "rumble-local", siteChannel: "rumble-site" },
+ { type: "clip", id: "d", video: "v4" },
+ { type: "clip", id: "e", src: "media/x.mp4" },
+ { type: "card", id: "k" },
+ ],
+ };
+ assert.deepEqual(citedChannels(m), [{ slug: "main", clips: 2 }, { slug: "other", clips: 1 }, { slug: "rumble-site", clips: 1 }]);
+});
+
+test("one channel's backlog: listed is held + not downloaded; done when nothing is left to download or transcribe", () => {
+ const r = backlogOf("chan", answer());
+ assert.equal(r.listed, 2798);
+ assert.equal(r.held, 2751);
+ assert.equal(r.transcribed, 1454);
+ assert.equal(r.done, false);
+ assert.equal(backlogWords(r), "chan 1,454/2,798 transcribed · 2,751 held");
+ const d = backlogOf("chan", answer({ undownloaded: 0, untranscribed: 0, transcribed: 2751 }));
+ assert.equal(d.done, true);
+ assert.match(backlogWords(d), /complete$/);
+ assert.equal(backlogOf("chan", null).done, false, "no answer is never done");
+});
+
+test("Prioritize: the focus gains the channels, the ones in it kept; a site focus is the editor's", () => {
+ assert.deepEqual(focusBodyFor({ kind: "none" }, ["a"]), { body: { focus: { kind: "channels", slugs: ["a"] } }, added: ["a"], already: [] });
+ assert.deepEqual(focusBodyFor({ kind: "channels", slugs: ["x", "a"] }, ["a", "b"]).body.focus.slugs, ["x", "a", "b"]);
+ assert.deepEqual(focusBodyFor({ kind: "channels", slugs: ["a"] }, ["a"]).added, []);
+ assert.throws(() => focusBodyFor({ kind: "site", siteId: "s1" }, ["a"]), /site "s1"/);
+ assert.throws(() => focusBodyFor(null, []), /name the channels/);
+});
+
+test("the watch: armed, recorded, fired ONCE when every watched channel is done; cleared; an unreadable file refused", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "umtool-watch-"));
+ await armSourceWatch(dir, ["a", "b"], { now: "2026-11-01T00:00:00.000Z" });
+ const notDone = [backlogOf("a", answer({ undownloaded: 0, untranscribed: 0 })), backlogOf("b", answer())];
+ assert.deepEqual((await recordSourceCheck(dir, notDone)).fired, false);
+ // One channel read and done is not enough: both must be.
+ assert.deepEqual((await recordSourceCheck(dir, [notDone[0]])).fired, false);
+ const done = [notDone[0], backlogOf("b", answer({ undownloaded: 0, untranscribed: 0 }))];
+ assert.equal((await recordSourceCheck(dir, done, { now: "2026-11-02T00:00:00.000Z" })).fired, true);
+ assert.equal((await recordSourceCheck(dir, done)).fired, false, "once");
+ const { doc } = await readSourceWatch(dir);
+ assert.equal(doc.watch.firedAt, "2026-11-02T00:00:00.000Z");
+ assert.deepEqual(doc.watch.fired.map((r) => r.slug), ["a", "b"]);
+ await clearSourceWatch(dir);
+ assert.equal((await readSourceWatch(dir)).doc.watch, null);
+ assert.ok((await readSourceWatch(dir)).doc.last, "what was last seen stays");
+ await assert.rejects(armSourceWatch(dir, []), /no channel/);
+ await writeFile(path.join(dir, SOURCE_WATCH_FILE), "nope");
+ await assert.rejects(armSourceWatch(dir, ["a"]), (e) => e.status === 409);
+ assert.equal(await readFile(path.join(dir, SOURCE_WATCH_FILE), "utf8"), "nope");
+});
diff --git a/umtool/lib/report/sourceBacklog.ts b/umtool/lib/report/sourceBacklog.ts
@@ -0,0 +1,63 @@
+import { askEditor, EditorError } from "@/lib/articles/generation";
+import { readManifest } from "@/lib/projects/report.mjs";
+import { backlogOf, citedChannels, focusBodyFor, focusedOf, readSourceWatch, recordSourceCheck } from "./sourceBacklog.mjs";
+
+// The source backlog's editor half (UI notes item 16): lib/report/sourceBacklog.mjs
+// holds the rules and the watch; this asks the editor, with umtool's WORKER_TOKEN,
+// for each cited channel's snapshot counts and the focus, and asks it to
+// prioritize. SERVER-ONLY.
+
+export type BacklogRow = ReturnType<typeof backlogOf> & { clips: number; focused: boolean; error?: string };
+export type BacklogView = {
+ channels: BacklogRow[];
+ focus: unknown;
+ editorError: string | null;
+ watch: { slugs: string[]; armedAt: string; firedAt?: string } | null;
+ watchError: string | null;
+ fired: boolean;
+};
+
+/** Read every cited channel's backlog, record it (the watch may fire), answer the view. */
+export async function readBacklog(dir: string, manifest: Record<string, unknown> | null = null): Promise<BacklogView> {
+ const m = (manifest ?? (await readManifest(dir)) ?? {}) as Record<string, unknown>;
+ const cited = citedChannels(m) as { slug: string; clips: number }[];
+ let editorError: string | null = null;
+ // Fresh: a read right after Prioritize or a change of counts must see it (askEditor keeps a GET 2 s).
+ const focus = await askEditor<{ value?: { focus?: unknown } }>("/api/ops/settings?key=channelPriority", { fresh: true })
+ .then((r) => r.value?.focus ?? null)
+ .catch((e: unknown) => {
+ editorError = e instanceof Error ? e.message : String(e);
+ return null;
+ });
+ const inFocus = new Set(focusedOf(focus) as string[]);
+ const channels: BacklogRow[] = await Promise.all(
+ cited.map(async ({ slug, clips }) => {
+ try {
+ const r = await askEditor(`/api/ops/channel/${encodeURIComponent(slug)}`, { fresh: true });
+ return { ...(backlogOf(slug, r) as ReturnType<typeof backlogOf>), clips, focused: inFocus.has(slug) };
+ } catch (e) {
+ if (!(e instanceof EditorError) || e.status !== 404) editorError ??= e instanceof Error ? e.message : String(e);
+ return { ...(backlogOf(slug, null) as ReturnType<typeof backlogOf>), clips, focused: inFocus.has(slug), error: e instanceof EditorError && e.status === 404 ? "the editor does not archive it" : "not read" };
+ }
+ }),
+ );
+ let fired = false;
+ // Recorded only for an armed watch (no file is made in a project nobody asked to watch), and only
+ // a real answer: an editor that did not answer says nothing about the backlog.
+ const before = await readSourceWatch(dir);
+ if (before.doc.watch && !before.doc.watch.firedAt && !editorError && channels.some((c) => c.held !== null)) {
+ fired = await recordSourceCheck(dir, channels.filter((c) => !c.error))
+ .then((r: { fired: boolean }) => r.fired)
+ .catch(() => false);
+ }
+ const { doc, error } = fired ? await readSourceWatch(dir) : before;
+ return { channels, focus, editorError, watch: doc.watch, watchError: error ?? null, fired };
+}
+
+/** PRIORITIZE: the editor's focus gains `slugs` (the ones in focus kept). */
+export async function prioritize(slugs: string[]): Promise<{ added: string[]; already: string[]; focus: unknown }> {
+ const cur = await askEditor<{ value?: { focus?: unknown } }>("/api/ops/settings?key=channelPriority", { fresh: true });
+ const { body, added, already } = focusBodyFor(cur.value?.focus ?? null, slugs) as { body: { focus: unknown }; added: string[]; already: string[] };
+ if (added.length) await askEditor("/api/ops/channel-priority", { method: "POST", body });
+ return { added, already, focus: body.focus };
+}
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;
}
diff --git a/umtool/lib/research/case-stages.test.ts b/umtool/lib/research/case-stages.test.ts
@@ -15,7 +15,8 @@ import path from "node:path";
let tmp: string;
let editor: http.Server;
-const asked: { path: string; body: Record<string, unknown> }[] = [];
+// The case stages' stub records {path, body}; the intake stub (capture-posts) records {route, ...body}.
+const asked: ({ path: string; body: Record<string, unknown> } & { route?: string })[] = [];
let lib: {
verify: typeof import("./case-verify");
leads: typeof import("./case-leads");
@@ -37,6 +38,8 @@ before(async () => {
caseDir = made.dir;
const { caseStagesRoute } = await import("../../e2e/fixtures/editor-stub-case-stages.mjs");
const { importPageRoute } = await import("../../e2e/fixtures/editor-stub-import-page.mjs");
+ // capture-posts is the intake stub's (shared with U4's Add post).
+ const { intakeRoute } = await import("../../e2e/fixtures/editor-stub-intake.mjs");
const json = (res: http.ServerResponse, status: number, body: unknown) => {
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(body));
@@ -46,11 +49,12 @@ before(async () => {
req.on("data", (c) => (raw += c));
req.on("end", () => then(raw ? JSON.parse(raw) : null));
};
- const ctx = { channels, json, readBody, push: (r: { path: string; body: Record<string, unknown> }) => asked.push(r) };
+ const ctx = { channels, json, readBody, push: (r: { path: string; body: Record<string, unknown> }) => asked.push(r as (typeof asked)[number]) };
editor = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://stub");
if (caseStagesRoute(req, res, url, ctx)) return;
if (importPageRoute(req, res, url, ctx)) return;
+ if (intakeRoute(req, res, url, ctx)) return;
json(res, 404, { ok: false, error: `no route ${url.pathname}` });
});
await new Promise<void>((r) => editor.listen(0, "127.0.0.1", r));
@@ -224,7 +228,7 @@ test("evidence: an excluded target, a capture at a date, a forum attachment mark
const f = await lib.evidence.addForumAttachment(CASE, lib.fixture.FORUM, "70003");
assert.equal(f.label, "forum attachment, post #3, unverified");
- assert.deepEqual(asked.filter((x) => x.path === "/api/ops/capture-posts").at(-1)?.body, { slug: lib.fixture.FORUM, ids: ["70003"], shots: true, media: true });
+ assert.deepEqual(asked.filter((x) => x.route === "capture-posts").at(-1), { route: "capture-posts", slug: lib.fixture.FORUM, ids: ["70003"], shots: true, media: true });
let fr = f;
for (let i = 0; i < 20 && fr.state === "queued"; i++) {
await wait(200);
diff --git a/umtool/report-to-video/chrome-posts.mjs b/umtool/report-to-video/chrome-posts.mjs
@@ -282,7 +282,7 @@ export function postsHtml(schedule, render, window, opts = {}) {
return (
`<article class="post${shot ? " has-shot" : ""}${logo ? " has-logo" : ""}${plate ? "" : " no-plate"}" data-post="${esc(p.id)}" data-k="c${j}"${style}>` +
(shot
- ? `<div class="body shot-body">${flag}<div class="shot-view"><img class="shot" data-k="s${j}" src="${esc(shot)}" alt=""></div></div>`
+ ? `<div class="body shot-body">${flag}<div class="shot-view"${Number.isInteger(p.crop) ? ` data-crop="${p.crop}" style="max-height: ${p.crop}px"` : ""}><img class="shot" data-k="s${j}" src="${esc(shot)}" alt=""></div></div>`
: `<div class="body">${flag}` +
`<div class="meta">` +
(platform ? `<span class="platform">${esc(platform)}</span>` : "") +
@@ -396,7 +396,8 @@ export function postsHtml(schedule, render, window, opts = {}) {
/* A post's screenshot in place of its words: always as wide as the words
would be, so it reads; its viewport is no taller than a full card of
them -- or than \`shotMaxHeight\` -- and a taller one pans up through
- it (postsCues \`pans\`). */
+ it (postsCues \`pans\`). A post's OWN shotMaxHeight is a crop
+ (data-crop): its top that tall, never panned. */
.shot-body { padding: ${pad - 6}px; }
.shot-view { position: relative; overflow: hidden; border-radius: 6px;
max-height: ${set.shotMaxHeight ?? Math.round(metaSize * 1.3) + 8 + set.maxLines * lineH + 2 * pad}px; }
@@ -473,7 +474,8 @@ export function postsHtml(schedule, render, window, opts = {}) {
const pans = cards.map((c) => {
const view = c.querySelector(".shot-view");
const img = view && view.querySelector("img.shot");
- return img ? Math.max(0, Math.round(img.offsetHeight - view.clientHeight)) : 0;
+ // A post's own crop (data-crop) shows its top and never pans to the rest.
+ return img && !view.hasAttribute("data-crop") ? Math.max(0, Math.round(img.offsetHeight - view.clientHeight)) : 0;
});
document.documentElement.dataset.pans = pans.join(",");
const plan = postsCues({ posts: P.posts, heights, pans, column: P.column, gap: P.gap,
diff --git a/umtool/report-to-video/chrome-posts.test.mjs b/umtool/report-to-video/chrome-posts.test.mjs
@@ -518,6 +518,15 @@ test("shotMaxHeight caps a screenshot's viewport in px; unset, a full card of wo
assert.notEqual(cap(RENDER), "820");
});
+test("a post's OWN shotMaxHeight is a crop: its viewport that tall, marked so the page never pans it", () => {
+ const sched = schedule([POST("a", "2024-10-19T17:01:17.640Z", { shot: "shots/a.png", shotMaxHeight: 300 }), POST("b", "2024-10-19T17:01:18.640Z", { shot: "shots/b.png" })]);
+ const win = snapWindow(postWindows(sched)[0], { fps: 30, total: sched.total });
+ const html = postsHtml(sched, RENDER, win, { fonts: FONTS, shotSrcs: { a: "assets/shot00.png", b: "assets/shot01.png" } });
+ assert.match(html, /<div class="shot-view" data-crop="300" style="max-height: 300px"><img class="shot" data-k="s\d+" src="assets\/shot00\.png"/);
+ assert.match(html, /<div class="shot-view"><img class="shot" data-k="s\d+" src="assets\/shot01\.png"/, "a post with no crop is drawn as before");
+ assert.match(html, /!view\.hasAttribute\("data-crop"\)/, "a cropped shot is not panned");
+});
+
test("postsCues: a tall screenshot holds on its top, pans to its bottom, and holds before it leaves", () => {
const posts = [{ id: "p0", appear: 10, out: [30, 30.5] }, { id: "p1", appear: 12, out: [30, 30.5] }];
const plan = postsCues({ posts, heights: [800, 200], pans: [600, 0], column: 2000, enter: 0.5, panHold: 1.2 });
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -1886,7 +1886,10 @@ export function pipSegments(schedule) {
export const POST_PLATFORMS = Object.freeze(["bluesky", "x", "web"]);
/** The cuts a post may be limited to (`posts[].variant`) -- build-video's VARIANTS. */
const POST_VARIANTS = Object.freeze(["sourced", "full"]);
-const POST_KEYS = ["id", "platform", "author", "handle", "date", "text", "url", "attachTo", "hide", "siteChannel", "siteUrl", "postId", "shot", "thread", "variant", "accent", "logo", "flag"];
+const POST_KEYS = ["id", "platform", "author", "handle", "date", "text", "url", "attachTo", "hide", "siteChannel", "siteUrl", "postId", "shot", "thread", "variant", "accent", "logo", "flag", "shotMaxHeight"];
+/** A post's own crop of its screenshot (`posts[].shotMaxHeight`), in px: its top that tall, never panned. */
+export const POST_CROP_MIN = 120;
+export const POST_CROP_MAX = 1080;
/** A post's `flag`: at most this many characters. */
export const POST_FLAG_MAX = 60;
@@ -1996,6 +1999,14 @@ export function validatePosts(posts, timeline = [], render = null) {
if (p.flag != null && (typeof p.flag !== "string" || !p.flag.trim() || p.flag.length > POST_FLAG_MAX)) {
errors.push(`${w}.flag must be a short label (1 to ${POST_FLAG_MAX} characters)`);
}
+ // A CROP of this post's screenshot (UI notes item 13): the top that many px
+ // of it, the rest cut off and never panned to -- what keeps a quoted post or a
+ // media thumbnail below the post's own words off the screen.
+ if (p.shotMaxHeight != null) {
+ if (!(Number.isInteger(p.shotMaxHeight) && p.shotMaxHeight >= POST_CROP_MIN && p.shotMaxHeight <= POST_CROP_MAX)) {
+ errors.push(`${w}.shotMaxHeight must be a whole number of pixels from ${POST_CROP_MIN} to ${POST_CROP_MAX}`);
+ } else if (typeof p.shot !== "string" || !p.shot) errors.push(`${w}.shotMaxHeight crops the post's screenshot, and the post has no shot`);
+ }
});
// Posts that will be drawn need a column that fits the footage box.
if (render && deckOn(render) && resolveDeck(render).posts.show && posts.some((p) => isObj(p) && !p.hide)) {
@@ -2245,6 +2256,7 @@ function postFieldsOf(p, provenance, links) {
...(typeof p.accent === "string" && p.accent ? { accent: p.accent } : {}),
...(typeof p.logo === "string" && p.logo ? { logo: p.logo } : {}),
...(typeof p.flag === "string" && p.flag.trim() ? { flag: p.flag.trim() } : {}),
+ ...(typeof p.shot === "string" && p.shot && Number.isInteger(p.shotMaxHeight) ? { crop: p.shotMaxHeight } : {}),
};
}