commit de545b34e235ee585a5854d6da2df466744560a7
parent 4889d6add278c2cb1610a8007a72edc72dc76ea3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 18:48:54 -0500
Merge lane/post-reels: a post is a timeline item beside clips -- a native card drawn from the archived post (author, date, text, engagement, a reply's parents, a quote, a repost) with its attachments played in it (images held, GIFs looped, videos with their sound, trimmable), timed by a reading-time rule plus its media; other authors blurred by capture-posts' thread rule; rendered under the deck's chrome, played in Play the cut, listed on the Cut tab, trimmed on a post bench; umtool posts reel (several channels, --own, --with-media, --replies), new --from-posts, timeline insert post:<ch>/<id>, posts set-item
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
40 files changed, 3451 insertions(+), 44 deletions(-)
diff --git a/umtool/app/api/report/post-item/route.ts b/umtool/app/api/report/post-item/route.ts
@@ -0,0 +1,173 @@
+import { readFile, realpath, stat } from "node:fs/promises";
+import path from "node:path";
+import { postCardHtml } from "umtool-report-to-video/post-item";
+import { jobState, startJob } from "@/lib/research/case-editor";
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/lib/report/manifest.mjs";
+import { rangeResponse, resolveReport } from "@/lib/report/serve.mjs";
+import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+
+export const dynamic = "force-dynamic";
+
+// A POST ITEM's page, its files and its knobs (report-to-video/post-item.mjs;
+// umtool/docs/knobs.md, "A post item"): what Play the cut and the post bench
+// draw a post item with, and the bench's writer.
+//
+// GET ?project&id&w&h[&phase=read|media][&take] the card's page, the HTML the build
+// screenshots, at w × h (the footage box)
+// GET ?project&file=posts-media/… an attachment (byte ranges): only a file
+// under the project's posts-media/
+// GET ?project&font=regular|bold the cut's faces, for the page
+// GET ?project&id&media=<i>&job=<id> a transcription's state; once done, its
+// words are set on the attachment
+// POST {project, op: "set", id, patch, token} updatePostItem (hold, layout, redact, media.<i>.…)
+// POST {project, op: "transcribe", id, media} the editor's transcribe op on the attachment
+// (a local file, a job), its words beside it
+
+const noStore = { "cache-control": "no-store" };
+
+type Entry = Record<string, unknown> & { id: string; type?: string; media?: Array<Record<string, unknown>> };
+
+async function itemOf(project: { dir: string }, manifest: Record<string, unknown>, id: string, take: string | null) {
+ let m = manifest;
+ if (take) m = (await resolveTakeManifest(project.dir, take, { base: manifest })).manifest as Record<string, unknown>;
+ const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Entry[];
+ return { item: tl.find((e) => e?.type === "post" && e.id === id) ?? null, manifest: m };
+}
+
+/** A project file under posts-media/, never outside it (its real path checked). */
+async function postsFile(projectDir: string, rel: string): Promise<string | null> {
+ if (!rel.startsWith("posts-media/") || rel.split("/").includes("..")) return null;
+ const abs = path.join(projectDir, ...rel.split("/"));
+ const [real, root] = await Promise.all([realpath(abs).catch(() => null), realpath(path.join(projectDir, "posts-media")).catch(() => null)]);
+ if (!real || !root || !(real === root || real.startsWith(root + path.sep))) return null;
+ return abs;
+}
+
+const TYPES: Record<string, string> = {
+ ".mp4": "video/mp4", ".m4v": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".gif": "image/gif",
+ ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".json": "application/json",
+ ".ttf": "font/ttf", ".otf": "font/otf", ".woff2": "font/woff2",
+};
+
+const wordsRelOf = (src: string) => `${src.replace(/\.[^./]+$/, "")}.words.json`;
+
+export async function GET(request: Request) {
+ const q = new URL(request.url).searchParams;
+ const r = await resolveReport(q.get("project") ?? "");
+ if ("error" in r) return new Response(r.error, { status: r.status });
+ const render = ((r.manifest as Record<string, unknown>).render ?? {}) as Record<string, unknown>;
+
+ const font = q.get("font");
+ if (font) {
+ const file = font === "bold" ? render.fontBold : font === "regular" ? render.fontRegular : null;
+ if (typeof file !== "string" || !file) return new Response("no such face", { status: 404 });
+ const body = await readFile(file).catch(() => null);
+ if (!body) return new Response("the face is not on disk", { status: 404 });
+ return new Response(new Uint8Array(body), { headers: { "content-type": TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream", "cache-control": "max-age=3600" } });
+ }
+
+ const rel = q.get("file");
+ if (rel) {
+ const abs = await postsFile(r.project.dir, rel);
+ if (!abs) return new Response("not a post item's file", { status: 404 });
+ const st = await stat(abs).catch(() => null);
+ if (!st?.isFile()) return new Response("gone", { status: 404 });
+ const etag = `"${st.size.toString(16)}-${Math.round(st.mtimeMs).toString(16)}"`;
+ return rangeResponse(request, {
+ abs, size: st.size, etag,
+ headers: { "content-type": TYPES[path.extname(abs).toLowerCase()] ?? "application/octet-stream", "accept-ranges": "bytes", "cache-control": "no-cache" },
+ });
+ }
+
+ const id = q.get("id") ?? "";
+ let found;
+ try {
+ found = await itemOf(r.project, r.manifest as Record<string, unknown>, id, q.get("take") || null);
+ } catch (e) {
+ return new Response(e instanceof Error ? e.message : String(e), { status: 400 });
+ }
+ if (!found.item) return new Response(`no post item ${id}`, { status: 404 });
+
+ const job = q.get("job");
+ if (job) {
+ const i = Number(q.get("media"));
+ const m = found.item.media?.[i];
+ if (!m || typeof m.src !== "string") return Response.json({ error: `no attachment ${q.get("media")}` }, { status: 404 });
+ try {
+ const st = await jobState(job);
+ if (!st.done) return Response.json({ state: "transcribing", status: st.status }, { headers: noStore });
+ if (st.status !== "done") return Response.json({ state: "failed", status: st.status, tail: st.tail.slice(-3) }, { headers: noStore });
+ const words = wordsRelOf(m.src);
+ if (!(await stat(path.join(r.project.dir, ...words.split("/"))).catch(() => null))) {
+ return Response.json({ state: "failed", status: "done", error: "the job ended without its words file" }, { headers: noStore });
+ }
+ if (m.words !== words) {
+ await withEditNotes(r.project, async () => updatePostItem(r.project.dir, id, { media: { [i]: { words } } }, { token: await manifestToken(r.project.dir) }));
+ }
+ return Response.json({ state: "done", words }, { headers: noStore });
+ } catch (e) {
+ return Response.json({ state: "failed", error: e instanceof Error ? e.message : String(e) }, { status: 502 });
+ }
+ }
+
+ const w = Math.round(Number(q.get("w")) || 0);
+ const h = Math.round(Number(q.get("h")) || 0);
+ if (!(w >= 160 && w <= 3840 && h >= 90 && h <= 2160)) return new Response("w and h are the footage box, in px", { status: 400 });
+ const base = `/api/report/post-item?project=${encodeURIComponent(r.project.id)}`;
+ const parentShot = typeof found.item.parentShot === "string" ? `${base}&file=${encodeURIComponent(found.item.parentShot)}` : null;
+ const html = postCardHtml(found.item, {
+ width: w, height: h,
+ palette: (render.palette ?? {}) as Record<string, string>,
+ fonts: { regular: `${base}&font=regular`, bold: `${base}&font=bold` },
+ phase: q.get("phase") === "media" ? "media" : "read",
+ parentShotUrl: parentShot,
+ });
+ return new Response(html, { headers: { "content-type": "text/html; charset=utf-8", ...noStore } });
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/post-item");
+ if (refused) return refused;
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const id = String(body.id ?? "");
+ if (body.op === "set") {
+ try {
+ const { result, editNotes } = await withEditNotes(r.project, () =>
+ updatePostItem(r.project.dir, id, (body.patch ?? {}) as Record<string, unknown>, { token: body.token === undefined || body.token === null ? null : String(body.token) }),
+ );
+ return Response.json({ ok: true, entry: result.entry, token: result.token, editNotes }, { headers: noStore });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+ }
+ if (body.op === "transcribe") {
+ const found = await itemOf(r.project, r.manifest as Record<string, unknown>, id, null);
+ const i = Number(body.media);
+ const m = found.item?.media?.[i];
+ if (!m || typeof m.src !== "string") return Response.json({ error: `${id} has no attachment ${String(body.media)}` }, { status: 404 });
+ if (m.kind !== "video") return Response.json({ error: "only a video attachment has words to transcribe" }, { status: 400 });
+ const abs = await postsFile(r.project.dir, m.src);
+ if (!abs) return Response.json({ error: "the attachment is not in the project's posts-media/" }, { status: 404 });
+ const out = path.join(r.project.dir, ...wordsRelOf(m.src).split("/"));
+ try {
+ // The editor's transcription door: a local file, on a local worker, as a job -- never ASR by hand.
+ const job = await startJob("/api/ops/transcribe", { path: abs, words: true, out });
+ return Response.json({ ok: true, jobId: job }, { headers: noStore });
+ } catch (e) {
+ const status = (e as { status?: number }).status ?? 502;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
+ }
+ }
+ return Response.json({ error: "op is set or transcribe" }, { status: 400 });
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -110,6 +110,8 @@
// 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
+// reel <project> --channel <slug>… [--since/--until/--own/--with-media/--replies/--order/--limit] post items
+// set-item <project> <item> hold=… media.<i>.start=… a post item's knobs
// umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel
import process from "node:process";
import {
@@ -918,6 +920,9 @@ function usage() {
" recording (needs its diarization.json): highlights proposed from the host's laughs and comments,",
" then `umtool clips analyze` (the laugh scan + voices) unless --no-analyze; --scope auto reads the",
" narrated video auto-scope finds in the speakers' turns (--segment names one, else the longest)",
+ " --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media]",
+ " [--replies include|only|exclude] [--order chrono|reverse] [--limit N]: a POSTS REEL -- each",
+ " archived post a post item (its card, its attachments), the deck on (umtool posts reel adds more)",
" [--brand archilyzer-media] render.brand: the report-to-video brand preset",
" umtool doctor [--json] exit 1 if the report pipeline is missing a tool",
" or the media root is set and not there; the roots, and a leftover old cache",
@@ -1018,6 +1023,12 @@ 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 posts reel <project> --channel <slug> [--channel …] [--since D] [--until D] [--own] [--with-media]",
+ " [--replies include|only|exclude] [--order chrono|reverse] [--limit N] [--after <id|->] [--dry-run] [--json]",
+ " POST ITEMS: each archived post an entry of the cut (its card, its attachments played), one write;",
+ " a re-run adds only posts not already in the cut",
+ " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto] [media.<i>.start=<s>]",
+ " [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off] [media.<i>.push=on|off] [--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",
@@ -1653,7 +1664,8 @@ async function cmdNew() {
" [--from <sweep-report.md> | <share URL> | <channel>/<videoId>]\n" +
" [--site-origin <url>] [--seed chapters|frames [--target <seconds>]] [--brand archilyzer-media]\n" +
" [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]]\n" +
- " [--seed reactions --from <channel>/<videoId> [--target <seconds>] [--laugh-min X] [--scope FROM:TO|auto [--segment sN]] [--no-analyze]]",
+ " [--seed reactions --from <channel>/<videoId> [--target <seconds>] [--laugh-min X] [--scope FROM:TO|auto [--segment sN]] [--no-analyze]]\n" +
+ " [--from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies include|only|exclude] [--order chrono|reverse] [--limit N]]",
);
}
const kind = val("--kind") ?? "report-video";
@@ -1683,11 +1695,33 @@ async function cmdNew() {
...(val("--laugh-min") != null ? { laughMin: Number(val("--laugh-min")) } : {}),
...(val("--scope") != null ? { scope: parseScopeFlag(val("--scope")) } : {}),
...(val("--segment") != null ? { segment: val("--segment") } : {}),
+ ...(val("--from-posts") != null ? { postsChannel: val("--from-posts") } : {}),
});
} catch (e) {
die(e?.message ?? String(e));
}
+ // A posts reel (`--from-posts <slug>`): the timeline from the archive, through `posts reel`'s writer.
+ if (val("--from-posts") != null) {
+ const { postsReel } = await import("../lib/report/postReel.mjs");
+ const channels = [val("--from-posts"), ...argv.flatMap((a, i) => (a === "--channel" ? [argv[i + 1]] : []))];
+ let reel;
+ try {
+ reel = await postsReel({ id: r.id, dir: r.dir }, {
+ channels, since: val("--since") ?? null, until: val("--until") ?? null, own: has("--own"), withMedia: has("--with-media"),
+ replies: val("--replies") ?? "include", order: val("--order") ?? "chrono", ...(val("--limit") != null ? { limit: Number(val("--limit")) } : {}),
+ });
+ } catch (e) {
+ die(`${r.dir} was made, but the reel was not: ${e?.message ?? String(e)}`);
+ }
+ if (json) return out({ ok: true, ...r, reel: { channels: reel.channels, selected: reel.selected, added: reel.added, ids: reel.result?.ids ?? [] } });
+ console.log(`${r.dir}`);
+ console.log(` video.manifest.json ${reel.added} post item(s) from ${reel.channels.join(" + ")} (${reel.selected} selected) — the deck on`);
+ console.log(` more later: umtool posts reel ${r.id} --channel ${channels[0]} … adds only what is new`);
+ if (!r.siteOrigin) console.log(" NOTE: provenance.siteOrigin is empty: each post's QR opens the post itself (deck.qr.links original)");
+ return;
+ }
+
// The clip finder's seed (release 35): the scans and a second proposal pass
// right away, unless --no-analyze (the app's form runs them as a job).
let analyzed = null;
diff --git a/umtool/components/projects/PostBench.tsx b/umtool/components/projects/PostBench.tsx
@@ -0,0 +1,375 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { postBenchHref } from "@/lib/hrefs";
+import { POST_HOLD, POST_MEDIA_MIN_SPAN, postItemPlan, readingSeconds, ruleSeconds } from "umtool-report-to-video/post-item";
+import PostItemPlayer, { type PostPlan } from "./review/PostItemPlayer";
+
+// ---------------------------------------------------------------------------
+// THE POST BENCH, the client half (PostBenchPage.tsx): the item played on its
+// own clock in its final look (PostItemPlayer: the build's card page, the
+// attachments laid into its slot), and its knobs, each change shown at once
+// and saved by one write (updatePostItem, POST /api/report/post-item):
+//
+// hold the item's whole length (absent: the duration rule)
+// layout a grid of its 2-4 images, or one after another
+// redact other authors: auto (the privacy rule), blurred, shown
+// media[i] a video's or a GIF's in and out (the playhead sets them),
+// its sound, a crop of any attachment, an image's push-in,
+// and a video's words: Transcribe asks the EDITOR's
+// transcription (a job on a local worker), never ASR here
+// ---------------------------------------------------------------------------
+
+type Media = Record<string, unknown> & { src: string; kind: string; seconds?: number; start?: number; end?: number; mute?: boolean; crop?: number[]; push?: boolean; words?: string; audio?: boolean; width?: number; height?: number };
+type Entry = Record<string, unknown> & { id: string; media?: Media[]; hold?: number; mediaLayout?: string; redact?: boolean };
+
+const r2 = (v: number) => Math.round(v * 100) / 100;
+const CROPS: Array<{ label: string; crop: number[] | null }> = [
+ { label: "none", crop: null },
+ { label: "centre 80%", crop: [0.1, 0.1, 0.8, 0.8] },
+ { label: "top half", crop: [0, 0, 1, 0.5] },
+ { label: "bottom half", crop: [0, 0.5, 1, 0.5] },
+];
+
+export default function PostBench({
+ project, entry: initial, token: initialToken, box, plan: initialPlan, back, prev, next, fromPlay,
+}: {
+ project: string;
+ entry: Entry;
+ token: string | null;
+ box: { width: number; height: number };
+ plan: PostPlan;
+ back: { href: string; label: string };
+ prev: string | null;
+ next: string | null;
+ fromPlay: boolean;
+}) {
+ const router = useRouter();
+ const [entry, setEntry] = useState<Entry>(initial);
+ const [saved, setSaved] = useState<Entry>(initial);
+ const [token, setToken] = useState(initialToken);
+ const [status, setStatus] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const plan = useMemo(() => (entry === initial ? initialPlan : (postItemPlan(entry) as PostPlan)), [entry, initial, initialPlan]);
+ const total = plan.total;
+ const [s, setS] = useState(0);
+ const [playing, setPlaying] = useState(false);
+ const raf = useRef(0);
+ useEffect(() => {
+ if (!playing) return;
+ let last = performance.now();
+ const tick = (now: number) => {
+ const dt = (now - last) / 1000;
+ last = now;
+ setS((x) => {
+ const n = x + dt;
+ if (n >= total) {
+ setPlaying(false);
+ return total;
+ }
+ return n;
+ });
+ raf.current = requestAnimationFrame(tick);
+ };
+ raf.current = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(raf.current);
+ }, [playing, total]);
+ useEffect(() => {
+ const onKey = (ev: KeyboardEvent) => {
+ const tgt = ev.target as HTMLElement | null;
+ if (tgt?.closest("input, textarea, select")) return;
+ if (ev.key === " ") {
+ ev.preventDefault();
+ setPlaying((p) => (s >= total ? (setS(0), true) : !p));
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [s, total]);
+
+ const dirty = JSON.stringify(entry) !== JSON.stringify(saved);
+ const media = entry.media ?? [];
+ const setMedia = (i: number, patch: Partial<Media>) =>
+ setEntry((e) => ({ ...e, media: (e.media ?? []).map((m, j) => (j === i ? clean({ ...m, ...patch }) : m)) }));
+ const clean = (m: Media): Media => {
+ const out = { ...m } as Record<string, unknown>;
+ for (const [k, v] of Object.entries(out)) if (v === undefined || v === null) delete out[k];
+ return out as Media;
+ };
+
+ // The patch the writer takes: every knob as it stands now (null: the default again).
+ const patchOf = (e: Entry) => ({
+ hold: typeof e.hold === "number" ? e.hold : null,
+ mediaLayout: e.mediaLayout ?? null,
+ redact: typeof e.redact === "boolean" ? e.redact : null,
+ media: Object.fromEntries(
+ (e.media ?? []).map((m, i) => [
+ i,
+ {
+ start: typeof m.start === "number" ? m.start : null,
+ end: typeof m.end === "number" ? m.end : null,
+ mute: m.mute === true ? true : null,
+ crop: Array.isArray(m.crop) ? m.crop : null,
+ push: m.push === true ? true : null,
+ },
+ ]),
+ ),
+ });
+ const save = useCallback(async () => {
+ setError(null);
+ setStatus("saving…");
+ const res = await fetch("/api/report/post-item", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, op: "set", id: entry.id, patch: patchOf(entry), token }),
+ });
+ const j = (await res.json().catch(() => ({}))) as { entry?: Entry; token?: string; error?: string; errors?: string[] };
+ if (!res.ok || !j.entry) {
+ setStatus(null);
+ setError(j.errors?.join("; ") ?? j.error ?? `HTTP ${res.status}`);
+ return;
+ }
+ setEntry(j.entry);
+ setSaved(j.entry);
+ setToken(j.token ?? null);
+ setStatus("saved");
+ }, [entry, project, token]);
+
+ // Transcribe a video attachment through the editor (a job), then follow it.
+ const [jobs, setJobs] = useState<Record<number, { job: string; state: string; error?: string }>>({});
+ const transcribe = async (i: number) => {
+ setError(null);
+ const res = await fetch("/api/report/post-item", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, op: "transcribe", id: entry.id, media: i }) });
+ const j = (await res.json().catch(() => ({}))) as { jobId?: string; error?: string };
+ if (!res.ok || !j.jobId) {
+ setJobs((x) => ({ ...x, [i]: { job: "", state: "failed", error: j.error ?? `HTTP ${res.status}` } }));
+ return;
+ }
+ setJobs((x) => ({ ...x, [i]: { job: j.jobId!, state: "transcribing" } }));
+ };
+ useEffect(() => {
+ const running = Object.entries(jobs).filter(([, v]) => v.state === "transcribing" && v.job);
+ if (!running.length) return;
+ const t = setTimeout(async () => {
+ for (const [i, v] of running) {
+ const res = await fetch(`/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&media=${i}&job=${encodeURIComponent(v.job)}`);
+ const j = (await res.json().catch(() => ({}))) as { state?: string; words?: string; error?: string };
+ if (j.state === "done" && j.words) {
+ setMedia(Number(i), { words: j.words });
+ setSaved((e) => ({ ...e, media: (e.media ?? []).map((m, k) => (k === Number(i) ? { ...m, words: j.words } : m)) }));
+ router.refresh();
+ }
+ if (j.state !== "transcribing") setJobs((x) => ({ ...x, [i]: { ...v, state: j.state ?? "failed", error: j.error } }));
+ }
+ }, 2000);
+ return () => clearTimeout(t);
+ });
+
+ const stepOf = (i: number) => plan.steps.find((st) => st.items.some((m) => m.i === i)) ?? null;
+ const btn = cn(buttonVariants({ variant: "outline", size: "sm" }));
+ const reading = readingSeconds(entry);
+
+ return (
+ <div className="mx-auto grid max-w-[1400px] grid-cols-1 gap-4 min-[1100px]:grid-cols-[minmax(0,1fr)_360px]" data-post-bench={entry.id}>
+ <section className="min-w-0 space-y-2">
+ <div className="flex flex-wrap items-center gap-2 text-[12px]">
+ <Link href={back.href} className="ink-link" data-post-bench-back="">
+ {back.label}
+ </Link>
+ {prev && (
+ <Link href={postBenchHref(project, prev, fromPlay ? { play: { at: 0 } } : {})} className="ink-link" data-post-bench-prev={prev}>
+ ‹ {prev}
+ </Link>
+ )}
+ {next && (
+ <Link href={postBenchHref(project, next, fromPlay ? { play: { at: 0 } } : {})} className="ink-link" data-post-bench-next={next}>
+ {next} ›
+ </Link>
+ )}
+ <span className="ml-auto font-mono text-[13px] tabular-nums" data-post-bench-clock="">
+ {s.toFixed(1)} / {total.toFixed(1)} s
+ </span>
+ </div>
+ <div className="relative w-full overflow-hidden rounded border border-seam bg-black" style={{ aspectRatio: `${box.width} / ${box.height}` }}>
+ <PostItemPlayer project={project} entry={entry} plan={plan} box={box} s={s} playing={playing} />
+ </div>
+ <div className="flex items-center gap-2 text-[12px]">
+ <button type="button" className={btn} data-post-bench-play="" onClick={() => (s >= total ? (setS(0), setPlaying(true)) : setPlaying((p) => !p))}>
+ {playing ? "Pause" : "Play"}
+ </button>
+ <input
+ type="range"
+ min={0}
+ max={total}
+ step={0.05}
+ value={s}
+ onChange={(e) => setS(Number(e.target.value))}
+ className="flex-1"
+ aria-label="item position"
+ data-post-bench-scrub=""
+ />
+ </div>
+ {/* The plan, as a strip: the reading span, then each attachment's step. */}
+ <div className="relative h-6 w-full overflow-hidden rounded bg-[var(--color-panel)] text-[10.5px]" data-post-bench-plan="">
+ <div className="absolute inset-y-0 left-0 flex items-center bg-white/10 px-1" style={{ width: `${(plan.reading / total) * 100}%` }}>
+ read {plan.reading.toFixed(1)} s
+ </div>
+ {plan.steps.map((st, k) => (
+ <div key={k} className="absolute inset-y-0 flex items-center border-l border-black/40 bg-[var(--color-sel)]/25 px-1" style={{ left: `${(st.at / total) * 100}%`, width: `${(st.seconds / total) * 100}%` }} data-post-bench-step={st.kind}>
+ {st.kind} {st.seconds.toFixed(1)} s
+ </div>
+ ))}
+ <div className="absolute inset-y-0 w-px bg-[var(--color-signal,#e33)]" style={{ left: `${(s / total) * 100}%` }} />
+ </div>
+ </section>
+
+ <aside className="space-y-3 text-[12.5px]">
+ <section className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3">
+ <h2 className="micro mb-2">length</h2>
+ <p className="m-0 text-text-2">
+ the rule: {reading.toFixed(1)} s to read{media.length ? ` + the attachments` : ""} = <b data-post-bench-rule="">{ruleSeconds(entry).toFixed(1)} s</b>
+ </p>
+ <label className="mt-2 flex items-center gap-2">
+ hold
+ <input
+ type="number"
+ min={POST_HOLD.min}
+ max={POST_HOLD.max}
+ step={0.5}
+ value={typeof entry.hold === "number" ? entry.hold : ""}
+ placeholder="the rule"
+ onChange={(e) => setEntry((x) => ({ ...x, hold: e.target.value === "" ? undefined : Number(e.target.value) }))}
+ className="w-24 rounded border border-seam bg-ground px-1.5 py-0.5"
+ data-post-bench-hold=""
+ />
+ s
+ {typeof entry.hold === "number" && (
+ <button type="button" className="ink-link" onClick={() => setEntry((x) => ({ ...x, hold: undefined }))}>
+ clear
+ </button>
+ )}
+ </label>
+ {media.filter((m) => m.kind === "image").length >= 2 && (
+ <label className="mt-2 flex items-center gap-2">
+ images
+ <select value={entry.mediaLayout ?? "sequence"} onChange={(e) => setEntry((x) => ({ ...x, mediaLayout: e.target.value === "sequence" ? undefined : e.target.value }))} data-post-bench-layout="">
+ <option value="sequence">one after another</option>
+ <option value="grid">a grid, all at once</option>
+ </select>
+ </label>
+ )}
+ <label className="mt-2 flex items-center gap-2" title="auto: another author is blurred unless the subject, or gold/grey verified (post-item.mjs authorRedaction)">
+ other authors
+ <select
+ value={entry.redact === true ? "on" : entry.redact === false ? "off" : "auto"}
+ onChange={(e) => setEntry((x) => ({ ...x, redact: e.target.value === "auto" ? undefined : e.target.value === "on" }))}
+ data-post-bench-redact=""
+ >
+ <option value="auto">auto (the privacy rule)</option>
+ <option value="on">blur them all</option>
+ <option value="off">show them (public)</option>
+ </select>
+ </label>
+ </section>
+
+ {media.map((m, i) => {
+ const st = stepOf(i);
+ const timed = m.kind === "video" || m.kind === "gif";
+ const len = typeof m.seconds === "number" ? m.seconds : 0;
+ const srcNow = st && s >= st.at ? r2((st.srcFrom ?? 0) + Math.min(st.seconds, s - st.at)) : null;
+ return (
+ <section key={i} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-3" data-post-bench-media={i} data-post-bench-media-kind={m.kind}>
+ <h2 className="micro mb-2">
+ attachment {i + 1} · {m.kind}
+ {timed ? ` · ${len.toFixed(1)} s` : ""}
+ {m.kind === "video" && m.audio === false ? " · no sound" : ""}
+ </h2>
+ {timed && (
+ <div className="space-y-1.5">
+ <div className="flex items-center gap-2">
+ in
+ <input type="number" min={0} max={len} step={0.1} value={m.start ?? 0} onChange={(e) => setMedia(i, { start: Number(e.target.value) || undefined })} className="w-20 rounded border border-seam bg-ground px-1.5 py-0.5" data-post-bench-start={i} />
+ out
+ <input type="number" min={0} max={len} step={0.1} value={m.end ?? len} onChange={(e) => setMedia(i, { end: Number(e.target.value) >= len - 0.02 ? undefined : Number(e.target.value) })} className="w-20 rounded border border-seam bg-ground px-1.5 py-0.5" data-post-bench-end={i} />
+ <span className="text-text-2">plays {Math.max(POST_MEDIA_MIN_SPAN, (m.end ?? len) - (m.start ?? 0)).toFixed(1)} s</span>
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ <button type="button" className={btn} disabled={srcNow === null} onClick={() => srcNow !== null && setMedia(i, { start: srcNow || undefined })} data-post-bench-set-in={i}>
+ In at playhead
+ </button>
+ <button type="button" className={btn} disabled={srcNow === null} onClick={() => srcNow !== null && setMedia(i, { end: srcNow })} data-post-bench-set-out={i}>
+ Out at playhead
+ </button>
+ <button type="button" className={btn} onClick={() => setMedia(i, { start: undefined, end: undefined })}>
+ Whole
+ </button>
+ </div>
+ {m.kind === "video" && m.audio !== false && (
+ <label className="flex items-center gap-2">
+ <input type="checkbox" checked={m.mute !== true} onChange={(e) => setMedia(i, { mute: e.target.checked ? undefined : true })} data-post-bench-sound={i} />
+ its sound
+ </label>
+ )}
+ </div>
+ )}
+ {m.kind === "image" && (
+ <label className="flex items-center gap-2">
+ <input type="checkbox" checked={m.push === true} onChange={(e) => setMedia(i, { push: e.target.checked ? true : undefined })} data-post-bench-push={i} />
+ slow push-in
+ </label>
+ )}
+ <div className="mt-1.5 flex flex-wrap items-center gap-1.5">
+ crop
+ {CROPS.map((c) => (
+ <button
+ key={c.label}
+ type="button"
+ className={cn(btn, JSON.stringify(m.crop ?? null) === JSON.stringify(c.crop) && "border-[var(--color-sel)]")}
+ onClick={() => setMedia(i, { crop: c.crop ?? undefined })}
+ data-post-bench-crop={c.label}
+ >
+ {c.label}
+ </button>
+ ))}
+ </div>
+ {m.kind === "video" && m.audio !== false && (
+ <div className="mt-2 text-[12px]">
+ {m.words ? (
+ <span data-post-bench-words={i}>its words are transcribed (shown under it)</span>
+ ) : jobs[i]?.state === "transcribing" ? (
+ <span data-post-bench-transcribing={i}>transcribing on the editor…</span>
+ ) : (
+ <button type="button" className={btn} onClick={() => void transcribe(i)} data-post-bench-transcribe={i}>
+ Transcribe its words (the editor)
+ </button>
+ )}
+ {jobs[i]?.state === "failed" && <span className="ml-2 text-[var(--color-blocking,#c33)]">{jobs[i].error ?? "the transcription failed"}</span>}
+ </div>
+ )}
+ </section>
+ );
+ })}
+
+ <div className="flex items-center gap-2">
+ <button type="button" className={cn(buttonVariants({ variant: "go", size: "sm" }))} disabled={!dirty} onClick={() => void save()} data-post-bench-save="">
+ Save
+ </button>
+ <button type="button" className={btn} disabled={!dirty} onClick={() => setEntry(saved)}>
+ Revert
+ </button>
+ {status && !dirty && <span data-post-bench-status="">{status}</span>}
+ {dirty && <span className="text-text-2">unsaved</span>}
+ </div>
+ {error && (
+ <p className="m-0 text-[var(--color-blocking,#c33)]" data-post-bench-error="">
+ {error}
+ </p>
+ )}
+ </aside>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/PostBenchPage.tsx b/umtool/components/projects/PostBenchPage.tsx
@@ -0,0 +1,56 @@
+import { notFound } from "next/navigation";
+import AppShell from "@/components/shell/AppShell";
+import PostBench from "./PostBench";
+import { readManifest } from "@/lib/projects/report.mjs";
+import { manifestToken } from "@/lib/report/manifest.mjs";
+import { projectHref, playHref } from "@/lib/hrefs";
+import { deckGeometry, deckOn, feedGeometry, feedOn } from "umtool-report-to-video/deck";
+import { postItemPlan } from "umtool-report-to-video/post-item";
+import type { ProjectRef } from "@/lib/project-types";
+import type { PostPlan } from "./review/PostItemPlayer";
+
+// THE POST BENCH (report-to-video/post-item.mjs; knobs.md, "A post item"): one
+// post item of the cut on its own -- its card and attachments played on the
+// item's clock, and its knobs: an attachment's trim, sound, crop and push-in,
+// the images' grid, the blur of other authors, the item's hold, and a video's
+// words through the editor's transcription. Every save is updatePostItem
+// (POST /api/report/post-item {op: "set"}), the writer `umtool posts set-item` runs.
+
+export default async function PostBenchPage({ project, id, search = {} }: { project: ProjectRef; id: string; search?: Record<string, string | undefined> }) {
+ const m = (await readManifest(project.dir)) as Record<string, unknown> | null;
+ if (!m) notFound();
+ const tl = (Array.isArray(m.timeline) ? m.timeline : []) as Array<Record<string, unknown> & { id: string; type?: string }>;
+ const at = tl.findIndex((e) => e?.type === "post" && e.id === id);
+ if (at < 0) notFound();
+ const entry = tl[at];
+ const render = (m.render ?? {}) as Record<string, unknown>;
+ const box = deckOn(render)
+ ? (feedOn({ render, posts: (m.posts ?? []) as never[], entries: tl as never[] }) ? feedGeometry(render).footage : deckGeometry(render).footage)
+ : { width: Number(render.width ?? 1920), height: Number(render.height ?? 1080) };
+ const neighbours = tl.filter((e) => e?.type === "post").map((e) => e.id);
+ const k = neighbours.indexOf(id);
+ const fromPlay = search.from === "play";
+ const back = fromPlay ? playHref(project.id, { clip: id, at: Number(search.at ?? 0) || null }) : projectHref(project.id, { tab: "cut" });
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell
+ active="projects"
+ crumbs={[{ href: "/projects", label: "Projects" }, { href: projectHref(project.id), label: project.name }, { label: `post ${id}` }]}
+ note={`post item ${k + 1} of ${neighbours.length} · ${String(entry.post ?? "")}`}
+ />
+ <main className="deck-main flex-1 overflow-auto p-4">
+ <PostBench
+ project={project.id}
+ entry={entry}
+ token={await manifestToken(project.dir)}
+ box={{ width: box.width, height: box.height }}
+ plan={postItemPlan(entry) as unknown as PostPlan}
+ back={{ href: back, label: fromPlay ? "‹ Back to the cut" : "‹ The Cut tab" }}
+ prev={k > 0 ? neighbours[k - 1] : null}
+ next={k < neighbours.length - 1 ? neighbours[k + 1] : null}
+ fromPlay={fromPlay}
+ />
+ </main>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -4,6 +4,7 @@ import SongProject from "./SongProject";
import CutPage from "./CutPage";
import ReportProject from "./ReportProject";
import ClipBenchPage from "./ClipBenchPage";
+import PostBenchPage from "./PostBenchPage";
import ClaimBenchPage from "./ClaimBenchPage";
import SweepProject from "./SweepProject";
import TakesPage from "./TakesPage";
@@ -53,6 +54,8 @@ export default async function ProjectView({
if (rest.length === 0) return <ReportProject project={project} search={search} />;
// `/browse/<project>/clip/<id>` -- the bench. A view the kind does not
// declare is a 404 rather than a page that silently drops half its URL.
+ // `/projects/<project>/post/<id>` -- a post item's bench (report-to-video/post-item.mjs).
+ if (rest.length === 2 && rest[0] === "post") return <PostBenchPage project={project} id={rest[1]} search={search} />;
if (rest.length === 2 && rest[0] === "clip") {
return <ClipBenchPage project={project} clipId={rest[1]} search={search} />;
}
diff --git a/umtool/components/projects/TimelineEditor.tsx b/umtool/components/projects/TimelineEditor.tsx
@@ -201,7 +201,7 @@ export function TimelineList({ project, count, groupCount = 0, children }: { pro
if (draggingBar.current !== null) {
// A boundary goes after a CLIP.
const li = rowOf(e.target);
- if (!li || li.dataset.kind !== "clip") return;
+ if (!li || (li.dataset.kind !== "clip" && li.dataset.kind !== "post")) return;
e.preventDefault();
setOver(rowKey(li).at);
return;
@@ -238,7 +238,7 @@ export function TimelineList({ project, count, groupCount = 0, children }: { pro
return;
}
if (marker !== null) {
- if (!li || li.dataset.kind !== "clip") return;
+ if (!li || (li.dataset.kind !== "clip" && li.dataset.kind !== "post")) return;
e.preventDefault();
void run("section-boundary", { marker, afterId: rowKey(li).id });
return;
@@ -394,7 +394,8 @@ export function RowControls({ id, at, kind = "entry" }: { id: string; at: number
const [newSection, setNewSection] = useState(false);
if (!ctx) return null;
const { busy, run, dragging, sections, selected, toggle } = ctx;
- const isClip = kind === "clip";
+ // A footage row: a clip or a post item (both sit in sections and groups).
+ const isClip = kind === "clip" || kind === "post";
const mine = isClip ? sections.find((s) => s.clips.includes(id)) : undefined;
return (
<>
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -8,7 +8,7 @@ import {
} from "@/lib/projects/report.mjs";
import { listTakes } from "@/lib/report/takes.mjs";
import { buttonVariants } from "@/components/ui/button";
-import { clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takeWalkHref, takesHref, trailerHref } from "@/lib/hrefs";
+import { postBenchHref, clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, playHref, projectHref, takeWalkHref, takesHref, trailerHref } from "@/lib/hrefs";
import { readTrailerBeats } from "@/lib/report/trailerBeats.mjs";
import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs";
import FetchUnfetchedButton from "../FetchUnfetchedButton";
@@ -16,6 +16,7 @@ import TightWindowsPanel from "./TightWindowsPanel";
import { clipRecord, storedUrlOf } from "@/lib/clips/stored";
import { Fragment } from "react";
import { deckOn } from "umtool-report-to-video/deck";
+import { postItemSeconds } from "umtool-report-to-video/post-item";
import { sectionModel, sectionWords } from "@/lib/report/sectionEdit.mjs";
import { GroupBar, RowControls, RowNotes, SectionBar, TimelineList, type GroupInfo, type SectionInfo } from "../TimelineEditor";
import { groupModel } from "@/lib/report/claimGroups.mjs";
@@ -170,6 +171,51 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
// vocabulary is open -- one real manifest carries `scroll` and
// `chart` beside its cards -- and a page that only knows two words
// either crashes on the third or silently drops it.
+ // A POST ITEM (report-to-video/post-item.mjs): its own glyph, the post's day, author and
+ // first words, what it carries, how long it plays, and its bench.
+ if (e.kind === "post") {
+ const media = (Array.isArray(e.media) ? e.media : []) as { kind?: string }[];
+ const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim();
+ const inGroup = groupBars.of.get(e.id);
+ return (
+ <li
+ data-entry={e.id}
+ data-kind="post"
+ data-at={at}
+ data-group={inGroup}
+ tabIndex={0}
+ className={`rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 outline-none focus:border-[var(--color-sel)] ${inGroup ? "ml-6" : ""}`}
+ >
+ <div className="flex flex-wrap items-baseline gap-2 text-[12px]">
+ <RowControls id={e.id} at={at} kind="post" />
+ <span aria-hidden data-post-glyph="" title="a post item" className="font-display text-[14px] leading-none text-[var(--color-sel)]">
+ ❝
+ </span>
+ <span className="font-mono text-[var(--color-text)]">{e.id}</span>
+ <span className="num font-mono text-[11px] text-[var(--color-dim)]">{String(e.date ?? "").slice(0, 10)}</span>
+ <span className="text-[11px] text-[var(--color-dim)]">
+ {e.author ?? ""}
+ {e.handle ? ` @${e.handle}` : ""}
+ </span>
+ {e.repostedBy ? <Pill>repost</Pill> : null}
+ {(Array.isArray(e.parents) && e.parents.length) || e.parentShot || e.replyingTo ? <Pill>reply</Pill> : null}
+ <span data-post-carries="">
+ <Pill>{media.length ? media.map((m) => m.kind).join(" + ") : "text"}</Pill>
+ </span>
+ <span className="num micro ml-auto" data-post-seconds="">
+ {postItemSeconds(e).toFixed(1)}s{typeof e.hold === "number" ? " (hold)" : ""}
+ </span>
+ <Link href={postBenchHref(project.id, e.id)} className="ink-link text-[11px]" data-post-bench-link={e.id}>
+ bench
+ </Link>
+ </div>
+ {words && <div className="mt-0.5 text-[12px] text-[var(--color-dim)]">{words.length > 160 ? `${words.slice(0, 157)}…` : words}</div>}
+ <div className="basis-full">
+ <RowNotes id={e.id} project={project.id} />
+ </div>
+ </li>
+ );
+ }
if (e.kind !== "clip") {
return (
<li
diff --git a/umtool/components/projects/report/OverviewTab.tsx b/umtool/components/projects/report/OverviewTab.tsx
@@ -1,4 +1,5 @@
import { readFile } from "node:fs/promises";
+import { postItemSeconds } from "umtool-report-to-video/post-item";
import path from "node:path";
import Link from "next/link";
import { Suspense } from "react";
@@ -40,8 +41,10 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP
const readme = await readFile(path.join(project.dir, "README.md"), "utf8").catch(() => null);
const p = (m.provenance ?? {}) as Record<string, unknown>;
const clips = entries.filter((e) => e.kind === "clip");
- const nonClips = entries.filter((e) => e.kind !== "clip");
- const runtime = clips.reduce((n, e) => n + Math.max(0, e.end - e.start), 0);
+ // Post items (report-to-video/post-item.mjs) are counted on their own, and play their rule's seconds.
+ const posts = entries.filter((e) => e.kind === "post");
+ const nonClips = entries.filter((e) => e.kind !== "clip" && e.kind !== "post");
+ const runtime = clips.reduce((n, e) => n + Math.max(0, e.end - e.start), 0) + posts.reduce((n, e) => n + postItemSeconds(e), 0);
const article = frame.article;
const iterations =
article && article.site === ARTICLES_KEY ? await readArticleIterations(article.report).catch(() => null) : null;
@@ -88,7 +91,7 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP
<li className="flex gap-2.5 border-b border-seam py-1.5">
cut
<span className="ml-auto font-mono text-[11.5px] text-meter">
- {clips.length} clips{nonClips.length ? ` · ${nonClips.length} other` : ""} · {hms(runtime)}
+ {clips.length} clips{posts.length ? ` · ${posts.length} posts` : ""}{nonClips.length ? ` · ${nonClips.length} other` : ""} · {hms(runtime)}
</span>
</li>
<li className="flex gap-2.5 border-b border-seam py-1.5">
diff --git a/umtool/components/projects/report/ReportTabBody.tsx b/umtool/components/projects/report/ReportTabBody.tsx
@@ -1,4 +1,5 @@
import GeneratedBanner from "@/components/notes/GeneratedBanner";
+import { postItemSeconds } from "umtool-report-to-video/post-item";
import { NotesProvider } from "@/components/notes/NotesProvider";
import { channelFor, clipsOf } from "@/lib/projects/report.mjs";
import type { PieceFrame } from "@/lib/pieces/frame";
@@ -32,10 +33,12 @@ export async function reportCounts(detail: ClipDetail, dir: string): Promise<{ c
/** The page's one-line status: `4 clips · 2 other · 0:12 · not built`. */
export function reportStatus(detail: ClipDetail): string {
const clips = detail.entries.filter((e) => e.kind === "clip");
- const nonClips = detail.entries.filter((e) => e.kind !== "clip");
- const runtime = clips.reduce((n, e) => n + Math.max(0, e.end - e.start), 0);
+ const posts = detail.entries.filter((e) => e.kind === "post");
+ const nonClips = detail.entries.filter((e) => e.kind !== "clip" && e.kind !== "post");
+ const runtime = clips.reduce((n, e) => n + Math.max(0, e.end - e.start), 0) + posts.reduce((n, e) => n + postItemSeconds(e), 0);
return (
`${clips.length} clips` +
+ (posts.length ? ` · ${posts.length} posts` : "") +
(nonClips.length ? ` · ${nonClips.length} other` : "") +
` · ${hms(runtime)} · ${detail.build.built ? "built" : "not built"}`
);
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -6,7 +6,7 @@ import { buttonVariants } from "@/components/ui/button";
import { useSharedNotes } from "@/components/notes/NotesProvider";
import { NoteThread } from "@/components/notes/NoteThread";
import type { Anchor, CutAsk, Note } from "@/lib/annotations/types";
-import { clipBenchHref, takeClipHref } from "@/lib/hrefs";
+import { clipBenchHref, postBenchHref, takeClipHref } from "@/lib/hrefs";
import { cn } from "@/lib/utils";
import { footageAt } from "@/lib/report/footage-move.mjs";
import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
@@ -27,6 +27,7 @@ import WhatPlays, { type WorkingCut } from "./WhatPlays";
import { useCutApp } from "../cutApp/CutApp";
import { ClipExportButtons, ClipExportStatus, useClipExport } from "../ClipExport";
import AddPost from "./AddPost";
+import PostItemPlayer, { type PostPlan } from "./PostItemPlayer";
// ---------------------------------------------------------------------------
// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The
@@ -117,6 +118,9 @@ export type PlayEntry = {
rejected?: { reason: string; label: string; fact: boolean; why: string } | null;
/** The verdict's fields as written (Reject prefills from them; its keep-in-place Undo writes them back). */
review?: { verdict: string | null; reason: string | null; correction: string | null; rejectNote: string | null };
+ /** A post item (report-to-video/post-item.mjs): the entry its card is drawn from, and what plays when. */
+ post?: Record<string, unknown> & { id: string };
+ postPlan?: PostPlan;
};
export type PlayViewData = {
@@ -218,7 +222,7 @@ function approximateLine(edges: RenderCuts, info: EngineInfo | null) {
const picture = !info ? "" : info.picture === "webcodecs" ? "picture: WebCodecs" : info.picture === "mixed" ? "picture: WebCodecs, some clips on <video>" : "picture: <video>";
const silent = info ? Object.keys(info.silent) : [];
return [
- "Approximate: cards and teasers are placeholders, a push or a wipe is drawn as a dissolve, the chrome is composed on the estimate's clock;",
+ "Approximate: cards and teasers are placeholders (a post item plays its card and attachments, its sound from its own element), a push or a wipe is drawn as a dissolve, the chrome is composed on the estimate's clock;",
`${edge};`,
`${sound}${picture ? `; ${picture}` : ""}.`,
silent.length ? `No sound decoded for ${silent.join(", ")}.` : "",
@@ -579,6 +583,8 @@ export default function PlayCut({
const editHref = useCallback(() => {
const e = now();
const it = planRef.current.items[e.cur];
+ // A post item: its own bench (the post's attachments' trims, its hold and crop).
+ if (it?.type === "post") return postBenchHref(project, it.id, { play: { at: Math.round(Math.max(0, e.t - it.from) * 100) / 100 } });
if (!it?.clip) return null;
const at = Math.round(Math.max(0, e.t - it.from) * 100) / 100;
// A take with its own timeline: ITS bench, its patch (never the project's clip of the same id).
@@ -606,7 +612,7 @@ export default function PlayCut({
setPlaying(false);
// Where Back lands: this place, written now (the one push is the bench's).
window.history.replaceState(window.history.state, "", placeHref());
- if (app) {
+ if (app && planRef.current.items[now().cur]?.clip) {
// In place: Play stays as it is; on the way back the clip (and the source second) is found again.
const e = now();
const it = planRef.current.items[e.cur];
@@ -798,7 +804,9 @@ export default function PlayCut({
const postsWin = doc?.posts ? postsWindowAt(doc.posts.windows, tc) : null;
const missing = !!item?.clip && !entry?.media;
const broken = !!item && !!failed[item.id];
- const placeholder = item && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null;
+ // A post item plays its card and attachments (PostItemPlayer), not a placeholder.
+ const postNow = item && entry?.type === "post" && entry.post && entry.postPlan ? { item, entry } : null;
+ const placeholder = item && !postNow && (!item.clip || missing || broken) ? { kind: !item.clip ? "card" : "missing", item, entry } : null;
const pct = (n: number, of: number) => `${(n / of) * 100}%`;
// The reel strip's counter: the composed schedule's stamps when there is one, else the estimate's.
@@ -814,6 +822,19 @@ export default function PlayCut({
const pins = useMemo(() => mine.map((n) => ({ id: n.id, t: noteT(n.anchor as CutAnchor), text: n.text, open: n.status === "open" })), [mine, noteT, plan]);
const stripEntries = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]);
+ const postPlayer = (box2: { width: number; height: number }) =>
+ postNow ? (
+ <PostItemPlayer
+ key={postNow.item.id}
+ project={project}
+ take={take}
+ entry={postNow.entry.post!}
+ plan={postNow.entry.postPlan!}
+ box={box2}
+ s={Math.max(0, t - postNow.item.start)}
+ playing={ui.playing && !ui.waiting}
+ />
+ ) : null;
const placeholderCard = placeholder ? (
<div
data-play-placeholder={placeholder.kind}
@@ -961,6 +982,11 @@ export default function PlayCut({
<DeckFrame preview={doc} t={tc} texts={{}} testid="play-deck">
<div className="absolute inset-0" style={{ background: bg }} />
{footageCanvas(rect ? { left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H) } : undefined, box.width, box.height)}
+ {postNow && rect && (
+ <div className="absolute" style={{ left: pct(rect.x, g.W), top: pct(rect.y, g.H), width: pct(rect.width, g.W), height: pct(rect.height, g.H), background: bg }}>
+ {postPlayer({ width: box.width, height: box.height })}
+ </div>
+ )}
{placeholderCard}
{doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={tc} testid="play-feed" />}
{postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={tc} />}
@@ -976,6 +1002,7 @@ export default function PlayCut({
) : (
<div className="relative w-full overflow-hidden rounded border border-seam bg-black max-md:rounded-none max-md:border-0" style={{ aspectRatio: "16 / 9" }} data-testid="play-plain">
{footageCanvas({ inset: 0, width: "100%", height: "100%" }, 1280, 720)}
+ {postNow && <div className="absolute inset-0" style={{ background: bg }}>{postPlayer({ width: 1920, height: 1080 })}</div>}
{placeholderCard}
</div>
)}
@@ -1029,7 +1056,7 @@ export default function PlayCut({
<button
type="button"
data-play-edit={take && view.take?.ownTimeline ? "take" : ""}
- disabled={!item?.clip}
+ disabled={!item?.clip && !postNow}
onClick={editHere}
className={cn(buttonVariants({ variant: "outline", size: "sm" }))}
title={
@@ -1039,10 +1066,12 @@ export default function PlayCut({
: take
? "edit this clip on the bench (E): the edit goes to the project's cut, not this take's render; Back plays the project's cut"
: "edit this clip on the bench (E); Back to the cut returns here"
- : "a card is not edited on the clip bench"
+ : postNow
+ ? "open this post item's bench (E): its attachments' trims, sound and crop, its hold; Back returns here"
+ : "a card is not edited on the clip bench"
}
>
- Edit this clip
+ {postNow ? "Edit this post" : "Edit this clip"}
</button>
<span className="ml-auto flex flex-wrap items-center gap-x-2 text-[11.5px] text-muted" data-play-hud="">
{tally.length > 0 && <span className="sr-only" data-play-tally={tally.map((r) => `${r.verdict}:${r.count}`).join(",")} />}
diff --git a/umtool/components/projects/review/PostItemPlayer.tsx b/umtool/components/projects/review/PostItemPlayer.tsx
@@ -0,0 +1,209 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { POST_PUSH, mediaTimeAt, postLayout, stepAt, stepBoxes } from "umtool-report-to-video/post-item";
+
+// ---------------------------------------------------------------------------
+// A POST ITEM PLAYED (report-to-video/post-item.mjs; knobs.md, "Play the cut"):
+// the card drawn by the build's own page (/api/report/post-item, the HTML the
+// render screenshots) at the footage box's size and scaled into it, and its
+// attachments laid over the card's slot where the render lays them
+// (postLayout, stepBoxes) on the item's plan (postItemPlan): the first one's
+// first frame while the words are read, then each in turn -- a video playing
+// with its sound, a GIF looped, an image held (pushed in on when it asks).
+// The cut's clock is Play's own; each element follows it, re-seeked when it
+// drifts. A video's words (its transcript) show at the slot's foot.
+// ---------------------------------------------------------------------------
+
+export type PostPlan = {
+ reading: number;
+ total: number;
+ held: number;
+ steps: Array<{
+ kind: string;
+ at: number;
+ seconds: number;
+ srcFrom?: number;
+ srcTo?: number;
+ loop: boolean;
+ sound: boolean;
+ items: Array<Record<string, unknown> & { i: number; src: string; kind: string; crop?: number[]; push?: boolean; words?: string }>;
+ }>;
+};
+
+type Box = { width: number; height: number };
+type Cue = { start: number; end: number; text: string };
+
+const pct = (n: number, of: number) => `${(n / of) * 100}%`;
+/** How far a playing element may drift from the cut's clock before it is re-seeked. */
+const DRIFT = 0.3;
+
+export function postFileUrl(project: string, rel: string) {
+ return `/api/report/post-item?project=${encodeURIComponent(project)}&file=${encodeURIComponent(rel)}`;
+}
+
+function MediaEl({
+ project, m, box, b, step, s, playing, inStep,
+}: {
+ project: string;
+ m: PostPlan["steps"][number]["items"][number];
+ box: Box;
+ b: { x: number; y: number; width: number; height: number };
+ step: PostPlan["steps"][number];
+ s: number;
+ playing: boolean;
+ inStep: boolean;
+}) {
+ const ref = useRef<HTMLVideoElement | null>(null);
+ const crop = Array.isArray(m.crop) && m.crop.length === 4 ? m.crop : null;
+ const inner: React.CSSProperties = crop
+ ? { position: "absolute", width: `${100 / crop[2]}%`, height: `${100 / crop[3]}%`, left: `${(-crop[0] / crop[2]) * 100}%`, top: `${(-crop[1] / crop[3]) * 100}%`, maxWidth: "none" }
+ : { position: "absolute", inset: 0, width: "100%", height: "100%" };
+ const timed = step.kind === "video" || step.kind === "gif";
+ // Before its step: its first frame. In it: the source second the plan says.
+ const target = timed ? (inStep ? mediaTimeAt(step, s) : step.srcFrom ?? 0) : null;
+ const run = playing && inStep;
+ useEffect(() => {
+ const v = ref.current;
+ if (!v || target === null) return;
+ if (Math.abs(v.currentTime - target) > DRIFT || !run) {
+ try {
+ v.currentTime = target;
+ } catch {
+ // not seekable yet: the next tick tries again
+ }
+ }
+ if (run && v.paused) void v.play().catch(() => {});
+ if (!run && !v.paused) v.pause();
+ }, [target, run]);
+ const progress = inStep ? Math.min(1, Math.max(0, (s - step.at) / Math.max(0.1, step.seconds))) : 0;
+ return (
+ <div
+ data-post-media={m.i}
+ data-post-media-kind={m.kind}
+ className="absolute overflow-hidden"
+ style={{ left: pct(b.x, box.width), top: pct(b.y, box.height), width: pct(b.width, box.width), height: pct(b.height, box.height) }}
+ >
+ {timed ? (
+ <video
+ ref={ref}
+ src={postFileUrl(project, String(m.src))}
+ data-post-video={m.i}
+ data-post-video-playing={run ? "1" : "0"}
+ preload="auto"
+ playsInline
+ loop={step.loop}
+ muted={!(step.sound && run)}
+ style={{ ...inner, objectFit: "fill" }}
+ />
+ ) : (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={postFileUrl(project, String(m.src))}
+ alt=""
+ data-post-image={m.i}
+ style={{ ...inner, objectFit: "fill", transform: m.push ? `scale(${1 + POST_PUSH * progress})` : undefined, transformOrigin: "center" }}
+ />
+ )}
+ </div>
+ );
+}
+
+export default function PostItemPlayer({
+ project, take = null, entry, plan, box, s, playing,
+}: {
+ project: string;
+ take?: string | null;
+ entry: Record<string, unknown> & { id: string };
+ plan: PostPlan;
+ box: Box;
+ /** The item's own second (0: its first frame). */
+ s: number;
+ playing: boolean;
+}) {
+ const wrap = useRef<HTMLDivElement | null>(null);
+ const [scale, setScale] = useState(0);
+ useEffect(() => {
+ const node = wrap.current;
+ if (!node) return;
+ const ro = new ResizeObserver(([e]) => setScale(e.contentRect.width / box.width));
+ ro.observe(node);
+ return () => ro.disconnect();
+ }, [box.width]);
+ const layout = useMemo(() => postLayout(entry, box), [entry, box]);
+ const pageUrl = (phase: "read" | "media") =>
+ `/api/report/post-item?project=${encodeURIComponent(project)}&id=${encodeURIComponent(entry.id)}&w=${Math.round(box.width)}&h=${Math.round(box.height)}&phase=${phase}${take ? `&take=${encodeURIComponent(take)}` : ""}`;
+ const reading = s < plan.reading || !plan.steps.length;
+ const current = stepAt(plan, s);
+ // Beside the card, the first attachment is up (its first frame) while the words are read.
+ const shown = current ?? (layout.mode === "side" && plan.steps.length ? plan.steps[0] : null);
+ const inStep = !!current && shown === current;
+ const mediaPhase = layout.mode === "stack" && !reading;
+ // A video's words, when it was transcribed (media[i].words): the cue at its source second.
+ const wordsRel = shown?.kind === "video" ? (shown.items[0]?.words as string | undefined) : undefined;
+ const [cues, setCues] = useState<Record<string, Cue[]>>({});
+ useEffect(() => {
+ if (!wordsRel || cues[wordsRel]) return;
+ let gone = false;
+ fetch(postFileUrl(project, wordsRel))
+ .then((r) => (r.ok ? r.json() : null))
+ .then((doc) => {
+ if (gone || !doc) return;
+ const list = (Array.isArray(doc.cues) ? doc.cues : []) as Cue[];
+ setCues((c) => ({ ...c, [wordsRel]: list }));
+ })
+ .catch(() => {});
+ return () => {
+ gone = true;
+ };
+ }, [wordsRel, project, cues]);
+ const src = shown && inStep ? mediaTimeAt(shown, s) : null;
+ const cue = wordsRel && src !== null ? (cues[wordsRel] ?? []).find((c) => src >= c.start && src < c.end) ?? null : null;
+ return (
+ <div
+ ref={wrap}
+ data-post-play={entry.id}
+ data-post-layout={layout.mode}
+ data-post-step={reading ? "read" : current?.kind ?? "held"}
+ data-post-s={String(Math.round(s * 100) / 100)}
+ className="pointer-events-none absolute inset-0 overflow-hidden"
+ >
+ {scale > 0 && (
+ <div className="absolute left-0 top-0" style={{ width: box.width, height: box.height, transform: `scale(${scale})`, transformOrigin: "0 0" }}>
+ <iframe
+ title={`post ${entry.id}`}
+ src={pageUrl("read")}
+ data-post-card-frame="read"
+ className="absolute inset-0 border-0"
+ style={{ width: box.width, height: box.height, visibility: mediaPhase ? "hidden" : "visible" }}
+ />
+ {layout.mode === "stack" && (
+ <iframe
+ title={`post ${entry.id} (media)`}
+ src={pageUrl("media")}
+ data-post-card-frame="media"
+ className="absolute inset-0 border-0"
+ style={{ width: box.width, height: box.height, visibility: mediaPhase ? "visible" : "hidden" }}
+ />
+ )}
+ </div>
+ )}
+ {shown && layout.slot && (layout.mode === "side" || mediaPhase) && (
+ <>
+ {stepBoxes(shown, layout.slot).map((b: { x: number; y: number; width: number; height: number }, j: number) => (
+ <MediaEl key={`${plan.steps.indexOf(shown)}:${j}`} project={project} m={shown.items[j]} box={box} b={b} step={shown} s={s} playing={playing} inStep={inStep} />
+ ))}
+ {cue && (
+ <div
+ data-post-caption=""
+ className="absolute -translate-x-1/2 rounded bg-black/65 px-2 py-0.5 text-center text-white"
+ style={{ left: pct(layout.slot.x + layout.slot.width / 2, box.width), top: pct(layout.slot.y + layout.slot.height * 0.86, box.height), fontSize: Math.max(10, 34 * scale * (box.height / 1080)) }}
+ >
+ {cue.text}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -81,6 +81,10 @@ Inbox cannot disagree about what is wrong with one.
| `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] [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)) |
+| `posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run] [--json]` | **POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a "Replying to" line). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after` |
+| `posts set-item <project> <item> [hold=<s>\|off] [layout=sequence\|grid] [redact=on\|off\|auto] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\|off] [media.<i>.crop=x,y,w,h\|off] [media.<i>.push=on\|off] [--json]` | a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words |
+| `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters |
+| `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one |
| `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
@@ -634,6 +634,32 @@ post** (`components/projects/review/AddPost.tsx`, `/api/report/post-cards`, `lib
| 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}` |
+## A post item (a post as an entry of the cut)
+
+A post played as a timeline entry of its own -- its card and its attachments, beside clips or as a whole reel
+([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut): the shape, the duration rule, the privacy
+rule). Made by `umtool posts reel` (or `umtool new <p> --from-posts <slug>`, `umtool timeline <p> insert … post:<channel>/<postId>`);
+its knobs are one writer, `updatePostItem` (`lib/report/manifest.mjs`), refused in the build's words (`validatePostItem`).
+`null` / `off` clears a knob. Its bench is `/projects/<p>/post/<id>` (the Cut tab's row **bench**, Play's **Edit this post**).
+
+| Knob | In umtool | From a terminal | Route |
+|---|---|---|---|
+| `hold` — the item's whole length in seconds (1–120; absent: the duration rule) | post bench, **hold** | `umtool posts set-item <p> <item> hold=12` (`hold=off`) | `POST /api/report/post-item {project, op: "set", id, patch: {hold}, token}` |
+| `mediaLayout` — `grid`: its 2-4 images at once (3.5 s + 1 per extra); absent: one after another | post bench, **images** | `layout=grid` (`layout=sequence`) | same, `patch: {mediaLayout}` |
+| `redact` — other authors (the posts it answers, the one it quotes, a repost's original): absent, the privacy rule (blurred unless a subject or gold/grey verified); `false` shows them (judged public); `true` blurs even the verified | post bench, **other authors** | `redact=off` · `redact=on` · `redact=auto` | same, `patch: {redact}` |
+| `media[i].start`, `media[i].end` — a video's or a GIF's in and out, its own seconds (at least 0.5 s apart) | post bench, **in / out**, **In at playhead**, **Out at playhead**, **Whole** | `media.0.start=1.5 media.0.end=6` · `media.0.trim=off` | same, `patch: {media: {"0": {start, end}}}` |
+| `media[i].mute` — `true`: the video plays silent | post bench, **its sound** | `media.0.mute=on` (`=off`) | same |
+| `media[i].crop` — `[x, y, w, h]`, fractions of the picture: what of it is shown | post bench, **crop** (none, centre 80%, top half, bottom half) | `media.0.crop=0,0.1,1,0.8` (`=off`) | same |
+| `media[i].push` — an image's slow push-in (6% over its span) | post bench, **slow push-in** | `media.0.push=on` | same |
+| `media[i].words` — a video's transcript (`{cues: [{start, end, text}]}` beside it), its words shown under it in Play and the render | post bench, **Transcribe its words (the editor)**: the editor's `transcribe` op on the file (a job on a local worker), set when it is done | `pnpm ops transcribe --json '{"path": "<project>/posts-media/…_1.mp4", "words": true, "out": "<project>/posts-media/…_1.words.json"}'`, then set `words` by the bench | `POST {op: "transcribe", id, media}` → `{jobId}` · `GET ?project&id&media&job=` |
+
+| | In umtool | From a terminal | Route |
+|---|---|---|---|
+| a posts reel: the archive's posts as post items, re-run to add only what is new (one write, one undo point) | — | `umtool posts reel <p> --channel <slug> [--channel …] [--since D] [--until D] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after <id\|->] [--dry-run]` | — |
+| one post item among clips | — | `umtool timeline <p> insert --after <id\|-> post:<channel>/<postId> [--id ID]` (or `--to-section N`, `--group G`) | `POST /api/report/timeline {op: "insert", …}` with an entry |
+| move, remove, a section, a group | the Cut tab's row (⠿, ⋯, the section bars), Play's reel strip | `umtool timeline <p> move\|remove\|section-move\|section-add …` | as a clip's |
+| the card's page, an attachment, the faces | Play the cut, the post bench | — | `GET /api/report/post-item?project&id&w&h[&phase][&take]` · `?project&file=posts-media/…` · `?project&font=regular\|bold` |
+
## 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
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -402,6 +402,113 @@ A still **never derives** a QR target. A clip's code is derived from the archive
that serves it; a screenshot has no such archive, and a code that resolves to the
wrong place is worse than no code — so only an explicit `citeUrl` draws one.
+### Post items: a post as an entry of the cut
+
+A post card laid OVER a clip (`posts[]`, the deck's feed and popups) says what was
+posted while somebody talks. A **post item** is the post itself as an entry of the
+timeline — a slide of its own, with its attachments played in it — so a cut can be a
+reel of somebody's posts (*"a video dedicated to the Mr. Obvious tweets, playing all
+the recent ones like a slideshow and playing the attachments"*), or mix posts and clips
+freely. `report-to-video/post-item.mjs` is the model (pure: the build, Play, the writers
+and the lint read the same rules), `post-render.mjs` the render, `lib/report/postReel.mjs`
+the generator.
+
+```jsonc
+{ "type": "post", "id": "p-2116052735661654457",
+ "post": "ObviousRises-x/2116052735661654457", // <archive channel>/<postId>: where it came from
+ // The archive row, SNAPSHOTTED when it went in -- the cut renders the words and the
+ // counts it was made with, not whatever the archive says next week:
+ "platform": "x", "author": "MR. OBVIOUS", "handle": "ObviousRises",
+ "date": "2026-10-30T06:21:01.000Z", "text": "I am at my wits end …",
+ "url": "https://x.com/ObviousRises/status/2116052735661654457",
+ "engagement": { "likes": 479, "reposts": 36, "replies": 17, "quotes": 1 },
+ "subjects": ["ObviousRises"], // the accounts the cut is about (the privacy rule)
+ "repostedBy": { "author": "…", "handle": "…" }, // a repost: drawn as its original, "↻ … reposted"
+ "parents": [{ "id": "…", "author": "…", "handle": "…", "text": "…", "date": "…" }], // a reply: what it answers, nearest first (≤ 2)
+ "parentShot": "posts-media/<slug>/<id>/shot-thread.png", // …else the capture's thread shot
+ "replyingTo": "handle", // …else a "Replying to @…" line
+ "quoted": { "author": "…", "handle": "…", "text": "…" }, // the post it quotes
+ "media": [{ "src": "posts-media/ObviousRises-x/2116052735661654457/…_1.mp4", // copied INTO the project
+ "kind": "video", "seconds": 4.992, "width": 1080, "height": 1350, "audio": true,
+ "start": 0.5, "end": 4, "mute": false, // a video's or a GIF's trim, its sound
+ "crop": [0, 0.1, 1, 0.8], // [x, y, w, h], fractions of the picture
+ "push": true, // an image: a slow push-in
+ "words": "posts-media/…/…_1.words.json" }], // a video's transcript (the editor's)
+ "mediaLayout": "grid", // 2-4 images at once, not one after another
+ "hold": 12, // the item's whole length, overriding the rule
+ "redact": false } // other authors: false shows them, true blurs even verified ones
+```
+
+**How it plays.** A native card drawn from the snapshot — the author's name and
+handle, the date, the words, the counts, "reposted by", the posts it answers above it
+(a thread line down to it), the post it quotes inside it — in the deck's palette and
+faces, by the browser the build already uses for the chrome (`postCardHtml`; never a
+screenshot of the platform). Its attachments play inside it: the words are read
+first, then each attachment in turn — a video with its sound, from its trim; a GIF
+looped; an image held (pushed in on with `push`); 2-4 images at once with
+`mediaLayout: "grid"`. The layout (`postLayout`) is decided from the words: no
+attachment, the card alone; words that fit beside the attachments at a readable size,
+the card on the left and the attachments in a slot on the right, the first one's
+first frame up while the words are read; words that do not, the card alone while it
+is read, then the attachments large under a strip naming the post. Under the deck it
+is framed into the footage box like a clip, so the rail's pip, the section bars and
+the date (its day; the subtitle "author @handle on X", "reposted on X", "replying on
+X") ride over it; its QR is the post (`deckQrUrl`: its own page, or its archive's
+under `qr.links: "archive"` with a `siteChannel`).
+
+**The duration rule** (`post-item.mjs`, `POST_READ` and its neighbours):
+
+| | seconds |
+|---|---|
+| reading the post | `clamp(1 + words / 3, 3, 15)` — 3 words a second (about 180 a minute), a second to find the text first; the cap keeps a 500-word post from stalling the reel (it is shown at the size that fits, and `hold` gives it more) |
+| + each post it answers, and the post it quotes | `clamp(words / 3, 1, 4)` — context, not the post |
+| + a video | its trimmed span, `end − start` (at least 0.5) |
+| + a GIF | looped to at least 3 s (one pass when longer, at most 10) |
+| + an image | 3.5 |
+| + a grid of 2-4 images | 3.5 + 1 per image after the first |
+| `hold` | replaces the whole: a longer hold holds the last thing up, a shorter one cuts the attachments short at it |
+
+Words are runs of non-space; a link is one word; a repost's `RT @x:` prefix is its
+"reposted" line, not words.
+
+**The privacy rule** (`authorRedaction`) is the one capture-posts applies to a thread
+parent (`common/social/xThreadShot.ts`), applied to every OTHER author a card draws —
+the posts it answers, the post it quotes, a repost's original, and the post's own
+author when the item names its `subjects` and it is not one: the avatar, the name and
+the @handle are blurred (never in the page at all — a blurred stand-in is drawn) and
+so is an @mention of them in the words, UNLESS the author is a subject (the reel's
+accounts: a self-thread, his own post reposted), or the archive says they carry an
+organisation's gold check or a government's grey one (`badge`: X's blue check is
+bought, so a blue-checked private person is blurred like any other), or the item says
+`redact: false` (judged public). `redact: true` blurs even those; an author the
+archive does not name is blurred. The words of the post stay: what was said is the
+evidence, who a private person is, is not.
+
+**Made by `umtool posts reel`** ([cli.md](cli.md)): one or more channels' archives
+read as one, merged in time order, de-duplicated by post id (a profile's posts and
+its replies are two channels: `--channel ObviousRises-x --channel
+ObviousRises-x-replies`), filtered (`--since`, `--until`, `--own`, `--with-media`,
+`--replies include|only|exclude`, `--order`, `--limit`), every post the cut already
+plays skipped — by its id, as a repost's original, or reposted by one — so a re-run
+adds only what is new, and the rest put in through ONE write (`insertEntries`: one
+undo point, refused whole in the build's words). A reply's parents come from the
+archive (the replies channel carries the posts he answered), else from the capture's
+`shot-thread.png`, else a "Replying to" line. The attachments are COPIED into the
+project's `posts-media/` and measured (ffprobe: pixels, length, sound; X serves a GIF
+as a silent mp4 from `tweet_video/`). `umtool new <p> --from-posts <slug>` scaffolds a
+posts reel (the deck on; with no `siteOrigin` each QR opens the post), and `umtool
+timeline <p> insert … post:<channel>/<postId>` puts one in among clips.
+
+**Every writer takes it as it takes a clip**: move, remove, duplicate, undo; a deck
+marker may follow a post item and a section or a claim group may hold one
+(`sectionEdit`, `claimGroups`, `patchMarkers`, `reanchorAfterRemove`), and a take's
+timeline carries it as data (a take's walk opens clips only). Its knobs are `updatePostItem` (`umtool posts set-item`,
+the post bench). Play the cut plays it (the card from the same page, the attachments
+on Play's clock); the Cut tab lists it with its own glyph; the post bench
+(`/projects/<p>/post/<id>`) trims a video, sets the hold, the crop and the blur, and
+asks the editor to transcribe a video's words (`pnpm ops transcribe`'s op: a local
+file, a job; never ASR by hand), which then show under it in Play and the render.
+
## The on-screen deck (`render.chrome`)
Its knobs — the stamp's moment and count per clip, the stamp's look and words, the markers, a clip's sync and
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -53,6 +53,7 @@ import { makePlayCutFixture } from "./play-cut-fixture.mjs";
import { makeCutEditingFixture } from "./cut-editing-fixture.mjs";
import { makeReelFixture } from "./reel-fixture.mjs";
import { makeIntakeFixture } from "./intake-fixture.mjs";
+import { makePostItemsFixture } from "./post-items-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"));
@@ -1907,6 +1908,8 @@ makeCutEditingFixture({ reports, manifest, deckManifest, cachedWindow: path.join
makeReelFixture({ reports, deckManifest });
// 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") });
+// Post items (report-to-video/post-item.mjs): a cut mixing a clip and posts played as items, a synthesized posts archive (post-items.spec.ts).
+makePostItemsFixture({ 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/fixtures/post-items-fixture.mjs b/umtool/e2e/fixtures/post-items-fixture.mjs
@@ -0,0 +1,97 @@
+// POST ITEMS (report-to-video/post-item.mjs): a cut that mixes clips and posts
+// played as items of their own (post-items.spec.ts).
+//
+// post-items-fixture c01 a clip (playvid, the fixture's synthetic window,
+// cached in out/clips-raw), then three post items from a
+// SYNTHESIZED posts archive, channels/postchan-x:
+// p-txt text only (a self-reply: its parent drawn
+// above it, the subject's, plain)
+// p-img a picture (posts-media/…/2_1.png, 320×180)
+// p-vid a video with sound (posts-media/…/3_1.mp4,
+// 4 s testsrc 320×180, a 440 Hz tone), a
+// reply to a PRIVATE account (blurred)
+// the deck on, one section after c01. The archive also
+// holds a fourth post (4, text) the reel spec adds.
+// WRITES its manifest (the bench's trim): the spec puts
+// it back before each test.
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import { spawnSync } from "node:child_process";
+import path from "node:path";
+
+const ff = (args) => {
+ const r = spawnSync("ffmpeg", ["-v", "error", "-y", ...args]);
+ if (r.status !== 0) throw new Error(`ffmpeg ${args.join(" ")}: ${String(r.stderr)}`);
+};
+
+export const POST_CHANNEL = "postchan-x";
+
+const row = (id, o) => ({
+ id, slug: `${POST_CHANNEL}/${id}`, channelSlug: POST_CHANNEL, author: "postsubject", authorName: "Post Subject",
+ createdAt: "2026-10-30T10:00:00.000Z", uploadDate: "20261030", text: "", url: `https://x.com/postsubject/status/${id}`,
+ platform: "twitter", isReply: false, isRepost: false, links: [], threadId: id, lang: "en", engagement: { likes: 12, reposts: 3, replies: 1, quotes: 0 }, ...o,
+});
+
+/**
+ * @param {{ reports: string, channels: string, deckManifest: Function, cachedWindow: string }} o
+ */
+export function makePostItemsFixture({ reports, channels, deckManifest, cachedWindow }) {
+ // The archive and its captures.
+ const ch = path.join(channels, POST_CHANNEL);
+ mkdirSync(path.join(ch, "posts"), { recursive: true });
+ writeFileSync(path.join(ch, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", socialHandle: "postsubject", platform: "twitter", name: "Post Subject (X)" }, null, 2));
+ const rows = [
+ row("0", { createdAt: "2026-10-30T09:00:00.000Z", text: "The first thing I said about it." }),
+ row("1", { createdAt: "2026-10-30T10:00:00.000Z", text: "And a plain post with nothing but words in it, to read.", isReply: true, replyTo: { id: "0", author: "postsubject" } }),
+ row("2", { createdAt: "2026-10-30T11:00:00.000Z", text: "A picture of the thing.", mediaCount: 1 }),
+ row("9", { author: "someone_private", authorName: "Private Person", createdAt: "2026-10-30T11:30:00.000Z", text: "is this really true?" }),
+ row("3", { createdAt: "2026-10-30T12:00:00.000Z", text: "@someone_private Yes, and here is the video.", mediaCount: 1, isReply: true, replyTo: { id: "9", author: "someone_private" } }),
+ row("4", { createdAt: "2026-10-31T12:00:00.000Z", text: "One more post, a day later." }),
+ ];
+ writeFileSync(path.join(ch, "posts", "2026-10.jsonl"), rows.map((r) => JSON.stringify(r)).join("\n") + "\n");
+ const cap2 = path.join(ch, "posts-media", "2");
+ const cap3 = path.join(ch, "posts-media", "3");
+ mkdirSync(cap2, { recursive: true });
+ mkdirSync(cap3, { recursive: true });
+ ff(["-f", "lavfi", "-i", "testsrc=size=320x180:rate=1:duration=1", "-frames:v", "1", path.join(cap2, "2_1.png")]);
+ ff([
+ "-f", "lavfi", "-i", "testsrc=size=320x180:rate=30:duration=4",
+ "-f", "lavfi", "-i", "sine=frequency=440:duration=4",
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "48000", "-ac", "2", "-shortest", path.join(cap3, "3_1.mp4"),
+ ]);
+ writeFileSync(path.join(cap2, "capture.json"), JSON.stringify({ version: 1, id: "2", media: [{ name: "2_1.png", url: "https://pbs.twimg.com/media/x" }] }));
+ writeFileSync(path.join(cap3, "capture.json"), JSON.stringify({ version: 1, id: "3", media: [{ name: "3_1.mp4", url: "https://video.twimg.com/amplify_video/3/vid/x.mp4" }] }));
+
+ // The project: one clip, then the three post items as `posts reel` writes them.
+ const name = "post-items-fixture";
+ const dir = path.join(reports, name);
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "playvid_0.00-9.00.mp4"));
+ const media = path.join(dir, "posts-media", POST_CHANNEL);
+ mkdirSync(path.join(media, "2"), { recursive: true });
+ mkdirSync(path.join(media, "3"), { recursive: true });
+ copyFileSync(path.join(cap2, "2_1.png"), path.join(media, "2", "2_1.png"));
+ copyFileSync(path.join(cap3, "3_1.mp4"), path.join(media, "3", "3_1.mp4"));
+ const base = (r) => ({
+ type: "post", post: `${POST_CHANNEL}/${r.id}`, platform: "x", author: r.authorName, handle: r.author, date: r.createdAt, text: r.text, url: r.url,
+ engagement: r.engagement, subjects: ["postsubject"],
+ });
+ const timeline = [
+ { type: "clip", id: "c01", video: "playvid", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "This is a complete sentence.", onscreen: { title: "24 Oct 2020" } },
+ { ...base(rows[1]), id: "p-txt", parents: [{ id: "0", author: "Post Subject", handle: "postsubject", date: rows[0].createdAt, text: rows[0].text, url: rows[0].url }] },
+ { ...base(rows[2]), id: "p-img", media: [{ src: `posts-media/${POST_CHANNEL}/2/2_1.png`, kind: "image", width: 320, height: 180 }] },
+ {
+ ...base(rows[4]), id: "p-vid",
+ parents: [{ id: "9", author: "Private Person", handle: "someone_private", date: rows[3].createdAt, text: rows[3].text, url: rows[3].url }],
+ media: [{ src: `posts-media/${POST_CHANNEL}/3/3_1.mp4`, kind: "video", seconds: 4, width: 320, height: 180, audio: true }],
+ },
+ ];
+ const m = deckManifest(name, "The Post Items Fixture", timeline);
+ m.provenance = { ...m.provenance, channelSlug: POST_CHANNEL };
+ m.render.fetchPad = 0;
+ m.render.lockedEdges = false;
+ m.render.chrome = { ...m.render.chrome, deck: { ...(m.render.chrome?.deck ?? {}), markers: [{ after: "c01", label: "The posts" }] } };
+ writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+ return { dir };
+}
diff --git a/umtool/e2e/post-items.spec.ts b/umtool/e2e/post-items.spec.ts
@@ -0,0 +1,138 @@
+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";
+
+// ---------------------------------------------------------------------------
+// POST ITEMS (report-to-video/post-item.mjs; knobs.md, "A post item"): a cut
+// that mixes a clip with posts played as items of their own. Fixture:
+// e2e/fixtures/post-items-fixture.mjs -- c01 (a clip), p-txt (words only, a
+// self-reply under its parent), p-img (a picture), p-vid (a 4 s video with a
+// tone, a reply to a private account) from the synthesized archive postchan-x.
+//
+// The rule's seconds (reading 1 s + words / 3, at least 3; a parent 1-4 s;
+// then the attachments): p-txt 12 words + a 7-word parent = 5 + 2.33 = 7.33;
+// p-img 5 words = 3 + a picture 3.5 = 6.5; p-vid 7 words + a 4-word parent =
+// 3.33 + 1.33 = 4.67 to read, then the video's 4 s = 8.67.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const DIR = path.join(FIXTURE, "reports", "post-items-fixture");
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const PROJECT = "reports/post-items-fixture";
+const SHOTS = process.env.POST_ITEMS_SHOTS ?? null;
+
+type Entry = { id: string; type: string; media?: { start?: number; end?: number; mute?: boolean }[]; hold?: number };
+const timeline = () => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline;
+const umtool = (args: string[]) =>
+ execFileSync("node", ["bin/umtool.mjs", ...args], {
+ 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(120_000);
+ copyFileSync(`${MANIFEST}.pristine`, MANIFEST);
+ rmSync(path.join(DIR, "revisions"), { recursive: true, force: true });
+});
+
+const root = (page: Page) => page.locator("[data-play-cut]");
+
+test("the Cut tab lists the mixed cut: the clip, then post rows with their glyph, what they carry and how long they play", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.projectHref(PROJECT, { tab: "cut" }));
+ const rows = page.locator("[data-entry]");
+ await expect(rows).toHaveCount(4);
+ expect(await rows.evaluateAll((els) => els.map((e) => `${e.getAttribute("data-entry")}:${e.getAttribute("data-kind")}`))).toEqual([
+ "c01:clip", "p-txt:post", "p-img:post", "p-vid:post",
+ ]);
+ await expect(page.locator('[data-entry="c01"] [data-post-glyph]')).toHaveCount(0);
+ for (const id of ["p-txt", "p-img", "p-vid"]) await expect(page.locator(`[data-entry="${id}"] [data-post-glyph]`)).toBeVisible();
+ await expect(page.locator('[data-entry="p-txt"] [data-post-carries]')).toHaveText("text");
+ await expect(page.locator('[data-entry="p-img"] [data-post-carries]')).toHaveText("image");
+ await expect(page.locator('[data-entry="p-vid"] [data-post-carries]')).toHaveText("video");
+ await expect(page.locator('[data-entry="p-txt"] [data-post-seconds]')).toHaveText("7.3s");
+ await expect(page.locator('[data-entry="p-img"] [data-post-seconds]')).toHaveText("6.5s");
+ await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("8.7s");
+ await expect(page.locator('[data-entry="p-vid"]')).toContainText("Yes, and here is the video.");
+ // A post item takes a section's place like a clip: the bar after c01 opens on p-txt.
+ await expect(page.locator('[data-entry="p-vid"] [data-post-bench-link]')).toHaveAttribute("href", urls.postBenchHref(PROJECT, "p-vid"));
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-items-cut-tab.png"), fullPage: true });
+});
+
+test("Play plays a post item: its card, the private parent blurred, its video playing with the clock advancing", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.playHref(PROJECT, { bare: true, clip: "p-vid" }));
+ await expect(root(page)).toHaveAttribute("data-play-state", "paused");
+ await expect(root(page)).toHaveAttribute("data-play-item", "p-vid");
+ const player = page.locator('[data-post-play="p-vid"]');
+ await expect(player).toBeVisible();
+ await expect(player).toHaveAttribute("data-post-layout", "side");
+ await expect(player).toHaveAttribute("data-post-step", "read");
+ // The card is the build's page: the post's words, its counts, the parent above it blurred.
+ const card = page.frameLocator('[data-post-card-frame="read"]');
+ await expect(card.locator('[data-post-card="p-vid"]')).toBeVisible();
+ await expect(card.locator("[data-post-words]")).toContainText("Yes, and here is the video.");
+ await expect(card.locator('[data-post-parent="0"][data-redacted]')).toHaveCount(1);
+ await expect(card.locator("body")).not.toContainText("someone_private");
+ await expect(card.locator("body")).not.toContainText("Private Person");
+ // Its first frame is up beside the card while the words are read.
+ await expect(page.locator('[data-post-video="0"]')).toHaveAttribute("data-post-video-playing", "0");
+ const t0 = Number(await root(page).getAttribute("data-play-t"));
+ await page.locator("[data-play-toggle]").click();
+ await expect(player).toHaveAttribute("data-post-step", "video", { timeout: 15_000 });
+ await expect(page.locator('[data-post-video="0"]')).toHaveAttribute("data-post-video-playing", "1");
+ await expect.poll(async () => page.locator('[data-post-video="0"]').evaluate((v: HTMLVideoElement) => v.currentTime), { timeout: 10_000 }).toBeGreaterThan(0.5);
+ expect(await page.locator('[data-post-video="0"]').evaluate((v: HTMLVideoElement) => v.muted)).toBe(false);
+ const t1 = Number(await root(page).getAttribute("data-play-t"));
+ expect(t1).toBeGreaterThan(t0 + 4);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-items-play.png") });
+ await page.locator("[data-play-toggle]").click();
+ // Edit this post opens its bench, and Back to the cut returns to it.
+ await page.locator("[data-play-edit]").click();
+ await expect(page.locator('[data-post-bench="p-vid"]')).toBeVisible();
+ await page.locator("[data-post-bench-back]").click();
+ await expect(root(page)).toHaveAttribute("data-play-item", "p-vid");
+});
+
+test("the post bench trims the video attachment and saves it; the cut's seconds follow", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 1000 });
+ await page.goto(urls.postBenchHref(PROJECT, "p-vid"));
+ await expect(page.locator('[data-post-bench="p-vid"]')).toBeVisible();
+ await expect(page.locator("[data-post-bench-rule]")).toHaveText("8.7 s");
+ await page.locator('[data-post-bench-start="0"]').fill("1");
+ await page.locator('[data-post-bench-end="0"]').fill("3");
+ await expect(page.locator("[data-post-bench-rule]")).toHaveText("6.7 s");
+ await expect(page.locator('[data-post-bench-step="video"]')).toContainText("video 2.0 s");
+ await page.locator('[data-post-bench-sound="0"]').uncheck();
+ await page.locator("[data-post-bench-save]").click();
+ await expect(page.locator("[data-post-bench-status]")).toHaveText("saved");
+ const v = timeline().find((e) => e.id === "p-vid")!;
+ expect(v.media?.[0]).toMatchObject({ start: 1, end: 3, mute: true });
+ // A trim that leaves less than half a second is refused in the build's words, and nothing is written.
+ await page.locator('[data-post-bench-end="0"]').fill("1.2");
+ await page.locator("[data-post-bench-save]").click();
+ await expect(page.locator("[data-post-bench-error]")).toContainText("at least 0.5 s after start");
+ expect(timeline().find((e) => e.id === "p-vid")!.media?.[0]?.end).toBe(3);
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "post-items-bench.png") });
+ await page.goto(urls.projectHref(PROJECT, { tab: "cut" }));
+ await expect(page.locator('[data-entry="p-vid"] [data-post-seconds]')).toHaveText("6.7s");
+});
+
+test("umtool posts reel adds only what the cut does not play yet, in one write", async () => {
+ const dry = JSON.parse(umtool(["posts", "reel", PROJECT, "--channel", "postchan-x", "--own", "--dry-run", "--json"])) as { entries: { id: string }[]; already: number };
+ // 0 is p-txt's parent (not an item yet), 1-3 are in the cut, 4 is new; 9 is not the subject's.
+ expect(dry.entries.map((e) => e.id)).toEqual(["p-0", "p-4"]);
+ expect(dry.already).toBe(3);
+ umtool(["posts", "reel", PROJECT, "--channel", "postchan-x", "--own", "--since", "2026-10-31"]);
+ expect(timeline().map((e) => e.id)).toEqual(["c01", "p-txt", "p-img", "p-vid", "p-4"]);
+ const again = JSON.parse(umtool(["posts", "reel", PROJECT, "--channel", "postchan-x", "--own", "--since", "2026-10-31", "--json"])) as { added: number };
+ expect(again.added).toBe(0);
+});
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -265,6 +265,19 @@ export function projectAtHref(id: string, q: NoteOpt = {}): string {
}
/** The clip bench, one timeline entry. */
+/**
+ * A POST ITEM's bench (report-to-video/post-item.mjs): its attachments' trims,
+ * sound and crop, its hold. From Play ("Edit this clip"): Back lands `at`
+ * seconds into the item.
+ */
+export function postBenchHref(project: string, id: string, q: { play?: { at?: number | null } | null } = {}): string {
+ const play = q.play;
+ return withQuery(
+ `/projects/${encodePath(project)}/post/${encodeURIComponent(id)}`,
+ play ? { from: "play", at: play.at != null && play.at > 0 ? play.at.toFixed(2) : null } : {},
+ );
+}
+
export function clipBenchHref(
project: string,
clip: string,
diff --git a/umtool/lib/projects/kinds.mjs b/umtool/lib/projects/kinds.mjs
@@ -102,7 +102,8 @@ export const PROJECT_KINDS = [
// Views reachable under the project's own URL:
// /browse/<project>/clip/<id> the window bench
// /browse/<project>/claim/<id> the adjudication bench
- views: ["clip", "claim"],
+ // /browse/<project>/post/<id> a post item's bench
+ views: ["clip", "claim", "post"],
// What "new project" asks for, beyond a slug and a title. Declared HERE so
// the menu renders fields from data and never branches on a kind id.
// `brand` offers report-to-video's presets (render.brand); none is the
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -5,6 +5,7 @@
// this from a terminal with no server. It is also the only place that knows the
// manifest's shape -- the walk knows a marker file, the page knows a summary,
// and neither parses JSON.
+import { postItemSeconds } from "umtool-report-to-video/post-item";
import { readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { DEFAULT_VARIANT, cachedWindowsFor, fetchSpans } from "umtool-report-to-video/build-video";
@@ -895,7 +896,10 @@ export async function summariseReport(ctx) {
const others = (m?.timeline ?? []).filter((e) => e?.type !== "clip" && e?.type !== "card");
const build = await buildStateOf(dir, m);
- const runtime = clips.reduce((n, e) => n + Math.max(0, (e.end ?? 0) - (e.start ?? 0)), 0);
+ // Post items (report-to-video/post-item.mjs) play their duration rule's seconds.
+ const runtime =
+ clips.reduce((n, e) => n + Math.max(0, (e.end ?? 0) - (e.start ?? 0)), 0) +
+ (m?.timeline ?? []).filter((e) => e?.type === "post").reduce((n, e) => n + postItemSeconds(e), 0);
const sources = new Set(clips.map((e) => (e.src != null ? `src:${e.src}` : `${channelFor(m, e)}/${e.video}`))).size;
const locked = clips.filter((e) => e.lock).length;
diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs
@@ -315,7 +315,7 @@ export async function projectPlace(root, slugArg, folderArg = null) {
*
* @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null, laughMin?: number, scope?: [number, number | null] | "auto" | null, segment?: string | null, sitesDir?: string }} args
*/
-export async function scaffoldReportVideo({ root, slug: slugArg, folder: folderArg = null, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null, laughMin = undefined, scope = null, segment = null, sitesDir = undefined }) {
+export async function scaffoldReportVideo({ root, slug: slugArg, folder: folderArg = null, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null, laughMin = undefined, scope = null, segment = null, sitesDir = undefined, postsChannel = null }) {
const { id, slug, folder } = await projectPlace(root, slugArg, folderArg);
const dir = path.join(root, ...id.split("/"));
if (dir !== path.resolve(root, id) || path.dirname(dir) !== path.resolve(root, folder ?? ".")) {
@@ -359,6 +359,8 @@ export async function scaffoldReportVideo({ root, slug: slugArg, folder: folderA
}
// Release 36: `auto` (or a `segment`) is the narrated video auto-scope finds in the recording.
const reactionsScope = seed !== "reactions" ? null : scope === "auto" || segment ? "auto" : normalizeScope(scope);
+ if (postsChannel && (seed || src || timeline)) throw new Error("--from-posts makes a posts reel: give it without --from, --seed or a timeline");
+ if (postsChannel && !CHANNEL_SLUG_RE.test(String(postsChannel))) throw new Error(`"${postsChannel}" is not a channel slug`);
if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed");
if (target !== undefined && seed !== "frames" && seed !== "reactions") throw new Error("--target is the frames seed's length budget (or the reactions seed's): give it with --seed frames or --seed reactions");
const [tLo, tHi] = seed === "reactions" ? PARAM_BOUNDS.target : [10, 3600];
@@ -395,6 +397,14 @@ export async function scaffoldReportVideo({ root, slug: slugArg, folder: folderA
if (siteOrigin) provenance.siteOrigin = String(siteOrigin);
const doc = skeleton(slug, finalTitle, provenance, { brand });
+ // A posts reel (`--from-posts`): the deck on -- its rail, section bars and
+ // date over each post item -- and with no archive to link (no siteOrigin)
+ // its QR opens the post itself. The timeline is the reel's (postReel.mjs),
+ // written after this by `umtool posts reel`'s own writer.
+ if (postsChannel) {
+ doc.provenance.channelSlug = String(postsChannel);
+ doc.render.chrome = { engine: "hyperframes", layout: "deck", deck: provenance.siteOrigin ? {} : { qr: { links: "original" } } };
+ }
let seeded = 0;
if (seed === "chapters") {
diff --git a/umtool/lib/report/claimGroups.mjs b/umtool/lib/report/claimGroups.mjs
@@ -52,7 +52,8 @@ export const GROUP_KEYS = Object.freeze(["id", "section", "claim", "ids"]);
const GROUP_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
-const isClip = (e) => !!e && (e.kind ?? e.type) === "clip";
+// A FOOTAGE entry: a clip, or a post item (post-item.mjs) -- what a section holds and a marker follows.
+const isClip = (e) => !!e && ((e.kind ?? e.type) === "clip" || (e.kind ?? e.type) === "post");
const quoted = (s, n = 48) => {
const t = String(s ?? "");
return `"${t.length > n ? `${t.slice(0, n - 1)}…` : t}"`;
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -57,6 +57,7 @@ import {
variantsProblems, verdictOfInput,
} from "./knobs.mjs";
import { validateNarration } from "umtool-report-to-video/narration";
+import { validatePostItem, validatePostItems } from "umtool-report-to-video/post-item";
import { parseMuteFrom } from "./playback.mjs";
import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webpageReader } from "./linkPolicy.mjs";
import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources";
@@ -1864,6 +1865,8 @@ function structureErrors(manifest) {
...validateClipBlurEntries(manifest),
// Claim groups (claimGroups.mjs): each one's clips together, in one section.
...validateGroups(manifest),
+ // Post items (post-item.mjs): an archived post as an entry of its own.
+ ...validatePostItems(manifest),
];
}
@@ -1993,7 +1996,8 @@ export function reanchorAfterRemove(m, removed, i) {
const chrome = m?.render?.chrome;
if (!id || !chrome || typeof chrome !== "object") return notes;
const tl = m.timeline ?? [];
- const isClip = (e) => e && (e.kind ?? e.type) === "clip";
+ // A footage entry: a clip or a post item (a marker may follow either).
+ const isClip = (e) => e && ((e.kind ?? e.type) === "clip" || (e.kind ?? e.type) === "post");
const prevClip = [...tl.slice(0, i)].reverse().find(isClip) ?? null;
const nextInSection = tl.slice(i).find((e) => isClip(e) && (e.section ?? null) === (removed.section ?? null)) ?? null;
const obj = (v) => v && typeof v === "object" && !Array.isArray(v);
@@ -2309,6 +2313,90 @@ export async function insertEntry(dir, afterId, spec, { token = null, at = null
}, { prepare: (m) => policyWebpage(dir, m, typeof spec === "string" ? parseClipSpec(spec) : spec) }));
}
+/**
+ * INSERT SEVERAL ENTRIES IN ONE WRITE (a posts reel, `umtool posts reel`): each
+ * spec as insertEntry takes it, in order, after `afterId` (null: at the end;
+ * "" or "-": at the start) -- one structural write, so one undo point and one
+ * check of what they break together. Returns `{ ids, at, entries }`.
+ *
+ * @param {string} dir
+ * @param {string | null} afterId
+ * @param {unknown[]} specs
+ * @param {{ token?: string | null, op?: string }} [opts]
+ */
+export async function insertEntries(dir, afterId, specs, { token = null, op = "insert" } = {}) {
+ if (!Array.isArray(specs) || !specs.length) throw new Error("nothing to insert");
+ return prepAfter(dir, (r) => r.entries.filter((e) => e.type === "clip").map((e) => e.id), structural(dir, op, token, (m) => {
+ let i = afterId === null || afterId === undefined ? m.timeline.length : afterId === "" || afterId === "-" ? 0 : entryIndex(m.timeline, afterId) + 1;
+ const at = i;
+ const entries = [];
+ for (const spec of specs) {
+ const entry = entryFromSpec(m.timeline, spec);
+ if (entry.type === "post") {
+ const errors = validatePostItem(entry);
+ if (errors.length) throw new StructureRefused(errors);
+ }
+ m.timeline.splice(i, 0, entry);
+ entries.push(entry);
+ i += 1;
+ }
+ return { ids: entries.map((e) => e.id), at, entries };
+ }, { snapshotEvery: 0 }));
+}
+
+/** The knobs of a post item a write may set (post-item.mjs; knobs.md, "A post item"). */
+export const POST_ITEM_KNOBS = Object.freeze(["hold", "mediaLayout", "redact"]);
+/** A post item attachment's knobs: its trim, its sound, its crop, the push-in, its transcript. */
+export const POST_MEDIA_KNOBS = Object.freeze(["start", "end", "mute", "crop", "push", "words"]);
+
+/**
+ * SET A POST ITEM's KNOBS (the post bench, `umtool posts set-item`): `patch`
+ * is `{ hold?, mediaLayout?, redact?, media?: { <i>: { start?, end?, mute?,
+ * crop?, push?, words? } } }`; a null clears a knob (the default again). One
+ * structural write, refused in the build's words (validatePostItem).
+ *
+ * @param {string} dir
+ * @param {string} id
+ * @param {Record<string, any>} patch
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function updatePostItem(dir, id, patch, { token = null } = {}) {
+ if (!isObj(patch)) throw new Error("a post item's patch is an object");
+ for (const k of Object.keys(patch)) {
+ if (k !== "media" && !POST_ITEM_KNOBS.includes(k)) throw new Error(`${k} is not a post item knob (${[...POST_ITEM_KNOBS, "media"].join(", ")})`);
+ }
+ return structural(dir, "post-item", token, (m) => {
+ const i = entryIndex(m.timeline, id);
+ const e = m.timeline[i];
+ if (e?.type !== "post") throw new Error(`${id} is a ${e?.type ?? "?"} entry, not a post item`);
+ const set = (o, k, v) => {
+ if (v === null || v === undefined) delete o[k];
+ else o[k] = typeof v === "number" ? round2(v) : v;
+ };
+ for (const k of POST_ITEM_KNOBS) if (k in patch) set(e, k, patch[k]);
+ if (isObj(patch.media)) {
+ const media = Array.isArray(e.media) ? e.media : [];
+ for (const [key, mp] of Object.entries(patch.media)) {
+ const n = Number(key);
+ if (!Number.isInteger(n) || !media[n]) throw new Error(`${id} has no attachment ${key} (0–${media.length - 1})`);
+ if (!isObj(mp)) throw new Error(`media.${key} is an object of knobs`);
+ for (const k of Object.keys(mp)) if (!POST_MEDIA_KNOBS.includes(k)) throw new Error(`media.${key}.${k} is not an attachment knob (${POST_MEDIA_KNOBS.join(", ")})`);
+ for (const k of POST_MEDIA_KNOBS) {
+ if (!(k in mp)) continue;
+ if (k === "crop" && Array.isArray(mp.crop)) media[n].crop = mp.crop.map((v) => Math.round(Number(v) * 10000) / 10000);
+ else set(media[n], k, mp[k]);
+ }
+ // A trim back to the whole file is no trim.
+ if (media[n].start === 0) delete media[n].start;
+ if (Number.isFinite(media[n].seconds) && Number.isFinite(media[n].end) && Math.abs(media[n].end - media[n].seconds) < 0.02) delete media[n].end;
+ }
+ }
+ const errors = validatePostItem(e);
+ if (errors.length) throw new StructureRefused(errors);
+ return { id, at: i, entry: e };
+ });
+}
+
// ---- the link policy (UI notes 2026-10-30, #10; linkPolicy.mjs) -----------
/**
@@ -2391,10 +2479,10 @@ export function insertIntoIn(m, spec, { section = null, group = null } = {}) {
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");
+ if (entry.type !== "clip" && entry.type !== "post") throw new Error("only a clip or a post item 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);
+ const at = (id) => tl.findIndex((e) => (e?.type === "clip" || e?.type === "post") && e.id === id);
let target;
let after;
let g = null;
@@ -2420,7 +2508,7 @@ export function insertIntoIn(m, spec, { section = null, group = null } = {}) {
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);
+ const last = [...tl].reverse().find((e) => (e?.type === "clip" || e?.type === "post") && (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;
}
diff --git a/umtool/lib/report/patchMarkers.mjs b/umtool/lib/report/patchMarkers.mjs
@@ -27,7 +27,8 @@ import path from "node:path";
export const PATCH_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.patch\.json$/;
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
-const isClip = (e) => isObj(e) && (e.kind ?? e.type) === "clip";
+// A FOOTAGE entry: a clip, or a post item (post-item.mjs) -- what a section holds and a marker follows.
+const isClip = (e) => isObj(e) && ((e.kind ?? e.type) === "clip" || (e.kind ?? e.type) === "post");
/** The project's take patches: `*.patch.json` beside the manifest, by name. */
export async function patchFilesOf(dir) {
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -14,6 +14,7 @@ import { resolveFactcheck } from "umtool-report-to-video/factcheck";
import { clipDateKey, readManifest } from "../projects/report.mjs";
import { rejectionOf } from "./rejectReasons.mjs";
import { dateKeyLabel } from "./playCut.mjs";
+import { postDay, postItemPlan } from "umtool-report-to-video/post-item";
import { pickWindow, projectCache, windowVersion, windowsFor } from "./serve.mjs";
import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs";
import { readWorkingCut } from "./workingCut.mjs";
@@ -30,6 +31,30 @@ export function headingOf(e) {
}
/**
+ * A POST ITEM as Play plays it (post-item.mjs): the entry itself (its card is
+ * drawn from it, by the same HTML the build screenshots), the plan of what
+ * plays when, and the day for the reel strip's tint. Its files are served by
+ * /api/report/post-item, which serves only what a post item names.
+ */
+export function postPlayEntry(e) {
+ const day = postDay(e.date);
+ const dateKey = day ? Number(day.replace(/-/g, "")) : null;
+ const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim();
+ return {
+ id: e.id,
+ type: "post",
+ heading: `${e.author ?? (e.handle ? `@${e.handle}` : "a post")}: ${words.length > 80 ? `${words.slice(0, 77)}…` : words || "(no words)"}`,
+ section: e.section ?? null,
+ dateKey,
+ dateLabel: dateKeyLabel(dateKey),
+ date: day || null,
+ quote: words || null,
+ post: e,
+ postPlan: postItemPlan(e),
+ };
+}
+
+/**
* WHAT PLAYS BY DEFAULT is the LATEST take (operator, 1 Nov 2026): with no
* `take`, the newest working take (workingCut.mjs) -- the project's manifest
* as it is now with that take's patch, so the look is the next draft's and
@@ -80,6 +105,7 @@ export async function playView(project, { take = null, bare = false } = {}) {
const cache = await projectCache(project, manifest);
const entries = await Promise.all(
timeline.map(async (e) => {
+ if (e.type === "post") return postPlayEntry(e);
if (e.type !== "clip" || !fin(e.start) || !fin(e.end)) return { id: e.id, type: String(e.type ?? "entry"), heading: headingOf(e), section: e.section ?? null };
const win = pickWindow(await windowsFor(project, e, cache), null);
const dateKey = clipDateKey(e);
diff --git a/umtool/lib/report/postReel.mjs b/umtool/lib/report/postReel.mjs
@@ -0,0 +1,446 @@
+// A POSTS REEL (umtool/docs/report-video.md, "Post items"): a cut's timeline
+// built -- or extended -- from a channel's posts archive, each post a post item
+// (umtool-report-to-video/post-item.mjs) played like a slideshow, its
+// attachments with it.
+//
+// umtool posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until …]
+// [--own] [--with-media] [--replies include|only|exclude] [--order chrono|reverse]
+// [--limit N] [--after <id|->] [--dry-run] [--json]
+// umtool new <p> --from-posts <slug> [the same filters]
+//
+// THE ARCHIVE is the corpus's `channels/<slug>/posts/YYYY-MM.jsonl` (the last
+// line with an id wins: a re-fetch appends) and its captures,
+// `channels/<slug>/posts-media/<postId>/` (capture.json and the post's own
+// pictures and videos). Several channels are read as one archive -- a
+// profile's posts and its replies are two channels -- merged in time order
+// and de-duplicated by post id. The corpus is the one the project reads
+// (its provenance.channelsDir, else CHANNELS_DIR).
+//
+// EACH POST becomes an entry that carries what it says (postEntryFrom): its
+// words, author, date, link and counts snapshotted from the archive row; a
+// repost drawn as the post it reposts, "reposted by" its reposter; a reply
+// with the posts it answers (from the archive, nearest first, up to
+// POST_PARENTS_MAX) -- else the capture's `shot-thread.png` -- else a
+// "replying to" line; its attachments COPIED into the project
+// (`posts-media/<slug>/<postId>/`, never a link out of it) and measured (a
+// video's length and whether it has sound; X serves a GIF as a silent mp4
+// from `tweet_video/`).
+//
+// RE-RUNNING ADDS ONLY WHAT IS NOT THERE: a post already in the cut -- by its
+// id, or as the original of a repost already in it, or reposted by one -- is
+// skipped and counted. Everything new goes in through ONE write
+// (manifest.mjs insertEntries): one undo point, refused whole by the build's
+// checks.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { execFile } from "node:child_process";
+import { copyFile, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+import { POST_MEDIA_MAX, POST_PARENTS_MAX } from "umtool-report-to-video/post-item";
+import { channelsDirFor, readManifest } from "../projects/report.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { insertEntries, manifestToken } from "./manifest.mjs";
+import { deckPlatformOf } from "./postsCli.mjs";
+
+const execFileP = promisify(execFile);
+const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe";
+
+export const REEL_ORDERS = Object.freeze(["chrono", "reverse"]);
+export const REEL_REPLIES = Object.freeze(["include", "only", "exclude"]);
+const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
+const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
+const IMAGE_EXT = /\.(?:jpe?g|png|webp)$/i;
+const VIDEO_EXT = /\.(?:mp4|m4v|mov|webm)$/i;
+const GIF_EXT = /\.gif$/i;
+
+const str = (v) => (typeof v === "string" ? v : "");
+const same = (a, b) => !!a && !!b && String(a).replace(/^@/, "").toLowerCase() === String(b).replace(/^@/, "").toLowerCase();
+const timeOf = (row) => {
+ const t = Date.parse(str(row?.createdAt));
+ if (Number.isFinite(t)) return t;
+ const d = str(row?.uploadDate);
+ return /^\d{8}$/.test(d) ? Date.parse(`${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}T00:00:00Z`) : NaN;
+};
+
+/**
+ * Every row of a channel's posts archive, by id (the last line with an id
+ * wins), each with `channelSlug` set to `slug`. A channel with no archive is [].
+ */
+export async function readPostsArchive(channelsDir, slug) {
+ const dir = path.join(channelsDir, slug, "posts");
+ const names = (await readdir(dir).catch(() => [])).filter((n) => /^\d{4}-\d{2}\.jsonl$/.test(n)).sort();
+ 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;
+ try {
+ const row = JSON.parse(line);
+ if (row && row.id !== undefined) byId.set(String(row.id), { ...row, id: String(row.id), channelSlug: slug });
+ } catch {
+ // a torn line is not a post
+ }
+ }
+ }
+ return [...byId.values()];
+}
+
+/** The channel's own account (its config's socialHandle), or null. */
+export async function channelHandle(channelsDir, slug) {
+ try {
+ const c = JSON.parse(await readFile(path.join(channelsDir, slug, "config.json"), "utf8"));
+ return typeof c?.socialHandle === "string" && c.socialHandle ? c.socialHandle.replace(/^@/, "") : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The files a post's capture holds (`posts-media/<postId>/`): capture.json's
+ * `media` in its order (with each one's source url), else the folder's
+ * pictures and videos by name. Never `shot.png` or the thread shot.
+ *
+ * @returns {Promise<{ dir: string, media: Array<{ name: string, url: string | null }>, threadShot: string | null }>}
+ */
+export async function captureOf(channelsDir, slug, postId) {
+ const dir = path.join(channelsDir, slug, "posts-media", postId);
+ const names = await readdir(dir).catch(() => []);
+ let media = [];
+ try {
+ const cap = JSON.parse(await readFile(path.join(dir, "capture.json"), "utf8"));
+ if (Array.isArray(cap?.media)) {
+ media = cap.media.filter((m) => typeof m?.name === "string" && names.includes(m.name)).map((m) => ({ name: m.name, url: typeof m.url === "string" ? m.url : null }));
+ }
+ } catch {
+ // no record: the folder's own files
+ }
+ if (!media.length) {
+ media = names
+ .filter((n) => n !== "shot.png" && n !== "shot-thread.png" && (IMAGE_EXT.test(n) || VIDEO_EXT.test(n) || GIF_EXT.test(n)))
+ .sort()
+ .map((name) => ({ name, url: null }));
+ }
+ return { dir, media: media.slice(0, POST_MEDIA_MAX), threadShot: names.includes("shot-thread.png") ? path.join(dir, "shot-thread.png") : null };
+}
+
+/**
+ * The SELECTION, pure: `rows` (several channels' archives, each row's
+ * `channelSlug` set) filtered and ordered.
+ *
+ * since / until the post's UTC day, inclusive (YYYY-MM-DD)
+ * own the accounts' own posts: written by one of `handles`, not a repost
+ * replies include (default) | only | exclude
+ * withMedia only posts whose capture holds an attachment (`hasMedia(row)`)
+ * order chrono (oldest first, the default) | reverse
+ * limit at most this many
+ *
+ * Merged across channels in time order, de-duplicated by post id (the first
+ * channel named keeps it); a repost whose original is in the selection is
+ * the original's, not a second item.
+ */
+export function selectPosts(rows, { since = null, until = null, own = false, replies = "include", withMedia = false, hasMedia = () => true, order = "chrono", limit = null, handles = [] } = {}) {
+ const seen = new Set();
+ const list = [];
+ for (const r of rows) {
+ if (!r || seen.has(r.id)) continue;
+ seen.add(r.id);
+ list.push(r);
+ }
+ const day = (r) => {
+ const t = timeOf(r);
+ return Number.isFinite(t) ? new Date(t).toISOString().slice(0, 10) : "";
+ };
+ let out = list.filter((r) => {
+ const d = day(r);
+ if (since && (!d || d < since)) return false;
+ if (until && (!d || d > until)) return false;
+ if (own && (r.isRepost === true || !handles.some((h) => same(h, r.author)))) return false;
+ if (replies === "only" && r.isReply !== true) return false;
+ if (replies === "exclude" && r.isReply === true) return false;
+ if (withMedia && !hasMedia(r)) return false;
+ return true;
+ });
+ const ids = new Set(out.map((r) => r.id));
+ out = out.filter((r) => !(r.isRepost === true && r.repostOf?.id && ids.has(String(r.repostOf.id))));
+ out.sort((a, b) => (timeOf(a) - timeOf(b)) * (order === "reverse" ? -1 : 1) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) * (order === "reverse" ? -1 : 1));
+ return Number.isInteger(limit) && limit > 0 ? out.slice(0, limit) : out;
+}
+
+/** The post ids a cut already plays: each post item's own, its repost's original, and its reposter's. */
+export function postsInCut(manifest) {
+ const ids = new Set();
+ for (const e of manifest?.timeline ?? []) {
+ if (e?.type !== "post") continue;
+ const id = String(e.post ?? "").split("/")[1];
+ if (id) ids.add(id);
+ if (typeof e.repostId === "string") ids.add(e.repostId);
+ if (typeof e.originalId === "string") ids.add(e.originalId);
+ }
+ return ids;
+}
+
+/** A media file measured: its pixels, and for a video its length and whether it has sound. */
+export async function probeMediaFile(file) {
+ try {
+ const { stdout } = await execFileP(FFPROBE, ["-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height", "-of", "json", file]);
+ const j = JSON.parse(stdout);
+ const v = (j.streams ?? []).find((s) => s.codec_type === "video") ?? {};
+ const audio = (j.streams ?? []).some((s) => s.codec_type === "audio");
+ const seconds = Number(j.format?.duration);
+ return { width: Number.isInteger(v.width) ? v.width : undefined, height: Number.isInteger(v.height) ? v.height : undefined, audio, seconds: Number.isFinite(seconds) ? Math.round(seconds * 1000) / 1000 : undefined };
+ } catch {
+ return {};
+ }
+}
+
+/** The kind an attachment plays as: a picture; a GIF (X's `tweet_video/` mp4, or a .gif); else a video. */
+export function mediaKindOf(name, url, probe = {}) {
+ if (IMAGE_EXT.test(name)) return "image";
+ if (GIF_EXT.test(name) || /\/tweet_video\//.test(str(url))) return "gif";
+ if (probe.audio === false && Number.isFinite(probe.seconds) && probe.seconds <= 15) return "gif";
+ return "video";
+}
+
+/** A ref (a parent, the quoted post) from an archive row, or from what a row says of another. */
+function refOf(row, fallback = {}) {
+ const handle = str(row?.author).replace(/^@/, "") || str(fallback.author).replace(/^@/, "");
+ return {
+ ...(row?.id || fallback.id ? { id: String(row?.id ?? fallback.id) } : {}),
+ ...(str(row?.authorName) ? { author: row.authorName } : {}),
+ ...(handle ? { handle } : {}),
+ ...(typeof row?.badge === "string" ? { badge: row.badge } : row?.verifiedType === "Business" ? { badge: "gold" } : row?.verifiedType === "Government" ? { badge: "grey" } : {}),
+ ...(str(row?.createdAt) ? { date: row.createdAt } : {}),
+ ...(typeof row?.text === "string" ? { text: row.text } : {}),
+ ...(str(row?.url) || str(fallback.url) ? { url: str(row?.url) || fallback.url } : {}),
+ };
+}
+
+const counts = (e) => {
+ if (!e || typeof e !== "object") return undefined;
+ const out = {};
+ for (const k of ["likes", "reposts", "replies", "quotes"]) if (Number.isInteger(e[k]) && e[k] >= 0) out[k] = e[k];
+ return Object.keys(out).length ? out : undefined;
+};
+
+/**
+ * The entry for archive row `row` (pure but for what `io` reads): `index`
+ * finds a post by id across the channels read; `capture(slug, id)` its
+ * capture; `copy(fromFile, toRel)` puts a file into the project and returns
+ * its project-relative path; `probe(file)` measures it.
+ */
+export async function postEntryFrom(row, { index, io, subjects = [] }) {
+ const slug = row.channelSlug;
+ // A repost is drawn as the post it reposts, "reposted by" its reposter.
+ const original = row.isRepost === true && row.repostOf?.id ? index.get(String(row.repostOf.id)) ?? null : null;
+ const shown = row.isRepost === true ? original ?? { ...row, id: String(row.repostOf?.id ?? row.id), author: row.repostOf?.author ?? row.author, authorName: undefined, text: str(row.text).replace(/^RT @[A-Za-z0-9_]+:\s*/, ""), url: row.repostOf?.url ?? row.url, engagement: undefined } : row;
+ const shownSlug = shown.channelSlug ?? slug;
+ const entry = {
+ type: "post",
+ id: `p-${row.id}`,
+ post: `${slug}/${row.id}`,
+ platform: deckPlatformOf(row.platform),
+ ...(str(shown.authorName) ? { author: shown.authorName } : {}),
+ ...(str(shown.author) ? { handle: str(shown.author).replace(/^@/, "") } : {}),
+ date: str(shown.createdAt) || new Date(timeOf(row)).toISOString(),
+ text: typeof shown.text === "string" ? shown.text : "",
+ ...(str(shown.url) ? { url: shown.url } : {}),
+ ...(counts(shown.engagement) ? { engagement: counts(shown.engagement) } : {}),
+ ...(typeof shown.badge === "string" ? { badge: shown.badge } : {}),
+ // The accounts the reel is about: every other author it draws is blurred unless verified (post-item.mjs authorRedaction).
+ ...(subjects.length ? { subjects } : {}),
+ };
+ if (row.isRepost === true) {
+ entry.repostedBy = { ...(str(row.authorName) ? { author: row.authorName } : {}), handle: str(row.author).replace(/^@/, "") };
+ entry.originalId = String(row.repostOf?.id ?? shown.id);
+ }
+ // A reply: the posts it answers, nearest first, from the archive; else the thread shot; else a line.
+ const replyTo = shown.replyTo ?? null;
+ if (shown.isReply === true && replyTo?.id) {
+ const parents = [];
+ let at = replyTo;
+ while (at?.id && parents.length < POST_PARENTS_MAX) {
+ const p = index.get(String(at.id));
+ if (!p) break;
+ parents.push(refOf(p));
+ at = p.isReply === true ? p.replyTo : null;
+ }
+ if (parents.length) entry.parents = parents;
+ else {
+ const cap = await io.capture(shownSlug, String(shown.id));
+ if (cap.threadShot) entry.parentShot = await io.copy(cap.threadShot, `posts-media/${shownSlug}/${shown.id}/shot-thread.png`);
+ else if (str(replyTo.author)) entry.replyingTo = str(replyTo.author).replace(/^@/, "");
+ }
+ }
+ if (shown.quoted && typeof shown.quoted === "object") {
+ const q = index.get(String(shown.quoted.id ?? "")) ?? null;
+ entry.quoted = refOf(q ?? { ...shown.quoted, author: shown.quoted.author ?? shown.quoted.handle, authorName: shown.quoted.authorName ?? shown.quoted.name }, shown.quoted);
+ }
+ // Its attachments: the shown post's capture (a repost's original), else the row's own.
+ let cap = await io.capture(shownSlug, String(shown.id));
+ let capSlug = shownSlug;
+ let capId = String(shown.id);
+ if (!cap.media.length && shown !== row) {
+ cap = await io.capture(slug, row.id);
+ capSlug = slug;
+ capId = row.id;
+ }
+ const media = [];
+ for (const m of cap.media) {
+ const from = path.join(cap.dir, m.name);
+ const src = await io.copy(from, `posts-media/${capSlug}/${capId}/${m.name}`);
+ const probe = await io.probe(from);
+ const kind = mediaKindOf(m.name, m.url, probe);
+ media.push({
+ src, kind,
+ ...(probe.width ? { width: probe.width } : {}),
+ ...(probe.height ? { height: probe.height } : {}),
+ ...(kind !== "image" && probe.seconds ? { seconds: probe.seconds } : {}),
+ ...(kind === "video" ? { audio: probe.audio === true } : {}),
+ });
+ }
+ // A timed attachment that could not be measured cannot be planned: it is left out, and said.
+ const kept = media.filter((m) => m.kind === "image" || Number.isFinite(m.seconds));
+ if (kept.length) entry.media = kept;
+ return { entry, dropped: media.length - kept.length };
+}
+
+/** Copy a file into the project (never through a link out of it); the same bytes already there are left. */
+async function copyInto(projectDir, from, rel) {
+ const to = path.join(projectDir, ...rel.split("/"));
+ const [a, b] = await Promise.all([stat(from).catch(() => null), stat(to).catch(() => null)]);
+ if (b && a && a.size === b.size) return rel;
+ await mkdir(path.dirname(to), { recursive: true });
+ const real = await realpath(path.dirname(to));
+ const proj = await realpath(projectDir);
+ if (real !== proj && !real.startsWith(proj + path.sep)) throw new Error(`${path.dirname(rel)} leads out of the project (a link) — not copying through it`);
+ await copyFile(from, to);
+ return rel;
+}
+
+/** Parse YYYY-MM-DD (or null); throws in words. */
+function dayArg(v, what) {
+ if (v === null || v === undefined || v === "") return null;
+ if (!DAY_RE.test(String(v)) || Number.isNaN(Date.parse(String(v)))) throw new Error(`${what} takes a day, YYYY-MM-DD (got ${v})`);
+ return String(v);
+}
+
+/**
+ * BUILD OR EXTEND THE CUT from the archive: read `channels`, select, skip what
+ * the cut already plays, make each entry (its media copied in), and put them
+ * all in in ONE write after `after` (null: the end). `dryRun`: nothing copied
+ * or written -- the list of what would go in.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ channels: string[], since?: string|null, until?: string|null, own?: boolean, withMedia?: boolean,
+ * replies?: string, order?: string, limit?: number|null, after?: string|null, dryRun?: boolean, channelsDir?: string|null }} o
+ */
+export async function postsReel(project, o) {
+ const channels = [...new Set((o.channels ?? []).map((c) => String(c).trim()).filter(Boolean))];
+ if (!channels.length) throw new Error("name the posts channel: --channel <slug> (more than one: they are merged)");
+ for (const c of channels) if (!SLUG_RE.test(c)) throw new Error(`"${c}" is not a channel slug`);
+ const replies = o.replies ?? "include";
+ if (!REEL_REPLIES.includes(replies)) throw new Error(`--replies takes ${REEL_REPLIES.join(", ")}`);
+ const order = o.order ?? "chrono";
+ if (!REEL_ORDERS.includes(order)) throw new Error(`--order takes ${REEL_ORDERS.join(" or ")}`);
+ const since = dayArg(o.since, "--since");
+ const until = dayArg(o.until, "--until");
+ if (since && until && since > until) throw new Error(`--since ${since} is after --until ${until}`);
+ if (o.limit !== null && o.limit !== undefined && !(Number.isInteger(o.limit) && o.limit > 0)) throw new Error("--limit takes a whole number of posts");
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new Error(`${project.id} has no manifest`);
+ const channelsDir = o.channelsDir ?? channelsDirFor(project.dir, manifest);
+ const rows = [];
+ const handles = [];
+ for (const c of channels) {
+ const got = await readPostsArchive(channelsDir, c);
+ if (!got.length) throw new Error(`${c} has no posts archive under ${channelsDir} (channels/${c}/posts/*.jsonl) — is it a social channel?`);
+ rows.push(...got);
+ const h = await channelHandle(channelsDir, c);
+ if (h) handles.push(h);
+ }
+ // Every channel's rows by id, for the parents, the quoted post and a repost's original.
+ const index = new Map();
+ for (const r of rows) if (!index.has(r.id)) index.set(r.id, r);
+ const captures = new Map();
+ const capture = async (slug, id) => {
+ const k = `${slug}/${id}`;
+ if (!captures.has(k)) captures.set(k, await captureOf(channelsDir, slug, id));
+ return captures.get(k);
+ };
+ // "With media": the post's capture (or a repost's original's) holds an attachment.
+ const mediaIds = new Set();
+ if (o.withMedia) {
+ for (const r of rows) {
+ const shownId = r.isRepost === true && r.repostOf?.id ? String(r.repostOf.id) : r.id;
+ const shownSlug = index.get(shownId)?.channelSlug ?? r.channelSlug;
+ if ((await capture(shownSlug, shownId)).media.length || (await capture(r.channelSlug, r.id)).media.length) mediaIds.add(r.id);
+ }
+ }
+ const picked = selectPosts(rows, { since, until, own: o.own === true, replies, withMedia: o.withMedia === true, hasMedia: (r) => mediaIds.has(r.id), order, limit: null, handles });
+ const inCut = postsInCut(manifest);
+ const fresh = [];
+ let already = 0;
+ for (const r of picked) {
+ const orig = r.isRepost === true ? String(r.repostOf?.id ?? "") : "";
+ if (inCut.has(r.id) || (orig && inCut.has(orig))) {
+ already += 1;
+ continue;
+ }
+ fresh.push(r);
+ }
+ const take = Number.isInteger(o.limit) ? fresh.slice(0, o.limit) : fresh;
+ const io = {
+ capture,
+ copy: o.dryRun ? async (_from, rel) => rel : (from, rel) => copyInto(project.dir, from, rel),
+ probe: probeMediaFile,
+ };
+ const entries = [];
+ let dropped = 0;
+ for (const r of take) {
+ const made = await postEntryFrom(r, { index, io, subjects: [...new Set(handles)] });
+ entries.push(made.entry);
+ dropped += made.dropped;
+ }
+ const summary = { channels, channelsDir, archived: index.size, selected: picked.length, already, added: entries.length, droppedMedia: dropped };
+ if (o.dryRun || !entries.length) return { ...summary, entries, dryRun: o.dryRun === true, result: null, editNotes: null };
+ const { result, editNotes } = await withEditNotes(project, async () =>
+ insertEntries(project.dir, o.after ?? null, entries, { token: await manifestToken(project.dir), op: "posts-reel" }),
+ );
+ return { ...summary, entries: result.entries, dryRun: false, result, editNotes };
+}
+
+/**
+ * ONE POST ITEM from the archive (`umtool timeline <p> insert … post:<channel>/<postId>`):
+ * the entry as `posts reel` makes it -- its media copied into the project --
+ * not yet written. The channel's archive is read whole (its parents and a
+ * repost's original come from it); the subject is the channel's own account.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, any>} manifest
+ * @param {string} slug
+ * @param {string} postId
+ * @param {{ id?: string | null, channelsDir?: string | null }} [o]
+ */
+export async function postItemFromArchive(project, manifest, slug, postId, { id = null, channelsDir = null } = {}) {
+ if (!SLUG_RE.test(slug)) throw new Error(`"${slug}" is not a channel slug`);
+ const dir = channelsDir ?? channelsDirFor(project.dir, manifest);
+ const rows = await readPostsArchive(dir, slug);
+ const index = new Map(rows.map((r) => [r.id, r]));
+ const row = index.get(String(postId));
+ if (!row) throw new Error(`${slug} has no post ${postId} in its archive (${rows.length} read under ${path.join(dir, slug, "posts")})`);
+ const handle = await channelHandle(dir, slug);
+ const captures = new Map();
+ const io = {
+ capture: async (s, pid) => {
+ const k = `${s}/${pid}`;
+ if (!captures.has(k)) captures.set(k, await captureOf(dir, s, pid));
+ return captures.get(k);
+ },
+ copy: (from, rel) => copyInto(project.dir, from, rel),
+ probe: probeMediaFile,
+ };
+ const { entry } = await postEntryFrom(row, { index, io, subjects: handle ? [handle] : [] });
+ if (id) entry.id = id;
+ return entry;
+}
diff --git a/umtool/lib/report/postReel.test.mjs b/umtool/lib/report/postReel.test.mjs
@@ -0,0 +1,150 @@
+// postReel.mjs: a posts reel from a synthesized archive -- the selection, the
+// entries (a repost as its original, a reply with its parents, the media
+// copied in and measured), one write, and a re-run that adds only what is new.
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { after, test } from "node:test";
+import { postsReel, selectPosts, mediaKindOf } from "./postReel.mjs";
+import { postsCommand } from "./postsCli.mjs";
+import { removeEntry, undoStructural, updatePostItem, moveEntry } from "./manifest.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-post-reel-"));
+after(() => rm(ROOT, { recursive: true, force: true }));
+const CH = path.join(ROOT, "channels");
+const REPORTS = path.join(ROOT, "reports");
+
+const row = (id, o = {}) => ({
+ id, slug: `subj-x/${id}`, channelSlug: "subj-x", author: "Subject", authorName: "THE SUBJECT", createdAt: "2026-10-30T10:00:00.000Z",
+ text: `post ${id}`, url: `https://x.com/Subject/status/${id}`, platform: "twitter", isReply: false, isRepost: false, engagement: { likes: 1, reposts: 0, replies: 0, quotes: 0 }, ...o,
+});
+
+async function archive(slug, rows, handle = "Subject") {
+ await mkdir(path.join(CH, slug, "posts"), { recursive: true });
+ await writeFile(path.join(CH, slug, "config.json"), JSON.stringify({ socialHandle: handle, platform: "twitter" }));
+ await writeFile(path.join(CH, slug, "posts", "2026-10.jsonl"), rows.map((r) => JSON.stringify({ ...r, channelSlug: slug })).join("\n") + "\n");
+}
+async function capture(slug, id, files) {
+ const dir = path.join(CH, slug, "posts-media", id);
+ await mkdir(dir, { recursive: true });
+ for (const [name, make] of files) make(path.join(dir, name));
+ await writeFile(path.join(dir, "capture.json"), JSON.stringify({ version: 1, id, media: files.map(([name]) => ({ name, url: name.endsWith(".mp4") ? "https://video.twimg.com/amplify_video/1/vid/x.mp4" : "https://pbs.twimg.com/media/x" })) }));
+}
+const ff = (args) => execFileSync("ffmpeg", ["-v", "error", "-y", ...args]);
+const png = (f) => ff(["-f", "lavfi", "-i", "color=c=red:s=64x48", "-frames:v", "1", f]);
+const mp4 = (f) => ff(["-f", "lavfi", "-i", "testsrc=s=96x64:d=1.5", "-f", "lavfi", "-i", "sine=d=1.5", "-shortest", "-c:v", "libx264", "-c:a", "aac", f]);
+
+async function project(name) {
+ const dir = path.join(REPORTS, name);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1, slug: name, title: name, provenance: { siteOrigin: "", channelSlug: "subj-x", channelsDir: CH },
+ render: { width: 1920, height: 1080, fps: 30, palette: { bg: "#000000", fg: "#ffffff", muted: "#888888", accent: "#c8752a" }, chrome: { engine: "hyperframes", layout: "deck", deck: { qr: { links: "original" } } } },
+ timeline: [{ type: "clip", id: "c01", video: "v1", start: 1, end: 3 }],
+ }, null, 2));
+ return { id: name, dir };
+}
+const manifest = async (p) => JSON.parse(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"));
+
+await archive("subj-x", [
+ row("100", { createdAt: "2026-10-29T10:00:00.000Z" }),
+ row("101", { createdAt: "2026-10-30T09:00:00.000Z", mediaCount: 1 }),
+ row("102", { createdAt: "2026-10-30T12:00:00.000Z", text: "RT @Subject: post 101", isRepost: true, repostOf: { id: "101", author: "Subject" } }),
+ row("103", { createdAt: "2026-10-31T08:00:00.000Z", mediaCount: 1 }),
+ row("104", { createdAt: "2026-11-02T08:00:00.000Z" }),
+]);
+await archive("subj-x-replies", [
+ row("200", { author: "someone_private", authorName: "Private Person", createdAt: "2026-10-31T07:00:00.000Z", text: "is this true?" }),
+ row("201", { createdAt: "2026-10-31T07:30:00.000Z", text: "@someone_private yes it is", isReply: true, replyTo: { id: "200", author: "someone_private" } }),
+ row("202", { createdAt: "2026-10-31T09:00:00.000Z", text: "@gone no", isReply: true, replyTo: { id: "999", author: "gone_person" } }),
+]);
+await capture("subj-x", "101", [["101_1.jpg", png]]);
+await capture("subj-x", "103", [["103_1.mp4", mp4]]);
+
+test("the selection: days inclusive, own, replies, with media, merged and de-duplicated, a repost of a selected post dropped", () => {
+ const rows = [row("1", { createdAt: "2026-10-29T23:59:00Z" }), row("2", { createdAt: "2026-10-30T00:00:00Z", isReply: true }), row("3", { author: "other", createdAt: "2026-10-31T00:00:00Z" }), row("4", { createdAt: "2026-10-31T05:00:00Z", isRepost: true, repostOf: { id: "2" } })];
+ assert.deepEqual(selectPosts(rows, { since: "2026-10-30" }).map((r) => r.id), ["2", "3"]);
+ assert.deepEqual(selectPosts(rows, { own: true, handles: ["subject"] }).map((r) => r.id), ["1", "2"]);
+ assert.deepEqual(selectPosts(rows, { replies: "only" }).map((r) => r.id), ["2"]);
+ assert.deepEqual(selectPosts(rows, { replies: "exclude", order: "reverse" }).map((r) => r.id), ["4", "3", "1"]); // 4 reposts 2, which is not selected
+ assert.deepEqual(selectPosts(rows, { withMedia: true, hasMedia: (r) => r.id === "3" }).map((r) => r.id), ["3"]);
+ assert.deepEqual(selectPosts([...rows, row("1")], { limit: 2 }).map((r) => r.id), ["1", "2"]);
+ assert.equal(mediaKindOf("a.mp4", "https://video.twimg.com/tweet_video/x.mp4"), "gif");
+ assert.equal(mediaKindOf("a.jpg", null), "image");
+ assert.equal(mediaKindOf("a.mp4", "https://video.twimg.com/amplify_video/1/x.mp4", { audio: true, seconds: 3 }), "video");
+});
+
+test("a reel from two channels: one write after the cut's clip; media copied in and measured; a reply with its parent, blurred", async () => {
+ const p = await project("reel-a");
+ const r = await postsReel(p, { channels: ["subj-x", "subj-x-replies"], since: "2026-10-30", until: "2026-10-31", own: true });
+ assert.deepEqual(r.entries.map((e) => e.id), ["p-101", "p-201", "p-103", "p-202"]);
+ const m = await manifest(p);
+ assert.deepEqual(m.timeline.map((e) => e.id), ["c01", "p-101", "p-201", "p-103", "p-202"]);
+ const [, e101, e201, e103, e202] = m.timeline;
+ assert.deepEqual(e101.media.map((x) => [x.src, x.kind, x.width]), [["posts-media/subj-x/101/101_1.jpg", "image", 64]]);
+ assert.equal(e103.media[0].kind, "video");
+ assert.equal(e103.media[0].audio, true);
+ assert.ok(Math.abs(e103.media[0].seconds - 1.5) < 0.1);
+ assert.ok((await readFile(path.join(p.dir, "posts-media/subj-x/103/103_1.mp4"))).length > 0);
+ assert.deepEqual(e201.parents, [{ id: "200", author: "Private Person", handle: "someone_private", date: "2026-10-31T07:00:00.000Z", text: "is this true?", url: "https://x.com/Subject/status/200" }]);
+ assert.deepEqual(e201.subjects, ["Subject"]);
+ assert.equal(e202.replyingTo, "gone_person");
+ assert.equal(e101.engagement.likes, 1);
+ // One undo point for the whole reel.
+ assert.ok(r.result.snapshot && !r.result.snapshot.skipped);
+});
+
+test("re-running adds only what is new; a repost of a post in the cut is the same post", async () => {
+ const p = await project("reel-b");
+ const first = await postsReel(p, { channels: ["subj-x"], until: "2026-10-30" });
+ assert.deepEqual(first.entries.map((e) => e.id), ["p-100", "p-101"]);
+ const again = await postsReel(p, { channels: ["subj-x"], until: "2026-10-30" });
+ assert.equal(again.added, 0);
+ assert.equal(again.already, 2);
+ const more = await postsReel(p, { channels: ["subj-x"] });
+ assert.deepEqual(more.entries.map((e) => e.id), ["p-103", "p-104"]);
+ // A repost alone (its original not selected) is drawn as the original, reposted by the subject.
+ const q = await project("reel-c");
+ const rep = await postsReel(q, { channels: ["subj-x"], since: "2026-10-30", until: "2026-10-30", limit: 1, order: "reverse" });
+ assert.equal(rep.entries.length, 1);
+ assert.equal(rep.entries[0].id, "p-101"); // the repost of 101 is 101's
+});
+
+test("a mixed cut's structural writes take a post item like a clip: move, remove, its knobs, undo; the CLI", async () => {
+ const p = await project("reel-d");
+ await postsReel(p, { channels: ["subj-x"], since: "2026-10-31", until: "2026-10-31" });
+ await moveEntry(p.dir, "p-103", 0);
+ assert.deepEqual((await manifest(p)).timeline.map((e) => e.id), ["p-103", "c01"]);
+ await updatePostItem(p.dir, "p-103", { hold: 4, media: { 0: { start: 0.2, end: 1.2, mute: true } } });
+ const e = (await manifest(p)).timeline[0];
+ assert.equal(e.hold, 4);
+ assert.deepEqual([e.media[0].start, e.media[0].end, e.media[0].mute], [0.2, 1.2, true]);
+ await assert.rejects(updatePostItem(p.dir, "p-103", { media: { 0: { start: 1.1 } } }), /at least 0.5 s after start/);
+ await assert.rejects(updatePostItem(p.dir, "c01", { hold: 3 }), /not a post item/);
+ await removeEntry(p.dir, "p-103");
+ assert.deepEqual((await manifest(p)).timeline.map((x) => x.id), ["c01"]);
+ await undoStructural(p.dir);
+ assert.deepEqual((await manifest(p)).timeline.map((x) => x.id), ["p-103", "c01"]);
+ // The CLI: set-item, and reel --dry-run --json.
+ const out = [];
+ assert.equal(await postsCommand(["set-item", "reel-d", "103", "hold=off", "media.0.trim=off"], { root: REPORTS, out: (s) => out.push(s), err: (s) => out.push(s) }), 0, out.join("\n"));
+ const after2 = (await manifest(p)).timeline[0];
+ assert.equal(after2.hold, undefined);
+ assert.equal(after2.media[0].start, undefined);
+ const lines = [];
+ assert.equal(await postsCommand(["reel", "reel-d", "--channel", "subj-x", "--dry-run", "--json"], { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(s) }), 0, lines.join("\n"));
+ const j = JSON.parse(lines.join("\n"));
+ assert.equal(j.dryRun, true);
+ assert.deepEqual(j.entries.map((x) => x.id), ["p-100", "p-101", "p-104"]);
+});
+
+test("a take's window times a post item by the duration rule, not a card's 4 s", async () => {
+ const { windowEntries } = await import("./takeMaker.mjs");
+ const post = (id, words) => ({ type: "post", id, post: `subj-x/${id}`, platform: "x", date: "2026-10-30T00:00:00Z", text: Array.from({ length: words }, () => "w").join(" ") });
+ // 42 words: 1 + 14 = 15 s each; a 20 s window from 0 touches the first two.
+ const tl = [post("a", 42), post("b", 42), post("c", 42), { type: "clip", id: "c01", video: "v", start: 0, end: 3 }];
+ assert.deepEqual(windowEntries(tl, { at: 0, dur: 20 }).ids, ["a", "b"]);
+ assert.deepEqual(windowEntries(tl, { at: 44, dur: 2 }).ids, ["c", "c01"]);
+});
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -33,7 +33,7 @@ import path from "node:path";
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 { PostsRefused, StaleToken, StructureRefused, manifestToken, updatePostItem, updatePosts, upsertPost } from "./manifest.mjs";
import { postWarnings } from "./postCards.mjs";
export const POSTS_USAGE = [
@@ -50,9 +50,20 @@ export const POSTS_USAGE = [
" 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).",
+ " umtool posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own]",
+ " [--with-media] [--replies include|only|exclude] [--order chrono|reverse] [--limit N] [--after <id|->]",
+ " [--dry-run] [--json]",
+ " POST ITEMS: each archived post as an entry of the cut, its card and its attachments (report-video.md, \"Post items\"):",
+ " the channels merged in time order, de-duplicated by post id; a post already in the cut is skipped, so a re-run",
+ " adds only what is new -- in ONE write (one undo point), at the end unless --after.",
+ " umtool posts set-item <project> <item> [hold=<s>|off] [layout=sequence|grid] [redact=on|off|auto]",
+ " [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off]",
+ " [media.<i>.push=on|off] [media.<i>.trim=off] [--json]",
+ " a post item's knobs (the post bench's writer, updatePostItem): its hold, its images' grid, the blur of other authors,",
+ " an attachment's trim, sound, crop (fractions of its picture) and push-in.",
].join("\n");
-const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop"]);
+const VALUED = new Set(["--attach", "--flag", "--author", "--id", "--crop", "--since", "--until", "--replies", "--order", "--limit", "--after"]);
const SLUG_RE = /^[A-Za-z0-9._-]+$/;
const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
@@ -301,9 +312,13 @@ export async function addPostFromArchive(project, { slug, postId, attach = null,
export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
const words = [];
const flags = new Map();
+ const channels = [];
for (let i = 0; i < args.length; i += 1) {
const a = args[i];
- if (VALUED.has(a)) {
+ if (a === "--channel") {
+ channels.push(args[i + 1] ?? "");
+ i += 1;
+ } else if (VALUED.has(a)) {
flags.set(a, args[i + 1] ?? "");
i += 1;
} else if (a.startsWith("--")) flags.set(a, true);
@@ -319,6 +334,8 @@ export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => con
};
try {
const [verb, projectArg, ref] = words;
+ if (verb === "reel" && projectArg && !flags.has("--help")) return await reelCommand(projectArg, { channels, flags, str, root, json, dryRun, out });
+ if (verb === "set-item" && projectArg && ref && !flags.has("--help")) return await setItemCommand(projectArg, ref, words.slice(3), { root, json, out });
if ((verb !== "add" && verb !== "set") || !projectArg || !ref || flags.has("--help")) {
err(POSTS_USAGE);
return 2;
@@ -424,3 +441,108 @@ async function setCommand(projectArg, ref, pairs, { root, json, out }) {
if (editNotes) out(` edit noted for ${editNotes.generatedBy}`);
return 0;
}
+
+async function projectOf(projectArg, root) {
+ 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}"`);
+ return r.project;
+}
+
+/** One line for a post item: its id, day, kind and first words. */
+export function postItemLine(e) {
+ const media = Array.isArray(e.media) ? e.media : [];
+ const what = media.length ? media.map((m) => m.kind).join("+") : "text";
+ const ctx = e.repostedBy ? " (repost)" : e.parents?.length ? ` (reply, ${e.parents.length} parent${e.parents.length === 1 ? "" : "s"})` : e.parentShot ? " (reply, thread shot)" : e.replyingTo ? " (reply)" : "";
+ const words = String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim();
+ return `${e.id} ${String(e.date ?? "").slice(0, 10)} ${what}${ctx} ${words.length > 70 ? `${words.slice(0, 67)}…` : words}`;
+}
+
+/** `posts reel`: the timeline built or extended from the archive (postReel.mjs postsReel). */
+async function reelCommand(projectArg, { channels, flags, str, root, json, dryRun, out }) {
+ const project = await projectOf(projectArg, root);
+ const limitRaw = str("--limit");
+ const limit = limitRaw === null ? null : Number(limitRaw);
+ if (limitRaw !== null && !(Number.isInteger(limit) && limit > 0)) throw new CliError(`--limit takes a whole number of posts (got ${limitRaw})`);
+ const { postsReel } = await import("./postReel.mjs");
+ let r;
+ try {
+ r = await postsReel(project, {
+ channels, since: str("--since"), until: str("--until"), own: flags.has("--own"), withMedia: flags.has("--with-media"),
+ replies: str("--replies") ?? "include", order: str("--order") ?? "chrono", limit, after: str("--after"), dryRun,
+ });
+ } catch (e) {
+ if (e instanceof StructureRefused || e instanceof StaleToken) throw e;
+ throw new CliError(e instanceof Error ? e.message : String(e));
+ }
+ if (json) {
+ out(JSON.stringify({ ok: true, ...r, result: r.result ? { ids: r.result.ids, at: r.result.at, snapshot: r.result.snapshot, token: r.result.token } : null }, null, 2));
+ return 0;
+ }
+ out(`${r.dryRun ? "would add" : "added"} ${r.added} post item(s) to ${project.id} from ${r.channels.join(" + ")} (${r.selected} selected, ${r.already} already in the cut)`);
+ for (const e of r.entries) out(` ${postItemLine(e)}`);
+ if (r.droppedMedia) out(` NOTE: ${r.droppedMedia} attachment(s) could not be measured (ffprobe) and were left out`);
+ if (r.result?.snapshot?.rel && !r.result.snapshot.skipped) out(` undo point: ${r.result.snapshot.rel} (umtool timeline ${project.id} undo)`);
+ if (r.editNotes) out(` edit noted for ${r.editNotes.generatedBy}`);
+ return 0;
+}
+
+const onOff = (v, k) => {
+ if (ON.has(v)) return true;
+ if (OFF.has(v)) return false;
+ throw new CliError(`${k}= takes on or off, not ${JSON.stringify(v)}`);
+};
+
+/**
+ * `posts set-item`'s words as updatePostItem's patch: `hold=<s>|off`,
+ * `layout=sequence|grid`, `redact=on|off|auto`, `media.<i>.start|end=<s>`,
+ * `media.<i>.mute|push=on|off`, `media.<i>.crop=x,y,w,h|off`, `media.<i>.trim=off`.
+ */
+export function postItemPatchOf(pairs) {
+ /** @type {Record<string, any>} */
+ const out = {};
+ for (const pair of pairs) {
+ const eq = pair.indexOf("=");
+ if (eq < 1) throw new CliError(`${pair}: a knob is key=value`);
+ const k = pair.slice(0, eq);
+ const raw = pair.slice(eq + 1);
+ const v = raw.toLowerCase();
+ if (k === "hold") out.hold = OFF.has(v) || v === "" ? null : Number(raw);
+ else if (k === "layout") out.mediaLayout = v === "sequence" ? null : v;
+ else if (k === "redact") out.redact = v === "auto" || v === "" ? null : onOff(v, k);
+ else {
+ const m = /^media\.(\d+)\.(start|end|mute|crop|push|trim)$/.exec(k);
+ if (!m) throw new CliError(`${pair}: not a post item knob (hold=, layout=, redact=, media.<i>.start|end|mute|crop|push|trim=)`);
+ const media = (out.media ??= {});
+ const one = (media[m[1]] ??= {});
+ if (m[2] === "start" || m[2] === "end") one[m[2]] = OFF.has(v) || v === "" ? null : Number(raw);
+ else if (m[2] === "mute" || m[2] === "push") one[m[2]] = onOff(v, k) || null;
+ else if (m[2] === "trim") {
+ if (!OFF.has(v)) throw new CliError(`${k}= takes off (the whole attachment)`);
+ one.start = null;
+ one.end = null;
+ } else one.crop = OFF.has(v) || v === "" ? null : raw.split(",").map(Number);
+ }
+ }
+ if (!Object.keys(out).length) throw new CliError("nothing to set");
+ for (const [k, v] of Object.entries(out)) if (typeof v === "number" && !Number.isFinite(v)) throw new CliError(`${k}= takes a number`);
+ return out;
+}
+
+/** `posts set-item`: a post item's knobs, through updatePostItem. */
+async function setItemCommand(projectArg, ref, pairs, { root, json, out }) {
+ const patch = postItemPatchOf(pairs);
+ const project = await projectOf(projectArg, root);
+ const manifest = await readManifest(project.dir);
+ const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ const hit = tl.find((e) => e?.type === "post" && (e.id === ref || String(e.post ?? "").split("/")[1] === ref));
+ if (!hit) throw new CliError(`no post item ${ref} in ${project.id} (its id, or the post's id)`);
+ const { result, editNotes } = await withEditNotes(project, async () => updatePostItem(project.dir, hit.id, patch, { token: await manifestToken(project.dir) }));
+ if (json) {
+ out(JSON.stringify({ ok: true, id: hit.id, entry: result.entry, token: result.token, editNotes }, null, 2));
+ return 0;
+ }
+ const { postItemSeconds } = await import("umtool-report-to-video/post-item");
+ out(`set ${hit.id}: ${postItemSeconds(result.entry).toFixed(1)} s${result.entry.hold ? ` (hold)` : ""}`);
+ return 0;
+}
diff --git a/umtool/lib/report/sectionEdit.mjs b/umtool/lib/report/sectionEdit.mjs
@@ -30,7 +30,8 @@
// leave one first is refused in those words.
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
-const isClip = (e) => !!e && (e.kind ?? e.type) === "clip";
+// A FOOTAGE entry: a clip, or a post item (post-item.mjs) -- what a section holds and a marker follows.
+const isClip = (e) => !!e && ((e.kind ?? e.type) === "clip" || (e.kind ?? e.type) === "post");
/** The deck's markers as written (an array, maybe empty), or null without a deck. */
function deckMarkers(m) {
diff --git a/umtool/lib/report/sections.mjs b/umtool/lib/report/sections.mjs
@@ -29,7 +29,7 @@
export function sectionEnterFlags(timeline) {
let prev;
return (timeline ?? []).map((e) => {
- if (e?.type !== "clip") return false;
+ if (e?.type !== "clip" && e?.type !== "post") return false;
const s = e.section;
const enters = s !== undefined && s !== null && s !== prev;
prev = s;
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -48,6 +48,7 @@ import { link, lstat, mkdir, readFile, rename, rm, stat, symlink, unlink, writeF
import path from "node:path";
import { pathToFileURL } from "node:url";
import { mergePatch } from "umtool-report-to-video/montage-styles";
+import { postItemSeconds } from "umtool-report-to-video/post-item";
import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings";
import { markKeepFrames } from "umtool-report-to-video/prune-frames";
import { PIPELINE_DIR, RENDER_BUDGET, UMTOOL_DIR } from "./driver.mjs";
@@ -240,8 +241,9 @@ export async function loadMontageStyles({ file = montageStylesFile() } = {}) {
// The window.
// ---------------------------------------------------------------------------
-/** An entry's length by the manifest's own numbers: a clip's cut, else `seconds`, else 4 s. */
+/** An entry's length by the manifest's own numbers: a clip's cut, a post item's rule (post-item.mjs), else `seconds`, else 4 s. */
export function estimatedSeconds(e) {
+ if (e?.type === "post") return postItemSeconds(e);
if (e?.type === "clip") {
const a = Number(e.cutStart ?? e.start);
const b = Number(e.cutEnd ?? e.end);
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -52,6 +52,7 @@ import path from "node:path";
import { isCalendarDate } from "umtool-report-to-video/attribution";
import { deckOn } from "umtool-report-to-video/deck";
import { gappedLength, gapSpan, gapsOf } from "umtool-report-to-video/gaps";
+import { postItemSeconds } from "umtool-report-to-video/post-item";
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { readManifest } from "../projects/report.mjs";
import { withEditNotes } from "./edit-guard.mjs";
@@ -101,6 +102,8 @@ 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 (--after <id|-> | --to-section N | --group G) post:<channel>/<postId> [--id ID]",
+ " a POST ITEM from the posts archive (its card and attachments; umtool posts reel makes many)",
" 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",
@@ -235,8 +238,16 @@ export function timelineRows(manifest) {
})(),
}
: {}),
- date: typeof e.date === "string" ? e.date : null,
- title: typeof title === "string" ? title : null,
+ // A post item (post-item.mjs): the post it plays, how long, and its first words.
+ ...(e.type === "post"
+ ? {
+ post: String(e.post ?? ""),
+ seconds: postItemSeconds(e),
+ media: Array.isArray(e.media) ? e.media.map((m) => m?.kind) : [],
+ }
+ : {}),
+ date: typeof e.date === "string" ? (e.type === "post" ? e.date.slice(0, 10) : e.date) : null,
+ title: typeof title === "string" ? title : e.type === "post" ? `${String(e.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim().slice(0, 60)}` : null,
};
});
}
@@ -249,7 +260,9 @@ export function timelineLines(rows) {
r.type === "clip"
? `${String(r.video ?? "?").padEnd(14)} ${fmt(r.start)}–${fmt(r.end)}${r.cutStart != null ? ` (cut ${fmt(r.cutStart)}–${fmt(r.cutEnd)})` : ""}` +
(r.gaps?.length ? ` gaps ${r.gaps.map((g) => `−${fmt(g.from)}–${fmt(g.to)}`).join(" ")} (plays ${fmt(r.plays)}s)` : "")
- : "".padEnd(14);
+ : r.type === "post"
+ ? `${String(r.post ?? "").padEnd(14)} ${fmt(r.seconds)}s ${r.media?.length ? r.media.join("+") : "text"}`
+ : "".padEnd(14);
const label = [r.date, r.title].filter(Boolean).join(" ");
return `${String(r.index).padStart(3)} ${r.id.padEnd(w)} ${r.type.padEnd(tw)} ${span}${label ? ` ${label}` : ""}${r.rejected ? ` [${r.rejected}]` : ""}`;
});
@@ -521,7 +534,20 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
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 spec = need(rest[0], "a clip: <channel>/<video>@<start>-<end> (or a post item: post:<channel>/<postId>)");
+ // A POST ITEM (post-item.mjs): `post:<channel>/<postId>` from the posts archive, as `posts reel` makes it.
+ if (/^post:/.test(spec)) {
+ const m = /^post:([A-Za-z0-9][A-Za-z0-9._-]*)\/([A-Za-z0-9_-]+)$/.exec(spec);
+ if (!m) throw new CliError("a post item is post:<channel>/<postId>");
+ const { postItemFromArchive } = await import("./postReel.mjs");
+ const entry = await postItemFromArchive(project, manifest, m[1], m[2], { id: flags.has("--id") ? String(flags.get("--id")) : null });
+ if (toSection !== null || group !== null) {
+ ({ result, editNotes } = await write((token) => insertInto(project.dir, entry, toSection !== null ? { section: toSection } : { group }, { token })));
+ } else {
+ ({ result, editNotes } = await write((token) => insertEntry(project.dir, after, entry, { token, at })));
+ }
+ break;
+ }
const c = parseClipSpec(spec);
if (!c) throw new Error("a clip is <channel>/<video>@<start>-<end> in seconds");
const section = intFlag(flags, "--section");
@@ -898,7 +924,9 @@ function summaryOf(verb, r, attribution) {
return `${r.move ? "moved" : "copied"} ${r.source}'s span to ${r.id} at ${r.at}${r.section ? ` (§${r.section.index}${r.section.label ? ` ${r.section.label}` : ""})` : ""}${r.move && r.rest ? `; ${r.source} keeps ${r.rest.start}–${r.rest.end}` : r.move ? "" : ` (repeatOf ${r.source})`}`;
case "insert": {
const e = attribution ?? r.entry;
- const head = `inserted ${r.id} at ${r.at}: ${e.channel ? `${e.channel}/` : ""}${e.video}@${e.start}-${e.end}`;
+ const head = e.type === "post"
+ ? `inserted ${r.id} at ${r.at}: the post item ${e.post} (${postItemSeconds(e).toFixed(1)} s)`
+ : `inserted ${r.id} at ${r.at}: ${e.channel ? `${e.channel}/` : ""}${e.video}@${e.start}-${e.end}`;
const taken = r.idTaken ? `\n (${r.idTaken} was taken: it is ${r.id})` : "";
const placed =
(e.section !== undefined ? `\n section ${e.section}` : "") +
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -211,6 +211,7 @@ import {
} from "./cut-points.mjs";
// The snap itself (a montage's window snaps with it too), re-exported for the tests.
import { snap } from "./snap.mjs";
+import { buildPostSegment } from "./post-render.mjs";
export { snap };
// The lint a build runs before it renders, and the prune after its final mux.
import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs";
@@ -466,7 +467,7 @@ export function clipBaseFilters({ render, VW, VH, HH, hasHeader, attribPath, cha
/** Is this entry's segment framed into the footage box under the deck (rather than full frame)? */
export function framedUnderDeck(entry, render) {
- if (entry.type === "clip" || entry.type === "image") return true;
+ if (entry.type === "clip" || entry.type === "image" || entry.type === "post") return true;
return entry.type === "card" && !hidesDeck(entry, resolveDeck(render));
}
@@ -1126,7 +1127,7 @@ export function needsFetchMessage(missing) {
// The timeline's vocabulary is OPEN; the build loop treats everything it has
// no other branch for as a clip, and so does this.
-const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger", "intro"]);
+const NON_CLIP_TYPES = new Set(["card", "teaser", "image", "scroll", "chart", "ledger", "intro", "post"]);
const isClipEntry = (e) => !NON_CLIP_TYPES.has(e?.type);
/**
@@ -5523,6 +5524,11 @@ export async function chapterTitle(entry, index, provenance, { deck = false } =
if (entry.type === "image") {
return imageAttributionLine(entry) || `Image ${index + 1}`;
}
+ // A post item: who posted it, and the first words.
+ if (entry.type === "post") {
+ const words = String(entry.text ?? "").replace(/^RT @[A-Za-z0-9_]+:\s*/, "").replace(/\s+/g, " ").trim();
+ return `${entry.author ?? (entry.handle ? `@${entry.handle}` : "Post")}: ${words.length > 60 ? `${words.slice(0, 57)}…` : words || "(no words)"}`;
+ }
if (entry.type !== "clip") return entry.title ?? entry.heading ?? `Card ${index + 1}`;
try {
const meta = await clipMeta(entry, provenance);
@@ -6158,8 +6164,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
// A still has nothing to fetch and is already on disk, so this is a no-op
// rather than an error: a bench that walks the timeline asking for each
// entry's window should not have to know which kinds have one.
- if (entry?.type === "image" || entry?.type === "teaser" || (entry?.type === "clip" && hasLocalMedia(entry))) {
- const what = entry.type === "image" ? "an image" : entry.type === "teaser" ? "a teaser" : "a clip with its own `src`";
+ if (entry?.type === "image" || entry?.type === "teaser" || entry?.type === "post" || (entry?.type === "clip" && hasLocalMedia(entry))) {
+ const what = entry.type === "image" ? "an image" : entry.type === "teaser" ? "a teaser" : entry.type === "post" ? "a post item (its media is in the project)" : "a clip with its own `src`";
EMIT("note", { message: `${fetchOnly} is ${what} entry — nothing to fetch` });
EMIT("done", { out: null, nothingToFetch: true });
return { out: null, failures: [] };
@@ -6383,6 +6389,20 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly
EMIT("card", { id: entry.id, i, n: entries.length });
return buildImageSegment(entry, render, outDir, chrome, provenance, manifestDir, framing);
}
+ if (entry.type === "post") {
+ // A post item (post-render.mjs): its card drawn from the archived post, its attachments laid in.
+ EMIT("card", { id: entry.id, i, n: entries.length });
+ const fr = deck ? framing ?? segmentFraming(render) : null;
+ const df = fr ? deckFraming(render, { feed: fr.layout === "feed" }) : null;
+ const seg = await buildPostSegment(entry, {
+ render, outDir, manifestDir,
+ box: df ? { width: df.box.width, height: df.box.height } : { width: render.width, height: render.height },
+ place: df ? df.place : [`fps=${render.fps}`],
+ encode: encodeArgs(render), exec: execFileP, ffmpeg: FFMPEG, emit: (ev, f) => EMIT(ev, f),
+ });
+ if (fr) await writeCutRecord(seg, { version: 1, id: entry.id, framing: fr });
+ return seg;
+ }
if (entry.type === "scroll" || entry.type === "chart" || entry.type === "ledger") {
EMIT("card", { id: entry.id, i, n: entries.length });
if (!manifest.ledger?.length)
diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs
@@ -21,7 +21,8 @@ import { gappedLength, offsetIn, recordGaps, renderGaps } from "./gaps.mjs";
import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams.mjs";
import { INTRO_SECONDS } from "yt-dlp-transcript-common/lib/report/intro.mjs";
-import { attributionParts, deckSubtitle, deckSubtitleLines } from "./attribution.mjs";
+import { attributionParts, deckSubtitle, deckSubtitleLines, formatDeckDate } from "./attribution.mjs";
+import { postDeckText, postItemSeconds } from "./post-item.mjs";
import {
claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, stampsWithFinale, tallyOf, tallyVerdicts, validateFactcheck,
} from "./factcheck.mjs";
@@ -230,13 +231,13 @@ export function validateDeckMarkers(manifest) {
const hit = timeline.find((e) => e?.id === m.after.trim());
const where = `render.chrome.deck.markers[${i}].after`;
if (!hit) errors.push(`${where} names ${m.after}, which is not in the timeline`);
- else if (hit.type !== "clip") errors.push(`${where} names ${m.after}, a ${hit.type ?? "entry"}: a marker follows a clip`);
+ else if (hit.type !== "clip" && hit.type !== "post") errors.push(`${where} names ${m.after}, a ${hit.type ?? "entry"}: a marker follows a clip or a post item`);
});
// A subsection (`level: 2`) sits inside the section before it, so the
// first boundary of the cut -- by where it stands, not where it is listed
// -- opens a section. One refusal, naming the marker.
const pos = new Map();
- timeline.forEach((e, i) => { if (e?.type === "clip" && !pos.has(e.id)) pos.set(e.id, i); });
+ timeline.forEach((e, i) => { if ((e?.type === "clip" || e?.type === "post") && !pos.has(e.id)) pos.set(e.id, i); });
const first = markers
.map((m, i) => ({ m, i, p: isObj(m) && typeof m.after === "string" ? pos.get(m.after.trim()) : undefined }))
.filter((x) => x.p !== undefined)
@@ -960,6 +961,8 @@ export function estimatedDuration(entry, render = {}, D = transitionOf(render))
return Math.max(1, gappedLength(from, to, renderGaps(entry, render)));
}
if (entry.type === "image") return Number(entry.seconds ?? 4);
+ // A post item (post-item.mjs): its reading time and its attachments, or its `hold`.
+ if (entry.type === "post") return postItemSeconds(entry);
// The brand intro (intro.mjs) is exactly its `seconds` (introEntry fills the default).
if (entry.type === "intro") return Number(entry.seconds ?? INTRO_SECONDS);
// A teaser's dip makes its segment longer by the dissolve and the black (`teaserLead`).
@@ -1051,6 +1054,11 @@ export function deckText(entry, meta, provenance, deck, multiChannel) {
// the cut (umtool's On-screen rows, the schedule) names it by.
if (!title) title = teaserTitle(entry);
subtitle = "";
+ } else if (entry.type === "post") {
+ // A post item: its day as the deck's date, its author and platform under it.
+ const t = postDeckText(entry, (d) => formatDeckDate(d, deck.subtitle?.dateFormat ?? "long"));
+ if (!title) title = t.title;
+ subtitle = t.subtitle;
} else if (entry.type === "image") {
const parts = { channel: "", title: String(entry.title ?? "").trim(), date: String(entry.date ?? "").trim(), at: null };
const opts = { ...deck.subtitle, parts: ["title", "date"] };
@@ -1088,6 +1096,8 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin
return original ?? archiveMomentUrl(entry, provenance, entry.start);
}
if (entry.type === "image") return entry.citeUrl ?? null;
+ // A post item: the post's own page, or its archive's (postQrUrl, the posts' `links` rule).
+ if (entry.type === "post") return entry.citeUrl ?? (entry.url ? postQrUrl({ ...entry, postId: String(entry.post ?? "").split("/")[1] }, provenance, { links: links === "original" ? "original" : "archive" }) : null);
return null;
}
diff --git a/umtool/report-to-video/lint.mjs b/umtool/report-to-video/lint.mjs
@@ -84,6 +84,7 @@ import { validateClaims } from "./factcheck.mjs";
import { validateClipAudioEntries } from "./clip-audio.mjs";
import { validateClipBlurEntries } from "./clip-blur.mjs";
import { validateGapEntries } from "./gaps.mjs";
+import { postItemFiles, validatePostItems } from "./post-item.mjs";
import { validateFinaleEntries } from "./finale.mjs";
import { validateThreadEntries } from "./threads.mjs";
import { validateFlipEntries } from "./flips.mjs";
@@ -249,6 +250,10 @@ export function originQrsOf(manifest, { only = null, metaOf = null } = {}) {
export function imageSrcsOf(manifest, { only = null } = {}) {
const out = [];
for (const e of manifest.timeline ?? []) {
+ if (e?.type === "post" && (!only || e.id === only)) {
+ out.push(...postItemFiles(e));
+ continue;
+ }
if (e?.type !== "image" || (only && e.id !== only)) continue;
if (typeof e.src === "string") out.push({ where: `timeline ${e.id}`, src: e.src });
if (Array.isArray(e.panels)) {
@@ -314,6 +319,8 @@ export function validatorErrors(whole) {
...validateClipBlurEntries(whole),
// Seconds taken out of a clip's middle (gaps.mjs).
...validateGapEntries(whole),
+ // A post as a timeline item (post-item.mjs): its archived words, its attachments, its hold.
+ ...validatePostItems(whole),
];
if (deckOn(whole.render)) {
errors.push(...validatePosts(whole.posts, whole.timeline ?? [], whole.render).map((m) => `posts: ${m}`));
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -59,6 +59,8 @@
"./package.json": "./package.json",
"./pauses": "./pauses.mjs",
"./post-links": "./post-links.mjs",
+ "./post-item": "./post-item.mjs",
+ "./post-render": "./post-render.mjs",
"./presets": "./presets.mjs",
"./prune-frames": "./prune-frames.mjs",
"./render-cards": "./render-cards.mjs",
diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs
@@ -0,0 +1,710 @@
+// A POST AS A TIMELINE ITEM (umtool/docs/report-video.md, "Post items"): an
+// archived post -- an X post, a Bluesky one -- played as an entry of the cut in
+// its own right, beside clips, rather than as a card laid over one (`posts[]`,
+// deck.mjs). A "posts reel" is a cut made of them (`umtool posts reel`); any
+// cut may mix them with clips.
+//
+// { type: "post", id, post: "<channel>/<postId>",
+// platform, author, handle, date, text, url, engagement?,
+// repostedBy?: { author, handle }, quoted?: <ref>, parents?: [<ref>, …],
+// replyingTo?: "<handle>", parentShot?: "<file>",
+// media?: [{ src, kind: "image"|"video"|"gif", seconds?, width?, height?, audio?,
+// start?, end?, mute?, crop?: [x, y, w, h], push?, words? }],
+// mediaLayout?: "sequence"|"grid", hold?, redact?, onscreen? }
+//
+// where a <ref> (a post it quotes, the posts it answers, nearest first) is
+// `{ id?, author?, handle?, badge?, date?, text?, url? }`. The archive row is
+// SNAPSHOTTED into the entry when it goes in (postReel.mjs): a cut renders the
+// words and counts it was made with, not whatever the archive says next week.
+//
+// PURE and dependency-free: the build (post-render.mjs), Play the cut (in the
+// browser), the writers and the lint all read the same rules from here --
+// the validator, the duration rule, the plan of what plays when, the layout
+// and the card's HTML.
+
+/** The platforms a post item may come from (deck.mjs POST_PLATFORMS). */
+export const POST_ITEM_PLATFORMS = Object.freeze(["x", "bluesky", "web"]);
+export const POST_MEDIA_KINDS = Object.freeze(["image", "video", "gif"]);
+export const POST_MEDIA_LAYOUTS = Object.freeze(["sequence", "grid"]);
+
+/**
+ * THE DURATION RULE. A post item plays for the time it takes to read it, then
+ * its attachments, one after another:
+ *
+ * reading = clamp(READ.lead + words / READ.wps, READ.min, READ.max)
+ * + for each post it answers and the post it quotes:
+ * clamp(words / READ.wps, CONTEXT_READ.min, CONTEXT_READ.max) -- 1-4 s: context, not the post
+ * media = a video: its trimmed length (end - start), its sound on;
+ * a GIF: looped to at least GIF.min s (one pass when longer, at most GIF.max);
+ * an image: IMAGE_SECONDS; a grid of 2-4 images: GRID.base + GRID.per × (n - 1)
+ * seconds = reading + the media, in order -- or `hold`, which overrides the
+ * whole (a longer hold holds the last thing up; a shorter one cuts
+ * the attachments short at it).
+ *
+ * Words are runs of non-space; a link is one word. 3 words a second is a
+ * comfortable on-screen read (about 180 a minute), with a second to find the
+ * text first; the cap keeps a 500-word post from stalling the reel -- a post
+ * that long is shown at the size that fits, and `hold` gives it more.
+ */
+export const POST_READ = Object.freeze({ wps: 3, lead: 1, min: 3, max: 15 });
+export const POST_CONTEXT_READ = Object.freeze({ min: 1, max: 4 });
+export const POST_IMAGE_SECONDS = 3.5;
+export const POST_GIF = Object.freeze({ min: 3, max: 10 });
+export const POST_GRID = Object.freeze({ base: 3.5, per: 1 });
+export const POST_HOLD = Object.freeze({ min: 1, max: 120 });
+export const POST_MEDIA_MAX = 4;
+/** The posts it answers drawn above it (the reply chain), nearest first: at most this many. */
+export const POST_PARENTS_MAX = 2;
+/** A video attachment's shortest trimmed span, in seconds. */
+export const POST_MEDIA_MIN_SPAN = 0.5;
+/** An image's slow push-in (`push: true`): this much larger by the end of its span. */
+export const POST_PUSH = 0.06;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const round3 = (v) => Math.round(v * 1000) / 1000;
+const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
+const str = (v) => (typeof v === "string" ? v : "");
+
+/** Words on the card: runs of non-space (a link is one). */
+export function wordCount(text) {
+ const t = str(text).trim();
+ return t ? t.split(/\s+/).length : 0;
+}
+
+/** The text a card shows: a repost's own "RT @x: " prefix is the card's "reposted" line, not its words. */
+export function cardText(entry) {
+ const t = str(entry?.text);
+ return entry?.repostedBy ? t.replace(/^RT @[A-Za-z0-9_]+:\s*/, "") : t;
+}
+
+/** The posts it answers (nearest first), at most POST_PARENTS_MAX. */
+export const parentsOf = (entry) => (Array.isArray(entry?.parents) ? entry.parents.filter(isObj).slice(0, POST_PARENTS_MAX) : []);
+
+/** Seconds to read the post itself (the rule above, its first line). */
+export function readSeconds(entry) {
+ return clamp(POST_READ.lead + wordCount(cardText(entry)) / POST_READ.wps, POST_READ.min, POST_READ.max);
+}
+
+/** Seconds to read one post of its context (a parent, the quoted post). */
+export function contextReadSeconds(ref) {
+ return clamp(wordCount(ref?.text) / POST_READ.wps, POST_CONTEXT_READ.min, POST_CONTEXT_READ.max);
+}
+
+/** The whole reading time: the post and its context. */
+export function readingSeconds(entry) {
+ let s = readSeconds(entry);
+ for (const p of parentsOf(entry)) s += contextReadSeconds(p);
+ if (isObj(entry?.quoted)) s += contextReadSeconds(entry.quoted);
+ return round3(s);
+}
+
+/** A media item's trimmed source span `[from, to]` (a video's or a GIF's own seconds). */
+export function mediaSpan(m) {
+ const len = fin(m?.seconds) && m.seconds > 0 ? m.seconds : null;
+ const from = fin(m?.start) ? Math.max(0, m.start) : 0;
+ const to = fin(m?.end) ? m.end : len ?? from + POST_IMAGE_SECONDS;
+ return { from: round3(from), to: round3(len ? Math.min(to, len) : to) };
+}
+
+/** How long one attachment plays in the item (the rule above). */
+export function mediaSeconds(m) {
+ if (m?.kind === "video") {
+ const { from, to } = mediaSpan(m);
+ return round3(Math.max(POST_MEDIA_MIN_SPAN, to - from));
+ }
+ if (m?.kind === "gif") {
+ const { from, to } = mediaSpan(m);
+ const pass = Math.max(0.1, to - from);
+ return round3(pass >= POST_GIF.min ? Math.min(pass, POST_GIF.max) : Math.ceil(POST_GIF.min / pass) * pass);
+ }
+ return POST_IMAGE_SECONDS;
+}
+
+/** The attachments as they play: a grid of the images (mediaLayout "grid", 2-4 of them) is one step. */
+export function mediaSteps(entry) {
+ const media = Array.isArray(entry?.media) ? entry.media.filter(isObj).slice(0, POST_MEDIA_MAX) : [];
+ const indexed = media.map((m, i) => ({ ...m, i }));
+ const images = indexed.filter((m) => m.kind === "image");
+ if (entry?.mediaLayout === "grid" && images.length >= 2) {
+ const rest = indexed.filter((m) => m.kind !== "image");
+ return [
+ { kind: "grid", items: images, seconds: round3(POST_GRID.base + POST_GRID.per * (images.length - 1)) },
+ ...rest.map((m) => ({ kind: m.kind, items: [m], seconds: mediaSeconds(m) })),
+ ];
+ }
+ return indexed.map((m) => ({ kind: m.kind, items: [m], seconds: mediaSeconds(m) }));
+}
+
+/** The item's length by the rule, before `hold`. */
+export function ruleSeconds(entry) {
+ return round3(readingSeconds(entry) + mediaSteps(entry).reduce((n, s) => n + s.seconds, 0));
+}
+
+/** The item's length in the cut: `hold` when it is set, else the rule. */
+export function postItemSeconds(entry) {
+ return fin(entry?.hold) && entry.hold > 0 ? round3(entry.hold) : ruleSeconds(entry);
+}
+
+/**
+ * WHAT PLAYS WHEN inside a post item, in its own seconds (0 is its first
+ * frame): the reading span, then each step of the attachments. A step is
+ * `{ kind, items, at, seconds, srcFrom, srcTo, loop, sound }` -- a video's
+ * source span and whether its sound plays, a GIF's loop. With `hold` the plan
+ * is cut (or extended) to it: a step past the end is dropped, the last one
+ * cut at it; a longer hold holds the last step up (`held`). Both the render
+ * and Play the cut play this plan.
+ *
+ * @returns {{ reading: number, total: number, steps: Array<Record<string, any>>, held: number }}
+ */
+export function postItemPlan(entry) {
+ const reading = readingSeconds(entry);
+ const total = postItemSeconds(entry);
+ const steps = [];
+ let at = reading;
+ for (const s of mediaSteps(entry)) {
+ if (at >= total - 0.05) break;
+ const seconds = round3(Math.min(s.seconds, total - at));
+ const m = s.items[0];
+ const span = s.kind === "video" || s.kind === "gif" ? mediaSpan(m) : null;
+ steps.push({
+ kind: s.kind,
+ items: s.items,
+ at: round3(at),
+ seconds,
+ ...(span ? { srcFrom: span.from, srcTo: s.kind === "video" ? round3(Math.min(span.to, span.from + seconds)) : span.to } : {}),
+ loop: s.kind === "gif",
+ sound: s.kind === "video" && m.mute !== true && m.audio !== false,
+ });
+ at += seconds;
+ }
+ // A text-only post reads for the whole; one with attachments holds its last up to `hold`.
+ const held = steps.length ? round3(Math.max(0, total - at)) : 0;
+ return { reading: round3(Math.min(reading, total)), total, steps, held };
+}
+
+/** The step on screen at item second `s` (null in the reading span). */
+export function stepAt(plan, s) {
+ let cur = null;
+ for (const st of plan.steps) if (s >= st.at) cur = st;
+ return cur;
+}
+
+/** Where a video/GIF step's media is at item second `s`: its source second. */
+export function mediaTimeAt(step, s) {
+ if (!step || (step.kind !== "video" && step.kind !== "gif")) return null;
+ const local = Math.max(0, s - step.at);
+ if (step.kind === "gif") {
+ const pass = Math.max(0.1, step.srcTo - step.srcFrom);
+ return round3(step.srcFrom + (local % pass));
+ }
+ return round3(Math.min(step.srcTo, step.srcFrom + local));
+}
+
+// ---------------------------------------------------------------------------
+// PRIVACY: whose name, face and handle a card may show.
+// ---------------------------------------------------------------------------
+
+/**
+ * THE RULE capture-posts applies to a thread parent (common/social/
+ * xThreadShot.ts threadRedaction), applied to every OTHER author a post item
+ * draws -- the post it answers (and its parent), the post it quotes, the
+ * original of a repost: their avatar, display name and @handle are blurred
+ * (and an @mention of them in the words), unless
+ *
+ * - the item says `redact: false` (the operator has judged them public),
+ * - the author is the SUBJECT: the post's own author, or the account that
+ * reposted it (a self-thread, his own post reposted),
+ * - the archive says they carry an organisation's gold check or a
+ * government's grey one (`badge`). X's blue check is bought, so a
+ * blue-checked private person is blurred like any other;
+ *
+ * and `redact: true` blurs even those. An author the archive does not name
+ * is blurred. The words of the post stay: what was said is the evidence;
+ * who a private person is, is not.
+ *
+ * @param {{ handle?: string|null, badge?: string|null }} who
+ * @param {{ subjects?: string[], redact?: boolean }} [o]
+ * @returns {{ redact: boolean, reason: "off"|"forced"|"subject"|"verified"|"blue-check"|"private"|"unknown" }}
+ */
+export function authorRedaction(who, { subjects = [], redact = undefined } = {}) {
+ const same = (a, b) => !!a && !!b && String(a).replace(/^@/, "").toLowerCase() === String(b).replace(/^@/, "").toLowerCase();
+ const handle = str(who?.handle);
+ if (redact === false) return { redact: false, reason: "off" };
+ if (handle && subjects.some((s) => same(s, handle))) return { redact: redact === true, reason: redact === true ? "forced" : "subject" };
+ if (redact === true) return { redact: true, reason: "forced" };
+ if (!handle) return { redact: true, reason: "unknown" };
+ if (who?.badge === "gold" || who?.badge === "grey") return { redact: false, reason: "verified" };
+ if (who?.badge === "blue") return { redact: true, reason: "blue-check" };
+ return { redact: true, reason: "private" };
+}
+
+/**
+ * The subjects of an item: `subjects` when the item names them (a posts reel
+ * names the accounts whose archive it was made from), else its own author and
+ * the account that reposted it.
+ */
+export const subjectsOf = (entry) =>
+ Array.isArray(entry?.subjects) ? entry.subjects.filter((h) => typeof h === "string" && h) : [str(entry?.handle), str(entry?.repostedBy?.handle)].filter(Boolean);
+
+/**
+ * Every author the card draws besides the subject, with the rule's answer:
+ * `{ where, handle, redact, reason }` -- the parents, the quoted post, the
+ * original of a repost, and a reply's "replying to" handle when its parent is
+ * not archived.
+ */
+export function cardAuthors(entry) {
+ const subjects = subjectsOf(entry);
+ const o = { subjects, redact: typeof entry?.redact === "boolean" ? entry.redact : undefined };
+ const out = [];
+ // The post's own author, when the item names its subjects and it is not one (a repost of somebody else's post).
+ if (Array.isArray(entry?.subjects)) out.push({ where: "author", handle: str(entry.handle) || null, ...authorRedaction({ handle: entry.handle, badge: entry.badge }, o) });
+ parentsOf(entry).forEach((p, i) => out.push({ where: `parents[${i}]`, handle: str(p.handle) || null, ...authorRedaction(p, o) }));
+ if (isObj(entry?.quoted)) out.push({ where: "quoted", handle: str(entry.quoted.handle) || null, ...authorRedaction(entry.quoted, o) });
+ if (!parentsOf(entry).length && str(entry?.replyingTo)) out.push({ where: "replyingTo", handle: entry.replyingTo, ...authorRedaction({ handle: entry.replyingTo }, o) });
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// The validator: the writers refuse with it and the build refuses with it.
+// ---------------------------------------------------------------------------
+
+const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
+const NATIVE_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
+const HANDLE_RE = /^@?[A-Za-z0-9_.-]{1,64}$/;
+const BADGES = ["blue", "gold", "grey", "other"];
+const TEXT_MAX = 25000;
+
+/** A project-relative file a post item names: inside the project, never absolute or `..`. */
+export function relFileError(v, what) {
+ if (typeof v !== "string" || !v.trim()) return `${what} must be a file path relative to the manifest`;
+ if (v.startsWith("/") || v.startsWith("~") || /^[A-Za-z]:[\\/]/.test(v)) return `${what} must be relative to the manifest, not ${v}`;
+ if (v.split(/[\\/]/).includes("..")) return `${what} must stay inside the project (no ..): ${v}`;
+ return null;
+}
+
+function refErrors(r, where) {
+ const errors = [];
+ if (!isObj(r)) return [`${where} must be an object`];
+ for (const k of ["id", "author", "date", "text", "url"]) {
+ if (r[k] !== undefined && typeof r[k] !== "string") errors.push(`${where}.${k} must be a string`);
+ }
+ if (r.handle !== undefined && (typeof r.handle !== "string" || !HANDLE_RE.test(r.handle))) errors.push(`${where}.handle must be a handle`);
+ if (r.badge !== undefined && r.badge !== null && !BADGES.includes(r.badge)) errors.push(`${where}.badge must be one of ${BADGES.join(", ")}`);
+ if (typeof r.text === "string" && r.text.length > TEXT_MAX) errors.push(`${where}.text is longer than ${TEXT_MAX} characters`);
+ return errors;
+}
+
+/**
+ * Every reason post item `e` cannot be built, as sentences (empty: it can).
+ * Unknown keys are left alone: a timeline entry carries the walk's and the
+ * section's fields too.
+ */
+export function validatePostItem(e) {
+ const w = `timeline ${e?.id ?? "?"}`;
+ const errors = [];
+ if (!isObj(e)) return [`${w} must be an object`];
+ if (typeof e.post !== "string" || !/^[^/]+\/[^/]+$/.test(e.post) || !SLUG_RE.test(e.post.split("/")[0]) || !NATIVE_ID_RE.test(e.post.split("/")[1])) {
+ errors.push(`${w}.post must be <channel>/<postId>, the archive's post (got ${JSON.stringify(e.post)})`);
+ }
+ if (!POST_ITEM_PLATFORMS.includes(e.platform)) errors.push(`${w}.platform must be one of ${POST_ITEM_PLATFORMS.join(", ")}`);
+ if (typeof e.text !== "string") errors.push(`${w}.text must be the post's words (a string; "" for none)`);
+ else if (e.text.length > TEXT_MAX) errors.push(`${w}.text is longer than ${TEXT_MAX} characters`);
+ if (e.author !== undefined && typeof e.author !== "string") errors.push(`${w}.author must be a string`);
+ if (e.handle !== undefined && (typeof e.handle !== "string" || !HANDLE_RE.test(e.handle))) errors.push(`${w}.handle must be a handle`);
+ if (typeof e.date !== "string" || Number.isNaN(Date.parse(e.date))) errors.push(`${w}.date must be the post's date (ISO)`);
+ if (e.url !== undefined && (typeof e.url !== "string" || !/^https?:\/\//.test(e.url))) errors.push(`${w}.url must be an http(s) link`);
+ if (e.engagement !== undefined) {
+ if (!isObj(e.engagement)) errors.push(`${w}.engagement must be an object of counts`);
+ else for (const [k, v] of Object.entries(e.engagement)) if (!(Number.isInteger(v) && v >= 0)) errors.push(`${w}.engagement.${k} must be a whole number ≥ 0`);
+ }
+ if (e.repostedBy !== undefined) {
+ if (!isObj(e.repostedBy) || typeof e.repostedBy.handle !== "string" || !HANDLE_RE.test(e.repostedBy.handle)) errors.push(`${w}.repostedBy must be { author?, handle }`);
+ }
+ if (e.quoted !== undefined) errors.push(...refErrors(e.quoted, `${w}.quoted`));
+ if (e.parents !== undefined) {
+ if (!Array.isArray(e.parents)) errors.push(`${w}.parents must be a list (the posts it answers, nearest first)`);
+ else {
+ if (e.parents.length > POST_PARENTS_MAX) errors.push(`${w}.parents: at most ${POST_PARENTS_MAX} (the post it answers and its parent)`);
+ e.parents.forEach((p, i) => errors.push(...refErrors(p, `${w}.parents[${i}]`)));
+ }
+ }
+ if (e.replyingTo !== undefined && (typeof e.replyingTo !== "string" || !HANDLE_RE.test(e.replyingTo))) errors.push(`${w}.replyingTo must be a handle`);
+ if (e.parentShot !== undefined) {
+ const er = relFileError(e.parentShot, `${w}.parentShot`);
+ if (er) errors.push(er);
+ }
+ if (e.redact !== undefined && typeof e.redact !== "boolean") errors.push(`${w}.redact must be true or false`);
+ if (e.subjects !== undefined && !(Array.isArray(e.subjects) && e.subjects.length <= 8 && e.subjects.every((h) => typeof h === "string" && HANDLE_RE.test(h)))) {
+ errors.push(`${w}.subjects must be a list of handles (at most 8): the accounts the cut is about`);
+ }
+ if (e.badge !== undefined && e.badge !== null && !BADGES.includes(e.badge)) errors.push(`${w}.badge must be one of ${BADGES.join(", ")}`);
+ if (e.hold !== undefined && !(fin(e.hold) && e.hold >= POST_HOLD.min && e.hold <= POST_HOLD.max)) {
+ errors.push(`${w}.hold must be ${POST_HOLD.min}–${POST_HOLD.max} seconds (absent: the duration rule)`);
+ }
+ if (e.mediaLayout !== undefined && !POST_MEDIA_LAYOUTS.includes(e.mediaLayout)) errors.push(`${w}.mediaLayout must be one of ${POST_MEDIA_LAYOUTS.join(", ")}`);
+ if (e.media !== undefined) {
+ if (!Array.isArray(e.media)) errors.push(`${w}.media must be a list of attachments`);
+ else {
+ if (e.media.length > POST_MEDIA_MAX) errors.push(`${w}.media: at most ${POST_MEDIA_MAX} attachments`);
+ e.media.forEach((m, i) => errors.push(...mediaErrors(m, `${w}.media[${i}]`)));
+ }
+ }
+ return errors;
+}
+
+function mediaErrors(m, where) {
+ if (!isObj(m)) return [`${where} must be an object`];
+ const errors = [];
+ const er = relFileError(m.src, `${where}.src`);
+ if (er) errors.push(er);
+ if (!POST_MEDIA_KINDS.includes(m.kind)) errors.push(`${where}.kind must be one of ${POST_MEDIA_KINDS.join(", ")}`);
+ const timed = m.kind === "video" || m.kind === "gif";
+ if (timed && !(fin(m.seconds) && m.seconds > 0)) errors.push(`${where}.seconds must be its length (a ${m.kind} is measured when it goes in)`);
+ for (const k of ["width", "height"]) if (m[k] !== undefined && !(Number.isInteger(m[k]) && m[k] > 0)) errors.push(`${where}.${k} must be a whole number of pixels`);
+ for (const k of ["start", "end"]) {
+ if (m[k] === undefined) continue;
+ if (!timed) errors.push(`${where}.${k}: only a video or a GIF is trimmed`);
+ else if (!(fin(m[k]) && m[k] >= 0 && (!fin(m.seconds) || m[k] <= m.seconds + 0.05))) errors.push(`${where}.${k} must be a second inside it (0–${m.seconds})`);
+ }
+ if (timed && fin(m.start) && fin(m.end) && m.end - m.start < POST_MEDIA_MIN_SPAN) errors.push(`${where}: end must be at least ${POST_MEDIA_MIN_SPAN} s after start`);
+ for (const k of ["mute", "push", "audio"]) if (m[k] !== undefined && typeof m[k] !== "boolean") errors.push(`${where}.${k} must be true or false`);
+ if (m.push !== undefined && m.kind !== "image") errors.push(`${where}.push: only an image is pushed in on`);
+ if (m.crop !== undefined) {
+ const c = m.crop;
+ const ok = Array.isArray(c) && c.length === 4 && c.every((v) => fin(v) && v >= 0 && v <= 1) && c[2] > 0.05 && c[3] > 0.05 && c[0] + c[2] <= 1.0001 && c[1] + c[3] <= 1.0001;
+ if (!ok) errors.push(`${where}.crop must be [x, y, w, h] as fractions of the picture (each 0–1, the box inside it)`);
+ }
+ if (m.words !== undefined) {
+ const er2 = relFileError(m.words, `${where}.words`);
+ if (er2) errors.push(er2);
+ }
+ return errors;
+}
+
+/** Every post item's errors in a manifest (the writers' structure check and the build's lint). */
+export function validatePostItems(manifest) {
+ const errors = [];
+ const tl = Array.isArray(manifest?.timeline) ? manifest.timeline : [];
+ for (const e of tl) if (e?.type === "post") errors.push(...validatePostItem(e));
+ return errors;
+}
+
+/** Every file a post item reads beside the manifest, as `{ where, src }` (the lint checks each is there). */
+export function postItemFiles(entry) {
+ const out = [];
+ const w = `timeline ${entry?.id ?? "?"}`;
+ (Array.isArray(entry?.media) ? entry.media : []).forEach((m, i) => {
+ if (typeof m?.src === "string") out.push({ where: `${w}.media[${i}]`, src: m.src });
+ });
+ if (typeof entry?.parentShot === "string") out.push({ where: `${w}.parentShot`, src: entry.parentShot });
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// The card: its layout in the footage box, and its HTML.
+// ---------------------------------------------------------------------------
+
+/** Fira Sans's average advance, as a fraction of the size, over running English. */
+const CHAR_EM = 0.5;
+const LINE = 1.32;
+/** The text sizes tried, largest first, in px of a 1080-high frame (scaled to the box). */
+export const POST_TEXT_SIZES = Object.freeze([46, 42, 38, 34, 30, 27, 24, 22, 20, 18]);
+/** Below this size the words beside an attachment are too small: the card reads first, then the attachments play large. */
+export const POST_SIDE_MIN = 26;
+
+/** Lines `text` takes in a column `width` px wide at `size` px (an estimate: wrapping by average advance). */
+export function estimateLines(text, size, width) {
+ const per = Math.max(8, Math.floor(width / (size * CHAR_EM)));
+ return str(text).split("\n").reduce((n, para) => n + Math.max(1, Math.ceil(para.length / per)), 0);
+}
+
+/** The largest size in POST_TEXT_SIZES (scaled by `k`) at which `text` fits `width` × `height`; the smallest when none does. */
+export function fitSize(text, width, height, k = 1) {
+ for (const s0 of POST_TEXT_SIZES) {
+ const s = s0 * k;
+ if (estimateLines(text, s, width) * s * LINE <= height) return { size: Math.round(s), fits: true };
+ }
+ return { size: Math.round(POST_TEXT_SIZES[POST_TEXT_SIZES.length - 1] * k), fits: false };
+}
+
+/**
+ * THE LAYOUT, pure, in px of the box the item fills (the deck's footage box,
+ * or the whole frame without the deck):
+ *
+ * text no attachment: the card alone, centred, as wide as reads well
+ * side the card on the left, the attachments in a slot on the right, both
+ * up the whole item -- when the words fit beside them at POST_SIDE_MIN
+ * stack the words do not fit beside them: the card alone while it is read,
+ * then the attachments large under a strip naming the post
+ *
+ * `card` is the card's box in the reading span, `slot` the attachments' box
+ * in their span (`strip` the post's name over them, in a stack), `size` the
+ * text size the card starts from (the page shrinks it further if it must).
+ */
+export function postLayout(entry, { width, height }) {
+ const k = height / 1080;
+ const pad = Math.round(36 * k);
+ const steps = mediaSteps(entry);
+ const words = cardText(entry);
+ // What the card spends besides the words: its head (avatar, name, date), its counts, the context.
+ const context = parentsOf(entry).length * 130 * k + (isObj(entry?.quoted) ? 170 * k : 0) + (entry?.replyingTo || entry?.parentShot ? 40 * k : 0);
+ const chrome = 150 * k + context + (entry?.repostedBy ? 34 * k : 0);
+ const textCard = (w) => {
+ const cw = Math.min(w, Math.round(1180 * k));
+ const box = { x: Math.round((width - cw) / 2), y: pad, width: cw, height: height - 2 * pad };
+ return { box, fit: fitSize(words, cw - 2 * pad, box.height - 2 * pad - chrome, k) };
+ };
+ if (!steps.length) {
+ const t = textCard(width - 2 * pad);
+ return { mode: "text", card: t.box, slot: null, strip: null, size: t.fit.size, fits: t.fit.fits, pad };
+ }
+ const cardW = Math.round((width - 3 * pad) * 0.42);
+ const side = fitSize(words, cardW - 2 * pad, height - 4 * pad - chrome, k);
+ if (side.fits && side.size >= POST_SIDE_MIN * k) {
+ const card = { x: pad, y: pad, width: cardW, height: height - 2 * pad };
+ const slot = { x: 2 * pad + cardW, y: pad, width: width - 3 * pad - cardW, height: height - 2 * pad };
+ return { mode: "side", card, slot, strip: null, size: side.size, fits: true, pad };
+ }
+ const t = textCard(width - 2 * pad);
+ const stripH = Math.round(92 * k);
+ const strip = { x: pad, y: pad, width: width - 2 * pad, height: stripH };
+ const slot = { x: pad, y: pad + stripH + Math.round(pad / 2), width: width - 2 * pad, height: height - 2 * pad - stripH - Math.round(pad / 2) };
+ return { mode: "stack", card: t.box, slot, strip, size: t.fit.size, fits: t.fit.fits, pad };
+}
+
+/**
+ * Where each attachment of a step sits in the slot, in the box's px: one fills
+ * the slot (fitted, its aspect kept); a grid lays 2 side by side, 3 as one
+ * tall and two stacked, 4 as two by two -- each cell fitted.
+ */
+export function stepBoxes(step, slot, gap = 12) {
+ const n = step.items.length;
+ const cells = [];
+ if (n <= 1) cells.push({ ...slot });
+ else if (n === 2) {
+ const w = (slot.width - gap) / 2;
+ cells.push({ x: slot.x, y: slot.y, width: w, height: slot.height }, { x: slot.x + w + gap, y: slot.y, width: w, height: slot.height });
+ } else if (n === 3) {
+ const w = (slot.width - gap) / 2;
+ const h = (slot.height - gap) / 2;
+ cells.push({ x: slot.x, y: slot.y, width: w, height: slot.height }, { x: slot.x + w + gap, y: slot.y, width: w, height: h }, { x: slot.x + w + gap, y: slot.y + h + gap, width: w, height: h });
+ } else {
+ const w = (slot.width - gap) / 2;
+ const h = (slot.height - gap) / 2;
+ for (const [cx, cy] of [[0, 0], [1, 0], [0, 1], [1, 1]]) cells.push({ x: slot.x + cx * (w + gap), y: slot.y + cy * (h + gap), width: w, height: h });
+ }
+ return step.items.map((m, j) => {
+ const cell = cells[j];
+ const crop = Array.isArray(m.crop) ? m.crop : null;
+ const iw = (m.width ?? 16) * (crop ? crop[2] : 1);
+ const ih = (m.height ?? 9) * (crop ? crop[3] : 1);
+ const s = Math.min(cell.width / iw, cell.height / ih);
+ const w = Math.max(2, Math.floor((iw * s) / 2) * 2);
+ const h = Math.max(2, Math.floor((ih * s) / 2) * 2);
+ return { i: m.i, x: Math.round(cell.x + (cell.width - w) / 2), y: Math.round(cell.y + (cell.height - h) / 2), width: w, height: h, cell };
+ });
+}
+
+/** A string inside a quoted CSS url(): a <style> is raw text, so HTML entities would be read literally. */
+const cssStr = (s) => String(s ?? "").replace(/[\\'"\n<>]/g, (c) => (c === "<" ? "\\3c " : c === ">" ? "\\3e " : `\\${c === "\n" ? "a " : c}`));
+const esc = (s) =>
+ String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
+
+function rgb(hex) {
+ const h = String(hex ?? "#000").replace("#", "");
+ const f = h.length === 3 ? h.split("").map((c) => c + c).join("") : h.padEnd(6, "0").slice(0, 6);
+ return [0, 2, 4].map((i) => parseInt(f.slice(i, i + 2), 16) || 0);
+}
+/** Palette colour `a` toward `b` by `t`. */
+export function mixHex(a, b, t) {
+ const x = rgb(a);
+ const y = rgb(b);
+ return `#${x.map((v, i) => Math.round(v + (y[i] - v) * t).toString(16).padStart(2, "0")).join("")}`;
+}
+const rgbaOf = (hex, a) => `rgba(${rgb(hex).join(", ")}, ${a})`;
+
+const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+/** The card's date line: "Oct 30, 2026 · 04:00 UTC" (UTC: the same card on every machine). */
+export function cardDate(iso) {
+ const d = new Date(String(iso ?? ""));
+ if (Number.isNaN(d.getTime())) return "";
+ const hh = String(d.getUTCHours()).padStart(2, "0");
+ const mm = String(d.getUTCMinutes()).padStart(2, "0");
+ return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()} · ${hh}:${mm} UTC`;
+}
+/** The post's calendar day, `YYYY-MM-DD` (UTC), for the deck's date. */
+export const postDay = (iso) => {
+ const d = new Date(String(iso ?? ""));
+ return Number.isNaN(d.getTime()) ? "" : d.toISOString().slice(0, 10);
+};
+/** A count as X prints it: 999, 1.2K, 34K, 1.1M. */
+export function countText(n) {
+ if (!fin(n)) return "";
+ if (n < 1000) return String(n);
+ if (n < 10000) return `${(n / 1000).toFixed(1).replace(/\.0$/, "")}K`;
+ if (n < 1e6) return `${Math.round(n / 1000)}K`;
+ return `${(n / 1e6).toFixed(1).replace(/\.0$/, "")}M`;
+}
+const PLATFORM_NAME = { x: "X", bluesky: "Bluesky", web: "Web" };
+
+/** The deck's title and subtitle for a post item (deck.mjs deckText). */
+export function postDeckText(entry, formatDate = (d) => d) {
+ const hidden = cardAuthors(entry).some((a) => a.where === "author" && a.redact);
+ const who = hidden ? "a private account" : [str(entry?.author), entry?.handle ? `@${String(entry.handle).replace(/^@/, "")}` : ""].filter(Boolean).join(" ");
+ const verb = entry?.repostedBy ? "reposted on" : parentsOf(entry).length || entry?.replyingTo ? "replying on" : "on";
+ return {
+ title: formatDate(postDay(entry?.date)),
+ subtitle: `${who} ${verb} ${PLATFORM_NAME[entry?.platform] ?? "the web"}`.trim(),
+ };
+}
+
+const hueOf = (s) => {
+ let h = 0;
+ for (const c of String(s ?? "")) h = (h * 31 + c.charCodeAt(0)) % 360;
+ return h;
+};
+
+/** The words with @mentions of the blurred authors blurred (their handle never in the page). */
+function wordsHtml(text, blurred) {
+ const set = new Set(blurred.map((h) => h.replace(/^@/, "").toLowerCase()));
+ return esc(text)
+ .replace(/@([A-Za-z0-9_]{1,30})/g, (m, h) => (set.has(h.toLowerCase()) ? `<span class="redact">@${"x".repeat(Math.max(4, Math.min(12, h.length)))}</span>` : `<span class="mention">${m}</span>`))
+ .replace(/https?:\/\/\S+/g, (u) => `<span class="link">${u.length > 48 ? `${u.slice(0, 46)}…` : u}</span>`)
+ .replace(/\n/g, "<br>");
+}
+
+function avatarHtml(who, { redact, size, accent }) {
+ const name = str(who?.author) || str(who?.handle) || "?";
+ const initial = esc((name.replace(/^@/, "")[0] ?? "?").toUpperCase());
+ const bg = accent ?? `hsl(${hueOf(who?.handle)}, 38%, 42%)`;
+ return `<div class="avatar${redact ? " redact" : ""}" style="width:${size}px;height:${size}px;font-size:${Math.round(size * 0.46)}px;background:${bg}">${redact ? "" : initial}</div>`;
+}
+
+function nameHtml(who, { redact, cls = "" }) {
+ if (redact) return `<span class="who ${cls}"><span class="name redact">xxxxxxxxxxxx</span> <span class="handle redact">@xxxxxxxx</span></span>`;
+ const h = str(who?.handle).replace(/^@/, "");
+ return `<span class="who ${cls}"><span class="name">${esc(str(who?.author) || h)}</span>${h ? ` <span class="handle">@${esc(h)}</span>` : ""}</span>`;
+}
+
+/**
+ * The card's HTML: one page `width` × `height` (the box the item fills), the
+ * card drawn in the deck's palette and faces, the attachments' slot left as a
+ * well for the media to be laid into (the build overlays the files; Play the
+ * cut lays its elements over the same box). `phase` "read" draws the card;
+ * "media" in a stack layout the strip over the slot. `fonts` are urls for
+ * the regular and bold faces; with none, the page falls back to sans-serif.
+ * `parentShotUrl`: the capture's thread shot, drawn as the context when the
+ * post it answers is not archived.
+ *
+ * @param {Record<string, any>} entry
+ * @param {{ width: number, height: number, palette?: Record<string, string>, fonts?: { regular?: string, bold?: string },
+ * phase?: "read"|"media", parentShotUrl?: string|null, transparent?: boolean }} o
+ */
+export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, phase = "read", parentShotUrl = null, transparent = false }) {
+ const pal = { bg: "#12100c", fg: "#f6f1e6", muted: "#a2957f", accent: "#c8752a", ...palette };
+ const L = postLayout(entry, { width, height });
+ const k = height / 1080;
+ const size = L.size;
+ const authors = cardAuthors(entry);
+ const blurred = authors.filter((a) => a.redact && a.handle).map((a) => a.handle);
+ const red = (where) => authors.find((a) => a.where === where)?.redact ?? false;
+ const cardBg = mixHex(pal.bg, pal.fg, 0.07);
+ const line = mixHex(pal.bg, pal.fg, 0.18);
+ const own = { author: entry.author, handle: entry.handle };
+ const ownRed = red("author");
+ const strip = phase === "media" && L.mode === "stack";
+ const e = entry.engagement ?? {};
+ const counts = [["replies", e.replies], ["reposts", e.reposts], ["likes", e.likes], ["quotes", e.quotes]]
+ .filter(([, v]) => fin(v) && v > 0)
+ .map(([k2, v]) => `<span class="count"><b>${countText(v)}</b> ${k2 === "replies" && v === 1 ? "reply" : k2 === "reposts" && v === 1 ? "repost" : k2 === "likes" && v === 1 ? "like" : k2 === "quotes" && v === 1 ? "quote" : k2}</span>`)
+ .join("");
+ const ctx = [];
+ // The posts it answers, oldest first, a thread line down to the post.
+ const parents = parentsOf(entry);
+ for (let i = parents.length - 1; i >= 0; i -= 1) {
+ const p = parents[i];
+ const r = red(`parents[${i}]`);
+ const subject = !r && subjectsOf(entry).some((h) => String(h).toLowerCase() === String(p.handle ?? "").replace(/^@/, "").toLowerCase());
+ ctx.push(
+ `<div class="parent" data-post-parent="${i}"${r ? ' data-redacted=""' : ""}>${avatarHtml(p, { redact: r, size: Math.round(44 * k), accent: subject ? pal.accent : undefined })}<div class="pbody"><div class="phead">${nameHtml(p, { redact: r })}<span class="pdate">${esc(cardDate(p.date).split(" · ")[0])}</span></div><div class="ptext">${wordsHtml(str(p.text) || (p.url ? "(not archived)" : ""), blurred)}</div></div></div>`,
+ );
+ }
+ if (!parents.length && parentShotUrl) ctx.push(`<div class="pshot" data-post-parent-shot=""><img src="${esc(parentShotUrl)}" alt=""></div>`);
+ else if (!parents.length && entry.replyingTo) {
+ ctx.push(`<div class="replying" data-post-replying="">Replying to ${red("replyingTo") ? '<span class="redact">@xxxxxxxx</span>' : `<span class="mention">@${esc(String(entry.replyingTo).replace(/^@/, ""))}</span>`}</div>`);
+ }
+ const q = isObj(entry.quoted) ? entry.quoted : null;
+ const quoted = q
+ ? `<div class="quoted" data-post-quoted=""${red("quoted") ? ' data-redacted=""' : ""}><div class="phead">${avatarHtml(q, { redact: red("quoted"), size: Math.round(30 * k) })}${nameHtml(q, { redact: red("quoted") })}<span class="pdate">${esc(cardDate(q.date).split(" · ")[0])}</span></div><div class="qtext">${wordsHtml(str(q.text), blurred)}</div></div>`
+ : "";
+ const repost = entry.repostedBy
+ ? `<div class="repost" data-post-repost="">↻ ${esc(str(entry.repostedBy.author) || `@${entry.repostedBy.handle}`)} reposted</div>`
+ : "";
+ const head = `<div class="head"${ownRed ? ' data-redacted=""' : ""}>${avatarHtml(own, { redact: ownRed, size: Math.round(64 * k), accent: ownRed ? undefined : pal.accent })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[entry.platform] ?? "")}</div></div>`;
+ // A card alone (text, or a stack's reading) is as tall as its words, centred in its box; beside the attachments, the box's height.
+ const card = (box) => `<div class="card" data-post-card="${esc(entry.id)}" style="left:${box.x}px;${L.mode === "side" ? `top:${box.y}px;height:${box.height}px` : `top:${box.y + box.height / 2}px;transform:translateY(-50%);max-height:${box.height}px`};width:${box.width}px">${repost}${ctx.length ? `<div class="context">${ctx.join("")}</div>` : ""}${head}<div class="words" data-post-words="" style="font-size:${size}px">${wordsHtml(cardText(entry), blurred)}</div>${quoted}${counts ? `<div class="counts" data-post-counts="">${counts}</div>` : ""}</div>`;
+ const stripHtml = L.strip
+ ? `<div class="strip" data-post-strip="" style="left:${L.strip.x}px;top:${L.strip.y}px;width:${L.strip.width}px;height:${L.strip.height}px">${avatarHtml(own, { redact: ownRed, size: Math.round(56 * k), accent: ownRed ? undefined : pal.accent })}<div class="hwho">${nameHtml(own, { redact: ownRed, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="sline">${wordsHtml(cardText(entry).split("\n")[0].slice(0, 140) + (cardText(entry).length > 140 ? "…" : ""), blurred)}</div></div>`
+ : "";
+ const slot = L.slot && (L.mode === "side" || strip) ? `<div class="slot" data-post-slot="" style="left:${L.slot.x}px;top:${L.slot.y}px;width:${L.slot.width}px;height:${L.slot.height}px"></div>` : "";
+ const body = strip ? `${stripHtml}${slot}` : `${card(L.card)}${slot}`;
+ const minSize = Math.round(POST_TEXT_SIZES[POST_TEXT_SIZES.length - 1] * k);
+ return `<!doctype html>
+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=${width}, height=${height}">
+<style>
+@font-face { font-family: 'PostSans'; src: url('${cssStr(fonts.regular ?? "")}'); }
+@font-face { font-family: 'PostSansBold'; src: url('${cssStr(fonts.bold ?? "")}'); }
+* { margin: 0; padding: 0; box-sizing: border-box; }
+html, body { width: ${width}px; height: ${height}px; overflow: hidden; background: ${transparent ? "transparent" : pal.bg}; }
+body { position: relative; font-family: 'PostSans', sans-serif; color: ${pal.fg}; -webkit-font-smoothing: antialiased; font-synthesis: none; }
+b, .name, .mark { font-family: 'PostSansBold', sans-serif; font-weight: 400; }
+.card, .strip, .slot { position: absolute; }
+.card { display: flex; flex-direction: column; justify-content: center; gap: ${Math.round(18 * k)}px; padding: ${L.pad}px; background: ${cardBg}; border: 1px solid ${line}; border-radius: ${Math.round(18 * k)}px; overflow: hidden; }
+.repost { color: ${pal.muted}; font-size: ${Math.round(22 * k)}px; }
+.head, .strip { display: flex; align-items: center; gap: ${Math.round(16 * k)}px; }
+.strip { padding: 0 ${Math.round(20 * k)}px; background: ${cardBg}; border: 1px solid ${line}; border-radius: ${Math.round(14 * k)}px; }
+.hwho { display: flex; flex-direction: column; min-width: 0; }
+.who.big .name { font-size: ${Math.round(30 * k)}px; }
+.who.big .handle { font-size: ${Math.round(24 * k)}px; }
+.who .name { font-size: ${Math.round(22 * k)}px; color: ${pal.fg}; }
+.who .handle { font-size: ${Math.round(19 * k)}px; color: ${pal.muted}; }
+.date { color: ${pal.muted}; font-size: ${Math.round(20 * k)}px; margin-top: ${Math.round(2 * k)}px; }
+.mark { margin-left: auto; font-size: ${Math.round(30 * k)}px; color: ${pal.muted}; }
+.avatar { flex: none; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; font-family: 'PostSansBold', sans-serif; }
+.words { line-height: ${LINE}; overflow-wrap: anywhere; flex: 0 1 auto; min-height: 0; overflow: hidden; }
+.sline { margin-left: ${Math.round(12 * k)}px; color: ${pal.fg}; font-size: ${Math.round(24 * k)}px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1; }
+.mention, .link { color: ${pal.accent}; }
+.context { display: flex; flex-direction: column; gap: ${Math.round(10 * k)}px; }
+.parent { display: flex; gap: ${Math.round(14 * k)}px; position: relative; padding-bottom: ${Math.round(6 * k)}px; }
+.parent::after { content: ""; position: absolute; left: ${Math.round(21 * k)}px; top: ${Math.round(50 * k)}px; bottom: -${Math.round(6 * k)}px; width: 2px; background: ${line}; }
+.pbody { min-width: 0; flex: 1; }
+.phead { display: flex; align-items: baseline; gap: ${Math.round(10 * k)}px; }
+.pdate { color: ${pal.muted}; font-size: ${Math.round(18 * k)}px; }
+.ptext, .qtext { font-size: ${Math.round(22 * k)}px; line-height: 1.3; color: ${mixHex(pal.fg, pal.bg, 0.15)}; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden; overflow-wrap: anywhere; }
+.qtext { -webkit-line-clamp: 5; margin-top: ${Math.round(8 * k)}px; }
+.quoted { border: 1px solid ${line}; border-radius: ${Math.round(14 * k)}px; padding: ${Math.round(16 * k)}px; }
+.quoted .avatar { display: inline-flex; }
+.pshot img { max-width: 100%; max-height: ${Math.round(240 * k)}px; border-radius: ${Math.round(10 * k)}px; display: block; }
+.replying { color: ${pal.muted}; font-size: ${Math.round(21 * k)}px; }
+.counts { display: flex; gap: ${Math.round(24 * k)}px; color: ${pal.muted}; font-size: ${Math.round(21 * k)}px; border-top: 1px solid ${line}; padding-top: ${Math.round(14 * k)}px; flex: none; }
+.counts b { color: ${pal.fg}; }
+.redact { filter: blur(${Math.round(9 * k)}px); color: ${pal.muted}; }
+.avatar.redact { background: ${rgbaOf(pal.muted, 0.6)} !important; }
+.slot { background: ${rgbaOf("#000000", 0.32)}; border-radius: ${Math.round(14 * k)}px; }
+</style></head>
+<body data-post-item="${esc(entry.id)}" data-post-layout="${L.mode}" data-post-phase="${strip ? "media" : "read"}">${body}
+<script>
+// The words at the layout's size, shrunk while they overflow (the browser
+// knows how they wrap; the layout only estimated it). Then say so.
+(function () {
+ var w = document.querySelector('[data-post-words]');
+ var min = ${minSize};
+ function fit() {
+ if (w) { var s = parseFloat(w.style.fontSize); while (w.scrollHeight > w.clientHeight + 1 && s > min) { s -= 1; w.style.fontSize = s + 'px'; } }
+ document.body.setAttribute('data-post-ready', '1');
+ }
+ if (document.fonts && document.fonts.ready) document.fonts.ready.then(fit); else fit();
+})();
+</script></body></html>`;
+}
diff --git a/umtool/report-to-video/post-item.test.mjs b/umtool/report-to-video/post-item.test.mjs
@@ -0,0 +1,133 @@
+// post-item.mjs: a post as a timeline item -- the validator, the duration
+// rule, the plan of what plays when, the privacy rule and the layout.
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ POST_GIF, POST_IMAGE_SECONDS, POST_READ, authorRedaction, cardAuthors, cardText, mediaSeconds, mediaTimeAt, postCardHtml,
+ postDeckText, postItemPlan, postItemSeconds, postLayout, readingSeconds, ruleSeconds, stepAt, stepBoxes, validatePostItem, wordCount,
+} from "./post-item.mjs";
+import { deckText, estimatedDuration, deckQrUrl, resolveDeck, validateDeckMarkers } from "./deck.mjs";
+
+const base = (o = {}) => ({
+ type: "post", id: "p1", post: "someone-x/2116017249706225668", platform: "x",
+ author: "MR. OBVIOUS", handle: "ObviousRises", date: "2026-10-30T04:00:00.000Z",
+ text: "one two three four five six", url: "https://x.com/ObviousRises/status/2116017249706225668", ...o,
+});
+const video = (o = {}) => ({ src: "posts-media/someone-x/1/1_1.mp4", kind: "video", seconds: 6.2, width: 1920, height: 1080, audio: true, ...o });
+const image = (o = {}) => ({ src: "posts-media/someone-x/1/1_1.jpg", kind: "image", width: 1200, height: 900, ...o });
+
+test("a valid post item passes; each field is refused in words", () => {
+ assert.deepEqual(validatePostItem(base({ media: [video(), image()], engagement: { likes: 3 } })), []);
+ const bad = validatePostItem(base({ post: "nope", platform: "myspace", date: "soon", hold: 0.2, media: [video({ src: "/abs.mp4" }), image({ start: 1 }), { src: "a.png", kind: "sound" }] }));
+ assert.ok(bad.some((e) => e.includes(".post must be <channel>/<postId>")));
+ assert.ok(bad.some((e) => e.includes(".platform must be one of")));
+ assert.ok(bad.some((e) => e.includes(".date must be")));
+ assert.ok(bad.some((e) => e.includes(".hold must be 1–120")));
+ assert.ok(bad.some((e) => e.includes("media[0].src must be relative")));
+ assert.ok(bad.some((e) => e.includes("media[1].start: only a video or a GIF is trimmed")));
+ assert.ok(bad.some((e) => e.includes("media[2].kind must be one of")));
+ assert.ok(validatePostItem(base({ media: [video({ start: 3, end: 3.2 })] })).some((e) => e.includes("at least 0.5 s after start")));
+ assert.ok(validatePostItem(base({ media: [video({ end: 9 })] })).some((e) => e.includes("a second inside it")));
+ assert.ok(validatePostItem(base({ media: [video({ crop: [0.5, 0, 0.6, 1] })] })).some((e) => e.includes(".crop must be")));
+ assert.ok(validatePostItem(base({ parents: [{}, {}, {}] })).some((e) => e.includes("at most 2")));
+ assert.ok(validatePostItem(base({ media: [video(), video(), video(), video(), video()] })).some((e) => e.includes("at most 4 attachments")));
+});
+
+test("the duration rule: reading time (words / wps + lead, clamped) plus the attachments; hold overrides", () => {
+ assert.equal(wordCount(" a b\nc "), 3);
+ // Six words: 1 + 6/3 = 3 s (the floor).
+ assert.equal(readingSeconds(base()), POST_READ.min);
+ const long = base({ text: Array.from({ length: 30 }, () => "w").join(" ") });
+ assert.equal(readingSeconds(long), POST_READ.lead + 30 / POST_READ.wps);
+ assert.equal(readingSeconds(base({ text: Array.from({ length: 900 }, () => "w").join(" ") })), POST_READ.max);
+ // A repost's "RT @x: " is its reposted line, not words to read.
+ assert.equal(cardText(base({ text: "RT @ObviousRises: hello there", repostedBy: { handle: "ObviousRises" } })), "hello there");
+ // A parent and a quote add their own reading, clamped 1–4.
+ assert.equal(readingSeconds(base({ parents: [{ text: "a" }], quoted: { text: Array.from({ length: 60 }, () => "q").join(" ") } })), 3 + 1 + 4);
+ // Attachments in sequence.
+ assert.equal(mediaSeconds(video({ start: 1, end: 4 })), 3);
+ assert.equal(mediaSeconds(image()), POST_IMAGE_SECONDS);
+ assert.equal(mediaSeconds({ kind: "gif", seconds: 1.2 }), 3.6); // looped to ≥ 3 s: three passes
+ assert.equal(mediaSeconds({ kind: "gif", seconds: 25 }), POST_GIF.max);
+ assert.equal(ruleSeconds(base({ media: [video(), image()] })), 3 + 6.2 + 3.5);
+ assert.equal(postItemSeconds(base({ media: [video()], hold: 5 })), 5);
+ // A grid of images is one step: 3.5 + 1 per extra.
+ assert.equal(ruleSeconds(base({ mediaLayout: "grid", media: [image(), image(), image()] })), 3 + 5.5);
+ // The deck's estimate is the rule.
+ assert.equal(estimatedDuration(base({ media: [video()] })), 9.2);
+});
+
+test("the plan: the words first, then each attachment; a hold cuts it short or holds the last", () => {
+ const p = postItemPlan(base({ media: [video({ start: 1, end: 3 }), image()] }));
+ assert.equal(p.reading, 3);
+ assert.equal(p.total, 3 + 2 + 3.5);
+ assert.deepEqual(p.steps.map((s) => [s.kind, s.at, s.seconds]), [["video", 3, 2], ["image", 5, 3.5]]);
+ assert.equal(p.steps[0].srcFrom, 1);
+ assert.equal(p.steps[0].srcTo, 3);
+ assert.equal(p.steps[0].sound, true);
+ assert.equal(stepAt(p, 1), null);
+ assert.equal(stepAt(p, 4).kind, "video");
+ assert.equal(mediaTimeAt(p.steps[0], 4), 2);
+ const cut = postItemPlan(base({ media: [video(), image()], hold: 5 }));
+ assert.deepEqual(cut.steps.map((s) => [s.kind, s.seconds]), [["video", 2]]);
+ assert.equal(cut.steps[0].srcTo, 2);
+ const held = postItemPlan(base({ media: [image()], hold: 12 }));
+ assert.equal(held.held, 12 - 6.5);
+ assert.equal(postItemPlan(base({ media: [video({ mute: true })] })).steps[0].sound, false);
+ const gif = postItemPlan(base({ media: [{ src: "g.mp4", kind: "gif", seconds: 1.2 }] }));
+ assert.equal(gif.steps[0].loop, true);
+ assert.equal(mediaTimeAt(gif.steps[0], 3 + 1.5), 0.3);
+});
+
+test("the privacy rule: another author is blurred unless the subject, gold/grey verified, or redact:false", () => {
+ assert.deepEqual(authorRedaction({ handle: "someone" }, { subjects: ["ObviousRises"] }), { redact: true, reason: "private" });
+ assert.deepEqual(authorRedaction({ handle: "obviousrises" }, { subjects: ["ObviousRises"] }), { redact: false, reason: "subject" });
+ assert.deepEqual(authorRedaction({ handle: "NASA", badge: "gold" }), { redact: false, reason: "verified" });
+ assert.deepEqual(authorRedaction({ handle: "WhiteHouse", badge: "grey" }), { redact: false, reason: "verified" });
+ assert.deepEqual(authorRedaction({ handle: "bought", badge: "blue" }), { redact: true, reason: "blue-check" });
+ assert.deepEqual(authorRedaction({ handle: "x" }, { redact: false }), { redact: false, reason: "off" });
+ assert.deepEqual(authorRedaction({ handle: "NASA", badge: "gold" }, { redact: true }), { redact: true, reason: "forced" });
+ assert.deepEqual(authorRedaction({}), { redact: true, reason: "unknown" });
+ const e = base({ text: "@KacamnGamesYT you are wrong", parents: [{ handle: "KacamnGamesYT", author: "Kacamn", text: "a question" }] });
+ assert.deepEqual(cardAuthors(e).map((a) => [a.where, a.redact]), [["parents[0]", true]]);
+ const html = postCardHtml(e, { width: 1440, height: 810 });
+ // The parent's name and handle are never in the page, and the mention of them is blurred.
+ assert.ok(!html.includes("KacamnGamesYT"));
+ assert.ok(!html.includes("Kacamn"));
+ assert.ok(html.includes("a question"));
+ assert.ok(html.includes('data-redacted=""'));
+ // A self-thread (his own parent) is drawn plainly.
+ const self = postCardHtml(base({ parents: [{ handle: "ObviousRises", author: "MR. OBVIOUS", text: "first" }] }), { width: 1440, height: 810 });
+ assert.ok(!self.includes('data-redacted=""'));
+ // "Replying to" with no parent archived.
+ assert.ok(postCardHtml(base({ replyingTo: "private_person" }), { width: 1440, height: 810 }).includes("Replying to <span class=\"redact\">"));
+});
+
+test("the layout: text alone; the words beside the attachments when they fit; else read first, then the media large", () => {
+ const box = { width: 1440, height: 810 };
+ assert.equal(postLayout(base(), box).mode, "text");
+ const side = postLayout(base({ media: [video()] }), box);
+ assert.equal(side.mode, "side");
+ assert.ok(side.slot.x > side.card.x + side.card.width);
+ const words = Array.from({ length: 480 }, () => "word").join(" ");
+ const stack = postLayout(base({ text: words, media: [video()] }), box);
+ assert.equal(stack.mode, "stack");
+ assert.ok(stack.strip && stack.slot.y > stack.strip.y);
+ // A media box keeps its aspect inside the slot; a grid of two lays them side by side.
+ const [b] = stepBoxes({ items: [{ i: 0, width: 1920, height: 1080 }] }, side.slot);
+ assert.ok(Math.abs(b.width / b.height - 16 / 9) < 0.02);
+ const two = stepBoxes({ items: [{ i: 0, width: 100, height: 100 }, { i: 1, width: 100, height: 100 }] }, { x: 0, y: 0, width: 412, height: 200 });
+ assert.ok(two[1].x > two[0].x + two[0].width);
+});
+
+test("the deck: a post item's date is its title, its author and platform the subtitle; its QR the post", () => {
+ const deck = resolveDeck({ chrome: { engine: "hyperframes", layout: "deck" } });
+ const t = deckText(base(), null, {}, deck, false);
+ assert.equal(t.title, "Oct 30, 2026");
+ assert.equal(t.subtitle, "MR. OBVIOUS @ObviousRises on X");
+ assert.equal(postDeckText(base({ repostedBy: { handle: "ObviousRises" } })).subtitle, "MR. OBVIOUS @ObviousRises reposted on X");
+ assert.equal(deckQrUrl(base(), {}, { links: "original" }), base().url);
+ // A marker may follow a post item.
+ const m = { render: { chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "p1", label: "Then" }] } } }, timeline: [base(), { ...base(), id: "p2" }] };
+ assert.deepEqual(validateDeckMarkers(m), []);
+});
diff --git a/umtool/report-to-video/post-render.mjs b/umtool/report-to-video/post-render.mjs
@@ -0,0 +1,263 @@
+// A POST ITEM's SEGMENT (post-item.mjs; umtool/docs/report-video.md, "Post
+// items"): the card drawn by a browser from the archived post -- the deck's
+// palette and faces, never a screenshot of the platform -- and its
+// attachments laid into the card's slot by ffmpeg, on the item's plan
+// (postItemPlan): the words read first, then each attachment in turn, a
+// video with its sound, a GIF looped, an image held (pushed in on, when it
+// asks). Framed into the deck's footage box like a clip, so the deck's rail,
+// section bars and date stamp ride over it as over any segment.
+//
+// buildPostSegment(entry, ctx) render the card PNG(s), then one encode
+// postSegmentArgs(...) that encode's argv, PURE (the tests read it)
+//
+// The card is rendered once per change: `<id>.post.json` beside the segment
+// records the key (the entry, the box, the palette and faces, each
+// attachment's size and mtime), and a build whose key matches keeps the
+// segment it has.
+import { createHash } from "node:crypto";
+import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+import { POST_PUSH, postCardHtml, postItemPlan, postLayout, stepBoxes } from "./post-item.mjs";
+
+const r3 = (v) => Math.round(v * 1000) / 1000;
+const num = (v) => String(r3(v));
+
+/** The record beside a post item's segment: what it was built from. */
+export const postRecordPath = (seg) => seg.replace(/\.mp4$/, ".post.json");
+
+/**
+ * The cues of a video attachment's transcript (`media[i].words`: the editor's
+ * transcribe result, `{cues: [{start, end, text}]}` on the file's clock), or [].
+ */
+export async function readMediaCues(file) {
+ try {
+ const doc = JSON.parse(await readFile(file, "utf8"));
+ const cues = Array.isArray(doc?.cues) ? doc.cues : Array.isArray(doc) ? doc : [];
+ return cues
+ .filter((c) => c && Number.isFinite(c.start) && Number.isFinite(c.end) && typeof c.text === "string" && c.text.trim())
+ .map((c) => ({ start: c.start, end: c.end, text: c.text.replace(/\s+/g, " ").trim() }));
+ } catch {
+ return [];
+ }
+}
+
+/** A step's cues on the ITEM's clock: each cue inside its source span, moved to where it plays. */
+export function stepCaptions(step, cues) {
+ if (step?.kind !== "video" || !cues?.length) return [];
+ const end = step.at + step.seconds;
+ return cues
+ .filter((c) => c.end > step.srcFrom && c.start < step.srcTo)
+ .map((c) => ({ from: r3(Math.max(step.at, step.at + c.start - step.srcFrom)), to: r3(Math.min(end, step.at + c.end - step.srcFrom)), text: c.text }))
+ .filter((c) => c.to - c.from > 0.05);
+}
+
+/**
+ * The encode, pure. `cards`: the read-phase PNG and (a stack layout) the
+ * media-phase one; `files[i]`: attachment i's absolute path; `captions`:
+ * `[{from, to, textfile}]` on the item's clock (drawn over the slot's foot);
+ * `place`: the deck's framing filters after the box (deckFraming's `place`),
+ * none without the deck; `encode`: build-video's encodeArgs.
+ *
+ * @returns {string[]}
+ */
+export function postSegmentArgs({ entry, box, plan, layout, cards, files, render, place = [], encode = [], captions = [], fontfile = null, outPath }) {
+ const fps = render.fps ?? 30;
+ const T = plan.total;
+ const inputs = [];
+ const parts = [];
+ const add = (args) => {
+ inputs.push(...args);
+ return inputs.filter((a) => a === "-i").length - 1;
+ };
+ const read = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", cards.read]);
+ parts.push(`[${read}:v]scale=${box.width}:${box.height},setsar=1,fps=${fps}[b0]`);
+ let cur = "b0";
+ let n = 0;
+ const lay = (label, x, y, a, b) => {
+ const next = `b${++n}`;
+ parts.push(`[${cur}][${label}]overlay=x=${x}:y=${y}:enable='between(t,${num(a)},${num(b)})'[${next}]`);
+ cur = next;
+ };
+ if (layout.mode === "stack" && cards.media && plan.steps.length) {
+ const mi = add(["-loop", "1", "-framerate", String(fps), "-t", num(T), "-i", cards.media]);
+ parts.push(`[${mi}:v]scale=${box.width}:${box.height},setsar=1,fps=${fps}[mc]`);
+ lay("mc", 0, 0, plan.steps[0].at, T);
+ }
+ const audio = [];
+ plan.steps.forEach((step, si) => {
+ const last = si === plan.steps.length - 1;
+ const until = last ? T : step.at + step.seconds;
+ // Beside the card, the first attachment is up from the first frame (its first frame while the words are read).
+ const shownFrom = si === 0 && layout.mode === "side" ? 0 : step.at;
+ const boxes = stepBoxes(step, layout.slot);
+ step.items.forEach((m, j) => {
+ const b = boxes[j];
+ const file = files[m.i];
+ const crop = Array.isArray(m.crop) ? `crop=iw*${num(m.crop[2])}:ih*${num(m.crop[3])}:iw*${num(m.crop[0])}:ih*${num(m.crop[1])},` : "";
+ const label = `m${si}_${j}`;
+ if (step.kind === "image") {
+ if (m.push === true) {
+ const frames = Math.max(1, Math.round((until - shownFrom) * fps));
+ const k = add(["-i", file]);
+ parts.push(
+ `[${k}:v]${crop}scale=${b.width * 2}:${b.height * 2},setsar=1,` +
+ `zoompan=z='1+${POST_PUSH}*on/${frames}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=${frames}:s=${b.width}x${b.height}:fps=${fps},` +
+ `setpts=PTS-STARTPTS+${num(shownFrom)}/TB[${label}]`,
+ );
+ } else {
+ const k = add(["-loop", "1", "-framerate", String(fps), "-t", num(until), "-i", file]);
+ parts.push(`[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps}[${label}]`);
+ }
+ } else {
+ // A video or a GIF: its span from srcFrom, its first frame held from the item's start until it plays.
+ const len = until - step.at;
+ const k = add([...(step.loop ? ["-stream_loop", "-1"] : []), "-ss", num(step.srcFrom), "-t", num(len), "-i", file]);
+ parts.push(
+ `[${k}:v]${crop}scale=${b.width}:${b.height},setsar=1,fps=${fps},setpts=PTS-STARTPTS,` +
+ `tpad=start_duration=${num(step.at)}:start_mode=clone:stop_mode=clone:stop_duration=${num(T)}[${label}]`,
+ );
+ if (step.sound) {
+ const ms = Math.round(step.at * 1000);
+ const dur = Math.min(step.seconds, len);
+ audio.push({ label: `a${si}`, chain: `[${k}:a]aresample=${render.audioRate ?? 48000},aformat=channel_layouts=stereo,asetpts=PTS-STARTPTS,atrim=0:${num(dur)},afade=t=in:d=0.04,afade=t=out:st=${num(Math.max(0, dur - 0.06))}:d=0.06,adelay=${ms}|${ms}[a${si}]` });
+ }
+ }
+ lay(label, b.x, b.y, shownFrom, until);
+ });
+ });
+ // A video attachment's words (its transcript), at the slot's foot.
+ if (captions.length && fontfile && layout.slot) {
+ const size = Math.round(34 * (box.height / 1080));
+ const y = Math.round(layout.slot.y + layout.slot.height - size * 2.2);
+ const cx = Math.round(layout.slot.x + layout.slot.width / 2);
+ for (const c of captions) {
+ const next = `b${++n}`;
+ parts.push(
+ `[${cur}]drawtext=fontfile='${fontfile}':textfile='${c.textfile}':fontsize=${size}:fontcolor=white:box=1:boxcolor=black@0.62:boxborderw=${Math.round(size * 0.35)}:` +
+ `x=${cx}-text_w/2:y=${y}:enable='between(t,${num(c.from)},${num(c.to)})'[${next}]`,
+ );
+ cur = next;
+ }
+ }
+ parts.push(`[${cur}]format=yuv420p${place.length ? `,${place.join(",")}` : ",setsar=1"}[v]`);
+ const sil = add(["-f", "lavfi", "-t", num(T), "-i", `anullsrc=channel_layout=stereo:sample_rate=${render.audioRate ?? 48000}`]);
+ if (audio.length) {
+ parts.push(...audio.map((a) => a.chain));
+ parts.push(`[${sil}:a]${audio.map((a) => `[${a.label}]`).join("")}amix=inputs=${audio.length + 1}:normalize=0:duration=first[a]`);
+ } else parts.push(`[${sil}:a]anull[a]`);
+ return [
+ "-nostdin", "-v", "error", "-y",
+ ...inputs,
+ "-filter_complex", parts.join(";"),
+ "-map", "[v]", "-map", "[a]",
+ ...encode,
+ "-t", num(T),
+ outPath,
+ ];
+}
+
+async function loadChromium() {
+ let mod;
+ try {
+ mod = await import("@playwright/test");
+ } catch (err) {
+ throw new Error(`a post item's card is drawn by a browser, and Playwright is not available here (it ships with umtool): ${err.message}`);
+ }
+ const chromium = mod.chromium ?? mod.default?.chromium;
+ if (!chromium) throw new Error("Playwright loaded but has no chromium export");
+ return chromium;
+}
+
+/**
+ * Draw the card's pages as PNGs, `box` px each: `read` always, `media` for a
+ * stack layout. The page is a file beside them, so its faces and the parent
+ * shot load from disk (an about:blank page may not read file: urls).
+ */
+export async function renderPostCards(entry, { box, render, dir, manifestDir, layout }) {
+ await mkdir(dir, { recursive: true });
+ const fonts = {
+ regular: render.fontRegular ? pathToFileURL(render.fontRegular).href : "",
+ bold: render.fontBold ? pathToFileURL(render.fontBold).href : "",
+ };
+ const parentShotUrl = typeof entry.parentShot === "string" ? pathToFileURL(path.resolve(manifestDir, entry.parentShot)).href : null;
+ const phases = layout.mode === "stack" ? ["read", "media"] : ["read"];
+ const chromium = await loadChromium();
+ const browser = await chromium.launch({ headless: true });
+ const out = {};
+ try {
+ const ctx = await browser.newContext({ viewport: { width: box.width, height: box.height }, deviceScaleFactor: 1, offline: true, serviceWorkers: "block" });
+ const page = await ctx.newPage();
+ for (const phase of phases) {
+ const html = postCardHtml(entry, { width: box.width, height: box.height, palette: render.palette, fonts, phase, parentShotUrl });
+ const file = path.join(dir, `${phase}.html`);
+ await writeFile(file, html, "utf8");
+ await page.goto(pathToFileURL(file).href, { waitUntil: "load" });
+ await page.waitForSelector("body[data-post-ready='1']", { timeout: 15000 });
+ const png = path.join(dir, `${phase}.png`);
+ await page.screenshot({ path: png, clip: { x: 0, y: 0, width: box.width, height: box.height } });
+ out[phase] = png;
+ }
+ await ctx.close();
+ } finally {
+ await browser.close();
+ }
+ return out;
+}
+
+/**
+ * Build post item `entry`'s segment. `ctx`: `{ render, outDir, manifestDir,
+ * box, place, encode, exec, ffmpeg, emit }` -- the box it fills (the deck's
+ * footage box, or the frame), the deck's framing after it, build-video's
+ * encode args and ffmpeg runner. Returns the segment's path.
+ */
+export async function buildPostSegment(entry, { render, outDir, manifestDir, box, place = [], encode = [], exec, ffmpeg = "ffmpeg", emit = () => {} }) {
+ const seg = path.join(outDir, "segments", `${entry.id}.mp4`);
+ const plan = postItemPlan(entry);
+ const layout = postLayout(entry, box);
+ const files = (entry.media ?? []).map((m) => path.resolve(manifestDir, m.src));
+ for (const [i, f] of files.entries()) {
+ if (!(await stat(f).catch(() => null))) throw new Error(`${entry.id}: media[${i}] is not on disk: ${f} (src: ${entry.media[i].src})`);
+ }
+ const wordFiles = (entry.media ?? []).map((m) => (typeof m.words === "string" ? path.resolve(manifestDir, m.words) : null));
+ const stamps = await Promise.all([...files, ...wordFiles.filter(Boolean), ...(entry.parentShot ? [path.resolve(manifestDir, entry.parentShot)] : [])].map(async (f) => {
+ const st = await stat(f).catch(() => null);
+ return st ? `${f}:${st.size}:${Math.round(st.mtimeMs)}` : `${f}:-`;
+ }));
+ const key = createHash("sha256")
+ .update(JSON.stringify({ v: 1, entry, box, place, palette: render.palette, fonts: [render.fontRegular, render.fontBold], fps: render.fps, encode, stamps }))
+ .digest("hex");
+ const record = postRecordPath(seg);
+ const had = await readFile(record, "utf8").then((t) => JSON.parse(t), () => null);
+ if (had?.key === key && (await stat(seg).catch(() => null))) {
+ emit("note", { message: `${entry.id}: post item unchanged — its segment kept` });
+ return seg;
+ }
+ const cardDir = path.join(outDir, "cards", `post-${entry.id}`);
+ const cards = await renderPostCards(entry, { box, render, dir: cardDir, manifestDir, layout });
+ // Its video attachments' words, when transcribed: one textfile per cue.
+ const captions = [];
+ for (const [si, step] of plan.steps.entries()) {
+ if (step.kind !== "video") continue;
+ const m = step.items[0];
+ const wf = wordFiles[m.i];
+ if (!wf) continue;
+ for (const [ci, c] of stepCaptions(step, await readMediaCues(wf)).entries()) {
+ const textfile = path.join(cardDir, `cue-${si}-${ci}.txt`);
+ await writeFile(textfile, c.text, "utf8");
+ captions.push({ ...c, textfile });
+ }
+ }
+ const tmp = seg.replace(/\.mp4$/, ".post-tmp.mp4");
+ const argv = postSegmentArgs({ entry, box, plan, layout, cards, files, render, place, encode, captions, fontfile: render.fontBold ?? render.fontRegular ?? null, outPath: tmp });
+ try {
+ await exec(ffmpeg, argv, { maxBuffer: 1 << 24 });
+ } catch (err) {
+ const detail = String(err?.stderr ?? "").trim() || err?.message || String(err);
+ throw new Error(`${entry.id}: ffmpeg failed on the post item\n${detail}`);
+ }
+ await rename(tmp, seg);
+ await writeFile(record, JSON.stringify({ version: 1, id: entry.id, key, layout: layout.mode, total: plan.total, steps: plan.steps.length }, null, 2) + "\n", "utf8");
+ emit("note", { message: `${entry.id}: post item ${plan.total.toFixed(1)} s (${layout.mode}: ${plan.reading.toFixed(1)} s to read${plan.steps.length ? `, ${plan.steps.length} attachment step(s)` : ""})` });
+ return seg;
+}
diff --git a/umtool/report-to-video/post-render.test.mjs b/umtool/report-to-video/post-render.test.mjs
@@ -0,0 +1,62 @@
+// post-render.mjs: a post item's encode, read as argv (no encoder runs here).
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { postItemPlan, postLayout } from "./post-item.mjs";
+import { postSegmentArgs, stepCaptions } from "./post-render.mjs";
+
+const render = { fps: 30, audioRate: 48000 };
+const box = { width: 1440, height: 810 };
+const entry = (o = {}) => ({
+ type: "post", id: "p1", post: "c-x/1", platform: "x", author: "A", handle: "a", date: "2026-10-30T04:00:00Z", text: "six words of a short post",
+ media: [
+ { src: "m/v.mp4", kind: "video", seconds: 6, width: 1920, height: 1080, audio: true, start: 1, end: 4 },
+ { src: "m/i.jpg", kind: "image", width: 1000, height: 1000 },
+ ],
+ ...o,
+});
+const argsOf = (e) => {
+ const plan = postItemPlan(e);
+ const layout = postLayout(e, box);
+ const argv = postSegmentArgs({
+ entry: e, box, plan, layout, cards: { read: "/c/read.png", media: "/c/media.png" }, files: ["/m/v.mp4", "/m/i.jpg"], render,
+ place: ["pad=1920:1080:240:10:color=#000", "setsar=1", "fps=30"], encode: ["-c:v", "libx264"], outPath: "/o/p1.mp4",
+ });
+ return { plan, layout, argv, graph: argv[argv.indexOf("-filter_complex") + 1] };
+};
+
+test("the render plan: the card, the video from its trim with its sound delayed to its step, the image after it, the deck's framing", () => {
+ const { plan, argv, graph } = argsOf(entry());
+ assert.equal(plan.total, 3 + 3 + 3.5);
+ // The card for the whole item, the video's trimmed span, the image held to the end, silence under all.
+ assert.deepEqual(argv.slice(argv.indexOf("-i") - 6, argv.indexOf("-i") + 2), ["-loop", "1", "-framerate", "30", "-t", "9.5", "-i", "/c/read.png"]);
+ const v = argv.indexOf("/m/v.mp4");
+ assert.deepEqual(argv.slice(v - 5, v + 1), ["-ss", "1", "-t", "3", "-i", "/m/v.mp4"]);
+ assert.ok(argv.includes("/m/i.jpg"));
+ // Beside the card, the video's first frame is up while the words are read; it plays at 3 s.
+ assert.match(graph, /tpad=start_duration=3:start_mode=clone/);
+ assert.match(graph, /overlay=x=\d+:y=\d+:enable='between\(t,0,6\)'/);
+ assert.match(graph, /overlay=x=\d+:y=\d+:enable='between\(t,6,9.5\)'/);
+ // Its sound from the step's start, mixed over the silence.
+ assert.match(graph, /adelay=3000\|3000\[a0\]/);
+ assert.match(graph, /amix=inputs=2:normalize=0:duration=first\[a\]/);
+ assert.match(graph, /pad=1920:1080:240:10:color=#000,setsar=1,fps=30\[v\];/);
+ assert.deepEqual(argv.slice(-3), ["-t", "9.5", "/o/p1.mp4"]);
+});
+
+test("a muted video plays silent; a text-only post is the card alone; a stack lays the media page over the card when the media starts", () => {
+ const muted = argsOf(entry({ media: [{ src: "m/v.mp4", kind: "video", seconds: 6, width: 1920, height: 1080, mute: true }] }));
+ assert.match(muted.graph, /\[\d+:a\]anull\[a\]/);
+ const text = argsOf(entry({ media: undefined }));
+ assert.equal(text.argv.filter((a) => a === "-i").length, 2); // the card and the silence
+ const long = Array.from({ length: 480 }, () => "word").join(" ");
+ const stack = argsOf(entry({ text: long }));
+ assert.equal(stack.layout.mode, "stack");
+ assert.ok(stack.argv.includes("/c/media.png"));
+ assert.match(stack.graph, new RegExp(`\\[mc\\]overlay=x=0:y=0:enable='between\\(t,${stack.plan.reading},`));
+});
+
+test("a video attachment's transcript, on the item's clock", () => {
+ const plan = postItemPlan(entry());
+ const caps = stepCaptions(plan.steps[0], [{ start: 0, end: 1.5, text: "before" }, { start: 1.5, end: 2.5, text: "said" }, { start: 5, end: 6, text: "after" }]);
+ assert.deepEqual(caps.map((c) => [c.text, c.from, c.to]), [["before", 3, 3.5], ["said", 3.5, 4.5]]);
+});