commit d030ae48b0c3c40f832d5063e36420b6c57fe49c
parent 3deb510156fc2af3334287b2c1e91b11ef93ec5f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 25 Oct 2026 22:17:02 -0400
umtool timeline / scenes / posts add: the cut's structure, a clip's scene cuts and black spans, and a post card from the archive, from the command line
`umtool timeline <project>` lists the cut and runs the Cut tab's structural
ops (insert, move, remove, duplicate, post, post-remove, teaser, undo)
through the writers POST /api/report/timeline uses, with the token read just
before each write and the generated-manifest guard around it; an insert's
attribution goes through updateClip as `umtool window` does, its date checked
before the insert. `umtool scenes <project> <clip>` runs ffmpeg scdet +
blackdetect over the window the build would cut the clip from and prints
source seconds. `umtool posts add <project> <channel>/<postId>` builds the
post entry from the posts archive, copies its capture into posts-media/
(never through a link out of the project), and upserts it.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
11 files changed, 1343 insertions(+), 0 deletions(-)
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **An assistant can now change a report video's timeline, find a clip's scene cuts, and add a post from the archive, all from the command line.** `umtool timeline <project>` lists the cut (index, id, type, video, start–end, date and title) and does what the Cut tab's timeline does: `insert --after <id> <channel>/<video>@<start>-<end>` with `--title`, `--date`, `--quote` and `--cite`, `move <id> --to <index>`, `remove`, `duplicate`, `post`, `post-remove`, `teaser` and `undo`. It goes through the same writers as the page, so each change saves an undo point first, is refused when the build would refuse it, and leaves an edit note on a generated manifest. A bad `--date` is refused before anything is written. `umtool scenes <project> <clip>` prints where the picture cuts and where it goes black in the clip's fetched window, in the recording's own seconds, for setting a blur's from and to or a trim: the Huck dog clip is black 250.49–251.09 and cuts at 251.09. It fetches nothing. `umtool posts add <project> <channel>/<postId>` makes a post card from the posts archive (its words, date, link, handle and screenshot, with `--attach <clip>` and `--flag`) and copies the capture into the project's `posts-media/`. A post with no screenshot is refused, and the message names the `pnpm ops capture-posts` to run first.
- **A tall post screenshot in the posts feed grows into the room the column has, instead of shrinking to a thumbnail.** A screenshot was capped at the height of a card of words and drawn smaller to fit it, so a post with a picture (the Huck video's "Hucks home!!!!!! God Is Good!!!") came out a narrow strip beside empty space. Now a picture cut by that cap grows, up to its own full-width height, into the room left in the column beside the card under it — that card stays on screen; only cards further down scroll out as before. A post that fits, and a card of words, are drawn as they were. Needs a restart of umtool and a rebuild of the video.
- **Every wait before the archive asks a site now varies a little, and only ever upward.** A job every 20.0 s, a page every 3.0 s or a sync at the same minute each day is a machine's beat, so each such wait is now stretched by up to a quarter of itself at random, and never shortened: every pacing number stays a minimum (Rumble's 120 s, X's 5 min, the sleep between downloads). It covers the gap between two downloads and between two jobs on one platform, yt-dlp's `--sleep-requests` and `--sleep-subtitles` (drawn once per yt-dlp run, and shown in its logged command line), the archive.org, Wayback and web-fetch gaps, the rate-limit cooldowns and the platform hold's probe, the download lane's metadata-scan batches (60 to 75 titles) and its rests, Save Page Now's and the Kick recorder's polls, and each channel's sync interval (later by at most 30 minutes, the same on every tick until it syncs, and shown so on /operations/sync). The share is **Jitter on every wait before a request** on /settings (`pacing.jitter`, default 25 %; 0 turns it off). Three waits that already varied could come out SHORTER than their minimum and no longer do: the platform cooldown (±10 %), archive.org's back-off (±20 %) and a forum's page pause (as little as 0.85 of it, under its own 5 s floor). It now lands between the pause and 1.8 times it. Four loops that asked a site with no gap at all now wait between requests: a Bluesky feed's pages (3–6 s), a Nitter timeline's pages (4 s and up), the availability check's per-video probes (3 s and up) and umtool's network clip fetches in a build with no editor (one at a time per platform, 30 s apart, Rumble 120 s). Needs a restart of the editor and of umtool.
- **The download lane's metadata scan reads 60 titles at a time and lets the downloads run in between.** A filtered channel's scan holds its platform's download queue while it runs, and the lane used to scan the whole backlog in one go: on 2026-10-25 the scan of h3-podcast's 1,163 unread titles, which started the moment the channel's download pause was lifted, held YouTube from 03:20 to 06:36 and nothing downloaded. The lane now scans 60 titles (about 10 minutes on YouTube), gives that platform 20 minutes of downloads, then scans the next 60, and its log says so: "1103 listed videos left to scan for h3-podcast; the next batch after 20 minutes of downloads." A scan that a platform stopped (a soft block, a rate limit) is still not retried until the next restart. **Run** on the metadata-scan operation still scans the whole backlog. Needs a restart of the editor.
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -68,6 +68,11 @@
// a speaker-similarity score per montage clip -> <project>/voice-match.json
// umtool clips analyze|propose|show <project> [--from <channel>/<id>] [--target S] [--host N] …
// the clip finder (release 35): proposed clips from a long recording -> reactions.json
+// umtool timeline <project> [ls | insert --after <id|-> <channel>/<video>@<start>-<end> [--id ID] [--title …]
+// [--date …] [--quote …] [--cite S] | move <id> --to <index> | remove <id> | duplicate <id> |
+// post <json|@file> | post-remove <id> | teaser <id> <patch-json> | undo] the cut's structure
+// 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 …] a post from the archive
import process from "node:process";
import {
PROJECT_KINDS,
@@ -782,6 +787,19 @@ function usage() {
" re-fetch an article's scope, see what changed, update: the plan (the editor's);",
" --yes starts it, one editor job (needs WORKER_TOKEN and the editor)",
" umtool refresh --check [<article>] [--force] [--json] the daily suggestion check, now",
+ " umtool timeline <project> [ls] [--json] the cut: index, id, type, video, start–end, date title",
+ " umtool timeline <project> insert --after <id|-> <channel>/<video>@<start>-<end> [--id ID] [--title T]",
+ " [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U] a clip, then its attribution",
+ " umtool timeline <project> move <id> --to <index> | remove <id> | duplicate <id> [--at <index>]",
+ " umtool timeline <project> post <json|@file> | post-remove <id> | teaser <id> <patch-json|@file> | undo",
+ " the Cut tab's structure (POST /api/report/timeline's writers): each write snapshots the",
+ " manifest first (revisions/…-auto-before-<op>), is checked by the build, notes a generated cut",
+ " umtool scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 | --from S --to S] [--json]",
+ " scene cuts (scdet) and black spans (blackdetect) in the clip's fetched window, in SOURCE",
+ " seconds — for blur.from/blur.to and trims; nothing fetched (`umtool fetch` first)",
+ " umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--json]",
+ " a post entry from the corpus's posts archive, its screenshot copied into posts-media/;",
+ " refused when the post has no shot (`pnpm ops capture-posts` first)",
"",
`reading ${REPORTS_ROOT} (set REPORTS_DIR to move it)`,
"",
@@ -829,6 +847,11 @@ const COMMANDS = {
"voice-match": async () => process.exit(await (await import("../lib/report/voiceMatch.mjs")).voiceMatchCommand(argv.slice(argv.indexOf("voice-match") + 1))),
// The clip finder (release 35 C1): lib/report/reactions.mjs.
clips: async () => process.exit(await (await import("../lib/report/reactions.mjs")).clipsCommand(argv.slice(argv.indexOf("clips") + 1))),
+ // The cut's structure, scene cuts, posts from the archive (2026-10-25): lib/report/timelineCli.mjs,
+ // scenesCli.mjs, postsCli.mjs.
+ timeline: async () => process.exit(await (await import("../lib/report/timelineCli.mjs")).timelineCommand(argv.slice(argv.indexOf("timeline") + 1))),
+ scenes: async () => process.exit(await (await import("../lib/report/scenesCli.mjs")).scenesCommand(argv.slice(argv.indexOf("scenes") + 1))),
+ posts: async () => process.exit(await (await import("../lib/report/postsCli.mjs")).postsCommand(argv.slice(argv.indexOf("posts") + 1))),
inbox: cmdInbox,
schedule: () => tsxScript("schedule"),
refresh: () => tsxScript("refresh"),
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -52,6 +52,9 @@ Inbox cannot disagree about what is wrong with one.
| `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase |
| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) |
| `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) |
+| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `remove <id>` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written. Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) |
+| `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 add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--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 |
A project argument is an exact id, a directory, or a **unique** basename. Two
projects answering to one name is reported, never resolved by picking one.
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -57,6 +57,10 @@ sound plays as recorded.
downscale of the blurred master). The thumbnail's still, taken from a blurred second, is blurred too.
- **Only part of a clip:** `from` / `to` (source seconds, inside the window; a window save that would leave them
outside is refused) — the blur and the caption over that span only.
+- **Where to put them:** `umtool scenes <p> <clip>` prints the picture's scene cuts and black spans in the clip's
+ fetched window, in source seconds (ffmpeg `scdet` + `blackdetect`, the window the build would cut from). A blur
+ that should end where the footage does ends at the cut out of the black: eps-footage's window is black
+ 250.49–251.09 and cuts at 251.09.
- **Refused:** an unknown key, `on` other than `true`, a caption over 120 characters or empty, a strength outside
2–15, a span under 0.2 s or outside the window, a `blur` on anything but a clip, and a `blur` under
`render.montage` (a montage re-cuts its pictures).
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -1569,6 +1569,11 @@ the manifest first (`revisions/<stamp>-auto-before-<op>.manifest.json`, at most
one per op every two minutes). **Undo** restores the newest such snapshot byte for
byte (the current state is kept as `undo-saved`).
+From a terminal, `umtool timeline <p>` is the same: `ls`, `insert --after <id|-> <channel>/<video>@<start>-<end>`
+(with `--title`, `--date`, `--quote`, `--cite` written through the window writer), `move <id> --to <index>`,
+`remove`, `duplicate`, `post`, `post-remove`, `teaser`, `undo` — each reading the token just before its write
+([cli.md](cli.md)). `umtool posts add <p> <channel>/<postId>` makes the post from the archive and its capture.
+
A move recomputes `sectionEnter` — a clip enters when its `section` differs from
the previous clip's, the first clip included (`lib/report/sections.mjs`) — and only
in a manifest that already carries the flag; `section` itself never changes.
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -0,0 +1,289 @@
+// `umtool posts add` (2026-10-25): a post card for a report video, made from
+// the corpus's posts archive rather than typed -- the post's own words, date,
+// link and handle as the archive holds them, and its screenshot.
+//
+// umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F]
+// [--author A] [--id ID] [--dry-run] [--json]
+//
+// The row is `channels/<slug>/posts/YYYY-MM.jsonl`'s (common/lib/posts-server.ts
+// owns that layout; an X id names its month, so its shard is read first). The
+// screenshot is the capture's `channels/<slug>/posts-media/<postId>/shot.png`
+// (common/social/postCapture.ts), COPIED into the project as
+// `posts-media/<slug>/<postId>/shot.png` with its capture.json and the post's
+// pictures (copyCapture) -- a post's `shot` is relative to the
+// manifest and inside its folder (deck.mjs shotError), as every post the
+// Huck cut carries is. A post with no shot is refused, naming the capture to
+// run: a card drawn from text alone is a different card, and it should be a
+// choice, not what happens when nobody captured it.
+//
+// The entry goes in through upsertPost -- the writer POST /api/report/timeline
+// `{op: "post"}` runs -- with the token read just before it and the
+// generated-manifest guard around it: a post with that id already there is
+// replaced (its attachTo kept unless --attach says otherwise).
+//
+// Plain ESM: the CLI runs under bare node.
+import { copyFile, mkdir, readFile, readdir, realpath, stat } from "node:fs/promises";
+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 { StaleToken, StructureRefused, manifestToken, upsertPost } from "./manifest.mjs";
+
+export const POSTS_USAGE = [
+ "usage: umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID]",
+ " [--dry-run] [--json]",
+ " a post card from the corpus's posts archive (channels/<slug>/posts/*.jsonl): its words, date, link and handle,",
+ " and its screenshot (channels/<slug>/posts-media/<postId>/shot.png) copied into the project's posts-media/.",
+ " The id is x-<postId> (bsky-, post-) unless --id; --attach pins it to a clip; --author overrides the name",
+ " (default: the name an earlier post by the same handle carries in this cut, else the archive's).",
+ " A post with no screenshot is refused: `pnpm ops capture-posts --json '{\"slug\":…,\"ids\":[…]}'` first.",
+].join("\n");
+
+const VALUED = new Set(["--attach", "--flag", "--author", "--id"]);
+const SLUG_RE = /^[A-Za-z0-9._-]+$/;
+const POST_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+
+class CliError extends Error {}
+
+/** The month an X (snowflake) id was minted in, `YYYY-MM`, or null for any other id. */
+export function snowflakeMonth(id) {
+ if (!/^\d{15,20}$/.test(String(id))) return null;
+ const ms = Number((BigInt(id) >> 22n) + 1288834974657n);
+ const d = new Date(ms);
+ if (Number.isNaN(d.getTime()) || d.getUTCFullYear() < 2010) return null;
+ return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}`;
+}
+
+/**
+ * The archive's row for `postId` in channel `slug`, or null. The shard its id
+ * names first (X), then every shard newest first; within a shard the LAST
+ * line with the id wins (a re-fetch appends).
+ */
+export async function findPostRow(channelsDir, slug, postId) {
+ const dir = path.join(channelsDir, slug, "posts");
+ const names = (await readdir(dir).catch(() => [])).filter((n) => /^\d{4}-\d{2}\.jsonl$/.test(n)).sort().reverse();
+ const first = snowflakeMonth(postId);
+ const order = first && names.includes(`${first}.jsonl`) ? [`${first}.jsonl`, ...names.filter((n) => n !== `${first}.jsonl`)] : names;
+ const needle = `"id":"${postId}"`;
+ for (const name of order) {
+ const text = await readFile(path.join(dir, name), "utf8").catch(() => "");
+ if (!text.includes(needle)) continue;
+ let hit = null;
+ for (const line of text.split("\n")) {
+ if (!line.includes(needle)) continue;
+ try {
+ const row = JSON.parse(line);
+ if (String(row?.id) === postId) hit = row;
+ } catch {
+ // a torn line is not the post
+ }
+ }
+ if (hit) return { row: hit, shard: name };
+ }
+ return { row: null, shard: null, shards: names.length };
+}
+
+/** The deck's platform for an archive row's (deck.mjs POST_PLATFORMS). */
+export const deckPlatformOf = (p) => {
+ const v = String(p ?? "").toLowerCase();
+ return v === "twitter" || v === "x" ? "x" : v === "bluesky" ? "bluesky" : "web";
+};
+
+const ID_PREFIX = { x: "x", bluesky: "bsky", web: "post" };
+
+/** Where the project keeps a post's screenshot, relative to its manifest. */
+export const projectShotRel = (slug, postId) => `posts-media/${slug}/${postId}/shot.png`;
+
+/**
+ * The manifest's post entry for an archive row. `manifest` lends the author
+ * name an earlier post by the same handle carries (the Huck cut's posts say
+ * "Jeremy Hambly", the archive "TheQuartering").
+ */
+export function postEntryOf(row, { slug, postId, manifest = null, attach = null, flag = null, author = null, id = null }) {
+ const platform = deckPlatformOf(row.platform);
+ const handle = typeof row.author === "string" && row.author ? row.author.replace(/^@/, "") : null;
+ const earlier = (Array.isArray(manifest?.posts) ? manifest.posts : []).find(
+ (p) => p?.platform === platform && handle && String(p.handle ?? "").toLowerCase() === handle.toLowerCase() && typeof p.author === "string" && p.author,
+ );
+ const date =
+ typeof row.createdAt === "string" && row.createdAt
+ ? row.createdAt
+ : /^\d{8}$/.test(String(row.uploadDate ?? ""))
+ ? `${row.uploadDate.slice(0, 4)}-${row.uploadDate.slice(4, 6)}-${row.uploadDate.slice(6, 8)}`
+ : null;
+ return {
+ id: id ?? `${ID_PREFIX[platform]}-${postId}`,
+ platform,
+ author: author ?? earlier?.author ?? row.authorName ?? handle ?? undefined,
+ handle: handle ?? undefined,
+ date,
+ url: row.url,
+ ...(attach ? { attachTo: attach } : {}),
+ text: typeof row.text === "string" ? row.text : "",
+ shot: projectShotRel(slug, postId),
+ ...(flag ? { flag } : {}),
+ };
+}
+
+/** What of a capture's directory is copied beside the manifest: the shot, its record, the post's pictures. */
+export const CAPTURE_COPY_RE = /^(?:shot\.png|capture\.json|.+\.(?:png|jpe?g|webp|gif))$/i;
+
+/**
+ * Copy a capture's files into the project, as the posts the Huck cut carries
+ * were (`shot.png`, `capture.json` -- the shot's sha256 and when it was taken
+ * -- and the post's own pictures; not its videos). A file already there with
+ * the same bytes is left. Returns the names copied.
+ */
+export async function copyCapture(fromDir, toDir) {
+ const names = (await readdir(fromDir, { withFileTypes: true }).catch(() => []))
+ .filter((d) => d.isFile() && CAPTURE_COPY_RE.test(d.name))
+ .map((d) => d.name)
+ .sort();
+ const copied = [];
+ for (const name of names) {
+ const a = path.join(fromDir, name);
+ const b = path.join(toDir, name);
+ if (await sameFile(a, b)) continue;
+ await mkdir(toDir, { recursive: true });
+ await copyFile(a, b);
+ copied.push(name);
+ }
+ return copied;
+}
+
+/**
+ * Where a copy into `toDir` would land: "project" (inside the project's own
+ * folder), "linked" (through a link into the channel's posts-media -- the
+ * capture is already what the shot path reads), or "elsewhere". Judged by
+ * the real path of `toDir`'s deepest existing ancestor.
+ */
+export async function shotHome(projectDir, toDir, capturesDir) {
+ let probe = toDir;
+ let real = null;
+ for (;;) {
+ real = await realpath(probe).catch(() => null);
+ if (real || probe === path.dirname(probe)) break;
+ probe = path.dirname(probe);
+ }
+ const under = (a, b) => a === b || a.startsWith(b + path.sep);
+ const [proj, caps] = await Promise.all([realpath(projectDir).catch(() => projectDir), realpath(capturesDir).catch(() => null)]);
+ if (real && caps && under(real, caps)) return "linked";
+ if (real && under(real, proj)) return "project";
+ return "elsewhere";
+}
+
+const sameFile = async (a, b) => {
+ const [x, y] = await Promise.all([stat(a).catch(() => null), stat(b).catch(() => null)]);
+ if (!x || !y || x.size !== y.size) return false;
+ const [p, q] = await Promise.all([readFile(a), readFile(b)]);
+ return p.equals(q);
+};
+
+/**
+ * @param {string[]} args the words after `posts`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
+ * @returns {Promise<number>} the exit code
+ */
+export async function postsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ const words = [];
+ const flags = new Map();
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (VALUED.has(a)) {
+ flags.set(a, args[i + 1] ?? "");
+ i += 1;
+ } else if (a.startsWith("--")) flags.set(a, true);
+ else words.push(a);
+ }
+ const json = flags.has("--json");
+ const dryRun = flags.has("--dry-run");
+ const str = (name) => {
+ if (!flags.has(name)) return null;
+ const v = flags.get(name);
+ if (v === true || v === "") throw new CliError(`${name} needs a value`);
+ return String(v);
+ };
+ try {
+ const [verb, projectArg, ref] = words;
+ if (verb !== "add" || !projectArg || !ref || flags.has("--help")) {
+ err(POSTS_USAGE);
+ return 2;
+ }
+ const slash = ref.indexOf("/");
+ const slug = slash > 0 ? ref.slice(0, slash) : "";
+ const postId = slash > 0 ? ref.slice(slash + 1) : "";
+ if (!SLUG_RE.test(slug) || !POST_ID_RE.test(postId)) throw new CliError(`not <archive-channel>/<postId>: ${ref}`);
+ const r = await resolveProject(projectArg, root);
+ if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${projectArg}"`);
+ const project = r.project;
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ // The corpus the project reads (provenance.channelsDir), else the global one.
+ const channelsDir = channelsDirFor(project.dir, manifest);
+ const found = await findPostRow(channelsDir, slug, postId);
+ if (!found.row) {
+ throw new Error(
+ found.shards
+ ? `${slug} has no post ${postId} in its archive (${found.shards} shard(s) read under ${path.join(channelsDir, slug, "posts")})`
+ : `${slug} has no posts archive under ${channelsDir} — is it a social channel?`,
+ );
+ }
+ const shotFrom = path.join(channelsDir, slug, "posts-media", postId, "shot.png");
+ if (!(await stat(shotFrom).catch(() => null))) {
+ throw new Error(
+ `${slug}/${postId} has no screenshot (${shotFrom}) — capture it first:\n` +
+ ` pnpm ops capture-posts --json '${JSON.stringify({ slug, ids: [postId] })}'`,
+ );
+ }
+ const attach = str("--attach");
+ if (attach && !(manifest.timeline ?? []).some((e) => e?.type === "clip" && e.id === attach)) {
+ throw new CliError(`--attach ${attach}: no clip with that id in ${project.id}`);
+ }
+ const post = postEntryOf(found.row, { slug, postId, manifest, attach, flag: str("--flag"), author: str("--author"), id: str("--id") });
+ const shotTo = path.join(project.dir, ...post.shot.split("/"));
+ if (dryRun) {
+ out(json ? JSON.stringify({ ok: true, dryRun: true, post, shard: found.shard, shotFrom, shotTo }, null, 2) : `would add ${post.id} (${found.shard}):\n${JSON.stringify(post, null, 2)}\n shot ${shotFrom} -> ${shotTo}`);
+ return 0;
+ }
+ // The pictures first: a post whose `shot` names a file not there would build a broken card.
+ // Never THROUGH a link out of the project: a cut whose posts-media/<slug> links the
+ // channel's own captures (the Huck cut's do) already has them, and a link anywhere
+ // else would make this copy a write into somebody else's tree.
+ const where = await shotHome(project.dir, path.dirname(shotTo), path.dirname(path.dirname(shotFrom)));
+ if (where === "elsewhere") {
+ throw new Error(`${path.relative(project.dir, path.dirname(shotTo))} leads out of ${project.id} (a link) — not copying through it`);
+ }
+ const copied = where === "linked" ? [] : await copyCapture(path.dirname(shotFrom), path.dirname(shotTo));
+ const { result, editNotes } = await withEditNotes(project, async () =>
+ upsertPost(project.dir, post, { token: await manifestToken(project.dir) }),
+ );
+ if (json) {
+ out(JSON.stringify({ ok: true, ...result, shard: found.shard, shot: { from: shotFrom, to: shotTo, via: where }, copied, editNotes }, null, 2));
+ return 0;
+ }
+ out(`${result.created ? "added" : "replaced"} post ${result.post.id}${result.post.attachTo ? ` -> ${result.post.attachTo}` : ""} ${result.post.date}`);
+ out(` ${result.post.author ?? ""}${result.post.handle ? ` @${result.post.handle}` : ""}: ${result.post.text.split("\n")[0].slice(0, 100)}`);
+ out(` shot ${result.post.shot}${where === "linked" ? " (posts-media links the channel's captures)" : copied.length ? ` (copied: ${copied.join(", ")})` : " (already there)"}`);
+ if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel}`);
+ if (editNotes) {
+ out(
+ editNotes.errors.length
+ ? ` edit NOT noted (${editNotes.errors.join("; ")}) — ${editNotes.generatedBy} will overwrite it on the next rebuild`
+ : ` edit noted for ${editNotes.generatedBy} — port it into the generator's inputs`,
+ );
+ }
+ return 0;
+ } catch (e) {
+ if (e instanceof StructureRefused) {
+ err(`umtool posts: refused — the build would not take it:\n${e.errors.map((x) => ` ${x}`).join("\n")}`);
+ return 1;
+ }
+ if (e instanceof StaleToken) {
+ err(`umtool posts: ${e.message} — somebody else wrote it; run it again`);
+ return 1;
+ }
+ err(`umtool posts: ${e instanceof Error ? e.message : String(e)}`);
+ return e instanceof CliError ? 2 : 1;
+ }
+}
diff --git a/umtool/lib/report/postsCli.test.mjs b/umtool/lib/report/postsCli.test.mjs
@@ -0,0 +1,168 @@
+// `umtool posts add` (2026-10-25): a post card from the corpus's posts archive,
+// its screenshot copied beside the manifest, in through upsertPost.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, stat, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-posts-cli-"));
+const REPORTS = path.join(ROOT, "reports");
+const CHANNELS = path.join(ROOT, "channels");
+process.env.REPORTS_DIR = REPORTS;
+const { deckPlatformOf, findPostRow, postEntryOf, postsCommand, shotHome, snowflakeMonth } = await import("./postsCli.mjs");
+
+// 2110480074398969914 was posted 2026-10-14 (its snowflake says so).
+const XID = "2110480074398969914";
+const ROW = {
+ id: XID,
+ channelSlug: "acct-X",
+ author: "Acct",
+ authorName: "Acct",
+ createdAt: "2026-10-14T21:17:15.000Z",
+ uploadDate: "20261014",
+ text: "Adjusted his meds",
+ url: `https://x.com/Acct/status/${XID}`,
+ platform: "twitter",
+};
+
+async function setup() {
+ const posts = path.join(CHANNELS, "acct-X", "posts");
+ await mkdir(posts, { recursive: true });
+ // An older copy of the row in the same shard: the last line wins.
+ await writeFile(path.join(posts, "2026-10.jsonl"), [JSON.stringify({ ...ROW, text: "old" }), "{torn", JSON.stringify(ROW), ""].join("\n"));
+ await writeFile(path.join(posts, "2026-09.jsonl"), JSON.stringify({ ...ROW, id: "2100000000000000000", text: "no shot" }) + "\n");
+ const media = path.join(CHANNELS, "acct-X", "posts-media", XID);
+ await mkdir(media, { recursive: true });
+ await writeFile(path.join(media, "shot.png"), "PNG");
+ await writeFile(path.join(media, "capture.json"), '{"version":1}');
+ await writeFile(path.join(media, `${XID}_1.jpg`), "JPG");
+ await writeFile(path.join(media, `${XID}_2.mp4`), "MP4");
+ const bsky = path.join(CHANNELS, "pirate-bsky");
+ await mkdir(path.join(bsky, "posts"), { recursive: true });
+ await writeFile(path.join(bsky, "posts", "2026-09.jsonl"), JSON.stringify({ id: "3mwrc2zzvdk2u", author: "pirate.live", authorName: "Pirate", createdAt: "2026-09-30T21:30:27.487Z", text: "update", url: "https://bsky.app/profile/pirate.live/post/3mwrc2zzvdk2u", platform: "bluesky" }) + "\n");
+ await mkdir(path.join(bsky, "posts-media", "3mwrc2zzvdk2u"), { recursive: true });
+ await writeFile(path.join(bsky, "posts-media", "3mwrc2zzvdk2u", "shot.png"), "PNG");
+}
+
+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,
+ provenance: { siteOrigin: "https://example.test", channelSlug: "chan", channelsDir: CHANNELS },
+ render: { width: 1920, height: 1080, fps: 30 },
+ timeline: [{ type: "clip", id: "c01", video: "v1", start: 10, end: 20 }],
+ posts: [{ id: "x-1", platform: "x", author: "Real Name", handle: "Acct", date: "2026-08-24", text: "earlier", url: "https://x.com/Acct/status/1" }],
+ }, null, 2) + "\n");
+ return dir;
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+const runner = () => {
+ const lines = [];
+ return { lines, run: (...args) => postsCommand(args, { root: REPORTS, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }) };
+};
+
+await setup();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+test("snowflakeMonth: an X id names its month; nothing else does", () => {
+ assert.equal(snowflakeMonth(XID), "2026-10");
+ assert.equal(snowflakeMonth("3mwrc2zzvdk2u"), null);
+ assert.equal(snowflakeMonth("12"), null);
+ assert.equal(deckPlatformOf("twitter"), "x");
+ assert.equal(deckPlatformOf("bluesky"), "bluesky");
+ assert.equal(deckPlatformOf("forum"), "web");
+});
+
+test("findPostRow: the last line with the id; a torn line is skipped; a missing post is null", async () => {
+ const hit = await findPostRow(CHANNELS, "acct-X", XID);
+ assert.equal(hit.shard, "2026-10.jsonl");
+ assert.equal(hit.row.text, "Adjusted his meds");
+ const miss = await findPostRow(CHANNELS, "acct-X", "999");
+ assert.equal(miss.row, null);
+ assert.equal(miss.shards, 2);
+});
+
+test("postEntryOf: the deck's shape; the author an earlier post by the handle carries", () => {
+ const e = postEntryOf(ROW, { slug: "acct-X", postId: XID, manifest: { posts: [{ platform: "x", handle: "acct", author: "Real Name" }] }, attach: "c01", flag: "Same day" });
+ assert.deepEqual(e, {
+ id: `x-${XID}`,
+ platform: "x",
+ author: "Real Name",
+ handle: "Acct",
+ date: "2026-10-14T21:17:15.000Z",
+ url: ROW.url,
+ attachTo: "c01",
+ text: "Adjusted his meds",
+ shot: `posts-media/acct-X/${XID}/shot.png`,
+ flag: "Same day",
+ });
+ assert.equal(postEntryOf(ROW, { slug: "acct-X", postId: XID }).author, "Acct");
+ assert.equal(postEntryOf(ROW, { slug: "acct-X", postId: XID, author: "Given" }).author, "Given");
+});
+
+test("posts add: the entry through upsertPost, the capture's pictures copied (not its video); replace keeps attachTo", async () => {
+ const dir = await project("add");
+ const { lines, run } = runner();
+ assert.equal(await run("add", "add", `acct-X/${XID}`, "--attach", "c01", "--flag", "Same day"), 0);
+ const m = await read(dir);
+ const p = m.posts.find((x) => x.id === `x-${XID}`);
+ assert.equal(p.author, "Real Name");
+ assert.equal(p.attachTo, "c01");
+ assert.equal(p.shot, `posts-media/acct-X/${XID}/shot.png`);
+ assert.deepEqual((await readdir(path.join(dir, "posts-media", "acct-X", XID))).sort(), [`${XID}_1.jpg`, "capture.json", "shot.png"]);
+ assert.ok((await readdir(path.join(dir, "revisions"))).some((n) => n.endsWith("-auto-before-post.manifest.json")));
+ // Again, no --attach: replaced, its clip kept; nothing to copy.
+ assert.equal(await run("add", "add", `acct-X/${XID}`, "--json"), 0);
+ const res = JSON.parse(lines.at(-1));
+ assert.equal(res.created, false);
+ assert.deepEqual(res.copied, []);
+ assert.equal(res.post.attachTo, "c01");
+ // A bluesky post: bsky-<rkey>.
+ assert.equal(await run("add", "add", "pirate-bsky/3mwrc2zzvdk2u"), 0);
+ assert.ok((await read(dir)).posts.some((x) => x.id === "bsky-3mwrc2zzvdk2u" && x.platform === "bluesky" && x.author === "Pirate"));
+});
+
+test("posts add refuses: no screenshot (naming the capture), no such post, no such clip, a bad ref", async () => {
+ const dir = await project("refuse");
+ const before = await read(dir);
+ const { lines, run } = runner();
+ assert.equal(await run("add", "refuse", "acct-X/2100000000000000000"), 1);
+ assert.match(lines.at(-1), /no screenshot/);
+ assert.match(lines.at(-1), /pnpm ops capture-posts --json '\{"slug":"acct-X","ids":\["2100000000000000000"\]\}'/);
+ assert.equal(await run("add", "refuse", "acct-X/42"), 1);
+ assert.match(lines.at(-1), /has no post 42/);
+ assert.equal(await run("add", "refuse", `acct-X/${XID}`, "--attach", "nope"), 2);
+ assert.match(lines.at(-1), /no clip with that id/);
+ assert.equal(await run("add", "refuse", "nonsense"), 2);
+ assert.equal(await run("add"), 2);
+ assert.deepEqual(await read(dir), before);
+ assert.equal(await stat(path.join(dir, "posts-media")).catch(() => null), null);
+});
+
+test("posts add never copies through a link out of the project: linked captures are used, anything else refused", async () => {
+ const dir = await project("linked");
+ await mkdir(path.join(dir, "posts-media"), { recursive: true });
+ await symlink(path.join(CHANNELS, "acct-X", "posts-media"), path.join(dir, "posts-media", "acct-X"));
+ const { lines, run } = runner();
+ assert.equal(await run("add", "linked", `acct-X/${XID}`, "--json"), 0);
+ const res = JSON.parse(lines.at(-1));
+ assert.equal(res.shot.via, "linked");
+ assert.deepEqual(res.copied, []);
+ // The channel's capture dir is untouched (nothing written through the link).
+ assert.deepEqual((await readdir(path.join(CHANNELS, "acct-X", "posts-media", XID))).sort(), [`${XID}_1.jpg`, `${XID}_2.mp4`, "capture.json", "shot.png"]);
+
+ const other = await project("elsewhere");
+ const away = path.join(ROOT, "away");
+ await mkdir(away, { recursive: true });
+ await mkdir(path.join(other, "posts-media"), { recursive: true });
+ await symlink(away, path.join(other, "posts-media", "acct-X"));
+ assert.equal(await run("add", "elsewhere", `acct-X/${XID}`), 1);
+ assert.match(lines.at(-1), /leads out of elsewhere/);
+ assert.deepEqual(await readdir(away), []);
+ assert.equal(await shotHome(other, path.join(other, "posts-media", "fresh", "1"), path.join(CHANNELS, "acct-X", "posts-media")), "project");
+});
diff --git a/umtool/lib/report/scenesCli.mjs b/umtool/lib/report/scenesCli.mjs
@@ -0,0 +1,238 @@
+// `umtool scenes` (2026-10-25): where the picture cuts and where it goes black,
+// in one clip's FETCHED window, in SOURCE seconds -- what an agent reads to
+// choose `blur.from`/`blur.to` and a trim without watching the clip. Found by
+// hand first: eps-footage (BZCS-Azx_iE, window 227.36–299.00) is black
+// 250.49–251.09 and cuts at 251.09, so its blur ends there.
+//
+// umtool scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10]
+// [--pad 30 | --from S --to S] [--json]
+//
+// THE FILE IS THE BUILD'S. The window is found the way the render finds it
+// (report-to-video/sources.mjs resolveLocalSource over the build's fetch span:
+// the project's out/clips-raw, then the editor's window cache
+// channels/<slug>/data/<id>/clips/<from>-<to>.mp4, then a saved whole source),
+// in the channels tree the project reads (channelsDirFor). Nothing is fetched:
+// a clip with no window on disk is refused, naming `umtool fetch`.
+//
+// THE CLOCK IS THE BUILD'S. A window's t = 0 is its `from`; a window whose
+// picture starts late is offset by clockOffset (the build's startOffset rule).
+// One ffmpeg pass, `blackdetect` then `scdet`, over the clip's extent ± --pad
+// (clamped to the window), scaled down first -- the scores are SAD over the
+// frame, and a small frame scores a cut as a big one does.
+//
+// Plain ESM: the CLI runs under bare node.
+import { spawn } from "node:child_process";
+import { clockOffset } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+import { fetchSpan } from "umtool-report-to-video/build-video";
+import { ffprobeSource, resolveLocalSource } from "umtool-report-to-video/sources";
+import path from "node:path";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { channelFor, channelsDirFor, hasShadowChannels, readManifest } from "../projects/report.mjs";
+
+export const SCENES_USAGE = [
+ "usage: umtool 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, at least",
+ " --black-min s, a pixel black below --pix-th) in the clip's FETCHED window, in SOURCE seconds — for",
+ " choosing blur.from / blur.to (umtool set) and a trim (umtool window). Scans the clip's extent ± --pad",
+ " inside the window, or --from/--to (source seconds). Nothing is fetched: `umtool fetch <project>` first.",
+].join("\n");
+
+export const SCENE_DEFAULTS = Object.freeze({ blackMin: 0.05, threshold: 8, pixTh: 0.1, pad: 30 });
+/** The frame height the scan decodes to: enough for a cut, a fraction of the decode's cost. */
+const SCAN_HEIGHT = 360;
+
+class CliError extends Error {}
+
+const VALUED = new Set(["--black-min", "--threshold", "--pix-th", "--pad", "--from", "--to"]);
+
+const r2 = (n) => Math.round(n * 100) / 100;
+const r3 = (n) => Math.round(n * 1000) / 1000;
+
+/**
+ * ffmpeg's log lines into the scan's events, still on the scan's own clock
+ * (t = 0 at the scan's first frame).
+ *
+ * [Parsed_blackdetect_1 @ …] black_start:23.133333 black_end:23.733333 black_duration:0.6
+ * [Parsed_scdet_2 @ …] lavfi.scd.score: 26.976, lavfi.scd.time: 23.133333
+ *
+ * @param {string} log ffmpeg's stderr
+ * @returns {{ cuts: { t: number, score: number }[], black: { from: number, to: number }[] }}
+ */
+export function parseSceneLog(log) {
+ const cuts = [];
+ const black = [];
+ for (const m of String(log).matchAll(/lavfi\.scd\.score:\s*([\d.]+),\s*lavfi\.scd\.time:\s*([\d.]+)/g)) {
+ cuts.push({ t: Number(m[2]), score: Number(m[1]) });
+ }
+ for (const m of String(log).matchAll(/black_start:\s*([\d.]+)\s+black_end:\s*([\d.]+)/g)) {
+ black.push({ from: Number(m[1]), to: Number(m[2]) });
+ }
+ return { cuts, black };
+}
+
+/**
+ * The scan's events in SOURCE seconds: `zero` is the source second at the
+ * scan's t = 0 (the window's from + its clock offset + the seek into it).
+ * `clip` marks each with whether it falls inside the clip's extent.
+ */
+export function toSourceSeconds({ cuts, black }, zero, clip = null) {
+ const inside = (t) => (clip ? t >= clip.start - 0.005 && t <= clip.end + 0.005 : null);
+ return {
+ cuts: cuts.map((c) => {
+ const at = r2(zero + c.t);
+ return { at, score: r3(c.score), inClip: inside(at) };
+ }),
+ black: black.map((b) => {
+ const from = r2(zero + b.from);
+ const to = r2(zero + b.to);
+ return { from, to, dur: r2(to - from), inClip: clip ? from < clip.end && to > clip.start : null };
+ }),
+ };
+}
+
+/** The ffmpeg arguments for one scan of `file` from `seek` for `dur` seconds. */
+export function scanArgs(file, { seek, dur, blackMin, threshold, pixTh }) {
+ return [
+ "-hide_banner", "-nostdin", "-nostats", "-loglevel", "info",
+ "-ss", Math.max(0, seek).toFixed(3), "-t", Math.max(0, dur).toFixed(3),
+ "-i", file, "-an", "-sn", "-dn",
+ "-vf", `scale=-2:${SCAN_HEIGHT},blackdetect=d=${blackMin}:pix_th=${pixTh},scdet=threshold=${threshold}`,
+ "-f", "null", "-",
+ ];
+}
+
+function runFfmpeg(args, { ffmpeg = process.env.FFMPEG_BIN ?? "ffmpeg" } = {}) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(ffmpeg, args, { stdio: ["ignore", "ignore", "pipe"] });
+ let log = "";
+ child.stderr.on("data", (d) => {
+ log += d;
+ });
+ child.on("error", (e) => reject(new Error(`ffmpeg did not start (${e.message}) — is it installed? \`umtool doctor\``)));
+ child.on("exit", (code) => {
+ if (code === 0) resolve(log);
+ else reject(new Error(`ffmpeg exited ${code}: ${log.trim().split("\n").slice(-3).join(" / ")}`));
+ });
+ });
+}
+
+const numFlag = (flags, name, dflt) => {
+ if (!flags.has(name)) return dflt;
+ const n = Number(flags.get(name));
+ if (!Number.isFinite(n) || n < 0) throw new CliError(`${name} must be a number ≥ 0`);
+ return n;
+};
+
+/**
+ * The scan of one clip: the window the build would cut it from, and what is
+ * in it. Exported for the tests (`ffmpeg` stubs the binary).
+ */
+export async function scanClip(project, clipId, opts = {}) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ const entry = (manifest.timeline ?? []).find((e) => e?.id === clipId);
+ if (!entry) throw new CliError(`no timeline entry with id ${clipId} in ${project.id}`);
+ if (entry.type !== "clip") throw new CliError(`${clipId} is a ${entry.type ?? "non-clip"} entry, not a clip`);
+ if (entry.src) throw new CliError(`${clipId} plays its own file (src: ${entry.src}), not a fetched window`);
+ const { blackMin, threshold, pixTh, pad } = { ...SCENE_DEFAULTS, ...opts };
+ const slug = channelFor(manifest, entry);
+ const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+ const rawDir = path.join(project.dir, "out", "clips-raw");
+ const config = { rawDir, channelsDir, probe: ffprobeSource };
+ // What the build would fetch, then the extent alone (a window that holds the clip but not its pad).
+ const span = fetchSpan(entry, manifest.render ?? {});
+ const hit =
+ (await resolveLocalSource({ video: entry.video, slug, from: span.from, to: span.to }, config)) ??
+ (await resolveLocalSource({ video: entry.video, slug, from: entry.start, to: entry.end }, config));
+ if (!hit) {
+ // A state, not a usage error: exit 1, as a refused write is.
+ throw new Error(
+ `${clipId} (${slug}/${entry.video} ${entry.start}–${entry.end}) has no window on disk — ` +
+ `\`umtool fetch ${project.id}\` asks the editor for it`,
+ );
+ }
+ const winFrom = hit.windowStart;
+ const winTo = hit.windowEnd;
+ const from = Math.max(winFrom, opts.from ?? entry.start - pad);
+ const to = Math.min(winTo, opts.to ?? entry.end + pad);
+ if (!(to - from > 0)) throw new CliError(`nothing to scan: ${r2(from)}–${r2(to)} is outside the window ${winFrom}–${winTo}`);
+ const off = await (opts.clockOffset ?? clockOffset)(hit.path);
+ const seek = Math.max(0, from - winFrom - off);
+ const zero = winFrom + off + seek;
+ const log = await runFfmpeg(scanArgs(hit.path, { seek, dur: to - from, blackMin, threshold, pixTh }), opts.ffmpeg ? { ffmpeg: opts.ffmpeg } : {});
+ const events = toSourceSeconds(parseSceneLog(log), zero, { start: entry.start, end: entry.end });
+ return {
+ project: project.id,
+ clip: {
+ id: clipId,
+ channel: slug,
+ video: entry.video,
+ start: entry.start,
+ end: entry.end,
+ ...(entry.cutStart != null && entry.cutEnd != null ? { cutStart: entry.cutStart, cutEnd: entry.cutEnd } : {}),
+ ...(entry.blur && typeof entry.blur === "object" ? { blur: entry.blur } : {}),
+ },
+ window: { file: hit.path, kind: hit.kind, from: winFrom, to: winTo, clockOffset: off },
+ scanned: { from: r2(from), to: r2(to) },
+ params: { blackMin, threshold, pixTh },
+ ...events,
+ };
+}
+
+/**
+ * @param {string[]} args the words after `scenes`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, ffmpeg?: string }} [opts]
+ * @returns {Promise<number>} the exit code
+ */
+export async function scenesCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), ffmpeg } = {}) {
+ const words = [];
+ const flags = new Map();
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (VALUED.has(a)) {
+ flags.set(a, args[i + 1] ?? "");
+ i += 1;
+ } else if (a.startsWith("--")) flags.set(a, true);
+ else words.push(a);
+ }
+ const json = flags.has("--json");
+ try {
+ const [projectArg, clipId] = words;
+ if (!projectArg || !clipId || flags.has("--help")) {
+ err(SCENES_USAGE);
+ return 2;
+ }
+ const r = await resolveProject(projectArg, root);
+ if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${projectArg}"`);
+ const opts = {
+ blackMin: numFlag(flags, "--black-min", SCENE_DEFAULTS.blackMin),
+ threshold: numFlag(flags, "--threshold", SCENE_DEFAULTS.threshold),
+ pixTh: numFlag(flags, "--pix-th", SCENE_DEFAULTS.pixTh),
+ pad: numFlag(flags, "--pad", SCENE_DEFAULTS.pad),
+ from: flags.has("--from") ? numFlag(flags, "--from", 0) : undefined,
+ to: flags.has("--to") ? numFlag(flags, "--to", 0) : undefined,
+ ...(ffmpeg ? { ffmpeg } : {}),
+ };
+ const s = await scanClip(r.project, clipId, opts);
+ if (json) {
+ out(JSON.stringify(s, null, 2));
+ return 0;
+ }
+ const c = s.clip;
+ out(`${c.id} ${c.channel}/${c.video} extent ${c.start}–${c.end}${c.cutStart != null ? ` cut ${c.cutStart}–${c.cutEnd}` : ""}` +
+ (c.blur ? ` blur ${c.blur.from ?? c.start}–${c.blur.to ?? c.end}` : ""));
+ out(`window ${s.window.from}–${s.window.to} (${s.window.kind}) ${s.window.file}${s.window.clockOffset ? ` clock +${s.window.clockOffset}` : ""}`);
+ out(`scanned ${s.scanned.from}–${s.scanned.to}, source seconds`);
+ const mark = (inClip) => (inClip ? " in clip" : "");
+ out(`\nblack (≥ ${s.params.blackMin} s): ${s.black.length || "none"}`);
+ for (const b of s.black) out(` ${b.from.toFixed(2)}–${b.to.toFixed(2)} (${b.dur.toFixed(2)} s)${mark(b.inClip)}`);
+ out(`\ncuts (score ≥ ${s.params.threshold}): ${s.cuts.length || "none"}`);
+ for (const x of s.cuts) out(` ${x.at.toFixed(2)} score ${x.score.toFixed(1)}${mark(x.inClip)}`);
+ return 0;
+ } catch (e) {
+ err(`umtool scenes: ${e instanceof Error ? e.message : String(e)}`);
+ return e instanceof CliError ? 2 : 1;
+ }
+}
diff --git a/umtool/lib/report/scenesCli.test.mjs b/umtool/lib/report/scenesCli.test.mjs
@@ -0,0 +1,102 @@
+// `umtool scenes` (2026-10-25): scene cuts and black spans in a clip's fetched
+// window, in SOURCE seconds. The parsers on ffmpeg's own log lines; then one
+// real scan of a four-second window made here (red, black, blue), found the
+// way the build finds it (the editor's window cache, channels/<slug>/data/<id>/clips/).
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { execFileSync } from "node:child_process";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-scenes-cli-"));
+process.env.REPORTS_DIR = path.join(ROOT, "reports");
+const { parseSceneLog, scanArgs, scenesCommand, toSourceSeconds } = await import("./scenesCli.mjs");
+
+const hasFfmpeg = (() => {
+ try {
+ execFileSync(process.env.FFMPEG_BIN ?? "ffmpeg", ["-version"], { stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+})();
+
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const LOG = [
+ "[Parsed_scdet_2 @ 0x7f5f580103c0] lavfi.scd.score: 29.058, lavfi.scd.time: 5.866667",
+ "frame= 189 fps=0.0 q=-0.0 size=N/A time=00:00:06.30 bitrate=N/A speed=12.6x",
+ "[Parsed_scdet_2 @ 0x7f5f580103c0] lavfi.scd.score: 26.976, lavfi.scd.time: 23.133333",
+ "[Parsed_blackdetect_1 @ 0x7f5f58010140] black_start:23.133333 black_end:23.733333 black_duration:0.6",
+ "[Parsed_scdet_2 @ 0x7f5f580103c0] lavfi.scd.score: 29.097, lavfi.scd.time: 23.733333",
+].join("\n");
+
+test("parseSceneLog + toSourceSeconds: eps-footage's window, as found by hand (black 250.49–251.09, cut 251.09)", () => {
+ const ev = parseSceneLog(LOG);
+ assert.equal(ev.cuts.length, 3);
+ assert.deepEqual(ev.black, [{ from: 23.133333, to: 23.733333 }]);
+ // The window 227.36–299.00, scanned from its start: t = 0 is source 227.36.
+ const s = toSourceSeconds(ev, 227.36, { start: 228.36, end: 260.03 });
+ assert.deepEqual(s.black, [{ from: 250.49, to: 251.09, dur: 0.6, inClip: true }]);
+ assert.deepEqual(s.cuts.map((c) => c.at), [233.23, 250.49, 251.09]);
+ assert.equal(s.cuts[2].score, 29.097);
+ assert.equal(toSourceSeconds(ev, 227.36, { start: 260, end: 270 }).black[0].inClip, false);
+});
+
+test("scanArgs: one pass, seek and length, both filters with their knobs", () => {
+ const a = scanArgs("/w.mp4", { seek: 1.5, dur: 30, blackMin: 0.05, threshold: 8, pixTh: 0.1 });
+ assert.deepEqual(a.slice(a.indexOf("-ss"), a.indexOf("-ss") + 4), ["-ss", "1.500", "-t", "30.000"]);
+ assert.match(a[a.indexOf("-vf") + 1], /blackdetect=d=0\.05:pix_th=0\.1,scdet=threshold=8$/);
+});
+
+test("scenes: the clip's window on disk, scanned; source seconds out; a clip with no window refused", { skip: !hasFfmpeg && "no ffmpeg" }, async () => {
+ const channels = path.join(ROOT, "channels");
+ const clips = path.join(channels, "chan", "data", "vid1", "clips");
+ await mkdir(clips, { recursive: true });
+ // 1.5 s red, 0.6 s black, 1.9 s blue: the window 10.00–14.00.
+ execFileSync(process.env.FFMPEG_BIN ?? "ffmpeg", [
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", "color=c=red:s=160x90:r=25:d=1.5",
+ "-f", "lavfi", "-i", "color=c=black:s=160x90:r=25:d=0.6",
+ "-f", "lavfi", "-i", "color=c=blue:s=160x90:r=25:d=1.9",
+ "-filter_complex", "[0:v][1:v][2:v]concat=n=3:v=1:a=0[v]", "-map", "[v]",
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", path.join(clips, "10.00-14.00.mp4"),
+ ]);
+ const dir = path.join(ROOT, "reports", "scan");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({
+ schemaVersion: 1,
+ slug: "scan",
+ provenance: { siteOrigin: "https://example.test", channelSlug: "chan", channelsDir: channels },
+ render: { fetchPad: 0.5 },
+ timeline: [
+ { type: "clip", id: "c01", video: "vid1", start: 10.5, end: 13.5 },
+ { type: "clip", id: "gone", video: "vid2", start: 1, end: 3 },
+ { type: "card", id: "k", heading: "x" },
+ ],
+ }));
+ const lines = [];
+ const run = (...args) => scenesCommand(args, { root: path.join(ROOT, "reports"), out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) });
+ assert.equal(await run("scan", "c01", "--json"), 0);
+ const s = JSON.parse(lines.at(-1));
+ assert.equal(s.window.kind, "corpus-window");
+ assert.deepEqual([s.window.from, s.window.to], [10, 14]);
+ assert.deepEqual(s.scanned, { from: 10, to: 14 });
+ assert.equal(s.black.length, 1);
+ assert.ok(Math.abs(s.black[0].from - 11.5) <= 0.05, `black from ${s.black[0].from}`);
+ assert.ok(Math.abs(s.black[0].to - 12.1) <= 0.05, `black to ${s.black[0].to}`);
+ assert.ok(s.cuts.some((c) => Math.abs(c.at - 12.1) <= 0.05), JSON.stringify(s.cuts));
+ // --from/--to narrow the scan: the seek lands on the same source clock.
+ assert.equal(await run("scan", "c01", "--from", "11", "--to", "13", "--json"), 0);
+ const n = JSON.parse(lines.at(-1));
+ assert.deepEqual(n.scanned, { from: 11, to: 13 });
+ assert.ok(Math.abs(n.black[0].from - 11.5) <= 0.05 && Math.abs(n.black[0].to - 12.1) <= 0.05, JSON.stringify(n.black));
+ assert.equal(await run("scan", "gone"), 1);
+ assert.match(lines.at(-1), /has no window on disk — `umtool fetch scan`/);
+ assert.equal(await run("scan", "k"), 2);
+ assert.match(lines.at(-1), /not a clip/);
+ assert.equal(await run("scan"), 2);
+});
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -0,0 +1,358 @@
+// `umtool timeline` (2026-10-25): the STRUCTURE of the cut from a terminal --
+// what is in the timeline and in what order, a teaser's lines, the posts, and
+// undo. The same writers POST /api/report/timeline runs (lib/report/manifest.mjs
+// "STRUCTURE": insertEntry, moveEntry, removeEntry, duplicateEntry, upsertPost,
+// removePost, updateTeaser, undoStructural), through the same generated-manifest
+// guard (edit-guard.mjs), each write carrying the token read from the file just
+// before it -- so an edit here beside an open Cut tab is refused, not lost, and
+// every op snapshots the manifest first (`revisions/<stamp>-auto-before-<op>`)
+// and is checked by the build's own validators.
+//
+// umtool timeline <project> [ls] index, id, type, video, start–end, date title
+// umtool timeline <project> insert --after <id|-> <channel>/<video>@<start>-<end>
+// [--id ID] [--title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]
+// umtool timeline <project> move <id> --to <index>
+// umtool timeline <project> remove <id> | duplicate <id>
+// umtool timeline <project> post <json|@file> | post-remove <id>
+// umtool timeline <project> teaser <id> <patch-json|@file>
+// umtool timeline <project> undo
+//
+// An insert's attribution (--title, --date, --quote, --cite, --cite-url) is a
+// second write, through updateClip -- the writer `umtool window` and the
+// bench use, which is what validates it. The date is checked BEFORE the
+// insert, so a bad one refuses with nothing written.
+//
+// Plain ESM: the CLI runs under bare node.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { isCalendarDate } from "umtool-report-to-video/attribution";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { parseClipSpec } from "./clipEditorModel.mjs";
+import {
+ StaleToken,
+ StructureRefused,
+ duplicateEntry,
+ insertEntry,
+ manifestToken,
+ moveEntry,
+ removeEntry,
+ removePost,
+ undoStructural,
+ updateClip,
+ updateTeaser,
+ upsertPost,
+} from "./manifest.mjs";
+
+export const TIMELINE_USAGE = [
+ "usage: umtool timeline <project> [ls] [--json] the cut: index, id, type, video, start–end, date title",
+ " umtool timeline <project> insert --after <id|-> <channel>/<video>@<start>-<end> [--id ID]",
+ " [--title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]",
+ " a clip after <id> (`-`: at the start); the attribution through `umtool window`'s writer",
+ " umtool timeline <project> move <id> --to <index> <index> is its place AFTER the move (0 first)",
+ " umtool timeline <project> remove <id> | duplicate <id> (--at <index> names one of an id's twins)",
+ " umtool timeline <project> post <json|@file> add a post, or replace the one with its id",
+ " umtool timeline <project> post-remove <id>",
+ " umtool timeline <project> teaser <id> <patch-json|@file> lines, beat, dip, tail, tailWait (null removes one)",
+ " umtool timeline <project> undo restore the newest automatic snapshot",
+ "",
+ "Every write snapshots the manifest first (revisions/…-auto-before-<op>), is checked by the build's own",
+ "validators, and on a generated manifest leaves an `edit` note for its generator. The Cut tab's timeline.",
+].join("\n");
+
+const VERBS = ["ls", "insert", "move", "remove", "duplicate", "post", "post-remove", "teaser", "undo"];
+const VALUED = new Set(["--after", "--to", "--at", "--id", "--title", "--date", "--quote", "--cite", "--cite-url"]);
+
+class CliError extends Error {}
+
+async function projectOf(arg, root) {
+ if (!arg) throw new CliError("which project?");
+ const r = await resolveProject(arg, root);
+ if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${arg}"`);
+ return r.project;
+}
+
+/** The words and the valued flags. A valued flag takes the next word whatever it is (`--after -`). */
+export function splitTimelineArgs(args) {
+ const words = [];
+ const flags = new Map();
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (VALUED.has(a)) {
+ flags.set(a, args[i + 1] ?? "");
+ i += 1;
+ } else if (a.startsWith("--")) flags.set(a, true);
+ else words.push(a);
+ }
+ return { words, flags };
+}
+
+/** A JSON argument, or `@file` for one read from disk. */
+async function jsonArg(raw, what) {
+ if (raw === undefined || raw === "") throw new CliError(`${what} needs a JSON value (or @file)`);
+ const text = raw.startsWith("@") ? await readFile(path.resolve(raw.slice(1)), "utf8") : raw;
+ try {
+ return JSON.parse(text);
+ } catch (e) {
+ throw new CliError(`${what}: not JSON (${e instanceof Error ? e.message : e})`);
+ }
+}
+
+const intFlag = (flags, name) => {
+ if (!flags.has(name)) return null;
+ const v = flags.get(name);
+ const n = Number(v);
+ if (v === true || v === "" || !Number.isInteger(n)) throw new CliError(`${name} needs a whole number (got ${v === true ? "nothing" : v})`);
+ return n;
+};
+
+const fmt = (n) => (typeof n === "number" && Number.isFinite(n) ? n.toFixed(2) : "—");
+
+/** One row of `ls`: what an agent needs to name an entry and see where it is. */
+export function timelineRows(manifest) {
+ return (manifest?.timeline ?? []).map((e, index) => {
+ const title = e.title ?? e.onscreen?.title ?? e.heading ?? e.label ?? null;
+ return {
+ index,
+ id: String(e.id ?? ""),
+ type: String(e.type ?? "entry"),
+ ...(e.type === "clip"
+ ? {
+ channel: e.channel ?? manifest?.provenance?.channelSlug ?? null,
+ video: e.video ?? null,
+ start: e.start ?? null,
+ end: e.end ?? null,
+ ...(e.cutStart != null && e.cutEnd != null ? { cutStart: e.cutStart, cutEnd: e.cutEnd } : {}),
+ }
+ : {}),
+ date: typeof e.date === "string" ? e.date : null,
+ title: typeof title === "string" ? title : null,
+ };
+ });
+}
+
+export function timelineLines(rows) {
+ const w = Math.max(2, ...rows.map((r) => r.id.length));
+ const tw = Math.max(4, ...rows.map((r) => r.type.length));
+ return rows.map((r) => {
+ const span =
+ r.type === "clip"
+ ? `${String(r.video ?? "?").padEnd(14)} ${fmt(r.start)}–${fmt(r.end)}${r.cutStart != null ? ` (cut ${fmt(r.cutStart)}–${fmt(r.cutEnd)})` : ""}`
+ : "".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}` : ""}`;
+ });
+}
+
+const noted = (editNotes) =>
+ !editNotes
+ ? ""
+ : editNotes.errors.length
+ ? ` edit NOT noted (${editNotes.errors.join("; ")}) — ${editNotes.generatedBy} will overwrite it on the next rebuild`
+ : editNotes.added + editNotes.updated + editNotes.deleted
+ ? ` edit noted for ${editNotes.generatedBy} — port it into the generator's inputs`
+ : "";
+
+/** The attribution flags of an insert, as updateClip's patch (an empty value deletes, as in `umtool window`). */
+export function attributionPatch(flags) {
+ const patch = {};
+ for (const [flag, key] of [
+ ["--title", "title"],
+ ["--date", "date"],
+ ["--quote", "quote"],
+ ["--cite", "cite"],
+ ["--cite-url", "citeUrl"],
+ ]) {
+ if (!flags.has(flag)) continue;
+ const v = flags.get(flag);
+ patch[key] = v === true ? "" : v;
+ }
+ if (patch.date && !isCalendarDate(String(patch.date).trim())) {
+ throw new CliError(`date must be a real calendar date written YYYY-MM-DD (got \`${patch.date}\`)`);
+ }
+ if (patch.cite !== undefined && patch.cite !== "") {
+ const n = Number(patch.cite);
+ if (!Number.isFinite(n) || n < 0) throw new CliError("--cite must be a number of seconds ≥ 0");
+ patch.cite = n;
+ }
+ return patch;
+}
+
+/**
+ * @param {string[]} args the words after `timeline`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
+ * @returns {Promise<number>} the exit code
+ */
+export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ const { words, flags } = splitTimelineArgs(args);
+ const json = flags.has("--json");
+ try {
+ const [projectArg, verb = "ls", ...rest] = words;
+ if (!projectArg || flags.has("--help")) {
+ err(TIMELINE_USAGE);
+ return 2;
+ }
+ if (!VERBS.includes(verb)) throw new CliError(`unknown: timeline ${verb} — ${VERBS.join(", ")}`);
+ const project = await projectOf(projectArg, root);
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+
+ if (verb === "ls") {
+ const rows = timelineRows(manifest);
+ if (json) {
+ out(JSON.stringify({
+ project: project.id,
+ token: await manifestToken(project.dir),
+ generatedBy: manifest.generatedBy ?? null,
+ timeline: rows,
+ posts: Array.isArray(manifest.posts) ? manifest.posts : [],
+ }, null, 2));
+ return 0;
+ }
+ for (const line of timelineLines(rows)) out(line);
+ const posts = Array.isArray(manifest.posts) ? manifest.posts : [];
+ out(`${rows.length} entr${rows.length === 1 ? "y" : "ies"}${posts.length ? `, ${posts.length} post(s)` : ""} in ${project.id}`);
+ for (const p of posts) out(` post ${p.id}${p.attachTo ? ` -> ${p.attachTo}` : ""}${p.hide ? " (hidden)" : ""} ${p.date ?? ""}`);
+ return 0;
+ }
+
+ const at = intFlag(flags, "--at");
+ const need = (v, what) => {
+ if (!v) throw new CliError(`${verb} needs ${what}`);
+ return v;
+ };
+ // The token is read from the file just before each write: a write between
+ // this read and the writer's lock is a StaleToken, never overwritten.
+ const write = async (fn) => withEditNotes(project, async () => fn(await manifestToken(project.dir)));
+
+ /** @type {Record<string, any>} */
+ let result;
+ let editNotes = null;
+ let attribution = null;
+ switch (verb) {
+ case "insert": {
+ if (!flags.has("--after")) throw new CliError("insert needs --after <id> (or --after - for the start)");
+ const after = String(flags.get("--after"));
+ const spec = need(rest[0], "a clip: <channel>/<video>@<start>-<end>");
+ const patch = attributionPatch(flags);
+ let entry = spec;
+ if (flags.has("--id")) {
+ const c = parseClipSpec(spec);
+ if (!c) throw new CliError("a clip is <channel>/<video>@<start>-<end> in seconds");
+ entry = { type: "clip", id: String(flags.get("--id")), ...c };
+ }
+ ({ result, editNotes } = await write((token) => insertEntry(project.dir, after === "-" || after === "" ? null : after, entry, { token, at })));
+ if (flags.has("--id") && result.id !== flags.get("--id")) {
+ result.idTaken = String(flags.get("--id"));
+ }
+ if (Object.keys(patch).length) {
+ try {
+ const done = await write((token) => updateClip(project.dir, result.id, patch, { token }));
+ attribution = done.result.entry;
+ editNotes = done.editNotes ?? editNotes;
+ } catch (e) {
+ // The clip is in; only its header failed. Say both, and how to finish.
+ const msg = e instanceof Error ? e.message : String(e);
+ if (json) out(JSON.stringify({ ok: false, inserted: result, attributionError: msg, editNotes }, null, 2));
+ else err(`inserted ${result.id} at ${result.at}, but its attribution was refused: ${msg}\n finish with: umtool window ${project.id} ${result.id} …`);
+ return 1;
+ }
+ }
+ break;
+ }
+ case "move": {
+ const id = need(rest[0], "an entry id");
+ const to = intFlag(flags, "--to");
+ if (to === null) throw new CliError("move needs --to <index> (its place after the move; `umtool timeline <project>` lists them)");
+ ({ result, editNotes } = await write((token) => moveEntry(project.dir, id, to, { token, at })));
+ break;
+ }
+ case "remove": {
+ const id = need(rest[0], "an entry id");
+ ({ result, editNotes } = await write((token) => removeEntry(project.dir, id, { token, at })));
+ break;
+ }
+ case "duplicate": {
+ const id = need(rest[0], "an entry id");
+ ({ result, editNotes } = await write((token) => duplicateEntry(project.dir, id, { token, at })));
+ break;
+ }
+ case "post": {
+ const post = await jsonArg(rest[0], "post");
+ ({ result, editNotes } = await write((token) => upsertPost(project.dir, post, { token })));
+ break;
+ }
+ case "post-remove": {
+ const id = need(rest[0], "a post id");
+ ({ result, editNotes } = await write((token) => removePost(project.dir, id, { token })));
+ break;
+ }
+ case "teaser": {
+ const id = need(rest[0], "a teaser id");
+ const patch = await jsonArg(rest[1], "teaser");
+ ({ result, editNotes } = await write((token) => updateTeaser(project.dir, id, patch, { token, at })));
+ break;
+ }
+ case "undo": {
+ ({ result, editNotes } = await write((token) => undoStructural(project.dir, { token })));
+ break;
+ }
+ }
+
+ if (json) {
+ out(JSON.stringify({ ok: true, op: verb, ...result, ...(attribution ? { entry: attribution } : {}), editNotes }, null, 2));
+ return 0;
+ }
+ out(summaryOf(verb, result, attribution));
+ if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel}`);
+ else if (result.snapshot?.error) out(` NO undo point: ${result.snapshot.error}`);
+ const n = noted(editNotes);
+ if (n) out(n);
+ return 0;
+ } catch (e) {
+ if (e instanceof StructureRefused) {
+ err(`umtool timeline: refused — the build would not take it:\n${e.errors.map((x) => ` ${x}`).join("\n")}`);
+ return 1;
+ }
+ if (e instanceof StaleToken) {
+ err(`umtool timeline: ${e.message} — somebody else wrote it; run it again`);
+ return 1;
+ }
+ err(`umtool timeline: ${e instanceof Error ? e.message : String(e)}`);
+ return e instanceof CliError ? 2 : 1;
+ }
+}
+
+function summaryOf(verb, r, attribution) {
+ switch (verb) {
+ 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 taken = r.idTaken ? `\n (${r.idTaken} was taken: it is ${r.id})` : "";
+ const attr = attribution
+ ? `\n header: ${attribution.title ?? "(the record's own title)"} · ${attribution.date ?? "(the record's upload date)"} @ ${attribution.cite ?? attribution.start}` +
+ (attribution.quote ? `\n quote: ${attribution.quote}` : "") +
+ (attribution.citeUrl ? `\n QR: ${attribution.citeUrl}` : "")
+ : "";
+ return head + taken + attr;
+ }
+ case "move":
+ return `moved ${r.id}: ${r.from} -> ${r.to}`;
+ case "remove":
+ return `removed ${r.id} (was at ${r.at})`;
+ case "duplicate":
+ return `duplicated as ${r.id} at ${r.at}`;
+ case "post":
+ return `${r.created ? "added" : "replaced"} post ${r.post.id}${r.post.attachTo ? ` -> ${r.post.attachTo}` : ""}`;
+ case "post-remove":
+ return `removed post ${r.removed.id}`;
+ case "teaser":
+ return `${r.id}: ${JSON.stringify(r.entry)}`;
+ case "undo":
+ return `undid ${r.op}: restored ${r.restored}${r.saved ? ` (the state before the undo kept as ${r.saved})` : ""}`;
+ default:
+ return JSON.stringify(r);
+ }
+}
diff --git a/umtool/lib/report/timelineCli.test.mjs b/umtool/lib/report/timelineCli.test.mjs
@@ -0,0 +1,152 @@
+// `umtool timeline` (2026-10-25): the cut's structure from a terminal, through
+// the writers POST /api/report/timeline runs -- the same snapshots, the same
+// build validators, the same edit notes on a generated manifest.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-timeline-cli-"));
+process.env.REPORTS_DIR = ROOT;
+const { attributionPatch, splitTimelineArgs, timelineCommand, timelineLines, timelineRows } = await import("./timelineCli.mjs");
+
+const MANIFEST = {
+ schemaVersion: 1,
+ slug: "cut",
+ title: "Cut",
+ provenance: { siteOrigin: "https://example.test", channelSlug: "chan" },
+ render: { width: 1920, height: 1080, fps: 30 },
+ timeline: [
+ { type: "teaser", id: "t1", lines: ["One", "Two"] },
+ { type: "clip", id: "c01", video: "v1", start: 10, end: 20, date: "2026-08-24", title: "First" },
+ { type: "clip", id: "c02", channel: "other", video: "v2", start: 30, end: 41, cutStart: 31, cutEnd: 40 },
+ ],
+ posts: [{ id: "x-1", platform: "x", date: "2026-08-24T10:00:00.000Z", text: "words", url: "https://x.com/a/status/1", attachTo: "c02" }],
+};
+
+async function project(name, extra = {}) {
+ const dir = path.join(ROOT, name);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ ...MANIFEST, ...extra }, null, 2) + "\n");
+ return dir;
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+const ids = async (dir) => (await read(dir)).timeline.map((e) => e.id);
+const runner = () => {
+ const lines = [];
+ return { lines, run: (...args) => timelineCommand(args, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }) };
+};
+
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+test("splitTimelineArgs: a valued flag takes the next word, even `-`", () => {
+ const { words, flags } = splitTimelineArgs(["p", "insert", "--after", "-", "chan/v@1-2", "--title", "T", "--json"]);
+ assert.deepEqual(words, ["p", "insert", "chan/v@1-2"]);
+ assert.equal(flags.get("--after"), "-");
+ assert.equal(flags.get("--title"), "T");
+ assert.equal(flags.get("--json"), true);
+});
+
+test("attributionPatch: the window flags; a bad date or cite refused before anything is written", () => {
+ const f = (o) => new Map(Object.entries(o));
+ assert.deepEqual(attributionPatch(f({ "--title": "T", "--date": "2026-08-24", "--cite": "12.5", "--quote": "q" })), {
+ title: "T",
+ date: "2026-08-24",
+ cite: 12.5,
+ quote: "q",
+ });
+ assert.throws(() => attributionPatch(f({ "--date": "2026-02-30" })), /real calendar date/);
+ assert.throws(() => attributionPatch(f({ "--cite": "soon" })), /--cite must be/);
+});
+
+test("ls: index, id, type, video, start–end, date title", async () => {
+ await project("ls");
+ const rows = timelineRows(MANIFEST);
+ assert.deepEqual(rows.map((r) => [r.index, r.id, r.type]), [[0, "t1", "teaser"], [1, "c01", "clip"], [2, "c02", "clip"]]);
+ assert.equal(rows[1].channel, "chan");
+ assert.equal(rows[2].channel, "other");
+ assert.deepEqual([rows[2].cutStart, rows[2].cutEnd], [31, 40]);
+ const lines = timelineLines(rows);
+ assert.match(lines[1], /^\s+1\s+c01\s+clip\s+v1\s+10\.00–20\.00\s+2026-08-24 First$/);
+ assert.match(lines[2], /cut 31\.00–40\.00/);
+ const { lines: out, run } = runner();
+ assert.equal(await run("ls", "--json"), 0);
+ const doc = JSON.parse(out[0]);
+ assert.equal(doc.timeline.length, 3);
+ assert.equal(typeof doc.token, "string");
+ assert.equal(doc.posts[0].id, "x-1");
+});
+
+test("insert: a clip after an id (or `-`, the start), its attribution through updateClip; snapshots first", async () => {
+ const dir = await project("insert");
+ const { lines, run } = runner();
+ assert.equal(await run("insert", "insert", "--after", "c01", "chan/v9@5-12.5", "--id", "new", "--title", "Nine", "--date", "2026-09-01", "--quote", "said it", "--cite", "6"), 0);
+ let m = await read(dir);
+ assert.deepEqual(m.timeline.map((e) => e.id), ["t1", "c01", "new", "c02"]);
+ assert.deepEqual(m.timeline[2], { type: "clip", id: "new", channel: "chan", video: "v9", start: 5, end: 12.5, title: "Nine", quote: "said it", date: "2026-09-01", cite: 6 });
+ assert.ok((await readdir(path.join(dir, "revisions"))).some((n) => n.endsWith("-auto-before-insert.manifest.json")));
+ // The id taken: a fresh one, and said so.
+ assert.equal(await run("insert", "insert", "--after", "-", "chan/v9@1-3", "--id", "new"), 0);
+ assert.match(lines.at(-2) + lines.at(-1), /new was taken: it is new-2/);
+ assert.equal((await ids(dir))[0], "new-2");
+ // A bad date: refused before the insert, nothing written.
+ const before = await read(dir);
+ assert.equal(await run("insert", "insert", "--after", "c01", "chan/v9@20-30", "--date", "2026-13-01"), 2);
+ assert.deepEqual(await read(dir), before);
+ assert.equal(await run("insert", "insert", "chan/v9@20-30"), 2);
+ assert.match(lines.at(-1), /needs --after/);
+ assert.equal(await run("insert", "insert", "--after", "c01", "nonsense"), 1);
+ assert.match(lines.at(-1), /<channel>\/<video>@<start>-<end>/);
+ m = await read(dir);
+ assert.equal(m.timeline.length, 5);
+});
+
+test("move, duplicate, remove, and undo — each refused only for what it breaks", async () => {
+ const dir = await project("move");
+ const { lines, run } = runner();
+ assert.equal(await run("move", "move", "c02", "--to", "0"), 0);
+ assert.deepEqual(await ids(dir), ["c02", "t1", "c01"]);
+ assert.equal(await run("move", "move", "c02"), 2);
+ assert.match(lines.at(-1), /needs --to/);
+ assert.equal(await run("move", "duplicate", "c01"), 0);
+ assert.deepEqual(await ids(dir), ["c02", "t1", "c01", "c01-copy"]);
+ assert.equal(await run("move", "remove", "c01-copy"), 0);
+ // A post is attached to c02: the build would refuse the cut without it.
+ assert.equal(await run("move", "remove", "c02"), 1);
+ assert.match(lines.at(-1), /attachTo "c02" is not a clip/);
+ assert.deepEqual(await ids(dir), ["c02", "t1", "c01"]);
+ assert.equal(await run("move", "remove", "nope"), 1);
+ assert.match(lines.at(-1), /no timeline entry with id nope/);
+ // Undo: the newest automatic snapshot (the remove), then the one before it.
+ assert.equal(await run("move", "undo"), 0);
+ assert.match(lines.at(-1) + lines.at(-2), /undid remove/);
+ assert.deepEqual(await ids(dir), ["c02", "t1", "c01", "c01-copy"]);
+});
+
+test("teaser, post and post-remove (JSON or @file); a generated manifest gets its edit notes", async () => {
+ const dir = await project("structure", { generatedBy: "make.py" });
+ const { lines, run } = runner();
+ assert.equal(await run("structure", "teaser", "t1", '{"lines":["Only"],"beat":1.234}', "--json"), 0);
+ const res = JSON.parse(lines.at(-1));
+ assert.equal(res.ok, true);
+ assert.equal(res.editNotes.generatedBy, "make.py");
+ let m = await read(dir);
+ assert.deepEqual(m.timeline[0], { type: "teaser", id: "t1", lines: ["Only"], beat: 1.23 });
+ assert.equal(await run("structure", "teaser", "c01", '{"lines":["x"]}'), 1);
+ assert.match(lines.at(-1), /not a teaser/);
+ const file = path.join(ROOT, "post.json");
+ await writeFile(file, JSON.stringify({ id: "x-2", platform: "x", date: "2026-08-25", text: " two ", url: "https://x.com/a/status/2", attachTo: "c01" }));
+ assert.equal(await run("structure", "post", `@${file}`), 0);
+ m = await read(dir);
+ assert.deepEqual(m.posts[1], { id: "x-2", platform: "x", date: "2026-08-25", text: "two", url: "https://x.com/a/status/2", attachTo: "c01" });
+ assert.equal(await run("structure", "post", '{"id":"x-3","platform":"myspace","date":"2026-08-25","text":"t","url":"https://a.test/3"}'), 1);
+ assert.match(lines.at(-1), /platform must be/);
+ assert.equal(await run("structure", "post", "{not json"), 2);
+ assert.equal(await run("structure", "post-remove", "x-2"), 0);
+ assert.deepEqual((await read(dir)).posts.map((p) => p.id), ["x-1"]);
+ const notes = JSON.parse(await readFile(path.join(dir, "notes.json"), "utf8"));
+ assert.ok(notes.notes.length > 0);
+});