commit 4b1d6b76a69dda159842e39ee8920a881d2aab26
parent 41679eb22f28fdd1ef2bf61206e509f9bdcb4940
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 18:18:35 -0500
umtool: posts reel -- build or extend a cut from a posts archive, one undoable write; new --from-posts; timeline insert post:<channel>/<id>; posts set-item
lib/report/postReel.mjs: `umtool posts reel <p> --channel <slug> [--channel …] [--since]
[--until] [--own] [--with-media] [--replies include|only|exclude] [--order chrono|reverse]
[--limit N] [--after <id|->] [--dry-run]` reads one or more channels' archives as one
(merged in time order, de-duplicated by post id), selects, skips every post the cut
already plays (by its id, a repost's original, a repost of it) -- so a re-run adds only
what is new -- and puts each in as a post item in ONE write (insertEntries, one undo
point). Each entry snapshots the archive row (words, author, date, link, counts); a
repost is drawn as its original, "reposted by"; a reply carries the posts it answers
from the archive (nearest first, up to 2), else the capture's shot-thread.png, else a
"replying to" line; the accounts reeled are its `subjects` (every other author is
blurred by the privacy rule); its attachments are copied into the project's
posts-media/ and measured (ffprobe: pixels, length, sound; X's tweet_video/ mp4 is a GIF).
`umtool new <p> --from-posts <slug> [filters]` scaffolds a posts reel (the deck on; with no
siteOrigin each QR opens the post). `umtool timeline <p> insert … post:<channel>/<postId>`
puts one post item in, beside clips, after an entry, into a section or a group. `umtool
posts set-item <p> <item> hold=… layout=grid redact=… media.<i>.start|end|mute|crop|push=…`
is the post bench's writer (updatePostItem). `timeline ls` names a post item's post,
length and attachments.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
7 files changed, 809 insertions(+), 15 deletions(-)
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/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/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,141 @@
+// 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"]);
+});
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/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/post-item.mjs b/umtool/report-to-video/post-item.mjs
@@ -239,8 +239,13 @@ export function authorRedaction(who, { subjects = [], redact = undefined } = {})
return { redact: true, reason: "private" };
}
-/** The subjects of an item: its own author and the account that reposted it. */
-export const subjectsOf = (entry) => [str(entry?.handle), str(entry?.repostedBy?.handle)].filter(Boolean);
+/**
+ * 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:
@@ -252,6 +257,8 @@ 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) });
@@ -328,6 +335,10 @@ export function validatePostItem(e) {
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)`);
}
@@ -537,7 +548,8 @@ 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 who = [str(entry?.author), entry?.handle ? `@${String(entry.handle).replace(/^@/, "")}` : ""].filter(Boolean).join(" ");
+ 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)),
@@ -598,6 +610,7 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p
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]]
@@ -625,10 +638,10 @@ export function postCardHtml(entry, { width, height, palette = {}, fonts = {}, p
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">${avatarHtml(own, { redact: false, size: Math.round(64 * k), accent: pal.accent })}<div class="hwho">${nameHtml(own, { redact: false, cls: "big" })}<div class="date">${esc(cardDate(entry.date))}</div></div><div class="mark">${esc(PLATFORM_NAME[entry.platform] ?? "")}</div></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>`;
const card = (box) => `<div class="card" data-post-card="${esc(entry.id)}" style="left:${box.x}px;top:${box.y}px;width:${box.width}px;height:${box.height}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: false, size: Math.round(56 * k), accent: pal.accent })}<div class="hwho">${nameHtml(own, { redact: false, 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>`
+ ? `<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}`;