commit 6545526f85c8f816a82d50ce0bf8e3bab412a31b
parent a53dcc3509035601e9a77a9fb4044a31d98b71e3
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 22:00:25 -0500
Merge main (L5 ingredient rail, E2, L8a verb registry) into lane/agent-to-ui
The inspector's verbs get their registry rows (provenance ls|set, title, still, still ls, timeline
teaser-insert, links --embed-ids; still confirms: a file with no undo point) and their help in
groups.mjs; usage() and cli.md regenerated (node umtool/lib/cli/docs.mjs). Every new write route calls
crossSiteRefusal. PlayCut keeps both: L5's Life cycle link and the Still button.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
86 files changed, 8719 insertions(+), 777 deletions(-)
diff --git a/.env.example b/.env.example
@@ -34,6 +34,11 @@
# umtool. Private, same rules as the editor.
#UMTOOL_BIND=0.0.0.0
+# The names umtool is reached by when not localhost (a LAN IP, a custom domain,
+# a Tailscale name): its pages' writes are refused from any other (DNS
+# rebinding). Comma-separated, no ports. RUNNING_IN_DOCKER.md, "Reaching the
+# editor from another machine".
+#UMTOOL_ALLOWED_HOSTS=archive-box.lan,192.168.1.20
# The published port numbers, if 8080-8083 collide with something you run.
# These are the OUTSIDE ports; the ports inside the containers never change.
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -123,7 +123,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| action | what it does | example |
|---|---|---|
| `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. {"focus": {"kind": "site", "siteId"} \| {"kind": "channels", "slugs"} \| {"kind": "none"}} alone is the deck's focus bar: those channels lead every lane (a site focus follows its membership); "none" ends it. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'`<br>`pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'` |
+| `channel-rank` | channel-rank places one channel in the order every lane and the sync scheduler follow inside a tier (one rank per channel, 0 first; unranked channels come after every ranked one, by slug): {"slug"} and exactly one of "rank": <n> (before any channel holding it) or null (unranked), "top": true, "bottom": true, "before": "<slug>", "after": "<slug>" (a ranked channel; immediately next to it, a tie on its rank included). The channels after it move down only as far as they must. Only the rank moves — no tier, override or lane changes, unlike /channels' "Add to top". Refused: an unknown channel, an unranked anchor, a channel paused for every operation. Answers {slug, rank, order: \[{slug, rank}, …\]}. | `pnpm ops channel-rank --json '{"slug":"x","top":true}'`<br>`pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'`<br>`pnpm ops channel-rank --json '{"slug":"x","rank":null}'` |
| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "<regex with named groups year, month, day>"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "<slug>, <slug>"} (CHANNEL.md, mirror; then mirror-scan). Caption languages and the live chat: "patch": {"subLangs": "en.\*", "chat": "with-download" \| "later" \| "never"} (CHANNEL.md, subLangs and chat). Manual downloads: "patch": {"downloadMode": "manual"} — only videos you add (import-video, the video page) are downloaded; the download lane, a sync's new uploads and download-missing leave the channel alone; "" (or "auto") is automatic (CHANNEL.md, downloadMode). | `pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` |
+| `create-site` | create-site is the New site form: {"siteId", "siteTitle"} and any of its fields — "headerTitle" (default the title), "siteDescription", "homeTagline", "wordmarkLead", "accent" (an id or "#rrggbb"), "siteUrl", "cloudflareProject", "hubUrl", "audience" ("private" \| "public"; default PRIVATE), "listed" (default FALSE), "publishAuto", "search", "archives", "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB" (null = the global default), "groups" (\[{"id", "name", "selectedByDefault"?, "description"?, "inline"?}\]), "defaultGroupId", "channels" (slugs, or {"slug", "groupId"?}: the pool), "citedChannels" (slugs), "socialLinks" (\[{"label", "url", "svg"}\], null = inherit), "relatedSites". Saved by the form's action (its validation, its sentences). An existing id is refused (409) unless "update": true — the site page's Save with the keys given changed, every other key kept — one read-modify-write under the site's lock. An unknown channel, or a channel's groupId naming no group of the site, is refused. Answers {siteId, created, site}. | `pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}'`<br>`pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}'` |
| `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` |
| `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` |
| `delete-article` | delete-article deletes an article, as `archilyzer reports delete <id>` does: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? (unpublish it, and drop a site page naming it with no report of its own, first). It removes the article's directory (report, video, history, notes, iterations), each iteration's video project under settings.generation.projectsRoot and its staged exports. Refused with the plan (409): a published article or such a site page without "force"; a queued or running iteration, force or not. | `pnpm ops delete-article --json '{"id":"demo-article","dryRun":true}'`<br>`pnpm ops delete-article --json '{"id":"demo-article","force":true}'` |
@@ -131,7 +133,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `delete-site` | delete-site deletes a site, plan first: {"id"}, "dryRun"? (answer the plan — every path with its size, what is kept and why — and write nothing), "force"? It removes sites/<id>/ (site.json, its pool and pages, tags, charts, its reports), its publish state and last bundle (export/.export-builds/<id>/) and compose's staging for it (export/.export-index/sites/<id>/). Channel data is never touched; the Pages project, what was deployed and a deployed hub are kept (a delete does not undeploy). Refused with the plan (409) unless "force": a deploy target (cloudflareProject), a deploy in its publish state, reports of its own. Refused, force or not: no such site (404), a site dir that is a link, a publish stage running. | `pnpm ops delete-site --json '{"id":"demo-site","dryRun":true}'` |
| `create-channel` | create-channel is the New channel form: {"fields": {"name", "handling": "youtube"\|"transcribe", "url"?, "platform"?, "sourceKind"?, "postFetcher"?, "socialHandle"?, …}} with channel-config's patch keys; "slug"? (else derived from the name), "sites"? (absent = on no site). "fetchPlaylist", "fetchPostsNow" and "prioritizeDownload" are the form's checkboxes, OFF unless true; a job they start comes back as jobId(s), so --wait follows it. An X search page URL (x.com/search?q=…), or "platform": "x-search" with "xSearchQuery" (and "xSearchSince"?, "xSearchUntil"?, "xSearchWindowMonths"?, "xSearchLang"?), makes an X SEARCH channel: the matching posts from any account, walked by fetch-posts in search windows; never on a site (sites refused). | `pnpm ops create-channel --json '{"fields":{"name":"Example (X)","handling":"transcribe","url":"https://x.com/example"}}'`<br>`pnpm ops create-channel --json '{"fields":{"name":"Demo search","handling":"transcribe","url":"https://x.com/search?q=%22demo%20phrase%22"}}'` |
| `rename-channel` | rename-channel moves a channel to a new slug, as Danger → Rename does: {"slug", "newSlug"}. Refused while the channel is busy (a job, a lane unit, media in transition) or when the new slug is taken. Old links break. | `pnpm ops rename-channel --json '{"slug":"old-slug","newSlug":"new-slug"}'` |
-| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` |
+| `delete-channel` | delete-channel removes a channel's whole directory, as Danger → Delete does: {"slug", "confirm"} — "confirm" must repeat the slug. Every site whose pool or cited scope names it is rewritten without it (answered as "sitesUpdated"; a site whose write is refused is a "warnings" line). No undo outside the transcripts/ repo's own history. | `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` |
| `metadata-scan` | metadata-scan reads every listed video's title, date and description into the channel's scan file, fetching no media: {"slug"}. Not held by the download pause and needs no disk floor; one request per video, so it respects the platform's cooldown and records one when pushed back. | `pnpm ops metadata-scan --json '{"slug":"the-quartering"}'` |
| `refresh-metadata` | refresh-metadata re-reads ONE video's metadata.info.json from its source (no subtitles, no media) on the platform's queue: {"slug", "id"}. The job's log ends with what the source now says — live\_status, formats, audio-only formats and whether any is non-fragmented, English captions, the keys that changed. An id with no data/<id>/ is refused (a refresh re-reads a video already archived), as are archive.org and Wayback records. | `pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait` |
| `browser-lookup` | browser-lookup reads Odysee records from their pages in a headless browser, for when yt-dlp's lookup answers 429: {"slug", "ids": \[...\]} (at most 50) writes each record (none yet: whole, `_source: "browser"`) or completes it (the keys it lacks, and the one media file the page's player asked for); "listing": true (with "scrolls", default 5, at most 40) adds the uploads the channel page shows to the playlist, newest first, through the title match filter. One page a minute; not refused for a held platform. The log ends with a `summary: {...}` line. | `pnpm ops browser-lookup --json '{"slug":"demo-odysee","ids":["<claimId>"]}' --wait`<br>`pnpm ops browser-lookup --json '{"slug":"demo-odysee","listing":true,"scrolls":5}' --wait` |
@@ -184,7 +186,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `dismiss-service` | — | |
| `rerun-service-jobs` | — | |
| `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` |
-| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:<slug>:<id>), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). | |
+| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:<slug>:<id>), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | |
| `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | |
| `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | |
| `drop-saved-alternate` | drop-saved-alternate deletes one saved alternate of one video, as its "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}. "file" is a name `get saved-alternates` lists under "alternates"; the active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. | |
diff --git a/OPERATING.md b/OPERATING.md
@@ -60,7 +60,14 @@ pnpm ops get channel example
stops the listing but not the backlog, and a `paused` tier stops every lane, transcription too.
- `"fetchPlaylist": true` on `create-channel` stores the playlist at once (the form's "Fetch playlist now"); a social channel's is `"fetchPostsNow": true`.
- Rename or delete: `pnpm ops rename-channel --json '{"slug":"old","newSlug":"new"}'`,
- `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` — both refused while the channel is busy.
+ `pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'` — both refused while the channel is busy. A delete
+ takes the channel off every site that names it (pool and cited scope) and says which (`sitesUpdated`).
+- A site for it: `pnpm ops create-site --json '{"siteId":"example","siteTitle":"Examplealyzer","channels":["example"]}'`
+ — the New site form, private and unlisted unless `"audience": "public"` / `"listed": true`. An existing id is
+ refused; `"update": true` is the site page's Save with the keys given changed, every other key kept.
+- Its place in the queue: `pnpm ops channel-rank --json '{"slug":"example","top":true}'` (or `"bottom"`,
+ `"before"`/`"after": "<slug>"`, `"rank": <n>`, `"rank": null`) — the rank alone; /channels' "Add to top" also
+ sets the tier to normal and turns the download lane on.
## Archive a new creator end to end, without interruptions
diff --git a/RUNNING_IN_DOCKER.md b/RUNNING_IN_DOCKER.md
@@ -224,6 +224,22 @@ of a YAML config file and a mandatory database. Templates are in
Both attach through Caddy's `forward_auth`. The overlays set
`ARCHILYZER_AUTH_MODE=forward` for you.
+**umtool answers writes only to the names it knows.** Its pages' writes --
+Save version and Open in draft, an ingredient's actions, every ⌘K command
+(`POST /api/cli`) -- are refused when the address the browser used is not
+this machine (`localhost`, `*.localhost`, `127.x`, `::1`): a page whose DNS
+name is re-pointed at the box (DNS rebinding) must not drive it. Caddy passes
+the address on, so reaching umtool as `http://192.168.1.20:8083`, a custom
+domain or a Tailscale name reads fine and refuses every write until you name it:
+
+```sh
+# .env — host names or IPs, comma-separated, no ports
+UMTOOL_ALLOWED_HOSTS=archive-box.lan,192.168.1.20,archive-box.tail1234.ts.net
+```
+
+On the host (`archilyzer service install`), set it in the unit's environment
+the same way. An SSH tunnel to `127.0.0.1:8083` needs nothing.
+
### The rail, and its escape hatch
```
diff --git a/common/controller/siteMemberships.test.ts b/common/controller/siteMemberships.test.ts
@@ -0,0 +1,56 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, stat } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { writeSite, type Site } from "../lib/site";
+import { dropChannelFromSites } from "./siteMemberships";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/siteMemberships.test.ts
+//
+// A deleted channel leaves no site naming it (9 Nov: `mooler` stayed in
+// efapalyzer's pool): the pool and the cited scope drop it, through writeSite;
+// a site that does not name it is not written.
+
+const site = (siteId: string, extra: Partial<Site> = {}): Site => ({
+ siteId,
+ siteTitle: siteId,
+ siteDescription: "",
+ headerTitle: siteId,
+ homeTagline: "",
+ groups: [{ id: "default", name: "All", selectedByDefault: true }],
+ defaultGroupId: "default",
+ channels: [],
+ ...extra,
+});
+
+test("drops the slug from every pool and cited scope; leaves other sites unwritten", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "ttb-site-drop-"));
+ const paths = { sitesDir: path.join(dir, "sites"), channelsDir: path.join(dir, "channels") } as Paths;
+ const file = (id: string) => path.join(paths.sitesDir, id, "site.json");
+ const read = async (id: string) => JSON.parse(await readFile(file(id), "utf8")) as Site;
+ try {
+ await writeSite(site("pool", { channels: [{ slug: "gone", order: 0 }, { slug: "kept", groupId: "default", order: 1 }] }), paths);
+ await writeSite(site("cites", { citedChannels: [{ slug: "gone" }, { slug: "other" }] }), paths);
+ await writeSite(site("only-cites", { citedChannels: [{ slug: "gone" }] }), paths);
+ await writeSite(site("untouched", { channels: [{ slug: "kept", order: 0 }] }), paths);
+ const untouchedAt = (await stat(file("untouched"))).mtimeMs;
+
+ const r = await dropChannelFromSites(paths, "gone");
+ assert.deepEqual(r, { updated: ["cites", "only-cites", "pool"], failed: [] });
+ assert.deepEqual((await read("pool")).channels, [{ slug: "kept", groupId: "default", order: 1 }]);
+ assert.deepEqual((await read("cites")).citedChannels, [{ slug: "other" }]);
+ assert.equal("citedChannels" in (await read("only-cites")), false, "an empty scope is not written");
+ assert.equal((await stat(file("untouched"))).mtimeMs, untouchedAt, "a site not naming it is not written");
+
+ assert.deepEqual(await dropChannelFromSites(paths, "gone"), { updated: [], failed: [] }, "a second pass finds none");
+ assert.deepEqual(await dropChannelFromSites({ ...paths, sitesDir: path.join(dir, "none") }, "gone"), {
+ updated: [],
+ failed: [],
+ });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/siteMemberships.ts b/common/controller/siteMemberships.ts
@@ -0,0 +1,48 @@
+import type { Paths } from "../lib/paths";
+import { getSite, listSiteIds, patchSite, type Site } from "../lib/site";
+
+// A DELETED CHANNEL LEAVES NO SITE NAMING IT (lane editor-gaps; 9 Nov:
+// deleting `mooler` left it in efapalyzer's site.json, fixed by hand). Every
+// site's pool (`channels`) and cited scope (`citedChannels`) drop the slug,
+// through the one site writer (writeSite), the way a rename re-points them
+// (renameChannel.ts, step 5), each as a patchSite under the site's lock. A
+// site that does not name it is not written.
+//
+// Best-effort per site, because the channel is already gone: a site whose
+// write is refused (its own file no longer valid) is named in `failed` with
+// the writer's sentence and the others still go through.
+export type SiteDropResult = {
+ updated: string[];
+ failed: { siteId: string; error: string }[];
+};
+
+export async function dropChannelFromSites(paths: Paths, slug: string): Promise<SiteDropResult> {
+ const result: SiteDropResult = { updated: [], failed: [] };
+ for (const siteId of [...listSiteIds(paths)].sort()) {
+ try {
+ // A cheap look first, so a site that does not name it is not written;
+ // the edit itself is a patch, read again INSIDE the site's lock, so a
+ // concurrent edit of the site (a Reports-tab pages patch) is not
+ // written over with this copy.
+ if (!namesChannel(getSite(siteId, paths), slug)) continue;
+ const saved = await patchSite(
+ siteId,
+ (current) => ({
+ channels: current.channels.filter((c) => c.slug !== slug),
+ citedChannels: (current.citedChannels ?? []).filter((c) => c.slug !== slug),
+ }),
+ paths,
+ );
+ if (saved) result.updated.push(siteId);
+ } catch (err) {
+ result.failed.push({ siteId, error: (err as Error).message });
+ }
+ }
+ return result;
+}
+
+function namesChannel(site: Site, slug: string): boolean {
+ return (
+ site.channels.some((c) => c.slug === slug) || (site.citedChannels ?? []).some((c) => c.slug === slug)
+ );
+}
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -144,6 +144,44 @@ export function isDownloadMode(v: unknown): v is DownloadMode {
// yt-dlp's `--sub-langs` when the channel names none.
export const DEFAULT_SUB_LANGS = "en.*,live_chat";
+// THE FORM'S CHECK OF A `subLangs` VALUE. yt-dlp splits `--sub-langs` on
+// commas and matches each entry — a regex, or `all` — against a track's
+// language; a leading `-` excludes. A value it cannot use fails every caption
+// download on the channel at the moment it runs, so Configure and
+// `channel-config` refuse it at the save instead: an empty entry (two commas,
+// or one at an end), a space inside an entry, an entry that is not a regular
+// expression, a value over 200 characters. Spaces AROUND an entry are not a
+// problem: `normalizeSubLangs` drops them.
+export const SUB_LANGS_MAX_LENGTH = 200;
+
+export function normalizeSubLangs(value: string): string {
+ return value
+ .split(",")
+ .map((x) => x.trim())
+ .join(",");
+}
+
+export function subLangsProblem(value: string): string | null {
+ const v = normalizeSubLangs(value.trim());
+ if (!v) return null;
+ if (v.length > SUB_LANGS_MAX_LENGTH) {
+ return `is ${v.length} characters; at most ${SUB_LANGS_MAX_LENGTH}`;
+ }
+ for (const entry of v.split(",")) {
+ if (!entry) return `has an empty entry (two commas, or one at an end)`;
+ if (/\s/.test(entry)) return `entry "${entry}" has a space in it — entries are separated by commas`;
+ const pattern = entry.startsWith("-") ? entry.slice(1) : entry;
+ if (!pattern) return `entry "-" excludes nothing — a "-" goes before a language, e.g. -live_chat`;
+ if (pattern === "all") continue;
+ try {
+ new RegExp(`^(?:${pattern})$`);
+ } catch (e) {
+ return `entry "${entry}" is not a valid regular expression: ${(e as Error).message}`;
+ }
+ }
+ return null;
+}
+
// The `--sub-langs` a caption download passes: the channel's (or the
// default), WITHOUT the live chat unless `chat` fetches it with the download.
// An entry that is `live_chat` itself is dropped; one that would still match
diff --git a/common/lib/channelPriority.ts b/common/lib/channelPriority.ts
@@ -635,6 +635,113 @@ export function renameChannelInPriority(
return { focus, channels };
}
+// --- Placing one channel's rank ---------------------------------------------
+
+// WHERE A CHANNEL GOES IN THE ORDER (`pnpm ops channel-rank`). The model has
+// ONE rank per channel, ascending, unranked after every ranked channel (then by
+// slug) — the same order inside every tier group (`orderWithin`). A placement
+// moves one channel and leaves the order of every other exactly as it was:
+//
+// rank n the channel takes rank n, before any channel holding it;
+// top / bottom before every ranked channel / after every ranked channel;
+// before / after immediately before / after another RANKED channel, a tie
+// on its rank included (an unranked one has no place to be
+// next to — refused);
+// unrank the rank removed: last in its tier, by slug.
+//
+// Only the rank moves. Unlike "Add to top" (the deck's promote, which also
+// sets the tier to normal and turns the download lane on), a placement never
+// changes a tier, an override, a focus or an auto-pause.
+export type RankPlacement =
+ | { kind: "rank"; rank: number }
+ | { kind: "top" }
+ | { kind: "bottom" }
+ | { kind: "before"; slug: string }
+ | { kind: "after"; slug: string }
+ | { kind: "unrank" };
+
+// A placement the document cannot carry out, in the words the caller sees.
+export class RankPlacementError extends Error {}
+
+export function placeChannelRank(
+ model: ChannelPriority,
+ rawSlug: string,
+ place: RankPlacement,
+): ChannelPriority {
+ const slug = rawSlug.trim();
+ if (!slug) throw new RankPlacementError("No channel slug supplied.");
+ const current = model.channels[slug];
+ if (place.kind === "unrank") {
+ if (current?.rank === undefined) return model;
+ const { rank: _dropped, ...rest } = current;
+ return { ...model, channels: { ...model.channels, [slug]: rest } };
+ }
+ // The other ranked channels in the order the lanes take them (rank, then
+ // slug — orderWithin's rule), and where in that list this one goes.
+ const others = rankedOrder(model).filter((r) => r.slug !== slug);
+ let at: number;
+ let rank: number;
+ if (place.kind === "rank") {
+ if (!Number.isInteger(place.rank) || place.rank < 0) {
+ throw new RankPlacementError(`A rank is a whole number, 0 or more (0 = first); got ${place.rank}.`);
+ }
+ // Before every channel already holding that rank or a later one.
+ at = others.findIndex((r) => r.rank >= place.rank);
+ if (at < 0) at = others.length;
+ rank = place.rank;
+ } else if (place.kind === "top") {
+ at = 0;
+ rank = others[0]?.rank ?? 0;
+ } else if (place.kind === "bottom") {
+ at = others.length;
+ rank = others.length ? others[others.length - 1].rank + 1 : 0;
+ } else {
+ const anchor = place.slug.trim();
+ if (anchor === slug) {
+ throw new RankPlacementError(`"${slug}" cannot be placed ${place.kind} itself.`);
+ }
+ const i = others.findIndex((r) => r.slug === anchor);
+ if (i < 0) {
+ throw new RankPlacementError(
+ `"${anchor}" has no rank, so there is no place ${place.kind} it — rank it first ` +
+ `(top, bottom or a rank), or place "${slug}" by rank.`,
+ );
+ }
+ if (place.kind === "before") {
+ at = i;
+ rank = i > 0 ? others[i - 1].rank + 1 : others[i].rank;
+ } else {
+ at = i + 1;
+ rank = others[i].rank + 1;
+ }
+ }
+ // Strictly after the channel before it, so a tie never reorders it by slug.
+ if (at > 0) rank = Math.max(rank, others[at - 1].rank + 1);
+ // Every channel after it moves down only as far as it must to stay after
+ // it and after the one before it, and two that were tied stay tied — so the
+ // order of the rest is kept exactly.
+ const channels: Record<string, ChannelPriorityEntry> = { ...model.channels };
+ let floor = rank;
+ let prevOld: number | null = null;
+ for (const r of others.slice(at)) {
+ // Tied with the one before it (and so after it by slug): tied still.
+ const next: number = prevOld !== null && r.rank === prevOld ? floor : r.rank > floor ? r.rank : floor + 1;
+ if (next !== r.rank) channels[r.slug] = { ...model.channels[r.slug], rank: next };
+ prevOld = r.rank;
+ floor = next;
+ }
+ channels[slug] = { ...(current ?? { tier: DEFAULT_CHANNEL_TIER }), rank };
+ return { ...model, channels };
+}
+
+// The ranked channels in the order the lanes take them: rank, then slug.
+export function rankedOrder(model: ChannelPriority): { slug: string; rank: number }[] {
+ return Object.entries(model.channels)
+ .filter(([, e]) => e.rank !== undefined)
+ .map(([slug, e]) => ({ slug, rank: e.rank as number }))
+ .sort((a, b) => a.rank - b.rank || a.slug.localeCompare(b.slug));
+}
+
export function tierOrder(tier: ChannelTier): number {
const i = CHANNEL_TIERS.indexOf(tier);
return i < 0 ? CHANNEL_TIERS.length : i;
diff --git a/common/lib/channelRank.test.ts b/common/lib/channelRank.test.ts
@@ -0,0 +1,99 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ placeChannelRank,
+ rankedOrder,
+ RankPlacementError,
+ sanitizeChannelPriority,
+ type ChannelPriority,
+} from "./channelPriority";
+
+// `pnpm ops channel-rank`: one channel moved in the ONE order; every other
+// channel's order kept exactly; nothing but the rank changes.
+const doc = (channels: ChannelPriority["channels"]): ChannelPriority => ({ focus: { kind: "none" }, channels });
+const order = (m: ChannelPriority) => rankedOrder(m).map((r) => r.slug);
+const ABC = doc({
+ a: { tier: "normal", rank: 0 },
+ b: { tier: "low", rank: 1, overrides: { sync: "normal" } },
+ c: { tier: "normal", rank: 2 },
+ u: { tier: "paused", overrides: { sync: "normal" } },
+});
+
+test("top and bottom: first and last of the ranked channels; tier and overrides untouched", () => {
+ const top = placeChannelRank(ABC, "c", { kind: "top" });
+ assert.deepEqual(order(top), ["c", "a", "b"]);
+ assert.deepEqual(top.channels.b, { tier: "low", rank: 2, overrides: { sync: "normal" } });
+ const bottom = placeChannelRank(ABC, "a", { kind: "bottom" });
+ assert.deepEqual(order(bottom), ["b", "c", "a"]);
+ assert.equal(bottom.channels.a.rank, 3, "after the last rank; nothing else shifts");
+ assert.equal(bottom.channels.b.rank, 1);
+ // An unranked channel taken to the top keeps its tier and overrides.
+ const u = placeChannelRank(ABC, "u", { kind: "top" });
+ assert.deepEqual(order(u), ["u", "a", "b", "c"]);
+ assert.deepEqual(u.channels.u, { tier: "paused", overrides: { sync: "normal" }, rank: 0 });
+ // A channel with no entry at all gets one, at the default tier.
+ assert.deepEqual(placeChannelRank(ABC, "new", { kind: "bottom" }).channels.new, { tier: "normal", rank: 3 });
+ // Nothing ranked: top and bottom are both rank 0.
+ assert.equal(placeChannelRank(doc({}), "x", { kind: "top" }).channels.x.rank, 0);
+ assert.equal(placeChannelRank(doc({}), "x", { kind: "bottom" }).channels.x.rank, 0);
+});
+
+test("before and after another ranked channel", () => {
+ assert.deepEqual(order(placeChannelRank(ABC, "a", { kind: "before", slug: "c" })), ["b", "a", "c"]);
+ assert.deepEqual(order(placeChannelRank(ABC, "c", { kind: "after", slug: "a" })), ["a", "c", "b"]);
+ assert.deepEqual(order(placeChannelRank(ABC, "a", { kind: "after", slug: "c" })), ["b", "c", "a"]);
+ assert.deepEqual(order(placeChannelRank(ABC, "u", { kind: "before", slug: "a" })), ["u", "a", "b", "c"]);
+ assert.throws(
+ () => placeChannelRank(ABC, "a", { kind: "before", slug: "u" }),
+ (e: Error) => e instanceof RankPlacementError && /"u" has no rank, so there is no place before it/.test(e.message),
+ );
+ assert.throws(() => placeChannelRank(ABC, "a", { kind: "after", slug: "a" }), /cannot be placed after itself/);
+});
+
+test("rank n: taken pushes it and everything below down one; free takes the gap; unrank removes it", () => {
+ const taken = placeChannelRank(ABC, "c", { kind: "rank", rank: 1 });
+ assert.deepEqual(order(taken), ["a", "c", "b"]);
+ assert.deepEqual(rankedOrder(taken), [
+ { slug: "a", rank: 0 },
+ { slug: "c", rank: 1 },
+ { slug: "b", rank: 2 },
+ ]);
+ const gap = placeChannelRank(doc({ a: { tier: "normal", rank: 0 }, c: { tier: "normal", rank: 10 } }), "b", {
+ kind: "rank",
+ rank: 5,
+ });
+ assert.deepEqual(rankedOrder(gap), [
+ { slug: "a", rank: 0 },
+ { slug: "b", rank: 5 },
+ { slug: "c", rank: 10 },
+ ]);
+ assert.throws(() => placeChannelRank(ABC, "a", { kind: "rank", rank: -1 }), /a whole number, 0 or more/);
+ assert.throws(() => placeChannelRank(ABC, "a", { kind: "rank", rank: 1.5 }), /a whole number, 0 or more/);
+ const un = placeChannelRank(ABC, "b", { kind: "unrank" });
+ assert.deepEqual(order(un), ["a", "c"]);
+ assert.deepEqual(un.channels.b, { tier: "low", overrides: { sync: "normal" } });
+ // A channel whose entry said only its rank is dropped by the sanitizer.
+ assert.equal(sanitizeChannelPriority(placeChannelRank(ABC, "a", { kind: "unrank" })).channels.a, undefined);
+ assert.equal(placeChannelRank(ABC, "u", { kind: "unrank" }), ABC, "nothing to remove: the input");
+});
+
+test("ties: after X lands immediately after X, before its tie partners, and ties below stay tied", () => {
+ const tied = doc({
+ a: { tier: "normal", rank: 0 },
+ x: { tier: "normal", rank: 0 },
+ y: { tier: "normal", rank: 0 },
+ p: { tier: "normal", rank: 3 },
+ q: { tier: "normal", rank: 3 },
+ });
+ assert.deepEqual(order(tied), ["a", "x", "y", "p", "q"]);
+ assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "after", slug: "a" })), ["a", "z", "x", "y", "p", "q"]);
+ assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "after", slug: "x" })), ["a", "x", "z", "y", "p", "q"]);
+ assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "before", slug: "y" })), ["a", "x", "z", "y", "p", "q"]);
+ assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "before", slug: "a" })), ["z", "a", "x", "y", "p", "q"]);
+ const moved = placeChannelRank(tied, "z", { kind: "after", slug: "a" });
+ assert.equal(moved.channels.x.rank, moved.channels.y.rank, "x and y were tied and stay tied");
+ assert.equal(moved.channels.p.rank, 3, "a channel already far enough down does not move");
+ assert.equal(moved.channels.p.rank, moved.channels.q.rank);
+ // Moving a channel out of a tie.
+ assert.deepEqual(order(placeChannelRank(tied, "a", { kind: "after", slug: "y" })), ["x", "y", "a", "p", "q"]);
+});
diff --git a/common/lib/liveNow-server.ts b/common/lib/liveNow-server.ts
@@ -0,0 +1,25 @@
+import path from "node:path";
+import { readFile } from "node:fs/promises";
+import { liveDownloadRefusal, liveNowState, type LiveNowState } from "./liveNow";
+
+// The live state a video's metadata.info.json records (lib/liveNow.ts), null
+// when it records none — or there is no readable record, which says nothing
+// either way: a download is not refused on a guess.
+export async function readLiveNowState(videoDir: string): Promise<LiveNowState | null> {
+ try {
+ const meta = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")) as unknown;
+ return liveNowState(meta as Parameters<typeof liveNowState>[0]);
+ } catch {
+ return null;
+ }
+}
+
+// The refusal for a download of this video, or null when its record says it
+// is not a stream in progress.
+export async function liveDownloadRefusalFor(
+ videoDir: string,
+ ids: { slug: string; videoId: string },
+): Promise<string | null> {
+ const state = await readLiveNowState(videoDir);
+ return state ? liveDownloadRefusal(state, ids) : null;
+}
diff --git a/common/lib/liveNow.test.ts b/common/lib/liveNow.test.ts
@@ -0,0 +1,53 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { liveDownloadRefusal, liveNowState } from "./liveNow";
+import { liveDownloadRefusalFor, readLiveNowState } from "./liveNow-server";
+
+test("liveNowState: is_live, is_upcoming and post_live are streams in progress; was_live and not_live are not", () => {
+ assert.equal(liveNowState({ live_status: "is_live" }), "is_live");
+ assert.equal(liveNowState({ live_status: "is_upcoming" }), "is_upcoming");
+ assert.equal(liveNowState({ live_status: "post_live" }), "post_live");
+ assert.equal(liveNowState({ live_status: "was_live" }), null, "a finished VOD downloads normally");
+ assert.equal(liveNowState({ live_status: "not_live" }), null);
+ assert.equal(liveNowState({}), null);
+ assert.equal(liveNowState(null), null);
+ // The boolean alone (an older record), and a status that overrules it.
+ assert.equal(liveNowState({ is_live: true }), "is_live");
+ assert.equal(liveNowState({ is_live: true, live_status: "was_live" }), null, "the newer field wins");
+ assert.equal(liveNowState({ is_live: "yes" }), null, "only a real true");
+});
+
+test("liveDownloadRefusal names record-live and refresh-metadata with runnable bodies", () => {
+ const ids = { slug: "demo-yt", videoId: "abcdefghijk" };
+ const live = liveDownloadRefusal("is_live", ids);
+ assert.match(live, /^abcdefghijk is live now \(live_status is_live\)/);
+ assert.match(live, /at 1x/);
+ assert.ok(live.includes(`pnpm ops record-live --json '{"slug":"demo-yt","id":"abcdefghijk"}'`), live);
+ assert.ok(live.includes(`pnpm ops refresh-metadata --json '{"slug":"demo-yt","id":"abcdefghijk"}'`), live);
+ assert.match(live, /wait for the VOD/);
+ assert.match(liveDownloadRefusal("is_upcoming", ids), /scheduled stream that has not started/);
+ const post = liveDownloadRefusal("post_live", ids);
+ assert.match(post, /VOD is still being processed/);
+ assert.equal(post.includes("record-live"), false, "an ended stream is not recorded");
+});
+
+test("readLiveNowState reads metadata.info.json; no record (or junk) is no answer", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "live-now-"));
+ try {
+ const dir = path.join(root, "v1");
+ await mkdir(dir);
+ assert.equal(await readLiveNowState(dir), null);
+ await writeFile(path.join(dir, "metadata.info.json"), "{not json");
+ assert.equal(await readLiveNowState(dir), null);
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "v1", live_status: "is_live" }));
+ assert.equal(await readLiveNowState(dir), "is_live");
+ assert.match((await liveDownloadRefusalFor(dir, { slug: "s", videoId: "v1" })) ?? "", /v1 is live now/);
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "v1", live_status: "was_live" }));
+ assert.equal(await liveDownloadRefusalFor(dir, { slug: "s", videoId: "v1" }), null);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/liveNow.ts b/common/lib/liveNow.ts
@@ -0,0 +1,65 @@
+// IS THIS VIDEO A STREAM THAT HAS NOT FINISHED? — and the sentence a
+// download-for-transcription says when it is.
+//
+// A one-video download of a video that is live reads the HLS at 1x: yt-dlp
+// follows the stream until it ends, and the platform's queue is held for the
+// stream's whole length (4 Nov: a transcribe-one on a live YouTube video sat
+// on platform:youtube for hours). Such a video is recorded by record-live, or
+// transcribed once its VOD exists — never downloaded as a finished video.
+//
+// What a download already knows is the video's metadata.info.json (yt-dlp's
+// `is_live` / `live_status`, the same fields skip-live and record-live read).
+// It is a snapshot: a stream that has ended since still says `is_live` until
+// the record is re-read, which is why the sentence names refresh-metadata.
+//
+// The three states are record-live's LIVE_STATES: `is_live`, `is_upcoming`
+// (scheduled, not started) and `post_live` (ended; its VOD is still being
+// processed and a download of it now is the stream's fragments, or an
+// incomplete file). `was_live` is a finished VOD and downloads normally.
+
+export type LiveNowState = "is_live" | "is_upcoming" | "post_live";
+
+export type LiveFields = {
+ is_live?: unknown;
+ live_status?: unknown;
+};
+
+export function liveNowState(meta: LiveFields | null | undefined): LiveNowState | null {
+ if (!meta || typeof meta !== "object") return null;
+ const status = typeof meta.live_status === "string" ? meta.live_status : "";
+ if (status === "is_live" || status === "is_upcoming" || status === "post_live") return status;
+ // An extractor that sets only the boolean (older records, some platforms).
+ // A `live_status` that says otherwise wins: it is the newer field.
+ if (meta.is_live === true && (status === "" || status === "is_live")) return "is_live";
+ return null;
+}
+
+// The refusal. `slug` and `videoId` make the two commands it names runnable
+// as they stand.
+export function liveDownloadRefusal(
+ state: LiveNowState,
+ { slug, videoId }: { slug: string; videoId: string },
+): string {
+ const body = JSON.stringify({ slug, id: videoId });
+ const record = `pnpm ops record-live --json '${body}'`;
+ const refresh = `pnpm ops refresh-metadata --json '${body}'`;
+ if (state === "is_upcoming") {
+ return (
+ `${videoId} is a scheduled stream that has not started (live_status is_upcoming): there is nothing to ` +
+ `transcribe yet. Record it from its start with record-live (${record}), or wait for the VOD; once it has ` +
+ `aired, ${refresh} re-reads its record.`
+ );
+ }
+ if (state === "post_live") {
+ return (
+ `${videoId}'s stream has ended but its VOD is still being processed (live_status post_live): a download now ` +
+ `reads the stream's fragments, not the finished video. Wait for the VOD; ${refresh} re-reads its record ` +
+ `once it is ready.`
+ );
+ }
+ return (
+ `${videoId} is live now (live_status is_live): a download would read the stream at 1x and hold the ` +
+ `platform's queue for as long as it runs. Record it with record-live (${record}), or wait for the VOD; ` +
+ `once it has ended, ${refresh} re-reads its record.`
+ );
+}
diff --git a/common/lib/site.ts b/common/lib/site.ts
@@ -307,6 +307,20 @@ export async function writeSite(
// interleave. A function patch is given the site as it is now (to reorder a
// list it did not read itself). Validated and written by writeSite. Null when
// the site has no site.json: a patch never creates a site.
+// THE SITE FILE'S LOCK: a read-modify-write of one site.json that must not
+// interleave with another (patchSite, the site form's save). Per process; NOT
+// re-entrant — never patchSite from inside it. writeSite does not take it.
+export function withSiteLock<T>(
+ siteId: string,
+ fn: () => Promise<T>,
+ paths: Paths = getPaths(),
+): Promise<T> {
+ if (!isValidSiteId(siteId)) {
+ throw new Error(`Invalid site id: ${String(siteId)}`);
+ }
+ return withJsonFileLock(siteConfigFile(paths, siteId), fn);
+}
+
export async function patchSite(
siteId: string,
patch:
@@ -318,7 +332,7 @@ export async function patchSite(
throw new Error(`Invalid site id: ${String(siteId)}`);
}
const file = siteConfigFile(paths, siteId);
- return withJsonFileLock(file, async () => {
+ return withSiteLock(siteId, async () => {
if (!fs.existsSync(file)) return null;
const current = getSite(siteId, paths);
const changes = typeof patch === "function" ? patch(current) : patch;
diff --git a/common/lib/subLangs.test.ts b/common/lib/subLangs.test.ts
@@ -0,0 +1,22 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { normalizeSubLangs, SUB_LANGS_MAX_LENGTH, subLangsProblem } from "./channelConfig";
+
+// Configure's caption languages (subLangs): what yt-dlp's --sub-langs can use
+// is saved; what would fail every caption download is refused at the save.
+test("subLangsProblem accepts yt-dlp's forms: regexes, all, exclusions, spaces around entries", () => {
+ for (const ok of ["en.*", "en.*,live_chat", "all,-live_chat", "en,es,fr", "en-US", "en(-GB)?", " en.* , es ", ""]) {
+ assert.equal(subLangsProblem(ok), null, ok);
+ }
+ assert.equal(normalizeSubLangs(" en.* , es "), "en.*,es");
+});
+
+test("subLangsProblem refuses an empty entry, a space inside an entry, a bare dash, a bad regex, an over-long value", () => {
+ assert.match(subLangsProblem("en,,es") ?? "", /has an empty entry/);
+ assert.match(subLangsProblem("en,") ?? "", /has an empty entry/);
+ assert.match(subLangsProblem("en us") ?? "", /entry "en us" has a space in it/);
+ assert.match(subLangsProblem("en,-") ?? "", /entry "-" excludes nothing/);
+ assert.match(subLangsProblem("en(") ?? "", /entry "en\(" is not a valid regular expression/);
+ assert.match(subLangsProblem("-[") ?? "", /entry "-\[" is not a valid regular expression/);
+ assert.match(subLangsProblem("e".repeat(SUB_LANGS_MAX_LENGTH + 1)) ?? "", /at most 200/);
+});
diff --git a/docker-compose.yml b/docker-compose.yml
@@ -216,6 +216,9 @@ services:
environment:
<<: *app-env
UMTOOL_CACHE_DIR: /data/builds/umtool-cache
+ # The names umtool is reached by besides localhost (a LAN IP, a domain,
+ # a Tailscale name): its pages' writes are refused from any other.
+ UMTOOL_ALLOWED_HOSTS: ${UMTOOL_ALLOWED_HOSTS:-}
volumes:
- corpus:/data/transcripts
- config:/data/config
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,11 @@
# Changelog
## [Unreleased]
+- **Deleting a channel takes it off every site.** On 9 Nov, deleting `mooler` left it in efapalyzer's `site.json`, and the site had to be fixed by hand. Danger → Delete and `pnpm ops delete-channel` now rewrite every site whose pool (`channels`) or cited scope (`citedChannels`) names the deleted channel, each as a `patchSite` under that site's lock, so a concurrent edit of the site is not written over (a rename already re-points them through the same writer). The ops answer names those sites in `sitesUpdated`. A site whose write is refused shows up as a `warnings` line, and the delete still stands. Sites that never named the channel are not written (`common/controller/siteMemberships.ts`).
+- **`pnpm ops create-site` is the New site form, without a browser.** On 9 Nov an agent had to call `writeSite` from a tsx script to make `efapalyzer`. `create-site` takes `{"siteId", "siteTitle"}` and any of the form's fields: header title (default the title), description, tagline, wordmark lead, accent, public URL, Pages project, hub URL, audience, listed, publish policy, search, archives, duplicates, transcript downloads, PWA, archive cap, groups, default group, channels, cited channels, social links and related sites. It builds the FormData the form posts and saves it through the form's own action (`saveSiteAction` → `writeSite`), so you get the same validation and the same sentences. A new site is **private and unlisted** unless the body says `"audience": "public"` / `"listed": true`. An existing id is refused (409) unless `"update": true`, which is the site page's Save with only the given keys changed; every other key, and the published page list, is kept. Unknown channels, a channel's `groupId` that names none of the site's groups, unknown keys and keys of the wrong type are refused before anything is written. The existence check, the read of the stored site and the save are one read-modify-write under the site's lock (`withSiteLock`). The site form's own Save now takes the same lock, so neither it nor an update is written over a concurrent edit such as a Reports-tab pages patch. It answers the saved site.
+- **`pnpm ops channel-rank` places one channel in the order the lanes follow.** Before this, only /channels' "Add to top" moved a channel, and it also sets the tier to normal and turns the download lane on. `channel-rank` moves the rank alone: `{"slug"}` plus exactly one of `"rank": <n>` (or `null` to unrank), `"top": true`, `"bottom": true`, `"before": "<slug>"` or `"after": "<slug>"`. Every other channel keeps its order: channels after it move down only as far as they must, ties stay tied, and `after` lands immediately after its anchor even when the anchor's rank is tied. It goes through the deck's one writer, so the four lane roots are recompiled in the same write. That writer now does its read-modify-write inside a settings lock, which every `saveSettings` takes too, so a concurrent deck save or a parallel `channel-rank` is never written over. Refused before any write: an unknown channel or anchor, an anchor with no rank, a rank that is not a whole number ≥ 0, and a channel paused for every operation (its rank would not be kept). It answers the saved rank and the whole ranked order (`common/lib/channelPriority.ts` `placeChannelRank`).
+- **Configure's Caption languages field (`subLangs`) is checked when you save.** Before, any text was saved, and a value yt-dlp's `--sub-langs` cannot use failed every caption download on the channel at the moment it ran. Configure and `pnpm ops channel-config` (`patch.subLangs`) now refuse it, in the field's words, with what you typed kept. Refused: an empty entry (two commas, or one at an end), a space inside an entry, a bare `-`, an entry that is not a regular expression, or a value over 200 characters. Spaces around an entry are dropped (`en.* , es` saves as `en.*,es`). A value saved before this check and submitted unchanged is kept, with a warning in the server log, so Configure is never locked on it. `all` and `-<lang>` exclusions are accepted as before (`common/lib/channelConfig.ts` `subLangsProblem`).
+- **Transcribe refuses a video that is live.** On 4 Nov a transcribe-one on a live YouTube video downloaded the stream at 1x and held `platform:youtube` for the stream's whole length. Now the video page's Transcribe and `pnpm ops transcribe-one` refuse a video whose `metadata.info.json` says it is live (`is_live`), scheduled (`is_upcoming`) or still processing its VOD (`post_live`), before anything is queued. The refusal names `pnpm ops record-live` for the stream (not for `post_live`), says to wait for the VOD otherwise, and names `refresh-metadata` to re-read the record once the stream has ended. The job checks again just before its download, in case the record was re-read while it waited. Only the audio download is refused: a video whose audio or container is already on disk still transcribes, and a youtube-handling video with English captions listed still has its captions fetched instead. A finished stream (`was_live`) downloads as before (`common/lib/liveNow.ts`).
- **The X run console: several X channels' posts fetched as one job that stops when the cookies go stale.** On 8 and 9 Nov an agent ran X fetch-posts by hand, one channel after another, watching the cookie jar age and putting off the rest once it went stale. `/review`'s new **X run** section lists the X posts channels in priority order (focus, tier, rank; paused ones unticked), with a tick and up/down buttons for each, and **Start X run** queues ONE `x-run` job on X's queue. The job fetches each channel in turn (new posts only, at most 200 each), waits X's queue gap (`pacing.jobGapSeconds.twitter`) between two channels, and checks the cookie jar again before EACH one. Once the jar is past `social.x.maxCookieAgeMinutes`, or the X alert is up, the run stops and the rest are **deferred until the next refresh**. It never refreshes cookies itself. The console shows each channel's state (queued, running, done with its new posts, deferred, failed), "N done, M deferred until the next refresh", the jar's age counted down to the limit, and the wait before the next channel. **Resume** runs the deferred channels after the operator presses Refresh cookies on /settings. A Retry of the job, and "Re-run stopped jobs", do the same. A restart does not resume a run: an interrupted run ends deferred. `pnpm ops x-run {"channels": [...]}` / `{"resume": "<run id>"}` and `pnpm ops get x-run` do the same from a terminal.
- **Account activity on a posts channel's page: posts per day, with the long silences marked.** A compact bar strip shows posts per UTC day over the archive's range. Long silences are shaded and listed: a gap of at least 3× the account's median gap AND 48 h, each linked to the post before it and the post after. An open-ended silence since the last post is listed too, when the last fetch came that long after it. Only the account's own posts count (a with-replies timeline also archives the posts it answers). The silence is the archive's ("no archived post"), and a stretch no fetch reached looks the same. Mr Obvious's 5–8 Nov gap reads 4 Nov 10:54 → 8 Nov 19:00 UTC on ObviousRises-x.
- **umtool: each character has a voice, auditioned on a page, the same in every project.** The operator wanted to "pick different voices for different characters, and in UI alone be able to try rendering different ones to compare … and try to maintain consistent voices for different repeating characters" -- tonight TheQuartering's reads were re-voiced by hand after scoring five voices against his real one. `/projects/<p>/voices` (from the Cut tab's Reads and voices) lists every character a project's reads use, the voice each reads in now and where it comes from (the cast, the project, the narrator's, the default), its reads in another voice, and its real voice. **Audition** reads one line (its own words here, a stock line, or typed) in 2-6 stock voices -- a job: the editor's tts, then each one's closeness to the real voice (speakers.json, TitaNet, local) -- played side by side at one loudness beside the real voice, a reference never a target. **Use for this project** or **Use everywhere** (the cast, `<reports>/.umtool/cast.json`), then the items to re-read, queued. A recording of an item can be made a character's read: kept, cleaned, converted to its stock voice. Every read -- a single post's and each piece of a thread read -- asks the same order (the read's own, the project's map, the cast, the narrator's, the default), and a cast voice of another engine is synthesized by it. `umtool cast ls|add|set|rm|undo|project|audition|use|reread`, `posts narrate … --recording`, and `umtool lint` warns when a cast character is read in another voice.
diff --git a/editor/app/api/ops/channel-rank/route.test.ts b/editor/app/api/ops/channel-rank/route.test.ts
@@ -0,0 +1,64 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { setupOpsCorpus, callPost } from "../_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/channel-rank/route.test.ts"
+//
+// `channel-rank`: one channel placed in the order through the deck's one
+// writer. Every REFUSAL here is answered before anything is written; the
+// writes end in revalidatePath, which a bare tsx process has no request store
+// for, so they are driven over HTTP in e2e/ops-api.spec.ts.
+
+const corpus = await setupOpsCorpus(null);
+for (const slug of ["alpha", "beta", "gamma", "off"]) {
+ await corpus.writeChannelConfig(slug, { url: `https://www.youtube.com/@${slug}` });
+}
+await corpus.writeSettings({
+ channelPriority: {
+ focus: { kind: "none" },
+ channels: { alpha: { tier: "normal", rank: 0 }, beta: { tier: "normal", rank: 1 }, off: { tier: "paused" } },
+ },
+});
+const { POST } = await import("./route");
+test.after(() => corpus.cleanup());
+const settingsText = () => readFile(corpus.settingsFile, "utf8");
+
+test("exactly one placement, of the right type; unknown keys refused", async () => {
+ const before = await settingsText();
+ for (const [body, re] of [
+ [{ slug: "alpha" }, /give exactly one placement/],
+ [{ slug: "alpha", top: true, bottom: true }, /give exactly one placement .*; got "top", "bottom"/],
+ [{ slug: "alpha", rank: -1 }, /"rank" must be a whole number, 0 or more/],
+ [{ slug: "alpha", rank: 1.5 }, /"rank" must be a whole number/],
+ [{ slug: "alpha", rank: "2" }, /"rank" must be a whole number/],
+ [{ slug: "alpha", top: false }, /"top" must be true/],
+ [{ slug: "alpha", before: "../x" }, /not a valid channel slug/],
+ [{ slug: "alpha", first: true }, /first/],
+ ] as const) {
+ const r = await callPost(POST, body);
+ assert.equal(r.status, 400, JSON.stringify(body));
+ assert.match(String(r.body.error), re, JSON.stringify(r.body));
+ }
+ assert.equal(await settingsText(), before, "nothing written");
+});
+
+test("an unknown channel is a 404; an unknown anchor, an unranked anchor, a paused-everywhere channel are refused", async () => {
+ const before = await settingsText();
+ const missing = await callPost(POST, { slug: "nope", top: true });
+ assert.equal(missing.status, 404);
+ assert.match(String(missing.body.error), /Channel "nope" not found/);
+ const anchor = await callPost(POST, { slug: "alpha", after: "nope" });
+ assert.equal(anchor.status, 400);
+ assert.match(String(anchor.body.error), /Channel "nope" not found \(the "after" anchor\)/);
+ const unranked = await callPost(POST, { slug: "alpha", before: "gamma" });
+ assert.equal(unranked.status, 400);
+ assert.match(String(unranked.body.error), /"gamma" has no rank, so there is no place before it/);
+ const self = await callPost(POST, { slug: "beta", after: "beta" });
+ assert.match(String(self.body.error), /cannot be placed after itself/);
+ const paused = await callPost(POST, { slug: "off", top: true });
+ assert.equal(paused.status, 400);
+ assert.match(String(paused.body.error), /"off" is paused for every operation/);
+ assert.equal(await settingsText(), before, "nothing written");
+});
diff --git a/editor/app/api/ops/channel-rank/route.ts b/editor/app/api/ops/channel-rank/route.ts
@@ -0,0 +1,85 @@
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import {
+ rankOf,
+ rankedOrder,
+ type RankPlacement,
+} from "yt-dlp-transcript-common/lib/channelPriority";
+import { channelExists } from "yt-dlp-transcript-common/controller/channels";
+import { setChannelRankAction } from "../../../channels/actions";
+import { OpsInputError, ops, opsFail, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, rank: <n> | null } | { slug, top: true } | { slug, bottom: true }
+// | { slug, before: <slug> } | { slug, after: <slug> }
+// -> { ok, slug, rank, order: [{slug, rank}, …] }
+//
+// ONE CHANNEL PLACED IN THE ORDER — the rank inside its tier that every lane
+// and the sync scheduler follow (one rank per channel; unranked after every
+// ranked channel, then by slug). Before this only /channels' "Add to top"
+// moved a channel, and it also sets the tier to normal and turns the download
+// lane on. This moves the rank alone, through the deck's one writer
+// (saveChannelPriorityAction), which recompiles the four lane roots in the
+// same write, under the settings lock. Every other channel keeps its order:
+// the ones after it move down only as far as they must, ties stay tied.
+//
+// Exactly one placement. `rank: null` removes the rank. Refused before any
+// write: an unknown channel or anchor, an anchor with no rank (nothing to be
+// next to), a rank that is not a whole number ≥ 0, a channel paused for every
+// operation (it is in no order; its rank would not be kept).
+// The answer is the saved rank and the whole ranked order.
+const PLACEMENTS = ["rank", "top", "bottom", "before", "after"] as const;
+
+export async function POST(request: Request) {
+ return ops(request, ["slug", ...PLACEMENTS], async (body) => {
+ const slug = reqSlug(body, "slug");
+ const given = PLACEMENTS.filter((k) => body[k] !== undefined);
+ if (given.length !== 1) {
+ throw new OpsInputError(
+ `give exactly one placement — "rank" (a number, or null to unrank), "top": true, "bottom": true, ` +
+ `"before": "<slug>" or "after": "<slug>"${given.length ? `; got ${given.map((k) => `"${k}"`).join(", ")}` : ""}`,
+ );
+ }
+ const paths = getPaths();
+ if (!(await channelExists(paths, slug))) {
+ return opsFail(`Channel "${slug}" not found`, 404);
+ }
+ const place = await readPlacement(body, given[0], async (anchor) => {
+ if (!(await channelExists(paths, anchor))) {
+ throw new OpsInputError(`Channel "${anchor}" not found (the "${given[0]}" anchor)`);
+ }
+ });
+ const result = await setChannelRankAction(slug, place);
+ if (result?.error) return opsFail(result.error);
+ const saved = getSettings().channelPriority;
+ return NextResponse.json({ ok: true, slug, rank: rankOf(saved, slug), order: rankedOrder(saved) });
+ });
+}
+
+async function readPlacement(
+ body: Record<string, unknown>,
+ key: (typeof PLACEMENTS)[number],
+ checkAnchor: (slug: string) => Promise<void>,
+): Promise<RankPlacement> {
+ const v = body[key];
+ if (key === "rank") {
+ if (v === null) return { kind: "unrank" };
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 0) {
+ throw new OpsInputError('"rank" must be a whole number, 0 or more (0 = first), or null to remove the rank');
+ }
+ return { kind: "rank", rank: v };
+ }
+ if (key === "top" || key === "bottom") {
+ if (v !== true) throw new OpsInputError(`"${key}" must be true`);
+ return { kind: key };
+ }
+ const anchor = reqSlug(body, key);
+ await checkAnchor(anchor);
+ return { kind: key, slug: anchor };
+}
+
+export function GET() {
+ return NextResponse.json({ ok: false, error: "POST only" }, { status: 405 });
+}
diff --git a/editor/app/api/ops/create-site/route.test.ts b/editor/app/api/ops/create-site/route.test.ts
@@ -0,0 +1,221 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { setupOpsCorpus, callPost } from "../_testCorpus";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/create-site/route.test.ts"
+//
+// `create-site`: the New site form over HTTP, saved by the form's own action
+// (saveSiteAction -> writeSite) — and "update": the site page's Save with the
+// given keys changed. The action does not revalidate, so its writes are
+// tested here, against a temp corpus.
+
+const corpus = await setupOpsCorpus(null);
+for (const slug of ["pooled", "critic", "other"]) {
+ await corpus.writeChannelConfig(slug, { url: `https://www.youtube.com/@${slug}` });
+}
+await corpus.writeSite("neighbour", {});
+const { POST } = await import("./route");
+const { getSite, writeSite, withSiteLock } = await import("yt-dlp-transcript-common/lib/site");
+const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
+const { siteToFormData } = await import("../../../sites/lib/siteFormData");
+const { saveSiteAction } = await import("../../../sites/actions");
+test.after(() => corpus.cleanup());
+
+const siteFile = async (id: string) =>
+ JSON.parse(await readFile(path.join(corpus.transcripts, "sites", id, "site.json"), "utf8")) as Record<
+ string,
+ unknown
+ >;
+
+test("a create is private and unlisted by default, its header the title, through the form's writer", async () => {
+ const r = await callPost(POST, { siteId: "efapalyzer", siteTitle: "Efapalyzer", channels: ["pooled"] });
+ assert.equal(r.status, 200, JSON.stringify(r.body));
+ assert.equal(r.body.created, true);
+ const file = await siteFile("efapalyzer");
+ assert.equal(file.siteTitle, "Efapalyzer");
+ assert.equal(file.headerTitle, "Efapalyzer");
+ assert.equal(file.audience, "private");
+ assert.equal(file.listed, false);
+ assert.deepEqual(file.channels, [{ slug: "pooled", order: 0 }]);
+ assert.equal("publish" in file, false, "publish off");
+ assert.equal("search" in file, false, "search on (absent)");
+ assert.deepEqual((r.body.site as { siteId: string }).siteId, "efapalyzer");
+
+ // Public, listed, grouped, cited, with a policy: every key the form's.
+ const pub = await callPost(POST, {
+ siteId: "shown",
+ siteTitle: "Shownalyzer",
+ headerTitle: "Shownalyzer",
+ wordmarkLead: "Shown",
+ audience: "public",
+ listed: true,
+ accent: "#cc3366",
+ cloudflareProject: "shown-pages",
+ siteUrl: "https://shown.example/",
+ publishAuto: "production",
+ groups: [
+ { id: "main", name: "Main", selectedByDefault: true },
+ { id: "extra", name: "Extra" },
+ ],
+ defaultGroupId: "main",
+ channels: [{ slug: "pooled", groupId: "extra" }],
+ citedChannels: ["critic", "pooled"],
+ archiveMaxMB: 24,
+ });
+ assert.equal(pub.status, 200, JSON.stringify(pub.body));
+ const s = await siteFile("shown");
+ assert.equal("audience" in s, false, "public is the absent default");
+ assert.equal("listed" in s, false, "listed is the absent default");
+ assert.equal(s.accent, "#cc3366");
+ assert.equal(s.siteUrl, "https://shown.example");
+ assert.deepEqual(s.publish, { auto: "production" });
+ assert.deepEqual(s.channels, [{ slug: "pooled", groupId: "extra", order: 0 }]);
+ assert.deepEqual(s.citedChannels, [{ slug: "critic" }], "a pooled slug is dropped from the cited scope");
+ assert.equal(s.archiveMaxBytes, 24 * 1024 * 1024);
+ assert.equal(s.wordmarkLead, "Shown");
+});
+
+test("an existing id is refused unless update; update keeps every key it does not name", async () => {
+ const before = await siteFile("shown");
+ const again = await callPost(POST, { siteId: "shown", siteTitle: "Other" });
+ assert.equal(again.status, 409);
+ assert.match(String(again.body.error), /Site "shown" already exists\. "update": true saves the keys given over it/);
+ assert.deepEqual(await siteFile("shown"), before, "nothing written");
+
+ const up = await callPost(POST, { siteId: "shown", update: true, homeTagline: "Every stream, searchable" });
+ assert.equal(up.status, 200, JSON.stringify(up.body));
+ assert.equal(up.body.created, false);
+ assert.deepEqual(await siteFile("shown"), { ...before, homeTagline: "Every stream, searchable" });
+
+ const none = await callPost(POST, { siteId: "nosuch", update: true, siteTitle: "X" });
+ assert.equal(none.status, 404);
+ assert.match(String(none.body.error), /Site "nosuch" not found — leave out "update" to create it/);
+});
+
+test("the form's refusals, and the door's, before anything is written", async () => {
+ for (const [body, status, re] of [
+ [{ siteId: "Bad Id", siteTitle: "X" }, 400, /not a valid site id/],
+ [{ siteId: "new", siteTitle: "X" }, 400, /new/],
+ [{ siteId: "untitled" }, 400, /a new site needs a "siteTitle"/],
+ [{ siteId: "blank", siteTitle: " " }, 400, /Site title is required/],
+ [{ siteId: "lead", siteTitle: "Leadalyzer", wordmarkLead: "lead" }, 400, /Wordmark lead must be how the header title starts/],
+ [{ siteId: "url", siteTitle: "U", siteUrl: "shown.example" }, 400, /Public URL must be an absolute http\(s\):\/\/ URL/],
+ [{ siteId: "aud", siteTitle: "A", audience: "friends" }, 400, /Unknown audience "friends"/],
+ [{ siteId: "pol", siteTitle: "P", audience: "public", publishAuto: "production" }, 400, /cloudflareProject/],
+ [{ siteId: "acc", siteTitle: "A", accent: "chartreuse" }, 400, /Unknown brand accent "chartreuse"/],
+ [{ siteId: "grp", siteTitle: "G", groups: [] }, 400, /At least one channel group is required/],
+ [{ siteId: "grp2", siteTitle: "G", groups: [{ name: "No id" }] }, 400, /"groups"\[0\] is not a channel group/],
+ [{ siteId: "ch", siteTitle: "C", channels: ["pooled", "ghost"] }, 400, /not a channel: "ghost"/],
+ [{ siteId: "cit", siteTitle: "C", citedChannels: ["ghost"] }, 400, /not a channel: "ghost"/],
+ [{ siteId: "typ", siteTitle: "T", listed: "yes" }, 400, /"listed" must be a boolean/],
+ [{ siteId: "typ2", siteTitle: "T", archiveMaxMB: "12" }, 400, /"archiveMaxMB" must be a number/],
+ [{ siteId: "unk", siteTitle: "U", pages: ["a"] }, 400, /pages/],
+ [
+ { siteId: "grptypo", siteTitle: "G", channels: [{ slug: "pooled", groupId: "typo" }] },
+ 400,
+ /"channels": "pooled" names group "typo", which is not one of the site's groups \("default"\)/,
+ ],
+ ] as const) {
+ const r = await callPost(POST, body);
+ assert.equal(r.status, status, JSON.stringify(body) + " " + JSON.stringify(r.body));
+ assert.match(String(r.body.error), re, JSON.stringify(r.body));
+ const id = (body as { siteId: string }).siteId;
+ if (id !== "new" && /^[a-z0-9-]+$/.test(id)) {
+ await assert.rejects(readFile(path.join(corpus.transcripts, "sites", id, "site.json")), `${id}: nothing written`);
+ }
+ }
+});
+
+// The round trip "update" rests on: a stored site, made into the form it would
+// post untouched, saved by the form's action, is the same site.json.
+test("siteToFormData -> saveSiteAction gives a full site back unchanged", async () => {
+ const paths = getPaths();
+ await writeSite(
+ {
+ siteId: "full",
+ siteTitle: "Fullalyzer",
+ siteDescription: "Everything set",
+ headerTitle: "Fullalyzer",
+ wordmarkLead: "Full",
+ homeTagline: "All of it",
+ socialLinks: [{ label: "Site", url: "https://full.example", svg: '<svg viewBox="0 0 24 24"><path d="M0 0h24v24H0z"/></svg>' }],
+ groups: [
+ { id: "main", name: "Main", selectedByDefault: true, order: 0, description: "The main ones" },
+ { id: "side", name: "Side", selectedByDefault: false, order: 1, inline: true },
+ ],
+ defaultGroupId: "side",
+ channels: [
+ { slug: "pooled", groupId: "main", order: 0 },
+ { slug: "other", order: 1 },
+ ],
+ citedChannels: [{ slug: "critic" }],
+ cloudflareProject: "full-pages",
+ accent: "brass",
+ siteUrl: "https://full.example",
+ pages: ["intro"],
+ relatedSites: [{ label: "Friends", siteIds: ["neighbour"] }],
+ search: false,
+ pwa: true,
+ archives: false,
+ duplicates: false,
+ transcriptDownloads: false,
+ archiveMaxBytes: 12_345_678,
+ hubUrl: "https://hub.example",
+ publish: { auto: "preview" },
+ },
+ paths,
+ );
+ const before = await siteFile("full");
+ const r = await saveSiteAction(undefined, siteToFormData(getSite("full", paths)));
+ assert.equal(r.ok, true, JSON.stringify(r));
+ assert.deepEqual(await siteFile("full"), before);
+ // And a private, inheriting, default-accent one.
+ await writeSite(
+ {
+ siteId: "plain",
+ siteTitle: "Plain",
+ siteDescription: "",
+ headerTitle: "Plain",
+ homeTagline: "",
+ groups: [{ id: "default", name: "All", selectedByDefault: true }],
+ defaultGroupId: "default",
+ channels: [],
+ audience: "private",
+ listed: false,
+ },
+ paths,
+ );
+ const plain = await siteFile("plain");
+ assert.equal((await saveSiteAction(undefined, siteToFormData(getSite("plain", paths)))).ok, true);
+ assert.deepEqual(await siteFile("plain"), plain);
+});
+
+// An update is ONE read-modify-write under the site's lock: an edit of the
+// site that holds the lock when the update arrives (a Reports-tab patch, say)
+// is read by the update, not written over by a copy taken before it landed.
+test("an update waits for a held edit of the site and keeps it", async () => {
+ const paths = getPaths();
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const held = withSiteLock(
+ "shown",
+ async () => {
+ const current = getSite("shown", paths);
+ await gate;
+ await writeSite({ ...current, homeTagline: "written while the update waited" }, paths);
+ },
+ paths,
+ );
+ const up = callPost(POST, { siteId: "shown", update: true, siteDescription: "after the held edit" });
+ await new Promise((r) => setTimeout(r, 20));
+ release();
+ await held;
+ const r = await up;
+ assert.equal(r.status, 200, JSON.stringify(r.body));
+ const file = await siteFile("shown");
+ assert.equal(file.homeTagline, "written while the update waited");
+ assert.equal(file.siteDescription, "after the held edit");
+});
diff --git a/editor/app/api/ops/create-site/route.ts b/editor/app/api/ops/create-site/route.ts
@@ -0,0 +1,167 @@
+import { existsSync } from "node:fs";
+import { NextResponse } from "next/server";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ getSite,
+ isValidSiteId,
+ siteConfigFile,
+ withSiteLock,
+ type Site,
+} from "yt-dlp-transcript-common/lib/site";
+import {
+ DEFAULT_GROUP_FALLBACK_ID,
+ FALLBACK_GROUP,
+ parseChannelGroups,
+} from "yt-dlp-transcript-common/lib/channelGroups";
+import { channelExists, isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { saveSiteFromForm } from "../../../sites/lib/saveSiteForm";
+import {
+ SITE_OPS_FIELDS,
+ SiteFieldError,
+ applySiteFields,
+ readChannels,
+ siteToFormData,
+} from "../../../sites/lib/siteFormData";
+import { OpsInputError, ops, opsFail, optBool, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { siteId, siteTitle, …the site form's fields…, update? }
+// -> { ok, siteId, created, site }
+//
+// THE NEW SITE FORM, OVER HTTP (lane editor-gaps; 9 Nov an agent had to call
+// writeSite from a tsx script to make a site). The body's keys are the form's
+// fields (app/sites/lib/siteFormData.ts SITE_OPS_FIELDS), built into the
+// FormData the form posts and saved by the form's own action — saveSiteAction,
+// so writeSite — with its validation and its sentences: a bad site id or a
+// reserved one, no title, a wordmark lead that is not how the header starts,
+// a URL that is not absolute, an unknown accent, audience or publish policy, a
+// group list with none, a deploying policy with no Pages project.
+//
+// A CREATE IS PRIVATE AND UNLISTED unless the body says otherwise ("audience":
+// "public", "listed": true) — the form defaults the other way because a
+// person at it is building a public site; a script making one is usually
+// making a reading copy. "headerTitle" defaults to "siteTitle". Every other
+// key is the form's default: one inline group, no channels, search, archives,
+// duplicates and transcript downloads on, publish off.
+//
+// AN EXISTING ID IS REFUSED (409) unless "update": true, which is the site
+// page's Save with the given keys changed: the stored site is the form, the
+// body's keys are laid over it, every key not named stays (the published page
+// list is the Reports tab's and is always kept). "update" on a site that does
+// not exist is a 404.
+//
+// Refused before anything is written, beside the action's own refusals: an
+// unknown key, a key of the wrong type, a channel (or cited channel) that does
+// not exist.
+export async function POST(request: Request) {
+ return ops(request, ["siteId", "update", ...SITE_OPS_FIELDS], async (body) => {
+ const siteId = reqString(body, "siteId").trim();
+ if (!isValidSiteId(siteId)) {
+ throw new OpsInputError(`"${siteId}" is not a valid site id (lowercase letters, numbers and hyphens)`);
+ }
+ const update = optBool(body, "update") === true;
+ const paths = getPaths();
+ if (!update && typeof body.siteTitle !== "string") {
+ throw new OpsInputError('a new site needs a "siteTitle"');
+ }
+ await refuseUnknownChannels(body);
+ const fields: Record<string, unknown> = {};
+ for (const key of SITE_OPS_FIELDS) if (body[key] !== undefined) fields[key] = body[key];
+ if (!update && fields.headerTitle === undefined) fields.headerTitle = fields.siteTitle;
+ // ONE READ-MODIFY-WRITE, under the site's lock (lib/site.ts withSiteLock):
+ // whether the site exists, the stored site an update starts from, and the
+ // form's save — so a concurrent edit of the site (a Reports-tab pages
+ // patch, a channel delete's membership patch) is never written over with
+ // the copy read here, and two creates of one id cannot both pass.
+ return withSiteLock(siteId, () => createOrUpdate(siteId, update, fields), paths);
+ });
+}
+
+async function createOrUpdate(
+ siteId: string,
+ update: boolean,
+ fields: Record<string, unknown>,
+): Promise<NextResponse> {
+ const paths = getPaths();
+ const exists = existsSync(siteConfigFile(paths, siteId));
+ if (exists && !update) {
+ return opsFail(
+ `Site "${siteId}" already exists. "update": true saves the keys given over it, as its form's Save does ` +
+ `(site-config sets its cited channels and publish policy alone).`,
+ 409,
+ );
+ }
+ if (!exists && update) {
+ return opsFail(`Site "${siteId}" not found — leave out "update" to create it`, 404);
+ }
+ const fd = siteToFormData(update ? getSite(siteId, paths) : blankSite(siteId));
+ try {
+ applySiteFields(fd, fields);
+ refuseUnknownGroups(fd);
+ } catch (e) {
+ if (e instanceof SiteFieldError) return opsFail(e.message);
+ throw e;
+ }
+ const saved = await saveSiteFromForm(fd);
+ if (!saved.ok) return opsFail(saved.error);
+ return NextResponse.json({ ok: true, siteId, created: !update, site: getSite(siteId, paths) });
+}
+
+// A channel's groupId that names no group of the site: the parser would drop
+// it without a word (the channel falls into the default group). The form only
+// offers the site's groups; over ops it is said.
+function refuseUnknownGroups(fd: FormData): void {
+ const groups = parseChannelGroups(JSON.parse(String(fd.get("groupsJson") ?? "[]")));
+ const ids = new Set(groups.map((g) => g.id));
+ const channels = JSON.parse(String(fd.get("channelsJson") ?? "[]")) as { slug?: unknown; groupId?: unknown }[];
+ for (const c of channels) {
+ if (typeof c.groupId === "string" && c.groupId && !ids.has(c.groupId)) {
+ throw new SiteFieldError(
+ `"channels": "${String(c.slug)}" names group "${c.groupId}", which is not one of the site's groups ` +
+ `(${[...ids].map((id) => `"${id}"`).join(", ") || "none"})`,
+ );
+ }
+ }
+}
+
+// What /sites/new starts from, private and unlisted.
+function blankSite(siteId: string): Site {
+ return {
+ siteId,
+ siteTitle: "",
+ siteDescription: "",
+ headerTitle: "",
+ homeTagline: "",
+ groups: [{ ...FALLBACK_GROUP }],
+ defaultGroupId: DEFAULT_GROUP_FALLBACK_ID,
+ channels: [],
+ audience: "private",
+ listed: false,
+ };
+}
+
+// The form offers only channels that exist; a slug here is checked the same.
+async function refuseUnknownChannels(body: Record<string, unknown>): Promise<void> {
+ const slugs: string[] = [];
+ try {
+ if (body.channels !== undefined) slugs.push(...readChannels(body.channels).map((c) => c.slug));
+ } catch (e) {
+ if (e instanceof SiteFieldError) throw new OpsInputError(e.message);
+ throw e;
+ }
+ if (Array.isArray(body.citedChannels)) {
+ slugs.push(...body.citedChannels.filter((s): s is string => typeof s === "string").map((s) => s.trim()));
+ }
+ const paths = getPaths();
+ const missing: string[] = [];
+ for (const slug of new Set(slugs)) {
+ if (!isValidChannelSlug(slug)) {
+ throw new OpsInputError(`"${slug}" is not a valid channel slug`);
+ }
+ if (!(await channelExists(paths, slug))) missing.push(slug);
+ }
+ if (missing.length > 0) {
+ throw new OpsInputError(`not a channel: ${missing.map((s) => `"${s}"`).join(", ")}`);
+ }
+}
diff --git a/editor/app/api/ops/delete-channel/route.ts b/editor/app/api/ops/delete-channel/route.ts
@@ -12,6 +12,10 @@ export const dynamic = "force-dynamic";
// compares them, and refuses in the form's own sentence. Every other refusal is
// the form's too: a busy channel, media in transition.
//
+// Every site whose pool or cited scope named the channel is rewritten without
+// it (through writeSite) and named in `sitesUpdated`; a site whose write is
+// refused is a `warnings` line.
+//
// There is no undo, and transcripts/ is its own git repo — the only way back
// is a commit there.
export async function POST(request: Request) {
@@ -21,6 +25,12 @@ export async function POST(request: Request) {
fd.set("confirmSlug", reqString(body, "confirm"));
const result = await deleteChannelFromForm(slug, fd);
if (!result.ok) return opsFail(result.error);
- return NextResponse.json({ ok: true, slug: result.slug, deleted: true });
+ return NextResponse.json({
+ ok: true,
+ slug: result.slug,
+ deleted: true,
+ sitesUpdated: result.sitesUpdated ?? [],
+ ...(result.warnings.length > 0 ? { warnings: result.warnings } : {}),
+ });
});
}
diff --git a/editor/app/api/ops/transcribe-one/route.test.ts b/editor/app/api/ops/transcribe-one/route.test.ts
@@ -214,3 +214,60 @@ test("English captions listed and no audio: the captions are fetched instead; as
assert.equal(bad.status, 400);
assert.match(String(bad.body.error), /"asr" must be a boolean/);
});
+
+// 4 Nov: a transcribe-one on a video that was LIVE downloaded the HLS at 1x and
+// held platform:youtube for the stream's length. Its record says so, and the
+// door refuses it with the commands that do the right thing — nothing queued.
+// The audio, or a container, already here owes no download and is transcribed.
+test("a live, scheduled or processing stream is refused before anything is queued; with its audio here it transcribes", async () => {
+ const before = (await corpus.listJobIds()).length;
+ await video("liveHHHHHHH", { live_status: "is_live", is_live: true });
+ const live = await callPost(POST, { slug: SLUG, id: "liveHHHHHHH", asr: true });
+ assert.equal(live.status, 400, JSON.stringify(live.body));
+ assert.match(String(live.body.error), /^liveHHHHHHH is live now \(live_status is_live\): a download would read the stream at 1x/);
+ assert.ok(
+ String(live.body.error).includes(`pnpm ops record-live --json '{"slug":"${SLUG}","id":"liveHHHHHHH"}'`),
+ String(live.body.error),
+ );
+ // Without "asr" and with no captions listed: the audio download is next, refused.
+ const plain = await callPost(POST, { slug: SLUG, id: "liveHHHHHHH" });
+ assert.equal(plain.status, 400);
+ assert.match(String(plain.body.error), /is live now/);
+
+ await video("upcomingIII", { live_status: "is_upcoming" });
+ const upcoming = await callPost(POST, { slug: SLUG, id: "upcomingIII" });
+ assert.equal(upcoming.status, 400);
+ assert.match(String(upcoming.body.error), /scheduled stream that has not started/);
+
+ await video("postliveJJJ", { live_status: "post_live" });
+ const post = await callPost(POST, { slug: SLUG, id: "postliveJJJ" });
+ assert.equal(post.status, 400);
+ assert.match(String(post.body.error), /VOD is still being processed/);
+ assert.equal((await corpus.listJobIds()).length, before, "nothing was queued");
+
+ // A (possibly stale) live record with English captions listed: the captions
+ // fetch is no audio download, so it goes through; asr: true is refused.
+ const captions = { automatic_captions: { en: [{ ext: "vtt", url: "https://example.invalid/en.vtt" }] } };
+ await video("livecapsMMM", { live_status: "post_live", ...captions });
+ const caps = await callPost(POST, { slug: SLUG, id: "livecapsMMM" });
+ assert.equal(caps.status, 200, JSON.stringify(caps.body));
+ assert.equal(caps.body.instead, "captions");
+ await until("the live video's caption fetch", () => ended(String(caps.body.jobId)));
+ await video("livecapsNNN", { live_status: "is_live", ...captions });
+ const capsAsr = await callPost(POST, { slug: SLUG, id: "livecapsNNN", asr: true });
+ assert.equal(capsAsr.status, 400);
+ assert.match(String(capsAsr.body.error), /livecapsNNN is live now/);
+
+ // A finished stream (was_live) downloads as any video does.
+ await video("wasliveKKKK", { live_status: "was_live" });
+ const vod = await callPost(POST, { slug: SLUG, id: "wasliveKKKK", asr: true });
+ assert.equal(vod.status, 200, JSON.stringify(vod.body));
+ await until("the VOD's audio download", () => ended(String(vod.body.jobId)));
+
+ // Audio already on disk: nothing to download, so nothing to refuse.
+ await video("liveaudioLL", { live_status: "is_live" }, { "audio.mp3": "fake audio\n" });
+ const here = await callPost(POST, { slug: SLUG, id: "liveaudioLL" });
+ assert.equal(here.status, 200, JSON.stringify(here.body));
+ assert.equal(job(String(here.body.jobId)).kind, "transcribe-one");
+ await until("the on-disk transcription", () => ended(String(here.body.jobId)));
+});
diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx
@@ -106,7 +106,10 @@ type Props = {
nextHref?: string;
position?: { index: number; total: number };
// The umtool front door, when UMTOOL_URL is set on the editor. One link:
- // "open in umtool" scaffolds a report video from this exact video.
+ // "open in umtool" opens this recording's life cycle there
+ // (/ingredients/<slug>/<id>: found, downloaded, transcribed, its windows,
+ // every cut that uses it, checked, rendered, published), where "make a
+ // video from it" scaffolds a report video from it.
umtoolUrl?: string | null;
// The transcription pool is paused (getWorkerPool().isPaused(), read by the
// page): the Transcribe rows offer "Transcribe now (workers paused)".
@@ -208,13 +211,13 @@ export function VideoPanel({
{umtoolUrl && (
<div className="text-sm">
<a
- href={`${umtoolUrl}/?from=${encodeURIComponent(`${slug}/${videoId}`)}`}
+ href={`${umtoolUrl}/ingredients/${encodeURIComponent(slug)}/${encodeURIComponent(videoId)}`}
className="underline"
data-umtool-link
>
Open in umtool
</a>
- <span className="text-muted-foreground"> — start a report video from this recording</span>
+ <span className="text-muted-foreground"> — this recording's life cycle: its windows, every cut that uses it, what was checked, rendered and published</span>
</div>
)}
<PipelineStatusStrip
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -31,6 +31,7 @@ import {
isEnglishCaptionTrack,
readListedCaptionTracks,
} from "yt-dlp-transcript-common/lib/listedCaptions-server";
+import { liveDownloadRefusalFor } from "yt-dlp-transcript-common/lib/liveNow-server";
import {
clipWindowQueueKey,
downloadQueueKey,
@@ -729,6 +730,9 @@ export async function whisperVideoAction(
};
const firstEntries = await readdir(videoDir).catch(() => [] as string[]);
const audioOnDisk = firstEntries.some(isRealAudioFile);
+ const firstHeld = audioOnDisk
+ ? null
+ : await transcriptionContainer({ paths, slug, videoDir, entries: firstEntries });
if (!audioOnDisk && asr !== true && r.config.handling === "youtube") {
const onDisk = englishVttsByPreference(firstEntries);
@@ -772,20 +776,29 @@ export async function whisperVideoAction(
prelude: [`Audio already on disk for ${videoId}; skipping download.`],
});
}
- } else {
- const held = await transcriptionContainer({ paths, slug, videoDir, entries: firstEntries });
- if (held?.kind === "container") {
- return queueTranscribeOne({
- slug,
- videoId,
- config: r.config,
- audioFilename,
- queueKey: transcribeQueue,
- fullAudioFirst: false,
- ...opts,
- prelude: [containerLine(videoId, held)],
- });
- }
+ } else if (firstHeld?.kind === "container") {
+ return queueTranscribeOne({
+ slug,
+ videoId,
+ config: r.config,
+ audioFilename,
+ queueKey: transcribeQueue,
+ fullAudioFirst: false,
+ ...opts,
+ prelude: [containerLine(videoId, firstHeld)],
+ });
+ }
+
+ // A STREAM IN PROGRESS IS NEVER DOWNLOADED FOR A TRANSCRIPTION (4 Nov): the
+ // one-video download would read the HLS at 1x and hold the platform's queue
+ // for the stream's length. Refused while its record says it is live,
+ // scheduled or still processing — only here, where the audio download is
+ // what comes next: audio or a container already here owes no download, and
+ // a captions-only fetch (above) is harmless, the managed path skipping a
+ // stream that really is live. lib/liveNow.ts.
+ if (!audioOnDisk) {
+ const live = await liveDownloadRefusalFor(videoDir, { slug, videoId });
+ if (live) return { ok: false, error: live };
}
const platformQueue = videoQueueKey(r.config, queueKey);
@@ -816,6 +829,10 @@ export async function whisperVideoAction(
if (held?.kind === "no-audio") {
onLog(`The container ${held.file} has no sound; downloading the audio instead.`);
}
+ // The door's live check again, at the moment of the download: the
+ // record may have been re-read while this job waited for its queue.
+ const live = await liveDownloadRefusalFor(videoDir, { slug, videoId });
+ if (live) throw new Error(live);
// Only this branch writes bytes. Transcribing audio that is already on
// disk produces a transcript.json measured in kilobytes, so a low disk
// is no reason to refuse it — the gate belongs on the fetch, not on the
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -22,6 +22,7 @@ import {
readChannelConfig,
} from "yt-dlp-transcript-common/controller/channels";
import { renameChannel } from "yt-dlp-transcript-common/controller/renameChannel";
+import { dropChannelFromSites } from "yt-dlp-transcript-common/controller/siteMemberships";
import { inspectChannelMedia } from "yt-dlp-transcript-common/lib/channelMedia";
import { channelMediaBusyReason } from "./lib/mediaBusy";
import {
@@ -39,7 +40,7 @@ import {
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { X_SEARCH_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/site";
import { xSearchFromUrl, xSearchQueryOfUrl } from "yt-dlp-transcript-common/lib/xSearch/config";
-import { saveSettings } from "../settings/saveSettings";
+import { saveSettings, saveSettingsHeld, withSettingsLock } from "../settings/saveSettings";
import {
LANES,
type AutoQueueKind,
@@ -53,6 +54,8 @@ import {
isChannelPaused,
clearAutoPause,
isDefaultChannelPriority,
+ placeChannelRank,
+ RankPlacementError,
rankOf,
renameChannelInPriority,
resolveFocusSlugs,
@@ -62,6 +65,7 @@ import {
type ChannelPriority,
type ChannelPriorityEntry,
type PriorityOperation,
+ type RankPlacement,
type SiteChannelIndex,
type StoredChannelTier,
} from "yt-dlp-transcript-common/lib/channelPriority";
@@ -215,6 +219,9 @@ export type ChannelLifecycleResult =
jobIds: string[];
// Non-fatal problems after the move (rename's metadata migration).
warnings: string[];
+ // Delete: the sites whose pool or cited scope named the channel and
+ // were rewritten without it.
+ sitesUpdated?: string[];
}
| ({ ok: false } & NonNullable<FormErrorState>);
@@ -356,15 +363,18 @@ export async function updateChannelAction(
formData: FormData,
): Promise<ActionResult> {
const values = formValues(formData);
+ const paths = getPaths();
+ const existing = await readChannelConfig(paths, slug);
+ if (!existing) return { error: `Channel "${slug}" not found`, values };
let parsed;
try {
- parsed = parseChannelForm(formData);
+ parsed = parseChannelForm(formData, { stored: existing });
} catch (e) {
return { error: (e as Error).message, values };
}
- const paths = getPaths();
- const existing = await readChannelConfig(paths, slug);
- if (!existing) return { error: `Channel "${slug}" not found`, values };
+ // A stored value today's checks refuse, saved unchanged: the save stands.
+ // The form has no place for a warning, so the server log says it.
+ for (const w of parsed.warnings) console.warn(`Channel ${slug} saved with a warning: ${w}`);
// Plan the site-membership writes (Sites section) before touching anything,
// so bad input errors out with no partial write. Null = field absent
// (zero sites configured / legacy submit) → leave memberships alone.
@@ -691,6 +701,17 @@ export async function deleteChannelFromForm(
} catch (e) {
return fail((e as Error).message);
}
+ // NO SITE GOES ON NAMING IT (9 Nov: a deleted channel stayed in a site's
+ // pool). Each site that names it is rewritten through writeSite; one whose
+ // write is refused is a warning — the channel is gone either way.
+ const sites = await dropChannelFromSites(getPaths(), slug).catch((e: Error) => ({
+ updated: [] as string[],
+ failed: [{ siteId: "*", error: e.message }],
+ }));
+ const warnings = sites.failed.map(
+ (f) => `Site "${f.siteId}" still names "${slug}": its update was refused: ${f.error}`,
+ );
+ if (warnings.length > 0) console.warn(`Channel delete ${slug}:`, warnings.join("; "));
// Same reason as createChannelAction: the deleted channel keeps a leaf in
// every compiled tree until something recompiles. A leaf matching nothing is
// harmless to dispatch and confusing to read.
@@ -701,7 +722,8 @@ export async function deleteChannelFromForm(
}
revalidatePath("/channels");
revalidatePath("/");
- return { ok: true, slug, jobIds: [], warnings: [] };
+ if (sites.updated.length > 0) revalidatePath("/sites");
+ return { ok: true, slug, jobIds: [], warnings, sitesUpdated: sites.updated };
}
// Change a channel's slug (its on-disk directory name). High-friction: the
@@ -837,6 +859,10 @@ export type ChannelPriorityEdit =
// `paused` channel ranked first is still behind (or absent from) every
// normal one. See prioritizeChannelDownloadAction.
| { kind: "promote"; slug: string }
+ // ONE CHANNEL MOVED IN THE ORDER (`pnpm ops channel-rank`): its rank alone,
+ // every other channel's order kept — placeChannelRank in the model. No tier,
+ // override, focus or lane changes, unlike promote.
+ | { kind: "rank"; slug: string; place: RankPlacement }
// NOT AN EDIT: the channel POPULATION changed (a channel was created or
// deleted), so the four trees have to be re-derived from an unchanged
// document. Never seeds — see the writer.
@@ -868,6 +894,7 @@ function applyPriorityEdit(
return renameChannelInPriority(model, edit.from, edit.to);
}
if (edit.kind === "focus") return { ...model, focus: edit.focus };
+ if (edit.kind === "rank") return placeChannelRank(model, edit.slug, edit.place);
if (edit.kind === "promote") {
const slug = edit.slug.trim();
if (!slug) return model;
@@ -952,86 +979,119 @@ export async function saveChannelPriorityAction(
opts?: { enableLanes?: readonly AutoQueueKind[] },
): Promise<ActionResult> {
const paths = getPaths();
- const settings = getSettings();
- const stored = settings.channelPriority;
+ // The channel population first, OUTSIDE the lock: it is a directory read,
+ // and nothing below writes it.
const configs = await listChannelConfigs(paths);
const slugs = configs.map((c) => c.slug);
- // THE LEGACY SEED, and it is the difference between this feature shipping
- // and this feature destroying the two hand-made 9+9 lane orders on its first
- // click (the S2/S3 review, finding 3, restated with its mechanism in 8).
- //
- // `laneDispatchRoot` is all-or-nothing on `isDefaultChannelPriority`: the
- // moment a document says ANYTHING, the stored trees stop being dispatched
- // from and the compiled ones take over. A first click that set one tier and
- // nothing else would therefore compile a tree in which no channel has a rank
- // — every one of them alphabetical inside `prio-normal` — and the operator's
- // order would be gone with no way back, because the trees it was written in
- // have just been overwritten.
- //
- // So: when the stored document says nothing AND the stored trees are not
- // already compiled, derive the document the migration would have produced
- // and apply the edit on top of THAT. The corpus's existing order survives a
- // first click by an operator who never ran the migration.
- //
- // NOT ON A `recompile` OR A `rename`: creating or renaming a channel is not
- // an operator's statement about priority, and neither must silently switch a
- // corpus from its stored trees to compiled ones.
- const base =
- edit.kind !== "recompile" &&
- edit.kind !== "rename" &&
- isDefaultChannelPriority(stored) &&
- !hasCompiledLaneRoots(settings.autoQueue)
- ? channelPriorityFromLegacy(
- // THE SEED READS THE LANE ORDERS, NOT THE FLAG. `excludeFromSync` is
- // deleted and `parseChannelConfig` drops the key, so nothing the
- // editor can read still carries it — turning those 15 channels into
- // `overrides: {sync:"paused"}` is the migration script's half, off
- // the raw config.json. What this seed is for is the ORDER, and the
- // order lives in the stored trees.
- configs.map((c) => ({ slug: c.slug, config: {} })),
- settings.autoQueue,
- )
- : stored;
- const next = sanitizeChannelPriority(applyPriorityEdit(base, edit));
- // WHEN A DEFAULT DOCUMENT STILL HAS TO COMPILE, and the two halves of the
- // question are different corpora.
- //
- // The runner's bypass means a default document dispatches from the STORED
- // tree, so what matters here is what that stored tree is:
- //
- // never compiled (hand-made, or the shipped default) -> LEAVE IT. This is
- // the same rule `laneDispatchRoot` applies, and compiling over it would
- // replace an operator's tree with an all-normal one at the moment the last
- // priority was cleared.
- //
- // already compiled -> RECOMPILE, even for a default document. Ending a
- // focus leaves the document saying nothing while every stored root still
- // opens with `prio-focus` — and the runner, back on its bypass, would
- // dispatch from exactly that tree and go on holding the channels the focus
- // was just ended for. There is no hand-made tree left to protect on a
- // corpus whose roots the compiler already wrote.
- const autoQueue = { ...settings.autoQueue };
- if (
- !isDefaultChannelPriority(next) ||
- hasCompiledLaneRoots(settings.autoQueue)
- ) {
- const focusSlugs = resolveFocusSlugs(next, siteChannelIndex(paths), slugs);
- const roots = compileLanes(next, slugs, focusSlugs);
- for (const lane of LANES) {
- autoQueue[lane] = { ...settings.autoQueue[lane], root: roots[lane] };
+ // THE READ-MODIFY-WRITE IS SERIALIZED (review of lane editor-gaps): the
+ // document is read INSIDE the settings lock and written before it is let go,
+ // so a concurrent deck save or a parallel `channel-rank` is never written
+ // over with a copy read before it landed. Every saveSettings takes the same
+ // lock (settings/saveSettings.ts).
+ const saved = await withSettingsLock(async (): Promise<ActionResult | "saved"> => {
+ const settings = getSettings();
+ const stored = settings.channelPriority;
+ // THE LEGACY SEED, and it is the difference between this feature shipping
+ // and this feature destroying the two hand-made 9+9 lane orders on its first
+ // click (the S2/S3 review, finding 3, restated with its mechanism in 8).
+ //
+ // `laneDispatchRoot` is all-or-nothing on `isDefaultChannelPriority`: the
+ // moment a document says ANYTHING, the stored trees stop being dispatched
+ // from and the compiled ones take over. A first click that set one tier and
+ // nothing else would therefore compile a tree in which no channel has a rank
+ // — every one of them alphabetical inside `prio-normal` — and the operator's
+ // order would be gone with no way back, because the trees it was written in
+ // have just been overwritten.
+ //
+ // So: when the stored document says nothing AND the stored trees are not
+ // already compiled, derive the document the migration would have produced
+ // and apply the edit on top of THAT. The corpus's existing order survives a
+ // first click by an operator who never ran the migration.
+ //
+ // NOT ON A `recompile` OR A `rename`: creating or renaming a channel is not
+ // an operator's statement about priority, and neither must silently switch a
+ // corpus from its stored trees to compiled ones.
+ const base =
+ edit.kind !== "recompile" &&
+ edit.kind !== "rename" &&
+ isDefaultChannelPriority(stored) &&
+ !hasCompiledLaneRoots(settings.autoQueue)
+ ? channelPriorityFromLegacy(
+ // THE SEED READS THE LANE ORDERS, NOT THE FLAG. `excludeFromSync` is
+ // deleted and `parseChannelConfig` drops the key, so nothing the
+ // editor can read still carries it — turning those 15 channels into
+ // `overrides: {sync:"paused"}` is the migration script's half, off
+ // the raw config.json. What this seed is for is the ORDER, and the
+ // order lives in the stored trees.
+ configs.map((c) => ({ slug: c.slug, config: {} })),
+ settings.autoQueue,
+ )
+ : stored;
+ let next: ChannelPriority;
+ try {
+ next = sanitizeChannelPriority(applyPriorityEdit(base, edit));
+ } catch (e) {
+ // A placement the document cannot carry out (next to an unranked channel,
+ // a rank that is not one) is the caller's to fix, said before any write.
+ if (e instanceof RankPlacementError) return { error: e.message };
+ throw e;
}
- }
- for (const lane of opts?.enableLanes ?? []) {
- autoQueue[lane] = { ...autoQueue[lane], enabled: true };
- }
- try {
- // BOTH BLOCKS IN ONE WRITE — the reason saveSettings takes a whole-settings
- // patch rather than one block. `channelPriority` is a full document (its
- // `channels` map replaces), and `autoQueue` carries all four lanes.
- await saveSettings({ channelPriority: next, autoQueue });
- } catch (e) {
- return { error: (e as Error).message };
- }
+ // A rank the sanitizer drops: a channel paused for every operation is in no
+ // group anywhere, so it orders nothing and its rank is not kept. Said, not
+ // saved as a silent no-op.
+ if (
+ edit.kind === "rank" &&
+ edit.place.kind !== "unrank" &&
+ next.channels[edit.slug.trim()]?.rank === undefined
+ ) {
+ return {
+ error:
+ `"${edit.slug.trim()}" is paused for every operation, so it is in no order a rank could place it in — ` +
+ `give it a tier first (pnpm ops channel-priority), then rank it.`,
+ };
+ }
+ // WHEN A DEFAULT DOCUMENT STILL HAS TO COMPILE, and the two halves of the
+ // question are different corpora.
+ //
+ // The runner's bypass means a default document dispatches from the STORED
+ // tree, so what matters here is what that stored tree is:
+ //
+ // never compiled (hand-made, or the shipped default) -> LEAVE IT. This is
+ // the same rule `laneDispatchRoot` applies, and compiling over it would
+ // replace an operator's tree with an all-normal one at the moment the last
+ // priority was cleared.
+ //
+ // already compiled -> RECOMPILE, even for a default document. Ending a
+ // focus leaves the document saying nothing while every stored root still
+ // opens with `prio-focus` — and the runner, back on its bypass, would
+ // dispatch from exactly that tree and go on holding the channels the focus
+ // was just ended for. There is no hand-made tree left to protect on a
+ // corpus whose roots the compiler already wrote.
+ const autoQueue = { ...settings.autoQueue };
+ if (
+ !isDefaultChannelPriority(next) ||
+ hasCompiledLaneRoots(settings.autoQueue)
+ ) {
+ const focusSlugs = resolveFocusSlugs(next, siteChannelIndex(paths), slugs);
+ const roots = compileLanes(next, slugs, focusSlugs);
+ for (const lane of LANES) {
+ autoQueue[lane] = { ...settings.autoQueue[lane], root: roots[lane] };
+ }
+ }
+ for (const lane of opts?.enableLanes ?? []) {
+ autoQueue[lane] = { ...autoQueue[lane], enabled: true };
+ }
+ try {
+ // BOTH BLOCKS IN ONE WRITE — the reason saveSettings takes a whole-settings
+ // patch rather than one block. `channelPriority` is a full document (its
+ // `channels` map replaces), and `autoQueue` carries all four lanes.
+ await saveSettingsHeld({ channelPriority: next, autoQueue });
+ } catch (e) {
+ return { error: (e as Error).message };
+ }
+ return "saved";
+ });
+ if (saved !== "saved") return saved;
revalidatePath("/channels");
revalidatePath("/operations");
revalidatePath("/operations/[id]", "page");
@@ -1116,6 +1176,18 @@ export async function prioritizeChannelDownloadPriorityAction(
);
}
+// Place one channel in the order (`pnpm ops channel-rank`): rank n, top,
+// bottom, before or after another ranked channel, or unranked. Through the one
+// writer, so the four lane roots are recompiled in the same write.
+export async function setChannelRankAction(
+ slug: string,
+ place: RankPlacement,
+): Promise<ActionResult> {
+ const trimmed = (slug ?? "").trim();
+ if (!trimmed) return { error: "No channel slug supplied." };
+ return saveChannelPriorityAction({ kind: "rank", slug: trimmed, place });
+}
+
export async function endFocusAction(): Promise<ActionResult> {
return saveChannelPriorityAction({ kind: "focus", focus: { kind: "none" } });
}
diff --git a/editor/app/channels/components/parseChannelForm.test.ts b/editor/app/channels/components/parseChannelForm.test.ts
@@ -358,6 +358,31 @@ test("subLangs and chat: parsed, refused when unknown, round-tripped through the
assert.equal("chat" in cleared, false);
});
+// Caption languages are checked at the save (lane editor-gaps): a value
+// yt-dlp's --sub-langs cannot use is refused in the field's words, on the form
+// and through the ops patch alike; spaces around an entry are dropped.
+test("subLangs: a value --sub-langs cannot use is refused; spaces around entries are dropped", () => {
+ assert.equal(parseChannelForm(form({ subLangs: "en.* , es" })).config.subLangs, "en.*,es");
+ assert.equal(parseChannelForm(form({ subLangs: "all,-live_chat" })).config.subLangs, "all,-live_chat");
+ assert.throws(() => parseChannelForm(form({ subLangs: "en,,es" })), /^Error: Caption languages has an empty entry/);
+ assert.throws(() => parseChannelForm(form({ subLangs: "en us" })), /Caption languages entry "en us" has a space in it/);
+ assert.throws(
+ () => parseChannelForm(form({ subLangs: "en(" })),
+ /Caption languages entry "en\(" is not a valid regular expression/,
+ );
+ const fd = channelConfigToFormData({ handling: "youtube", name: "Example VODs" });
+ applyChannelFormPatch(fd, { subLangs: "en,(" });
+ assert.throws(() => parseChannelForm(fd), /Caption languages entry "\(" is not a valid regular expression/);
+ // A value saved before the check, submitted unchanged, does not lock the
+ // form: kept as stored, with a warning. Changed, it is refused.
+ const stored = { subLangs: "en us" };
+ const kept = parseChannelForm(form({ subLangs: "en us" }), { stored });
+ assert.equal(kept.config.subLangs, "en us");
+ assert.match(kept.warnings[0] ?? "", /Caption languages entry "en us" has a space in it .*\. Kept as stored, since it is unchanged/);
+ assert.throws(() => parseChannelForm(form({ subLangs: "en uk" }), { stored }), /has a space in it/);
+ assert.deepEqual(parseChannelForm(form({ subLangs: "en.*" }), { stored }).warnings, []);
+});
+
// 2026-10-29: manual downloads (lib/manualDownloads.ts) are a Configure field
// and a `channel-config` patch key — and the operator's two-step recipe (set
// manual, THEN clear the download filter) must keep the mode across the second
diff --git a/editor/app/channels/components/parseChannelForm.ts b/editor/app/channels/components/parseChannelForm.ts
@@ -10,6 +10,8 @@ import {
KEEP_LATEST_MAX,
SYNC_INTERVAL_MAX_MINUTES,
SYNC_INTERVAL_MIN_MINUTES,
+ normalizeSubLangs,
+ subLangsProblem,
type AudioCheckConfig,
type ExtractionMode,
} from "yt-dlp-transcript-common/lib/channelConfig";
@@ -59,6 +61,16 @@ export type ParsedChannelForm = {
name: string;
slug: string;
config: ChannelConfig;
+ // Saved, but said: a stored value the form's checks would refuse today,
+ // submitted unchanged (see `stored`).
+ warnings: string[];
+};
+
+// What a Configure save knows of the channel as stored. A check added after a
+// value was saved (caption languages, lane editor-gaps) must not lock the form
+// on it: the stored value, submitted unchanged, is kept with a warning.
+export type ParseChannelFormContext = {
+ stored?: Pick<ChannelConfig, "subLangs"> | null;
};
// ChannelConfig keys the form authoritatively controls. updateChannelAction
@@ -104,7 +116,11 @@ export const CHANNEL_FORM_FIELDS = [
// Maps FormData -> ChannelConfig. Throws on invalid input so the server
// action can render an error message.
-export function parseChannelForm(formData: FormData): ParsedChannelForm {
+export function parseChannelForm(
+ formData: FormData,
+ ctx: ParseChannelFormContext = {},
+): ParsedChannelForm {
+ const warnings: string[] = [];
const name = String(formData.get("name") ?? "").trim();
if (!name) throw new Error("Name is required");
@@ -291,7 +307,19 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm {
// Caption languages and the live chat (2026-10-26). Blank = the default
// (`en.*,live_chat`), omitted; "with-download" is the default chat mode,
// omitted too, so choosing it clears a stored mode.
- const subLangs = stringOrUndef(formData, "subLangs");
+ const subLangsRaw = stringOrUndef(formData, "subLangs");
+ let subLangs = subLangsRaw ? normalizeSubLangs(subLangsRaw) : undefined;
+ if (subLangsRaw) {
+ const problem = subLangsProblem(subLangsRaw);
+ const stored = ctx.stored?.subLangs?.trim();
+ if (problem && stored && normalizeSubLangs(stored) === subLangs) {
+ // Unchanged from what is stored: kept as stored, and said.
+ subLangs = stored;
+ warnings.push(`Caption languages ${problem}. Kept as stored, since it is unchanged; yt-dlp may refuse it.`);
+ } else if (problem) {
+ throw new Error(`Caption languages ${problem}`);
+ }
+ }
const chatRaw = String(formData.get("chat") ?? "").trim();
if (chatRaw && !isChatMode(chatRaw)) {
throw new Error(`Live chat must be one of: ${CHAT_MODES.join(", ")}`);
@@ -502,7 +530,7 @@ export function parseChannelForm(formData: FormData): ParsedChannelForm {
if (wayback) config.wayback = wayback;
if (xSearch) config.xSearch = xSearch;
- return { name, slug, config };
+ return { name, slug, config, warnings };
}
// The platform select's value for an X search channel: not a platform (the
diff --git a/editor/app/settings/saveSettings.test.ts b/editor/app/settings/saveSettings.test.ts
@@ -18,7 +18,7 @@ const ROOT = mkdtempSync(path.join(os.tmpdir(), "save-settings-"));
process.env.TRANSCRIPTS_DIR = ROOT;
process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
-const { mergeSettingsPatch, saveSettings } = await import("./saveSettings");
+const { mergeSettingsPatch, saveSettings, saveSettingsHeld, withSettingsLock } = await import("./saveSettings");
const { defaultSiteSettings, getSettings } = await import(
"yt-dlp-transcript-common/lib/settings"
);
@@ -134,3 +134,26 @@ test("an icon stored by an older build survives unrelated saves; editing it is c
{ ...stored, svg: `<svg aria-hidden="true" fill="currentColor" viewBox="0 0 8 8"><path d="M0 0"/></svg>` },
]);
});
+
+// THE LOCK (review of lane editor-gaps): a long read-modify-write held under
+// withSettingsLock is not written over by a save that starts while it runs —
+// the save waits, reads what the held writer wrote, and keeps both changes.
+test("a save waits for a held read-modify-write and keeps its change", async () => {
+ writeFileSync(process.env.SETTINGS_FILE!, JSON.stringify(defaultSiteSettings()));
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const held = withSettingsLock(async () => {
+ const read = getSettings();
+ await gate; // an await between the read and the write, as the priority writer has
+ // The whole document as read, as a writer of a full block does: a save
+ // that slipped in between would be written over.
+ await saveSettingsHeld({ ...read, syncScheduler: { ...read.syncScheduler, maxConcurrentSyncs: 5 } });
+ });
+ const other = saveSettings({ minFreeDiskGB: 42 });
+ await new Promise((r) => setTimeout(r, 20));
+ release();
+ await Promise.all([held, other]);
+ const after = getSettings();
+ assert.equal(after.syncScheduler.maxConcurrentSyncs, 5);
+ assert.equal(after.minFreeDiskGB, 42, "the later save read the held writer's result");
+});
diff --git a/editor/app/settings/saveSettings.ts b/editor/app/settings/saveSettings.ts
@@ -3,6 +3,8 @@ import {
writeSettings,
type SiteSettings,
} from "yt-dlp-transcript-common/lib/settings";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { withJsonFileLock } from "yt-dlp-transcript-common/lib/jsonFile-server";
// THE EDITOR'S ONE SETTINGS WRITER (one-core phase 3 slice 4a).
//
@@ -53,6 +55,24 @@ export function mergeSettingsPatch(
return merged as SiteSettings;
}
-export async function saveSettings(patch: Patch): Promise<void> {
+// THE SETTINGS LOCK (review of lane editor-gaps). A save reads the file,
+// merges and writes; two saves that interleave — one reading before the other
+// has written — lose the first one's change. Every save runs inside the lock
+// on settings.json, so the read and the write of one save never straddle
+// another's. A writer whose read-modify-write is longer than one patch (the
+// channel-priority writer reads the document, compiles the lane roots and
+// writes both) takes the lock itself and saves with `saveSettingsHeld`.
+// Per process (withJsonFileLock); NOT re-entrant: never call saveSettings
+// from inside withSettingsLock.
+export function withSettingsLock<T>(fn: () => Promise<T>): Promise<T> {
+ return withJsonFileLock(getPaths().settingsFile, fn);
+}
+
+// A save for a caller already holding the lock.
+export async function saveSettingsHeld(patch: Patch): Promise<void> {
await writeSettings(mergeSettingsPatch(getSettings(), patch));
}
+
+export async function saveSettings(patch: Patch): Promise<void> {
+ await withSettingsLock(() => saveSettingsHeld(patch));
+}
diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts
@@ -1,33 +1,7 @@
"use server";
-import { PUBLISH_POLICIES, type PublishPolicy } from "yt-dlp-transcript-common/lib/settingsSchema";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
-import {
- parseAccent,
- parseAccentSetting,
-} from "yt-dlp-transcript-common/lib/accent";
-import {
- DEFAULT_ACCENT,
- wordmarkLeadFor,
-} from "yt-dlp-transcript-common/lib/brand";
-import {
- getSite,
- writeSite,
- isValidSiteId,
- reservedSiteIdProblem,
- parseRelatedSites,
- parseSiteChannels,
- parseSiteUrl,
- type Site,
-} from "yt-dlp-transcript-common/lib/site";
-import {
- parseSocialLinks,
- type SocialLink,
-} from "yt-dlp-transcript-common/lib/settings";
-import {
- parseChannelGroups,
- resolveDefaultGroupId,
-} from "yt-dlp-transcript-common/lib/channelGroups";
+import { isValidSiteId, withSiteLock } from "yt-dlp-transcript-common/lib/site";
import { migrateToSites } from "yt-dlp-transcript-common/controller/migrateToSites";
import {
SiteDeleteRefusedError,
@@ -36,288 +10,21 @@ import {
siteDeleteBlocked,
type SiteDeletePlan,
} from "yt-dlp-transcript-common/publish/siteDelete";
-import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks";
-import { formValues, type FormState, type FormValues } from "../lib/formState";
-import { reportSiteKeysFromForm } from "./lib/reportSiteKeys";
-import { citedChannelsFromForm } from "./lib/citedChannelsFromForm";
+import { saveSiteFromForm, type SaveResult } from "./lib/saveSiteForm";
-// A failure carries what was submitted, so SiteForm keeps what was typed
-// (lib/formState.ts).
-export type SaveResult = FormState<{ siteId: string; values: FormValues }>;
+export type { SaveResult } from "./lib/saveSiteForm";
+// The site form's Save: the save under the site's lock (lib/site.ts
+// withSiteLock), so it and a concurrent patch of the same site (the Reports
+// tab's pages, a channel delete's membership patch) never interleave. An
+// invalid id has no file to lock; the save refuses it in its own words.
export async function saveSiteAction(
_prev: SaveResult | undefined,
formData: FormData,
): Promise<SaveResult> {
- const values = formValues(formData);
const siteId = String(formData.get("siteId") ?? "").trim();
- if (!isValidSiteId(siteId)) {
- return {
- ok: false,
- error: "Site ID must be lowercase letters, numbers, and hyphens.",
- values,
- };
- }
- // `articles` and `new` are the editor's own /sites/ routes (writeSite refuses
- // them too): said here, before anything else is read.
- const reserved = reservedSiteIdProblem(siteId);
- if (reserved) return { ok: false, error: reserved, values };
- const siteTitle = String(formData.get("siteTitle") ?? "").trim();
- const headerTitle = String(formData.get("headerTitle") ?? "").trim();
- if (!siteTitle) {
- return { ok: false, error: "Site title is required", values };
- }
- if (!headerTitle) {
- return { ok: false, error: "Header title is required", values };
- }
- const siteDescription = String(formData.get("siteDescription") ?? "").trim();
- const homeTagline = String(formData.get("homeTagline") ?? "").trim();
- // The wordmark's heavy lead must be a proper prefix of the header title;
- // lib/siteSchema.ts would silently drop anything else, so say so here.
- const wordmarkLead = String(formData.get("wordmarkLead") ?? "").trim();
- if (wordmarkLead && !wordmarkLeadFor(headerTitle, wordmarkLead)) {
- return {
- ok: false,
- error: `Wordmark lead must be how the header title starts, same case, and shorter than it (e.g. "Jer" for "Jeralyzer") — or left blank.`,
- values,
- };
- }
- // Brand accent: a named id from the radio group, or "custom" + its hex
- // field. The default (Signal) is stored as absent — the two read the same.
- // A bare hex in `accent` (a form from before the radio group) is taken as
- // a custom colour.
- const accentChoice = String(formData.get("accent") ?? "").trim();
- const accentCustomRaw = String(formData.get("accentCustom") ?? "").trim();
- let accent: string | undefined;
- if (accentChoice === "custom") {
- accent = parseAccent(accentCustomRaw);
- if (!accent) {
- return {
- ok: false,
- error: "Custom accent must be a hex color like #cc3366.",
- values,
- };
- }
- } else if (accentChoice) {
- accent = parseAccentSetting(accentChoice);
- if (!accent) {
- return {
- ok: false,
- error: `Unknown brand accent "${accentChoice}".`,
- values,
- };
- }
- if (accent === DEFAULT_ACCENT) accent = undefined;
- }
- const cloudflareProject = String(
- formData.get("cloudflareProject") ?? "",
- ).trim();
- const siteUrlRaw = String(formData.get("siteUrl") ?? "").trim();
- if (siteUrlRaw && !parseSiteUrl(siteUrlRaw)) {
- return {
- ok: false,
- error: "Public URL must be an absolute http(s):// URL, or left blank.",
- values,
- };
- }
- const siteUrl = parseSiteUrl(siteUrlRaw);
- // Listed on the homepage and hub by default: the same opt-out idiom as
- // archives below (an unchecked box sends no key → persisted as false).
- const listed = formData.get("listed") === "on";
- // Who the site is built for (release 17 slice XP): only "private" is kept.
- const audienceRaw = String(formData.get("audience") ?? "public");
- if (audienceRaw !== "public" && audienceRaw !== "private") {
- return { ok: false, error: `Unknown audience "${audienceRaw}".`, values };
- }
- const isPrivate = audienceRaw === "private";
- // The publish lane's policy for this site (release 18). writeSite refuses a
- // deploying policy with no Pages project (sitePublishProblem) and stores a
- // private site's as "build".
- const publishAutoRaw = String(formData.get("publishAuto") ?? "off");
- if (!(PUBLISH_POLICIES as readonly string[]).includes(publishAutoRaw)) {
- return { ok: false, error: `Unknown publish policy "${publishAutoRaw}".`, values };
- }
- const publishAuto = publishAutoRaw as PublishPolicy;
- // Search (opt-out; off = pages only) and the page list, which is not on
- // this form: the stored one is carried over.
- let storedReports: Pick<Site, "pages"> | undefined;
- try {
- storedReports = getSite(siteId, getPaths());
- } catch {
- storedReports = undefined;
- }
- const reportKeys = reportSiteKeysFromForm(formData, storedReports);
-
- // Hub parent (per-site override of the family default) + PWA opt-in.
- const hubUrlRaw = String(formData.get("hubUrl") ?? "").trim();
- if (hubUrlRaw && !parseSiteUrl(hubUrlRaw)) {
- return {
- ok: false,
- error: "Hub URL must be an absolute http(s):// URL, or left blank.",
- values,
- };
- }
- const hubUrl = parseSiteUrl(hubUrlRaw);
- const pwa = formData.get("pwa") === "on";
- // Archives default on: an unchecked (default-on) box yields no "archives" key
- // → false → persisted as the explicit opt-out.
- const archives = formData.get("archives") === "on";
- // Duplicates default on, same opt-out idiom as archives.
- const duplicates = formData.get("duplicates") === "on";
- // Per-video transcript downloads default on, same opt-out idiom.
- const transcriptDownloads = formData.get("transcriptDownloads") === "on";
- const archiveMaxMBRaw = String(formData.get("archiveMaxMB") ?? "").trim();
- let archiveMaxBytes: number | undefined;
- if (archiveMaxMBRaw) {
- const mb = Number(archiveMaxMBRaw);
- if (!Number.isFinite(mb) || mb < 0) {
- return {
- ok: false,
- error: "Archive size cap must be a non-negative number of MB, or blank.",
- values,
- };
- }
- archiveMaxBytes = Math.floor(mb * 1024 * 1024);
- }
-
- let relatedSitesInput: unknown;
- try {
- relatedSitesInput = JSON.parse(
- String(formData.get("relatedSitesJson") ?? "[]"),
- );
- } catch {
- return { ok: false, error: "Related sites payload is malformed", values };
- }
- const relatedSites = parseRelatedSites(relatedSitesInput);
-
- let groupsInput: unknown;
- try {
- groupsInput = JSON.parse(String(formData.get("groupsJson") ?? "[]"));
- } catch {
- return { ok: false, error: "Channel groups payload is malformed", values };
- }
- const groups = parseChannelGroups(groupsInput);
- if (groups.length === 0) {
- return {
- ok: false,
- error: "At least one channel group is required (check ID/name fields)",
- values,
- };
- }
- const defaultGroupIdRaw = String(formData.get("defaultGroupId") ?? "").trim();
- const defaultGroupId = resolveDefaultGroupId(defaultGroupIdRaw, groups);
- if (defaultGroupIdRaw && defaultGroupIdRaw !== defaultGroupId) {
- return {
- ok: false,
- error: `Default group "${defaultGroupIdRaw}" is not among the configured group IDs`,
- values,
- };
- }
-
- // When inheriting, leave socialLinks undefined so writeSite omits the key and
- // the site falls back to the global default at render time.
- const inheritSocialLinks = formData.get("inheritSocialLinks") === "on";
- let socialLinks: SocialLink[] | undefined;
- if (!inheritSocialLinks) {
- let socialInput: unknown;
- try {
- socialInput = JSON.parse(String(formData.get("socialLinksJson") ?? "[]"));
- } catch {
- return { ok: false, error: "Social links payload is malformed", values };
- }
- const socialParsed = parseSocialLinks(socialInput);
- if (
- Array.isArray(socialInput) &&
- socialParsed.length !== socialInput.length
- ) {
- return {
- ok: false,
- error:
- "Each social link needs a label, URL (http(s)://, mailto:, or /), and SVG.",
- values,
- };
- }
- // A link whose SVG is unchanged from the site's file is kept as it is; a
- // new or edited one is checked (lib/socialLinks.ts socialLinksForSave).
- let stored: SocialLink[] = [];
- try {
- stored = getSite(siteId, getPaths()).socialLinks ?? [];
- } catch {
- stored = [];
- }
- const checked = socialLinksForSave(socialParsed, stored);
- if ("refused" in checked) {
- return {
- ok: false,
- error: `Social link "${checked.refused.label}" has an invalid SVG: ${checked.refused.problem}.`,
- values,
- };
- }
- socialLinks = checked.links;
- }
-
- let channelsInput: unknown;
- try {
- channelsInput = JSON.parse(String(formData.get("channelsJson") ?? "[]"));
- } catch {
- return {
- ok: false,
- error: "Channel membership payload is malformed",
- values,
- };
- }
- const channels = parseSiteChannels(channelsInput);
- // The cited scope: channels outside the pool this site's reports may cite
- // without publishing them (lib/citedChannelsFromForm.ts).
- const citedChannels = citedChannelsFromForm(formData, channels);
- if (citedChannels === null) {
- return { ok: false, error: "Cited channels payload is malformed", values };
- }
-
- const site: Site = {
- siteId,
- siteTitle,
- siteDescription,
- headerTitle,
- ...(wordmarkLead ? { wordmarkLead } : {}),
- homeTagline,
- ...(socialLinks !== undefined ? { socialLinks } : {}),
- groups,
- defaultGroupId,
- channels,
- ...(citedChannels.length > 0 ? { citedChannels } : {}),
- ...(accent ? { accent } : {}),
- ...(cloudflareProject ? { cloudflareProject } : {}),
- ...(siteUrl ? { siteUrl } : {}),
- // The Site is rebuilt from the form: a key missing here is dropped on save.
- ...(listed ? {} : { listed: false }),
- ...(isPrivate ? { audience: "private" as const } : {}),
- ...(publishAuto !== "off" ? { publish: { auto: publishAuto } } : {}),
- ...reportKeys,
- ...(hubUrl ? { hubUrl } : {}),
- ...(pwa ? { pwa: true } : {}),
- ...(archives ? {} : { archives: false }),
- ...(duplicates ? {} : { duplicates: false }),
- ...(transcriptDownloads ? {} : { transcriptDownloads: false }),
- ...(archiveMaxBytes !== undefined ? { archiveMaxBytes } : {}),
- ...(relatedSites.length > 0 ? { relatedSites } : {}),
- };
- try {
- await writeSite(site, getPaths());
- } catch (err) {
- return {
- ok: false,
- error: err instanceof Error ? err.message : String(err),
- values,
- };
- }
- // NO revalidatePath (release 24 H5): React commits a revalidating action's
- // state with the router's refresh of the page, which now and then did not
- // settle until the next AutoRefresh tick, so "Saved." came up to ~6 s late.
- // SiteForm seeds from `values` and refreshes the page itself once "Saved." is
- // in (lib/formState.ts seedAfterSave, lib/useRefreshAfterSave.ts) — the h1
- // above the tabs and /sites's list follow with that refresh.
- return { ok: true, siteId, values };
+ if (!isValidSiteId(siteId)) return saveSiteFromForm(formData);
+ return withSiteLock(siteId, () => saveSiteFromForm(formData));
}
export type DeleteResult = { ok: true } | { ok: false; error: string };
diff --git a/editor/app/sites/lib/saveSiteForm.ts b/editor/app/sites/lib/saveSiteForm.ts
@@ -0,0 +1,317 @@
+// The site form's save (moved out of sites/actions.ts, review of lane
+// editor-gaps, so a caller can hold the site's lock around it). NOT a "use
+// server" module: saveSiteAction is the action a client may call.
+
+import { PUBLISH_POLICIES, type PublishPolicy } from "yt-dlp-transcript-common/lib/settingsSchema";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import {
+ parseAccent,
+ parseAccentSetting,
+} from "yt-dlp-transcript-common/lib/accent";
+import {
+ DEFAULT_ACCENT,
+ wordmarkLeadFor,
+} from "yt-dlp-transcript-common/lib/brand";
+import {
+ getSite,
+ writeSite,
+ isValidSiteId,
+ reservedSiteIdProblem,
+ parseRelatedSites,
+ parseSiteChannels,
+ parseSiteUrl,
+ type Site,
+} from "yt-dlp-transcript-common/lib/site";
+import {
+ parseSocialLinks,
+ type SocialLink,
+} from "yt-dlp-transcript-common/lib/settings";
+import {
+ parseChannelGroups,
+ resolveDefaultGroupId,
+} from "yt-dlp-transcript-common/lib/channelGroups";
+import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks";
+import { formValues, type FormState, type FormValues } from "../../lib/formState";
+import { reportSiteKeysFromForm } from "./reportSiteKeys";
+import { citedChannelsFromForm } from "./citedChannelsFromForm";
+
+// A failure carries what was submitted, so SiteForm keeps what was typed
+// (lib/formState.ts).
+export type SaveResult = FormState<{ siteId: string; values: FormValues }>;
+
+// THE SITE FORM'S SAVE, without its lock: the caller holds the site's lock
+// (withSiteLock) around it, so the stored keys it carries over (the page
+// list, unchanged social link SVGs) and the write are one read-modify-write.
+// saveSiteAction is the form's; `pnpm ops create-site` takes the lock around
+// its own read of the stored site as well.
+export async function saveSiteFromForm(formData: FormData): Promise<SaveResult> {
+ const values = formValues(formData);
+ const siteId = String(formData.get("siteId") ?? "").trim();
+ if (!isValidSiteId(siteId)) {
+ return {
+ ok: false,
+ error: "Site ID must be lowercase letters, numbers, and hyphens.",
+ values,
+ };
+ }
+ // `articles` and `new` are the editor's own /sites/ routes (writeSite refuses
+ // them too): said here, before anything else is read.
+ const reserved = reservedSiteIdProblem(siteId);
+ if (reserved) return { ok: false, error: reserved, values };
+ const siteTitle = String(formData.get("siteTitle") ?? "").trim();
+ const headerTitle = String(formData.get("headerTitle") ?? "").trim();
+ if (!siteTitle) {
+ return { ok: false, error: "Site title is required", values };
+ }
+ if (!headerTitle) {
+ return { ok: false, error: "Header title is required", values };
+ }
+ const siteDescription = String(formData.get("siteDescription") ?? "").trim();
+ const homeTagline = String(formData.get("homeTagline") ?? "").trim();
+ // The wordmark's heavy lead must be a proper prefix of the header title;
+ // lib/siteSchema.ts would silently drop anything else, so say so here.
+ const wordmarkLead = String(formData.get("wordmarkLead") ?? "").trim();
+ if (wordmarkLead && !wordmarkLeadFor(headerTitle, wordmarkLead)) {
+ return {
+ ok: false,
+ error: `Wordmark lead must be how the header title starts, same case, and shorter than it (e.g. "Jer" for "Jeralyzer") — or left blank.`,
+ values,
+ };
+ }
+ // Brand accent: a named id from the radio group, or "custom" + its hex
+ // field. The default (Signal) is stored as absent — the two read the same.
+ // A bare hex in `accent` (a form from before the radio group) is taken as
+ // a custom colour.
+ const accentChoice = String(formData.get("accent") ?? "").trim();
+ const accentCustomRaw = String(formData.get("accentCustom") ?? "").trim();
+ let accent: string | undefined;
+ if (accentChoice === "custom") {
+ accent = parseAccent(accentCustomRaw);
+ if (!accent) {
+ return {
+ ok: false,
+ error: "Custom accent must be a hex color like #cc3366.",
+ values,
+ };
+ }
+ } else if (accentChoice) {
+ accent = parseAccentSetting(accentChoice);
+ if (!accent) {
+ return {
+ ok: false,
+ error: `Unknown brand accent "${accentChoice}".`,
+ values,
+ };
+ }
+ if (accent === DEFAULT_ACCENT) accent = undefined;
+ }
+ const cloudflareProject = String(
+ formData.get("cloudflareProject") ?? "",
+ ).trim();
+ const siteUrlRaw = String(formData.get("siteUrl") ?? "").trim();
+ if (siteUrlRaw && !parseSiteUrl(siteUrlRaw)) {
+ return {
+ ok: false,
+ error: "Public URL must be an absolute http(s):// URL, or left blank.",
+ values,
+ };
+ }
+ const siteUrl = parseSiteUrl(siteUrlRaw);
+ // Listed on the homepage and hub by default: the same opt-out idiom as
+ // archives below (an unchecked box sends no key → persisted as false).
+ const listed = formData.get("listed") === "on";
+ // Who the site is built for (release 17 slice XP): only "private" is kept.
+ const audienceRaw = String(formData.get("audience") ?? "public");
+ if (audienceRaw !== "public" && audienceRaw !== "private") {
+ return { ok: false, error: `Unknown audience "${audienceRaw}".`, values };
+ }
+ const isPrivate = audienceRaw === "private";
+ // The publish lane's policy for this site (release 18). writeSite refuses a
+ // deploying policy with no Pages project (sitePublishProblem) and stores a
+ // private site's as "build".
+ const publishAutoRaw = String(formData.get("publishAuto") ?? "off");
+ if (!(PUBLISH_POLICIES as readonly string[]).includes(publishAutoRaw)) {
+ return { ok: false, error: `Unknown publish policy "${publishAutoRaw}".`, values };
+ }
+ const publishAuto = publishAutoRaw as PublishPolicy;
+ // Search (opt-out; off = pages only) and the page list, which is not on
+ // this form: the stored one is carried over.
+ let storedReports: Pick<Site, "pages"> | undefined;
+ try {
+ storedReports = getSite(siteId, getPaths());
+ } catch {
+ storedReports = undefined;
+ }
+ const reportKeys = reportSiteKeysFromForm(formData, storedReports);
+
+ // Hub parent (per-site override of the family default) + PWA opt-in.
+ const hubUrlRaw = String(formData.get("hubUrl") ?? "").trim();
+ if (hubUrlRaw && !parseSiteUrl(hubUrlRaw)) {
+ return {
+ ok: false,
+ error: "Hub URL must be an absolute http(s):// URL, or left blank.",
+ values,
+ };
+ }
+ const hubUrl = parseSiteUrl(hubUrlRaw);
+ const pwa = formData.get("pwa") === "on";
+ // Archives default on: an unchecked (default-on) box yields no "archives" key
+ // → false → persisted as the explicit opt-out.
+ const archives = formData.get("archives") === "on";
+ // Duplicates default on, same opt-out idiom as archives.
+ const duplicates = formData.get("duplicates") === "on";
+ // Per-video transcript downloads default on, same opt-out idiom.
+ const transcriptDownloads = formData.get("transcriptDownloads") === "on";
+ const archiveMaxMBRaw = String(formData.get("archiveMaxMB") ?? "").trim();
+ let archiveMaxBytes: number | undefined;
+ if (archiveMaxMBRaw) {
+ const mb = Number(archiveMaxMBRaw);
+ if (!Number.isFinite(mb) || mb < 0) {
+ return {
+ ok: false,
+ error: "Archive size cap must be a non-negative number of MB, or blank.",
+ values,
+ };
+ }
+ archiveMaxBytes = Math.floor(mb * 1024 * 1024);
+ }
+
+ let relatedSitesInput: unknown;
+ try {
+ relatedSitesInput = JSON.parse(
+ String(formData.get("relatedSitesJson") ?? "[]"),
+ );
+ } catch {
+ return { ok: false, error: "Related sites payload is malformed", values };
+ }
+ const relatedSites = parseRelatedSites(relatedSitesInput);
+
+ let groupsInput: unknown;
+ try {
+ groupsInput = JSON.parse(String(formData.get("groupsJson") ?? "[]"));
+ } catch {
+ return { ok: false, error: "Channel groups payload is malformed", values };
+ }
+ const groups = parseChannelGroups(groupsInput);
+ if (groups.length === 0) {
+ return {
+ ok: false,
+ error: "At least one channel group is required (check ID/name fields)",
+ values,
+ };
+ }
+ const defaultGroupIdRaw = String(formData.get("defaultGroupId") ?? "").trim();
+ const defaultGroupId = resolveDefaultGroupId(defaultGroupIdRaw, groups);
+ if (defaultGroupIdRaw && defaultGroupIdRaw !== defaultGroupId) {
+ return {
+ ok: false,
+ error: `Default group "${defaultGroupIdRaw}" is not among the configured group IDs`,
+ values,
+ };
+ }
+
+ // When inheriting, leave socialLinks undefined so writeSite omits the key and
+ // the site falls back to the global default at render time.
+ const inheritSocialLinks = formData.get("inheritSocialLinks") === "on";
+ let socialLinks: SocialLink[] | undefined;
+ if (!inheritSocialLinks) {
+ let socialInput: unknown;
+ try {
+ socialInput = JSON.parse(String(formData.get("socialLinksJson") ?? "[]"));
+ } catch {
+ return { ok: false, error: "Social links payload is malformed", values };
+ }
+ const socialParsed = parseSocialLinks(socialInput);
+ if (
+ Array.isArray(socialInput) &&
+ socialParsed.length !== socialInput.length
+ ) {
+ return {
+ ok: false,
+ error:
+ "Each social link needs a label, URL (http(s)://, mailto:, or /), and SVG.",
+ values,
+ };
+ }
+ // A link whose SVG is unchanged from the site's file is kept as it is; a
+ // new or edited one is checked (lib/socialLinks.ts socialLinksForSave).
+ let stored: SocialLink[] = [];
+ try {
+ stored = getSite(siteId, getPaths()).socialLinks ?? [];
+ } catch {
+ stored = [];
+ }
+ const checked = socialLinksForSave(socialParsed, stored);
+ if ("refused" in checked) {
+ return {
+ ok: false,
+ error: `Social link "${checked.refused.label}" has an invalid SVG: ${checked.refused.problem}.`,
+ values,
+ };
+ }
+ socialLinks = checked.links;
+ }
+
+ let channelsInput: unknown;
+ try {
+ channelsInput = JSON.parse(String(formData.get("channelsJson") ?? "[]"));
+ } catch {
+ return {
+ ok: false,
+ error: "Channel membership payload is malformed",
+ values,
+ };
+ }
+ const channels = parseSiteChannels(channelsInput);
+ // The cited scope: channels outside the pool this site's reports may cite
+ // without publishing them (lib/citedChannelsFromForm.ts).
+ const citedChannels = citedChannelsFromForm(formData, channels);
+ if (citedChannels === null) {
+ return { ok: false, error: "Cited channels payload is malformed", values };
+ }
+
+ const site: Site = {
+ siteId,
+ siteTitle,
+ siteDescription,
+ headerTitle,
+ ...(wordmarkLead ? { wordmarkLead } : {}),
+ homeTagline,
+ ...(socialLinks !== undefined ? { socialLinks } : {}),
+ groups,
+ defaultGroupId,
+ channels,
+ ...(citedChannels.length > 0 ? { citedChannels } : {}),
+ ...(accent ? { accent } : {}),
+ ...(cloudflareProject ? { cloudflareProject } : {}),
+ ...(siteUrl ? { siteUrl } : {}),
+ // The Site is rebuilt from the form: a key missing here is dropped on save.
+ ...(listed ? {} : { listed: false }),
+ ...(isPrivate ? { audience: "private" as const } : {}),
+ ...(publishAuto !== "off" ? { publish: { auto: publishAuto } } : {}),
+ ...reportKeys,
+ ...(hubUrl ? { hubUrl } : {}),
+ ...(pwa ? { pwa: true } : {}),
+ ...(archives ? {} : { archives: false }),
+ ...(duplicates ? {} : { duplicates: false }),
+ ...(transcriptDownloads ? {} : { transcriptDownloads: false }),
+ ...(archiveMaxBytes !== undefined ? { archiveMaxBytes } : {}),
+ ...(relatedSites.length > 0 ? { relatedSites } : {}),
+ };
+ try {
+ await writeSite(site, getPaths());
+ } catch (err) {
+ return {
+ ok: false,
+ error: err instanceof Error ? err.message : String(err),
+ values,
+ };
+ }
+ // NO revalidatePath (release 24 H5): React commits a revalidating action's
+ // state with the router's refresh of the page, which now and then did not
+ // settle until the next AutoRefresh tick, so "Saved." came up to ~6 s late.
+ // SiteForm seeds from `values` and refreshes the page itself once "Saved." is
+ // in (lib/formState.ts seedAfterSave, lib/useRefreshAfterSave.ts) — the h1
+ // above the tabs and /sites's list follow with that refresh.
+ return { ok: true, siteId, values };
+}
diff --git a/editor/app/sites/lib/siteFormData.ts b/editor/app/sites/lib/siteFormData.ts
@@ -0,0 +1,208 @@
+// THE SITE FORM'S FIELDS, BUILT WITHOUT A BROWSER — for `pnpm ops create-site`.
+//
+// The site form posts a FormData that saveSiteAction rebuilds the whole Site
+// from (a key it does not post is dropped on save). So an ops caller goes
+// through the same action with the same FormData: `siteToFormData` is the form
+// a site would post if nothing in it were touched (what SiteForm seeds from),
+// and `applySiteFields` lays the caller's keys over it. A create starts from a
+// blank site, an update from the stored one — "update" is the site page's Save
+// with those fields changed, and every key not named stays as it was.
+//
+// Pure: no fs, no server. The round trip (stored site -> FormData -> action ->
+// the same site.json) is pinned in app/api/ops/create-site/route.test.ts.
+
+import { isAccentId } from "yt-dlp-transcript-common/lib/brand";
+import { parseChannelGroup } from "yt-dlp-transcript-common/lib/channelGroups";
+import type { Site } from "yt-dlp-transcript-common/lib/site";
+import { CITED_CHANNELS_FIELD } from "./citedChannelsFromForm";
+
+const MB = 1024 * 1024;
+
+const on = (fd: FormData, key: string, value: boolean) => {
+ if (value) fd.set(key, "on");
+ else fd.delete(key);
+};
+
+export function siteToFormData(site: Site): FormData {
+ const fd = new FormData();
+ fd.set("siteId", site.siteId);
+ fd.set("siteTitle", site.siteTitle);
+ fd.set("headerTitle", site.headerTitle);
+ fd.set("wordmarkLead", site.wordmarkLead ?? "");
+ fd.set("siteDescription", site.siteDescription);
+ fd.set("homeTagline", site.homeTagline);
+ setAccent(fd, site.accent);
+ fd.set("cloudflareProject", site.cloudflareProject ?? "");
+ fd.set("siteUrl", site.siteUrl ?? "");
+ fd.set("audience", site.audience === "private" ? "private" : "public");
+ fd.set("publishAuto", site.publish?.auto ?? "off");
+ // The opt-out checkboxes: absent / true = ticked.
+ on(fd, "search", site.search !== false);
+ on(fd, "listed", site.listed !== false);
+ on(fd, "archives", site.archives !== false);
+ on(fd, "duplicates", site.duplicates !== false);
+ on(fd, "transcriptDownloads", site.transcriptDownloads !== false);
+ on(fd, "pwa", site.pwa === true);
+ fd.set("hubUrl", site.hubUrl ?? "");
+ // bytes / 2^20 is exact in binary and String() round-trips, so the action's
+ // floor(MB * 2^20) gives the stored bytes back.
+ fd.set("archiveMaxMB", site.archiveMaxBytes !== undefined ? String(site.archiveMaxBytes / MB) : "");
+ setSocialLinks(fd, site.socialLinks);
+ fd.set("groupsJson", JSON.stringify(site.groups));
+ fd.set("defaultGroupId", site.defaultGroupId);
+ fd.set("channelsJson", JSON.stringify(site.channels));
+ fd.set(CITED_CHANNELS_FIELD, JSON.stringify((site.citedChannels ?? []).map((c) => c.slug)));
+ fd.set("relatedSitesJson", JSON.stringify(site.relatedSites ?? []));
+ return fd;
+}
+
+function setAccent(fd: FormData, accent: string | undefined) {
+ // Absent = the default accent (the radio group's first choice reads the same).
+ if (!accent || isAccentId(accent)) {
+ fd.set("accent", accent ?? "");
+ fd.delete("accentCustom");
+ return;
+ }
+ fd.set("accent", "custom");
+ fd.set("accentCustom", accent);
+}
+
+function setSocialLinks(fd: FormData, links: unknown[] | undefined | null) {
+ if (links === undefined || links === null) {
+ fd.set("inheritSocialLinks", "on");
+ fd.delete("socialLinksJson");
+ return;
+ }
+ fd.delete("inheritSocialLinks");
+ fd.set("socialLinksJson", JSON.stringify(links));
+}
+
+// The keys `create-site` takes beyond `siteId` and `update`, each the form
+// field of the same meaning.
+export const SITE_OPS_FIELDS = [
+ "siteTitle",
+ "headerTitle",
+ "siteDescription",
+ "homeTagline",
+ "wordmarkLead",
+ "accent",
+ "cloudflareProject",
+ "siteUrl",
+ "hubUrl",
+ "audience",
+ "publishAuto",
+ "listed",
+ "search",
+ "archives",
+ "duplicates",
+ "transcriptDownloads",
+ "pwa",
+ "archiveMaxMB",
+ "groups",
+ "defaultGroupId",
+ "channels",
+ "citedChannels",
+ "socialLinks",
+ "relatedSites",
+] as const;
+
+const STRING_FIELDS = new Set([
+ "siteTitle",
+ "headerTitle",
+ "siteDescription",
+ "homeTagline",
+ "wordmarkLead",
+ "cloudflareProject",
+ "siteUrl",
+ "hubUrl",
+ "audience",
+ "publishAuto",
+ "defaultGroupId",
+]);
+const BOOL_FIELDS = new Set(["listed", "search", "archives", "duplicates", "transcriptDownloads", "pwa"]);
+
+// A key of the wrong shape, in the caller's words. The VALUES are the action's
+// to judge (its sentences: an unknown audience, a bad URL, a group list with
+// none) — only what cannot be turned into a form field is refused here.
+export class SiteFieldError extends Error {}
+
+export function applySiteFields(fd: FormData, fields: Record<string, unknown>): void {
+ for (const [key, v] of Object.entries(fields)) {
+ if (v === undefined) continue;
+ if (STRING_FIELDS.has(key)) {
+ if (typeof v !== "string") throw new SiteFieldError(`"${key}" must be a string`);
+ fd.set(key, v);
+ } else if (BOOL_FIELDS.has(key)) {
+ if (typeof v !== "boolean") throw new SiteFieldError(`"${key}" must be a boolean`);
+ on(fd, key, v);
+ } else if (key === "accent") {
+ if (typeof v !== "string") throw new SiteFieldError(`"accent" must be a string (an accent id or "#rrggbb")`);
+ // A hex is the form's "custom"; anything else is the radio's id, for the
+ // action to accept or refuse by name.
+ const a = v.trim();
+ if (/^#?[0-9a-f]{6}$/i.test(a)) setAccent(fd, a);
+ else {
+ fd.set("accent", a);
+ fd.delete("accentCustom");
+ }
+ } else if (key === "archiveMaxMB") {
+ if (v !== null && (typeof v !== "number" || !Number.isFinite(v))) {
+ throw new SiteFieldError(`"archiveMaxMB" must be a number of MB, or null for the global default`);
+ }
+ fd.set("archiveMaxMB", v === null ? "" : String(v));
+ } else if (key === "groups") {
+ if (!Array.isArray(v)) throw new SiteFieldError(`"groups" must be an array of {id, name, …}`);
+ // The parser drops a group it cannot read, which on a form is a row the
+ // operator can see; over ops it would vanish without a word.
+ const bad = v.findIndex((g) => parseChannelGroup(g) === null);
+ if (bad >= 0) {
+ throw new SiteFieldError(
+ `"groups"[${bad}] is not a channel group: it needs an "id" (lowercase letters, digits, hyphens) and a "name"`,
+ );
+ }
+ fd.set("groupsJson", JSON.stringify(v.map((g, order) => (isObject(g) ? { order, ...g } : g))));
+ } else if (key === "channels") {
+ fd.set("channelsJson", JSON.stringify(readChannels(v)));
+ } else if (key === "citedChannels") {
+ if (!Array.isArray(v) || v.some((s) => typeof s !== "string")) {
+ throw new SiteFieldError(`"citedChannels" must be an array of channel slugs`);
+ }
+ fd.set(CITED_CHANNELS_FIELD, JSON.stringify(v));
+ } else if (key === "socialLinks") {
+ if (v !== null && !Array.isArray(v)) {
+ throw new SiteFieldError(`"socialLinks" must be an array of {label, url, svg}, or null to inherit the global default`);
+ }
+ setSocialLinks(fd, v as unknown[] | null);
+ } else if (key === "relatedSites") {
+ if (!Array.isArray(v)) throw new SiteFieldError(`"relatedSites" must be an array of {label?, siteIds}`);
+ fd.set("relatedSitesJson", JSON.stringify(v));
+ } else {
+ throw new SiteFieldError(`unknown site field "${key}"`);
+ }
+ }
+}
+
+// `channels`: slugs, or {slug, groupId?} — the pool, in the order given.
+export function readChannels(v: unknown): { slug: string; groupId?: string; order: number }[] {
+ if (!Array.isArray(v)) {
+ throw new SiteFieldError(`"channels" must be an array of channel slugs or {slug, groupId?}`);
+ }
+ return v.map((entry, order) => {
+ if (typeof entry === "string") return { slug: entry.trim(), order };
+ if (isObject(entry) && typeof entry.slug === "string") {
+ if (entry.groupId !== undefined && typeof entry.groupId !== "string") {
+ throw new SiteFieldError(`"channels": the groupId of "${entry.slug}" must be a string`);
+ }
+ return {
+ slug: entry.slug.trim(),
+ ...(typeof entry.groupId === "string" && entry.groupId.trim() ? { groupId: entry.groupId.trim() } : {}),
+ order,
+ };
+ }
+ throw new SiteFieldError(`"channels" must be an array of channel slugs or {slug, groupId?}`);
+ });
+}
+
+function isObject(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
diff --git a/editor/e2e/ops-api.spec.ts b/editor/e2e/ops-api.spec.ts
@@ -144,12 +144,23 @@ test("a channel's lifecycle over ops: create on a site, list, re-site, rename, d
expect(refused.body.error).toBe(
'Type the channel slug "made-renamed-x" exactly to confirm deletion',
);
+ // A deleted channel leaves no site naming it (lane editor-gaps, 9 Nov): back
+ // in mysite's pool, and in another site's cited scope.
+ expect(
+ (await ops(request, "channel-config", { slug: "made-renamed-x", sites: [{ siteId: "mysite" }] })).body,
+ ).toEqual({ ok: true });
+ await writeSite("citer", { channels: [] });
+ expect((await ops(request, "site-config", { siteId: "citer", citedChannels: ["made-renamed-x"] })).status).toBe(200);
+ const CITER = `${testPaths().transcriptsDir}/sites/citer/site.json`;
const gone = await ops(request, "delete-channel", {
slug: "made-renamed-x",
confirm: "made-renamed-x",
});
expect(gone.status).toBe(200);
+ expect(gone.body).toEqual({ ok: true, slug: "made-renamed-x", deleted: true, sitesUpdated: ["citer", "mysite"] });
expect(await list()).toEqual([]);
+ expect((await readJson<{ channels: unknown[] }>(SITE)).channels).toEqual([]);
+ expect((await readJson<{ citedChannels?: unknown[] }>(CITER)).citedChannels).toBeUndefined();
});
test("channel-config round-trips a download filter and refuses a bad regex", async ({
@@ -340,6 +351,97 @@ test("channel-priority sets and ends the focus", async ({ request }) => {
await expect.poll(async () => (await focusOf())?.kind ?? "none").toBe("none");
});
+// create-site (lane editor-gaps): the New site form over HTTP — the form's
+// action, so the site the /sites list shows; an existing id refused unless
+// "update", which keeps every key it does not name.
+test("create-site makes a private, unlisted site the /sites list shows; update changes only what it names", async ({
+ request,
+ page,
+}) => {
+ await resetData("one-youtube-channel-with-data");
+ await settings();
+ const made = await ops(request, "create-site", {
+ siteId: "opsalyzer",
+ siteTitle: "Opsalyzer",
+ channels: ["test-youtube"],
+ });
+ expect(made.status, JSON.stringify(made.body)).toBe(200);
+ type SiteFile = { siteTitle: string; homeTagline: string; audience?: string; listed?: boolean; channels: { slug: string }[] };
+ const file = `${testPaths().transcriptsDir}/sites/opsalyzer/site.json`;
+ const site = await readJson<SiteFile>(file);
+ expect(site).toMatchObject({ siteTitle: "Opsalyzer", audience: "private", listed: false });
+ expect(site.channels.map((c) => c.slug)).toEqual(["test-youtube"]);
+
+ await page.goto("/sites");
+ await expect(page.getByRole("link", { name: /Opsalyzer/ })).toBeVisible();
+
+ const again = await ops(request, "create-site", { siteId: "opsalyzer", siteTitle: "Other" });
+ expect(again.status).toBe(409);
+ expect(again.body.error).toMatch(/already exists/);
+
+ const up = await ops(request, "create-site", { siteId: "opsalyzer", update: true, homeTagline: "Searchable" });
+ expect(up.status, JSON.stringify(up.body)).toBe(200);
+ expect(await readJson<SiteFile>(file)).toEqual({ ...site, homeTagline: "Searchable" });
+});
+
+// channel-rank (lane editor-gaps): one channel moved in the order through the
+// deck's one writer — the rank alone; the tier and the lanes untouched, and
+// the four lane roots recompiled in the same write.
+test("channel-rank places a channel top, after another, by rank and unranked", async ({ request }) => {
+ await resetData("empty");
+ for (const slug of ["rank-a", "rank-b", "rank-c"]) await writeChannelConfig(slug, {});
+ await writeSettings({
+ minFreeDiskGB: 0,
+ channelPriority: {
+ focus: { kind: "none" },
+ channels: {
+ "rank-a": { tier: "normal", rank: 0 },
+ "rank-b": { tier: "low", rank: 1 },
+ "rank-c": { tier: "normal", rank: 2 },
+ },
+ },
+ });
+ type Prio = { channelPriority?: { channels?: Record<string, { tier: string; rank?: number }> } };
+ const ranks = async () => {
+ const c = (await readJson<Prio>(testPaths().settingsFile)).channelPriority?.channels ?? {};
+ return Object.fromEntries(Object.entries(c).map(([s, e]) => [s, e.rank ?? null]));
+ };
+
+ const top = await ops(request, "channel-rank", { slug: "rank-c", top: true });
+ expect(top.status, JSON.stringify(top.body)).toBe(200);
+ expect(top.body).toMatchObject({
+ ok: true,
+ slug: "rank-c",
+ rank: 0,
+ order: [
+ { slug: "rank-c", rank: 0 },
+ { slug: "rank-a", rank: 1 },
+ { slug: "rank-b", rank: 2 },
+ ],
+ });
+ await expect.poll(ranks).toEqual({ "rank-a": 1, "rank-b": 2, "rank-c": 0 });
+ const tiers = (await readJson<Prio>(testPaths().settingsFile)).channelPriority?.channels ?? {};
+ expect(tiers["rank-b"]?.tier).toBe("low");
+
+ const after = await ops(request, "channel-rank", { slug: "rank-b", after: "rank-c" });
+ expect(after.body).toMatchObject({ ok: true, rank: 1 });
+ await expect.poll(ranks).toEqual({ "rank-a": 2, "rank-b": 1, "rank-c": 0 });
+
+ const unrank = await ops(request, "channel-rank", { slug: "rank-a", rank: null });
+ expect(unrank.body).toMatchObject({ ok: true, slug: "rank-a", rank: null });
+ await expect.poll(ranks).toEqual({ "rank-b": 1, "rank-c": 0 });
+
+ // The compiled download root lists the channels in that order.
+ type Root = { autoQueue?: { download?: { root?: unknown } } };
+ const root = JSON.stringify((await readJson<Root>(testPaths().settingsFile)).autoQueue?.download?.root ?? null);
+ expect(root.indexOf("rank-c")).toBeGreaterThan(-1);
+ expect(root.indexOf("rank-c")).toBeLessThan(root.indexOf("rank-a"));
+
+ const refused = await ops(request, "channel-rank", { slug: "rank-c", before: "rank-a" });
+ expect(refused.status).toBe(400);
+ expect(refused.body.error).toMatch(/"rank-a" has no rank/);
+});
+
test("metadata-scan starts a job, and the job says it is a metadata-scan", async ({
request,
}) => {
diff --git a/package.json b/package.json
@@ -24,7 +24,7 @@
"wt": "node scripts/worktree.mjs",
"e2e:sharded": "node scripts/run-sharded-e2e.mjs",
"e2e:all": "node scripts/e2e-all.mjs",
- "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs",
+ "test:scripts": "node --test scripts/*.test.mjs umtool/report-to-video/*.test.mjs umtool/report-to-video/modules/*.test.mjs umtool/lib/*.test.mjs umtool/lib/report/*.test.mjs umtool/lib/annotations/*.test.mjs umtool/lib/articles/*.test.mjs umtool/lib/pieces/*.test.mjs umtool/lib/inbox/*.test.mjs umtool/lib/research/*.test.mjs umtool/lib/work/*.test.mjs umtool/lib/create/*.test.mjs umtool/lib/settings/*.test.mjs umtool/lib/queue/*.test.mjs umtool/lib/ingredients/*.test.mjs umtool/lib/cli/*.test.mjs",
"test": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 run test; a=$?; pnpm run test:scripts; b=$?; [ $a -eq 0 ] && [ $b -eq 0 ]",
"typecheck": "pnpm -r --no-bail --no-sort --workspace-concurrency=1 exec tsc --noEmit",
"lint": "pnpm --filter export run lint",
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -75,6 +75,8 @@
// pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}'
// pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'
// pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'
+// pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}'
+// pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}'
// pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'
// pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'
// pnpm ops articles-config --json '{"id":"demo-article","published":true}'
@@ -88,6 +90,9 @@
// pnpm ops delete-channel --json '{"slug":"x","confirm":"x"}'
// pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'
// pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'
+// pnpm ops channel-rank --json '{"slug":"x","top":true}'
+// pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'
+// pnpm ops channel-rank --json '{"slug":"x","rank":null}'
// pnpm ops lane --json '{"lane":"download","held":true}'
// pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'
// pnpm ops render-mode --json '{"on":false}'
@@ -373,7 +378,14 @@ export const JOB_VERBS = [
const ACTIONS = [
"channel-priority",
+ // One channel placed in the order the lanes follow ({slug} and one of rank
+ // | top | bottom | before | after), through the deck's one writer.
+ "channel-rank",
"channel-config",
+ // The New site form ({siteId, siteTitle, …its fields}), or the site page's
+ // Save with some keys changed ({siteId, update: true, …}), through the
+ // form's own action. Synchronous; no job.
+ "create-site",
// A site's cited-only channels and its publish policy ({siteId,
// citedChannels?, publishAuto?}), through the site form's own writer.
"site-config",
@@ -1270,6 +1282,12 @@ export function usage() {
' "whilePaused": true runs this one transcription during a pause-all on a',
' worker the pause alone switched off; the pause stays on (the video page\'s',
' "Transcribe now (workers paused)").',
+ ' A video its record says is live, scheduled or still processing its VOD',
+ ' (live_status is_live, is_upcoming, post_live) is refused before anything',
+ ' is queued — a download would read the stream at 1x and hold the platform',
+ ' queue: record it with record-live, or wait for the VOD (refresh-metadata',
+ ' re-reads the record once it has ended). With its audio on disk it',
+ ' transcribes.',
"",
'delete-file deletes one file of one video, as its Files list does:',
' {"slug", "id", "file"}. A tiered media file goes with its bytes on the',
@@ -1309,6 +1327,17 @@ export function usage() {
' {"kind": "none"}} alone is the deck\'s focus bar: those channels lead',
' every lane (a site focus follows its membership); "none" ends it.',
"",
+ 'channel-rank places one channel in the order every lane and the sync',
+ ' scheduler follow inside a tier (one rank per channel, 0 first; unranked',
+ ' channels come after every ranked one, by slug): {"slug"} and exactly one',
+ ' of "rank": <n> (before any channel holding it) or null (unranked), "top":',
+ ' true, "bottom": true, "before": "<slug>", "after": "<slug>" (a ranked',
+ ' channel; immediately next to it, a tie on its rank included). The channels',
+ ' after it move down only as far as they must. Only the rank moves — no tier,',
+ ' override or lane changes, unlike /channels\' "Add to top". Refused: an',
+ ' unknown channel, an unranked anchor, a channel paused for every',
+ ' operation. Answers {slug, rank, order: [{slug, rank}, …]}.',
+ "",
'sync lists a channel and downloads what is new, as its Sync button does:',
' {"slug"}. "full": true runs the periodic whole-listing sweep now (else',
' the configured cadence decides); "queueKey" picks another queue. On the',
@@ -1405,6 +1434,23 @@ export function usage() {
' download-missing leave the channel alone; "" (or "auto") is automatic',
' (CHANNEL.md, downloadMode).',
"",
+ 'create-site is the New site form: {"siteId", "siteTitle"} and any of its',
+ ' fields — "headerTitle" (default the title), "siteDescription",',
+ ' "homeTagline", "wordmarkLead", "accent" (an id or "#rrggbb"), "siteUrl",',
+ ' "cloudflareProject", "hubUrl", "audience" ("private" | "public"; default',
+ ' PRIVATE), "listed" (default FALSE), "publishAuto", "search", "archives",',
+ ' "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB" (null = the',
+ ' global default), "groups" ([{"id", "name", "selectedByDefault"?,',
+ ' "description"?, "inline"?}]), "defaultGroupId", "channels" (slugs, or',
+ ' {"slug", "groupId"?}: the pool), "citedChannels" (slugs), "socialLinks"',
+ ' ([{"label", "url", "svg"}], null = inherit), "relatedSites". Saved by',
+ ' the form\'s action (its validation, its sentences). An existing id is',
+ ' refused (409) unless "update": true — the site page\'s Save with the',
+ ' keys given changed, every other key kept — one read-modify-write under',
+ ' the site\'s lock. An unknown channel, or a channel\'s groupId naming no',
+ ' group of the site, is refused.',
+ ' Answers {siteId, created, site}.',
+ "",
'site-config sets two keys of a site as its form does: {"siteId"} and any of',
' "citedChannels" (the WHOLE cited scope, channel slugs: what the site\'s',
' reports may cite without publishing the channel; [] clears it; a slug the',
@@ -1479,8 +1525,10 @@ export function usage() {
' media in transition) or when the new slug is taken. Old links break.',
"",
'delete-channel removes a channel\'s whole directory, as Danger → Delete does:',
- ' {"slug", "confirm"} — "confirm" must repeat the slug. No undo outside the',
- ' transcripts/ repo\'s own history.',
+ ' {"slug", "confirm"} — "confirm" must repeat the slug. Every site whose',
+ ' pool or cited scope names it is rewritten without it (answered as',
+ ' "sitesUpdated"; a site whose write is refused is a "warnings" line). No',
+ ' undo outside the transcripts/ repo\'s own history.',
"",
'fetch-chat fetches ONE video\'s live chat replay and nothing else: {"slug",',
' "id"} — the chat-only yt-dlp pass (the channel\'s cookies, the platform\'s',
diff --git a/umtool/app/api/cli/route.ts b/umtool/app/api/cli/route.ts
@@ -0,0 +1,185 @@
+import path from "node:path";
+import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
+import { buildArgv, cliLine, confirmOf, pathArgsOf } from "@/lib/cli/argv.mjs";
+import { confineToProject } from "@/lib/cli/confine.mjs";
+import { formVerbs, verbRow } from "@/lib/cli/verbs.mjs";
+import { resolveProject } from "@/lib/projects/core.mjs";
+import { resolveProjectPath } from "@/lib/projects";
+import { addStep, getStep, isQid, listSteps, logFileOf, logTail } from "@/lib/queue/store.mjs";
+import { kickQueue, queueDir, queueRunnerStatus } from "@/lib/queue/runner";
+import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
+
+export const dynamic = "force-dynamic";
+
+// ⌘K COMMANDS (umtool redesign, lane palette L8a; umtool/docs/knobs.md, "⌘K commands"):
+// the verb registry's forms, run.
+//
+// GET { verbs, context, queue }: every ui:"form" row (lib/cli/verbs.mjs:
+// verb, summary, target, queue, args) and, with ?path=<the page's
+// pathname + search>, what the page is about -- { project, clip, post, take }
+// GET ?job=<id>[&since=N] { job }: the app job a form started (lib/jobs.ts jobView, its log from N)
+// GET ?qid=<qid> { step, log }: a queued form's step and its log's last lines
+// POST { verb, values, confirm? } -> 202 { job, line } | 202 { queued: { qid }, line }
+// the row's args validated and built into argv HERE (lib/cli/argv.mjs);
+// a row with `queue` (it renders, or holds the heavy slot) is added to the
+// durable queue, any other runs as one job on the app's runner
+// | 400 not a form verb, a value its schema refuses, a raw argv, a path
+// outside the project | 409 a row with `confirm` sent without confirm: true
+// | 403 not this app's own page, or a host that is not this machine (DNS
+// rebinding: lib/report/sameOrigin.mjs, UMTOOL_ALLOWED_HOSTS) | 409 another job runs
+// The same queued command asked again within 5 s is the step already there.
+//
+// The page never sends argv: a body that carries one is refused, and app/api/queue/route.ts
+// still refuses to add a step from a page. What runs is a registry row's argv, nothing else.
+const headers = { "cache-control": "no-store" };
+const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
+
+type Row = { verb: string; summary: string; ui: string; reason?: string; queue?: boolean; timeoutMin?: number; confirm?: { what: string } | null; args: Array<{ name: string; type: string; context?: string; pass?: string }> };
+
+/** A double Enter: the same command queued again this soon is the step already there. */
+const DEDUPE_MS = 5000;
+
+/** The project, and the selection, a page's address is about. */
+async function contextOf(raw: string | null) {
+ const ctx: { project: string | null; clip: string | null; post: string | null; take: string | null } = { project: null, clip: null, post: null, take: null };
+ if (!raw) return ctx;
+ let url: URL;
+ try {
+ url = new URL(raw, "http://x");
+ } catch {
+ return ctx;
+ }
+ const q = url.searchParams;
+ ctx.clip = q.get("clip");
+ ctx.take = q.get("take");
+ const segments = url.pathname.split("/").filter(Boolean).map((s) => {
+ try {
+ return decodeURIComponent(s);
+ } catch {
+ return s;
+ }
+ });
+ let rest: string[] = [];
+ if (segments[0] === "projects" && segments[1] === "at") {
+ ctx.project = q.get("path");
+ } else if (segments[0] === "projects" && segments.length > 1) {
+ const r = await resolveProjectPath(segments.slice(1)).catch(() => null);
+ if (r && "project" in r && r.project) {
+ ctx.project = r.project.id;
+ rest = (r as { rest?: string[] }).rest ?? [];
+ }
+ }
+ const [view, id] = rest;
+ if (id && view === "clip") ctx.clip = id;
+ if (id && view === "post") ctx.post = id;
+ if (id && view === "takes") ctx.take = id;
+ return ctx;
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const jobId = url.searchParams.get("job");
+ if (jobId) {
+ const job = getJob(jobId);
+ if (!job) return Response.json({ error: "no such job" }, { status: 404, headers });
+ return Response.json({ job: jobView(job, Math.max(0, Number(url.searchParams.get("since") ?? 0) || 0)) }, { headers });
+ }
+ const qid = url.searchParams.get("qid");
+ if (qid !== null) {
+ if (!isQid(qid)) return Response.json({ error: "?qid=<qid>" }, { status: 400, headers });
+ const step = (await getStep(queueDir(), qid)) as Record<string, unknown> | null;
+ if (!step) return Response.json({ error: "no such step" }, { status: 404, headers });
+ const log = await logTail(logFileOf(queueDir(), qid), 32 * 1024);
+ const pick = ["qid", "label", "state", "exitCode", "error", "blockedBy", "createdAt", "startedAt", "endedAt"] as const;
+ return Response.json({ step: Object.fromEntries(pick.map((k) => [k, step[k] ?? null])), log: log.slice(-200), runner: queueRunnerStatus() }, { headers });
+ }
+ return Response.json({ verbs: formVerbs(), context: await contextOf(url.searchParams.get("path")), queue: queueRunnerStatus() }, { headers });
+}
+
+/** Same-origin only: the browser says where a POST comes from, and one that says nothing is not a page of this app. */
+function refuseOrigin(request: Request): string | null {
+ const refused = crossSiteRefusal(request.headers);
+ if (refused) return refused;
+ const site = (request.headers.get("sec-fetch-site") ?? "").trim().toLowerCase();
+ if (site === "same-origin" || request.headers.get("origin")) return null;
+ return "refused: POST /api/cli runs only from this app's own pages -- in a terminal, run the command itself";
+}
+
+export async function POST(request: Request) {
+ const refused = refuseOrigin(request);
+ if (refused) return Response.json({ error: refused }, { status: 403, headers });
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object" || Array.isArray(body)) return Response.json({ error: "expected JSON: { verb, values }" }, { status: 400, headers });
+ if ("argv" in body || "args" in body || "cmd" in body || "command" in body) {
+ return Response.json({ error: "a raw command line is refused: name a verb of the registry and its values ({ verb, values })" }, { status: 400, headers });
+ }
+ const extra = Object.keys(body).filter((k) => k !== "verb" && k !== "values" && k !== "confirm");
+ if (extra.length) return Response.json({ error: `unexpected ${extra.join(", ")}: the body is { verb, values, confirm? }` }, { status: 400, headers });
+ const verb = typeof body.verb === "string" ? body.verb.trim() : "";
+ const row = verbRow(verb) as Row | null;
+ if (!row) return Response.json({ error: `no verb "${verb}" in the registry (umtool/lib/cli/verbs.mjs)` }, { status: 400, headers });
+ if (row.ui !== "form") return Response.json({ error: `umtool ${verb} has no form: ${row.reason}` }, { status: 400, headers });
+ const values = (body.values ?? {}) as Record<string, unknown>;
+ const pre = buildArgv(row, values);
+ if (!pre.ok) return Response.json({ error: pre.error, field: pre.field ?? null }, { status: 400, headers });
+ const confirmWhat = confirmOf(row, values);
+ if (confirmWhat && body.confirm !== true) {
+ return Response.json({ error: `this would ${confirmWhat}, with no undo: send it again with confirm: true`, confirm: confirmWhat }, { status: 409, headers });
+ }
+
+ // A project arg is one the CLI will find: said here, not as the job's first line.
+ let project: string | null = null;
+ let projectDir: string | null = null;
+ for (const a of row.args) {
+ const v = values[a.name];
+ if (a.type !== "project" || typeof v !== "string" || !v.trim()) continue;
+ const r = (await resolveProject(v.trim())) as { project?: { id: string; dir: string }; ambiguous?: unknown[] };
+ if (r.ambiguous) return Response.json({ error: `"${v}" is the name of ${r.ambiguous.length} projects — give its id`, field: a.name }, { status: 400, headers });
+ if (!r.project) return Response.json({ error: `no project matches "${v}"`, field: a.name }, { status: 400, headers });
+ if (a.name === "project") {
+ project = r.project.id;
+ projectDir = r.project.dir;
+ }
+ }
+ // A file a form names is a file of THE project, by its realpath; it runs as that absolute path
+ // (a row whose CLI joins it to the project itself: as typed).
+ const run: Record<string, unknown> = { ...values };
+ for (const a of pathArgsOf(row, values) as Row["args"]) {
+ if (!projectDir) return Response.json({ error: `${a.name}: a file names a project's file -- name the project`, field: a.name }, { status: 400, headers });
+ const c = await confineToProject(projectDir, String(values[a.name]));
+ if (!c.ok) return Response.json({ error: `${a.name}: ${c.error}`, field: a.name }, { status: 400, headers });
+ if (a.pass !== "relative") run[a.name] = c.abs;
+ }
+ const built = buildArgv(row, run);
+ if (!built.ok) return Response.json({ error: built.error, field: built.field ?? null }, { status: 400, headers });
+ const take = row.args.filter((a) => a.context === "take").map((a) => values[a.name]).find((v): v is string => typeof v === "string" && !!v.trim()) ?? null;
+ const line = cliLine(built.argv);
+ const label = `⌘K: umtool ${built.argv.join(" ")}`.slice(0, 160);
+
+ if (row.queue) {
+ try {
+ const same = JSON.stringify(built.argv);
+ const recent = ((await listSteps(queueDir())) as Array<{ qid: string; argv: string[]; state: string; createdAt: string; by?: string }>).find(
+ (s) => (s.state === "queued" || s.state === "running") && JSON.stringify(s.argv) === same && Date.now() - Date.parse(s.createdAt) < DEDUPE_MS,
+ );
+ if (recent) return Response.json({ ok: true, queued: { qid: recent.qid }, deduped: true, line, queue: queueRunnerStatus() }, { status: 200, headers });
+ const step = (await addStep(queueDir(), {
+ argv: built.argv,
+ label,
+ by: "the umtool app (⌘K)",
+ cwd: UMTOOL_DIR,
+ target: project ? { project, take } : null,
+ ...(row.timeoutMin ? { timeoutMin: row.timeoutMin } : {}),
+ })) as { qid: string };
+ kickQueue();
+ return Response.json({ ok: true, queued: { qid: step.qid }, line, queue: queueRunnerStatus() }, { status: 202, headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409, headers });
+ }
+ }
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind}) — run this when it is done`, running: jobView(running, running.log.length) }, { status: 409, headers });
+ const job = startJob(`umtool ${verb}`, [{ cwd: UMTOOL_DIR, env: {}, label: `umtool ${built.argv.join(" ")}`.slice(0, 200), argv: [process.execPath, umtoolCli(), ...built.argv], timeoutMs: (row.timeoutMin ?? 15) * 60_000 }], { project });
+ return Response.json({ ok: true, job: jobView(job), line }, { status: 202, headers });
+}
diff --git a/umtool/app/api/ingredients/action/route.ts b/umtool/app/api/ingredients/action/route.ts
@@ -0,0 +1,67 @@
+import { CHANNELS_DIR, REPORTS_ROOT } from "@/lib/paths";
+import { jobView, runningJob, startJob } from "@/lib/jobs";
+import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
+import { UMTOOL_DIR } from "@/lib/report/driver.mjs";
+import { EditorError, editorConfig } from "@/lib/report/fetchWindows.mjs";
+import { ActionError, parseClipList, planAction, quoteCheckArgv, startAction } from "@/lib/ingredients/actions.mjs";
+import { resolveProject } from "@/lib/projects/core.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE INGREDIENT RAIL'S ACTIONS (lane L5; lib/ingredients/actions.mjs): a stage's one click, in two steps.
+//
+// POST { action, ch, id, step: "plan", project?, clips?, window?, fix? }
+// -> { action, what, cost: "network" | "gpu" | "disk" | null, queue, start: { route, body }, plan? }
+// what the action will do, what it costs and which queue it lands on (the editor's own dry run for
+// fetch-windows and persist-videos); the page shows it and asks
+// POST { ...start.body, step: "start" }
+// persist | transcribe | fetch | evict -> { ok, action, jobIds, message } the editor's ops, asked here
+// quote-check -> 202 { ok, job } `umtool quote-check` on the job runner
+// (links: the plan's start names /api/report/links, umtool's own link check)
+//
+// The token never reaches the browser; the editor decides queues, pacing and whole-recording downloads.
+const headers = { "cache-control": "no-store" };
+
+export async function POST(request: Request) {
+ // Another site's page may not start a download, a transcription or an evict: a cross-site or foreign-Origin
+ // POST is refused (sameOrigin.mjs), and the body must be JSON -- which a no-cors form post cannot send.
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403, headers });
+ if (!/^application\/json\b/i.test(request.headers.get("content-type") ?? "")) return Response.json({ error: "the body must be application/json" }, { status: 415, headers });
+ const refused = refuseCaller(request, "/api/ingredients/action");
+ if (refused) return refused;
+ const b = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!b || typeof b !== "object") return Response.json({ error: "expected JSON" }, { status: 400, headers });
+ const req = {
+ action: String(b.action ?? ""),
+ ch: String(b.ch ?? ""),
+ id: String(b.id ?? ""),
+ ...(b.project !== undefined ? { project: String(b.project) } : {}),
+ ...(b.clips !== undefined ? { clips: b.clips as string[] } : {}),
+ ...(b.window !== undefined ? { window: String(b.window) } : {}),
+ ...(b.fix === true ? { fix: true } : {}),
+ ...(typeof b.key === "string" ? { key: b.key } : {}),
+ };
+ const ctx = { cfg: editorConfig(), reportsRoot: REPORTS_ROOT, channelsDir: CHANNELS_DIR };
+ try {
+ if (b.step === "plan") return Response.json(await planAction(req, ctx), { headers });
+ if (b.step !== "start") return Response.json({ error: 'step is "plan" or "start"' }, { status: 400, headers });
+ if (req.action === "quote-check") {
+ const r = await resolveProject(String(req.project ?? ""), REPORTS_ROOT);
+ if (!r?.project) return Response.json({ error: `no project "${req.project}"` }, { status: 404, headers });
+ const clips = parseClipList(req.clips) as string[];
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind}) — check the quotes when it is done`, running: jobView(running) }, { status: 409, headers });
+ const argv = quoteCheckArgv(UMTOOL_DIR, r.project.id, clips);
+ const job = startJob(`quote-check ${r.project.id} ${clips.join(",")}`, [{ cwd: UMTOOL_DIR, env: {}, label: `quote check: ${clips.join(", ")} (${r.project.id})`, argv, timeoutMs: 60 * 60_000 }], { project: r.project.id });
+ return Response.json({ ok: true, action: "quote-check", job: jobView(job), jobIds: [job.id], message: `quote check started (${job.id})` }, { status: 202, headers });
+ }
+ if (req.action === "links") return Response.json({ error: "a link check starts at /api/report/links" }, { status: 400, headers });
+ return Response.json(await startAction(req, ctx), { headers });
+ } catch (e) {
+ if (e instanceof ActionError) return Response.json({ error: e.message }, { status: (e as ActionError & { status: number }).status, headers });
+ if (e instanceof EditorError) return Response.json({ error: e.message }, { status: (e as EditorError & { status: number }).status, headers });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers });
+ }
+}
diff --git a/umtool/app/api/report/embed-ids/route.ts b/umtool/app/api/report/embed-ids/route.ts
@@ -6,6 +6,7 @@ import { readLinkCheck } from "@/lib/report/linkCheck.mjs";
import { readManifest } from "@/lib/projects/report.mjs";
import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
export const dynamic = "force-dynamic";
@@ -32,6 +33,8 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
const refused = refuseCaller(request, "/api/report/embed-ids");
if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
let body: Record<string, unknown>;
try {
body = await request.json();
diff --git a/umtool/app/api/report/ledger/route.ts b/umtool/app/api/report/ledger/route.ts
@@ -3,6 +3,7 @@ import { StaleToken, addLedgerRow, manifestToken, removeLedgerRow, updateLedgerR
import { isMeasureLedger, parseLedgerValue } from "@/lib/report/ledgerRows.mjs";
import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
import { EVENTS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, VALUE_KINDS, measureSchema } from "umtool-report-to-video/ledger-totals";
export const dynamic = "force-dynamic";
@@ -72,6 +73,8 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
const refused = refuseCaller(request, "/api/report/ledger");
if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
let body: Record<string, unknown>;
try {
body = await request.json();
diff --git a/umtool/app/api/report/post-item/inspector/route.ts b/umtool/app/api/report/post-item/inspector/route.ts
@@ -7,6 +7,7 @@ import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/l
import { attachmentOf } from "@/lib/report/postsCli.mjs";
import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
export const dynamic = "force-dynamic";
@@ -77,6 +78,8 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
const refused = refuseCaller(request, "/api/report/post-item/inspector");
if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
let body: Record<string, unknown>;
try {
body = await request.json();
diff --git a/umtool/app/api/report/provenance/route.ts b/umtool/app/api/report/provenance/route.ts
@@ -5,6 +5,7 @@ import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs";
import { provenanceView, updateProvenance } from "@/lib/report/inspectorEdits.mjs";
import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
import { sitesByOrigin } from "@/lib/report/siteDeploys.mjs";
import { CHANNELS_DIR, SITES_DIR } from "@/lib/paths.mjs";
@@ -47,6 +48,8 @@ export async function GET(request: Request) {
export async function PUT(request: Request) {
const refused = refuseCaller(request, "/api/report/provenance");
if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
let body: Record<string, unknown>;
try {
body = await request.json();
diff --git a/umtool/app/api/report/still-frame/route.ts b/umtool/app/api/report/still-frame/route.ts
@@ -2,6 +2,7 @@ import { readFile, stat } from "node:fs/promises";
import { resolveClip, resolveReport } from "@/lib/report/serve.mjs";
import { StillRefused, grabStill, listShots, shotFileOf } from "@/lib/report/stillGrab.mjs";
import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
export const dynamic = "force-dynamic";
@@ -35,6 +36,8 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
const refused = refuseCaller(request, "/api/report/still-frame");
if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
let body: Record<string, unknown>;
try {
body = await request.json();
diff --git a/umtool/app/api/report/teaser/route.ts b/umtool/app/api/report/teaser/route.ts
@@ -4,6 +4,7 @@ import { StaleToken, StructureRefused, manifestToken, updateTeaser } from "@/lib
import { insertTeaser, teaserLimits, teaserLineOf } from "@/lib/report/inspectorEdits.mjs";
import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
export const dynamic = "force-dynamic";
@@ -38,6 +39,8 @@ export async function GET(request: Request) {
export async function POST(request: Request) {
const refused = refuseCaller(request, "/api/report/teaser");
if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
let body: Record<string, unknown>;
try {
body = await request.json();
diff --git a/umtool/app/api/report/title/route.ts b/umtool/app/api/report/title/route.ts
@@ -4,6 +4,7 @@ import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs";
import { SUBTITLE_MAX, TITLE_MAX, updateTitle } from "@/lib/report/inspectorEdits.mjs";
import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
export const dynamic = "force-dynamic";
@@ -33,6 +34,8 @@ export async function GET(request: Request) {
export async function PUT(request: Request) {
const refused = refuseCaller(request, "/api/report/title");
if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
let body: Record<string, unknown>;
try {
body = await request.json();
diff --git a/umtool/app/ingredients/[channel]/[id]/page.tsx b/umtool/app/ingredients/[channel]/[id]/page.tsx
@@ -0,0 +1,50 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import AppShell from "@/components/shell/AppShell";
+import IngredientRail from "@/components/ingredients/IngredientRail";
+import { readIngredient } from "@/lib/ingredients";
+import { isChannelSlug, isVideoId } from "@/lib/ingredients/stages.mjs";
+import { editorConfig } from "@/lib/report/fetchWindows.mjs";
+import { workHref } from "@/lib/hrefs";
+
+export const dynamic = "force-dynamic";
+
+// ONE INGREDIENT'S LIFE CYCLE (lane L5; operator, 9 Nov 2026): /ingredients/<channel>/<video>[?window=<from>-<to>]
+// [&stage=<key>]. A recording of the corpus across its nine stages -- found, downloaded, transcribed, clock,
+// windows, used in, checked, rendered, published -- each read from the files that exist
+// (lib/ingredients/stages.mjs; `umtool ingredient` prints the same). Either Rumble id finds it. Read-only over
+// the corpus; each stage's action goes through the editor's or umtool's own (app/api/ingredients/action).
+
+type Params = { channel: string; id: string };
+type Search = { window?: string; stage?: string };
+
+export async function generateMetadata({ params }: { params: Promise<Params> }): Promise<Metadata> {
+ const { channel, id } = await params;
+ return { title: `${channel}/${id} · life cycle · umtool` };
+}
+
+export default async function IngredientPage({ params, searchParams }: { params: Promise<Params>; searchParams: Promise<Search> }) {
+ const { channel, id } = await params;
+ // Next hands the segments over decoded already: decoding again would turn a literal % into something else.
+ const ch = channel;
+ const vid = id;
+ if (!isChannelSlug(ch) || !isVideoId(vid)) notFound();
+ const search = await searchParams;
+ const data = await readIngredient(ch, vid, typeof search.window === "string" ? search.window : null);
+ const keys = data.stages.map((s) => s.key);
+ const firstWarn = data.stages.find((s) => s.pill.kind === "warn")?.key;
+ const initial =
+ typeof search.stage === "string" && keys.includes(search.stage) ? search.stage : data.focus ? "windows" : (firstWarn ?? (data.stages[5].rows.length ? "used" : "downloaded"));
+ const editor = editorConfig();
+ return (
+ <div className="flex h-full flex-col">
+ <AppShell
+ active="work"
+ crumbs={[{ href: workHref(), label: "Work" }, { label: ch }, { label: data.title ? `${vid} · ${data.title}` : vid }]}
+ />
+ <main className="deck-main flex-1 p-4" data-ingredient-page="">
+ <IngredientRail data={data} initialStage={initial} editorUrl={editor.url || null} />
+ </main>
+ </div>
+ );
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -139,6 +139,7 @@
// repeats <project> [--match id|file|audio] · combo <project> [<item>] k=v|off the combo counter
// attach <project> [<item>…|--all] a capture's media onto post items that carry none
// umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel
+// umtool ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json] a recording's life cycle, nine stages (/ingredients)
import process from "node:process";
import {
PROJECT_KINDS,
@@ -858,302 +859,15 @@ async function cmdCheckSources() {
console.log("# Nothing was run. Settings · system's Sources panel runs this chain through the job runner.");
}
-function usage() {
+// `umtool help`: generated from the verb registry's prose (lib/cli/groups.mjs, lib/cli/docs.mjs).
+async function usage() {
+ const { usageText } = await import("../lib/cli/docs.mjs");
console.log(
- [
- "umtool — the project tree, from a terminal",
- "",
- " umtool ls [--kind K] [--template T] [--state S] [--open] [--blocking]",
- " [--q TEXT] [--sort name|recent] [--json]",
- " umtool show <project> [--json]",
- " umtool check [<project>] [--json] exit 1 on anything blocking",
- " umtool links <project> [--json] [--fix] do the clip QRs open on their sites? (corpus.json -> slugToPage",
- " -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead",
- " umtool cast [ls] | add <id> --name … --voice <engine:voice> [--handles a,b] | set <id> … | rm <id> | undo",
- " | project <p> | audition <character> --voices a,b,c [--project <p>] [--text …] | use <p> <character> <voice>",
- " [--everywhere] | reread <p> <character> the CAST: characters' stock voices across projects (cast.json), a",
- " project's characters and their drift, an audition of candidate voices (scored against the real voice)",
- " umtool speaker-check <project> [--clip <id> …] [--json] which of the project's named voices (speakers.json) each",
- " clip is: TitaNet-small, local -> speaker-check.json; --set 'Name=<clip>,<channel>/<id>,channel:<slug>' / --remove / --list",
- " umtool quote-check <project> [--clips a,b] [--pad S] [--json] | --status is each clip's quote in the seconds it plays?",
- " the cut ±15 s of the source the render would use, transcribed by the editor (words on), the quote",
- " found in it and in the cues: ok | moved (heard N s away: window --align) | not-found -> quote-check.json;",
- " check calls moved and not-found blocking, and a take refuses them unless the clip is --quote-ruled",
- " umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>] every boundary of the take's master where the",
- " next post item draws a post the one before showed: its join, the SSIM across it, the largest jump",
- " umtool link-policy <project> [--via <site id|url>] [--direct a,b] [--clear] [--fix] [--json] the link policy",
- " (provenance.linkPolicy): cite via site X, these channels direct; --fix rewrites the clips that break it",
- " umtool patch-markers <project> [<file>.patch.json] [--fix] [--json] take patches whose deck markers name a",
- " clip not in the cut; --fix gives each the after of the cut's marker of the same label",
- " umtool decisions [--json]",
- " umtool inbox [--all] [--json] the decisions, grouped and ranked as the inbox shows them",
- " (--all: the hidden ones on parked/done pieces, and the quiet group)",
- " umtool schedule list | show <id> [--json] the recurring reports: chip, editions, tick log (read-only;",
- " a schedule is written through the editor: `pnpm ops report-schedule`)",
- " umtool folders [--json]",
- " umtool kinds [--json]",
- " umtool link <project> <site>/<report> | --clear [--json] the manifest names its article (a top-level",
- " `article`): what settles link-ambiguous; noted for the generator on a generated manifest",
- " umtool window <project> <clip> [--start S] [--end E] [--lock|--lock-end|…]",
- " attribution too: --title, --date YYYY-MM-DD, --cite, --cite-url, --quote",
- " --repeat-of <clip> it re-plays that clip on purpose (a callback): their overlap is not flagged or trimmed",
- " --correction TEXT what the REPORT got wrong here (never rendered)",
- " --walk-note TEXT an editorial note from the walk (not a correction; never rendered)",
- " --star / --no-star the walk's favourite: a trailer candidate (umtool trailer <p> --candidates)",
- " a window edit that leaves --cite (or the citeUrl's t=) more than 5 s before the clip, or",
- " after it, moves it to the clip's first second; an explicit --cite moves the QR's t= with it",
- " --verdict confirmed|incorrect what the walk said; incorrect needs --correction",
- " --reject <why> [--note TEXT] rejected on the walk, kept in place (`umtool timeline <p> reject`",
- " takes it out, on record): not-matching|wrong-speaker (fact errors: incorrect, the note its",
- " correction) or irrelevant|repeats|weak|privacy|other (rejected; other needs --note)",
- " --cut-start S --cut-end E --lock-cut the cut the video renders",
- " --align the cut snapped to the quote as HEARD (quote-check.json: a breath before its first word,",
- " its last let ring; the extent widened to hold it; lockCut kept) -- the per-clip fix for a moved quote",
- " --quote-ruled / --no-quote-ruled a person heard it and rules the quote check's verdict: a take renders it",
- " --move-stamp first|nearest|<s> | --clear-stamp with --start/--end: a stamp's second (claim.at,",
- " a mark's at) the new window would leave outside moves to the first second that plays, the nearest,",
- " or <s>, or loses its at -- in the same write; --move-mute nearest | --clear-mute the mute mark's",
- " --gap FROM-TO (repeatable) cut those source seconds out of the clip's middle: it plays",
- " as ONE segment of jump cuts (gaps.mjs; inside the cut, ≥ 0.2 s, 0.5 s kept between);",
- " --gap-remove S the gap holding source second S · --gaps 'A-B,C-D' the whole list ('' clears)",
- " an empty value (--title '') deletes the field",
- " --take <id> a take's clip (walk a take): the edit goes into takes/<id>/take.json's",
- " patch, an undo point first (`umtool timeline <p> --take <id> undo`); the manifest is untouched",
- " umtool walk <project> [--take <id>] [--all] [--json] the clip bench's walk: every clip in walk order,",
- " its verdict, fetched or not, and (→) the ones the walk visits; --take walks a take (a draft too)",
- " umtool present <project> [--take <id> | --cut] [--json] [--public] [--open] PRESENT MODE: the cut as slides,",
- " navigated like a deck (/projects/<p>/present); prints its address and its slides (#<slide id> opens",
- " one); --json the payload (posts with their censor data by kind, clips' spans, section/day dividers);",
- " --public the payload a public page would carry (censored, no reveal data); --open opens it",
- " umtool set <project> <clip> key=value … a clip's knobs (`key=` clears; umtool/docs/knobs.md):",
- " claim.at (a source second: the stamp lands, the count steps) claim.hold claim.stamp",
- " claim.count claim.label (the first mark's, or --mark <id>'s) · marks: mark.add=<verdict>[@<sec>]",
- " mark.remove=<id> mark.verdict=<verdict> marks=<json> (≤ 8, each its own stamp and count)",
- " · audio.offset (ms, + later) audio.gain (dB) audio.fadeIn audio.fadeOut",
- " · hideModules=diet,streak (those modules hidden over the entry's span; any entry)",
- " · shelfNote='words' (a line on the shelf over the entry's span; any entry)",
- " --take <t>: the entry knobs into the take's patch, the project's manifest untouched",
- " umtool intro <project> [key=value …] [--off] [--json] THE INTRO the cut opens on (render.intro): prints it,",
- " what the cut opens with and each version's on/off; key=value writes it (style seconds mark sound",
- " site title lines …; `key=` clears; a new one starts as boot-dark); --off takes it off;",
- " --take <t> --off|--on: that version opens on no intro (its patch's render.intro: null) or the cut's",
- " umtool look <project> key=value … the cut's knobs: factcheck.stamp.scale|motion|opacity|seconds,",
- " factcheck.verdicts.<V>.stampLabel|label|color, deck.markers=<json>, deck.markerLayout,",
- " variants=<json>, and the look's keys (transition=0.3, …)",
- " umtool migrate <project> [--dry-run] [--json] move the manifest into the video modules' homes",
- " (the fact-check verdicts and tally become deck.counter's series); renders the same",
- " umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder of a build (render.variants);",
- " --list: what was made, and the build's sync report (each clip's lag, past a frame flagged)",
- " umtool corrections <project> what the report got wrong + the walk's coverage",
- " umtool build <project> [--preset preview|fast|final] [--only ID]",
- " --run: the app's build job (UMTOOL_URL, else http://localhost:3050; --url), followed here;",
- " Ctrl-C cancels it; --replace stamps a newer deliverable aside",
- " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]",
- ` an article iteration's pipeline, one step a process: ${CHAIN_STEP_NAMES.join(", ")}`,
- " (resumes at the first step not done; --dry prints it; the project is <root>/<article>/i<n>/)",
- ` --draft-all (Draft everything): ${chainStepsOf("draft-all").map((s) => s.name).join(", ")} —`,
- " each draft a report-draft job on --model (else its route); a draft that fails does not stop it;",
- " --deck adds a step before the flips: the minimal on-screen deck on a cut with none",
- " umtool index [--rebuild] [--prune] [--since MS] [--json]",
- " umtool new <slug> [--from <report.md>|<share URL>|<channel>/<id>] [--site-origin URL] [--seed chapters|frames]",
- " <folder>/<slug>, or --folder <folder>: the project in a folder of the reports tree (its id",
- " <folder>/<slug>, routed /projects/<folder>/<slug>) — a spin-off beside its parent",
- " --seed frames: a draft supercut from the video's frame scan (pnpm ops frame-scan) — the events",
- " ranked (scoops, milestones, swings, pots, level-ups) into --target <seconds> (default 240), the",
- " deck on with the stats region drawing frameScan.overlay over each clip",
- " --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>]: every time",
- " the phrase was said in those channels' transcripts, chronological, cut from the --prefer",
- " channel's copy where it has one (a twin by date and duration); a context matching --exclude",
- " is left out; the scan beside the manifest as phrase-scan.json; --max N keeps N instances",
- " spread across the years in proportion (the rest: phrase-scan.json \"skippedByCap\")",
- " --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO|auto [--segment sN]] [--no-analyze]: the clip finder on a long",
- " 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",
- " umtool storage [<project>] where each project's out/ lives (dir, link, DANGLING)",
- " umtool storage move-out|move-back <project>|--all [--dry-run]",
- " umtool storage deliverables <project> --to media|local [--dry-run] clips/ + share-*/, then the switch",
- " out/ to the media root (UMTOOL_MEDIA_DIR) and back; run when nothing is building",
- " umtool snapshot <project> [--label L] copy the manifest into revisions/",
- " umtool diff <project> <snapshot> what changed since that snapshot",
- " umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] [--first TITLE]",
- " umtool export <project> <clip> [--context N | --raw [--from S --to S]] [--fetch] [--take T] [--open] one clip,",
- " clean, into <project>/exports/: the cut's edges, its gaps out, its mute; --context N what the cut",
- " plays ± N s; --raw the whole fetched window, or a span (the full exchange), as recorded; --fetch",
- " asks the editor first for what that needs; in the heavy slot; --open shows it",
- " umtool check-sources [<project>…] prints the re-check chain (never-checked/old when no args)",
- " umtool notes [<site>/<report>|<project>|--all] the operator's notes, as markdown (open ones)",
- " umtool notes reply <id> \"<text>\" [--resolve] answer one; resolve | wontfix | reopen <id>",
- " umtool modules list | apply <project> [--config F] [--dry-run | --take <id> [--at S --dur S | --full] …]",
- " a module-config.json onto the cut (writers), or as a take's patch",
- " umtool preset list | show <name> | save <name> --from <project> | apply <name|none> <project>",
- " the look presets (preset → manifest → style → take patch)",
- " umtool take <project> --id <id> --label L [--style S] [--patch F | --set p=v …] [--at S --dur S | --full]",
- " one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force;",
- " --from TAKE reuses that take's segments, chrome and batches; --keep-frames keeps the chrome)",
- " --draft (--no-render): record the take, render nothing -- walk it, edit it, render it later",
- " (`umtool take <p> --id <id> --full` renders a draft from its stored patch)",
- " --priority: render mode for the take's lifetime -- every other heavy job waits for it, the",
- " editor's transcription and download lanes are held; all let go at its end, failure or signal",
- " --draft --from TAKE: a draft that starts from that take's patch (its timeline its own from then on)",
- " umtool take <project> --id <id> --import-item <project>:<item>[,<item>…] [--after <entry>|--before <entry>]",
- " [--as <id>] [--dry-run] [--json] items of ANOTHER project cloned into the take (its patch), their",
- " narration and pick kept, the files they name hard-linked into this project; again: updated or unchanged",
- " umtool lint <project> [--take <id>] [--variant sourced|full] [--final] [--json] the manifest lint a build runs",
- " first, on the project's manifest or a take's (its patches applied), and the files its post items",
- " name (a picked read, an attachment not in the project: an error) -- exit 0 clean, 1 an error",
- " umtool take <project> --id <id> --promote [--anyway] make this the cut: the take's patch applied to the",
- " manifest, one undo point (revisions/…-auto-before-promote-take)",
- " umtool take status <project> [--id <id>] [--json] [--log] [--tail N] the take's render record (every render",
- " writes takes/<id>/render.json and the full render.log): exit 0 done, 3 queued/waiting/running, 1 failed",
- " umtool queue add [--after <qid>|last] [--label T] -- <umtool subcommand argv…> a step the umtool APP runs, in",
- " order, one at a time (it survives the session); prints the qid. ls [--all] | status <qid> | wait <qid>",
- " [--timeout S] | log <qid> | cancel <qid> | retry <qid> [--json]; status exits 0 done, 3 going, 1 failed",
- " umtool jobs [--json] every running and recent take render and queue step, across projects, and the app's jobs",
- " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]",
- " | ls <project> | relabel <project> <take> <label…> | supersede <project> <take> [--by <take>] [--clear]",
- " | delete <project> <take> [--dry-run] [--force] take housekeeping: a label fixed, a take folded away",
- " as superseded, a take deleted -- refused while a render names it",
- " umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render the",
- " operator waits for gets the machine (other heavy jobs wait; the editor's transcription and",
- " download lanes held); `on` is a window for a chain of renders (default 2h)",
- " on [--for D] [--print-token] -- <cmd …>: held while <cmd> runs (its env carries the token,",
- " the hold is its pid), released when it exits -- the form for a script; --print-token prints",
- " the token alone on stdout",
- " umtool pool [stats] [--since 7d] | prune [--max-gb N] [--dry-run] | verify [--sample N | --all] [--json]",
- " the render pool: every post, clip, chunk, sound and chrome frame a build made, by its key,",
- " hard-linked into any take that needs it again (UMTOOL_RENDER_POOL=0 off; _MAX_GB its cap)",
- " umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]",
- " a trailer cut from the take's finished master: the master's own frames, so the deck shows the",
- " whole timeline; beats are clip source seconds or master seconds ([--dry-run] the mapping only)",
- " --reel <name> [--take <t>]: a beat reel's beats and settings (promo/<name>-beats.json),",
- " written to takes/<t>/out/<slug>.<name>.mp4; no --take: its pinned, last-cut or latest master",
- " --vertical [--layout reframe] [the vertical flags]: the reel 9:16 (umtool vertical --reel)",
- " umtool vertical <project> --take <t> (--reel R | --beats F | --items a,b) [--clip full|framed|quote]",
- " [--post card|stack|media] [--side split|overlay] [--hook title|section|<copy>] [--reframe] [--json]",
- " a vertical short (1080x1920, -14 LUFS) of the take's items: each clip cut again in its layout,",
- " each post drawn in a portrait box; --reframe recomposes the finished 16:9 master instead",
- " umtool trailer-beats <project> [ls] | add <clip> [<from>-<to>] [--at N] [--label L] | add-raw <at> <dur> | set <n> <from>-<to>",
- " | remove <n> | move <n> --to <m> | order | limit <s|m:ss|x|instagram|shorts|tiktok> | xfade <s> | intro on|off",
- " | candidates [--add] the trailer's beats (promo/trailer-beats.json, the Trailer page's file): each",
- " beat's length, the running length against the platform limit (X 2:20), beats outside their clip",
- " | verdict <n> confirmed|note|clear | title T | take T | undo | reels | new-reel <name> [--from R]",
- " --reel <name>: that beat reel (promo/<name>-beats.json); every write is an undo point",
- " umtool tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence (its",
- " cut's, else the whole ones in its window), each edge into its pause; before -> after; --apply writes",
- " umtool ledger <project> [ls] [--scope S] [--json] | add <id> --date D --scope S --population P [--value V] --scopeBasis \"…\" [--<key> V …] | set <id> --<key> V … [--unset k,k] | rm <id>",
- " a measure ledger's rows, checked against its ledgerSchema (incl. promise / promise_check, run, retro)",
- " umtool measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]",
- " the measure slice the instruments draw from: events at their cut seconds, hidden rows, totals",
- " umtool rulings <project> [--json] | import [--dry-run] | set <clip> keep|cut|not-him|read-aloud [--reason R] [--match M] | clear <clip>",
- " the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out",
- " umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] [--json]",
- " the clip windows asked of the editor as one fetch-windows batch (one paced job per platform);",
- " each run recorded in <project>/fetch-runs.json; --refetch <clipId>[,…] / --refetch-video <slug>/<id>",
- " evict those clips' cached windows first (the editor's evict-clips), then fetch",
- " umtool prep <project> [--clips a,b] [--wait | --status] [--json]",
- " what the clip bench makes on a clip's first open (a long recording's excerpt, the waveform),",
- " made before the walk: queued and run in the background, one clip at a time, in the heavy slot",
- " (a small declared estimate), under nice/ionice; --wait runs it here; a write or a fetch queues it too",
- " umtool prune [<project> [--take X] [--anyway] | --all] [--keep N] [--older-than 3d] [--idle-work 3d] [--yes] [--json]",
- " takes' work files (segments, chrome frames, crossfade batches, encode chunks, the rail's prerail base):",
- " what each holds (hard links counted by inode), which takes keep theirs and why, what freeing the rest",
- " gives back; a dry run unless --yes. A take build prunes its project after; a render prunes when disk is",
- " low. --idle-work D: in a project untouched for D, the newest/picked takes' work goes too",
- " umtool prune [<project> | --all] --versions [--idle 3d] [--grace 7d] [--idle-work 3d] [--yes] [--json]",
- " whole SUPERSEDED takes, through `takes delete`: per version line (the id, digits folded:",
- " draft-# ; letters never: v6c ≠ v6d) the highest built number is kept, older ones while it is",
- " younger than --grace, and any take picked, judged, rendering, a base, noted on or refused;",
- " a project touched within --idle, or whose verdicts.json cannot be read, is skipped",
- " umtool fallback <project> [--dry-run | --clip <id> … | --restore <clipId>] [--json]",
- " stand-ins for refused montage windows: the instance's public alternate (YouTube first), on the clip",
- " umtool phrases \"<phrase>\" [\"<phrase>\" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] [--json]",
- " how often each phrase was said, by year, in one pass (the phrase finder's search)",
- " umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …] [--instances F] [--dry] [--json]",
- " a local speaker-similarity score per montage clip (TitaNet-small) -> <project>/voice-match.json",
- " umtool clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params]",
- " umtool clips propose <project> [--host N] [params] [--dry] | show <project> | segments <project>",
- " the clip finder: the laugh scan + voices on the recording's sound, then clips proposed",
- " (setup → reaction → tail) into the manifest (assist: by the assistant) and reactions.json;",
- " params --target S --laugh-min X --merge-gap S --setup-max S --clip-max S; a clip you edited is never moved",
- " umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]",
- " 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 clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--json]",
- " QUICK CLIP: a basic-mode project (the footage alone), its window asked of the editor, its",
- " edges snapped to the words (--snap words), rendered as a take; prints the mp4 and its share line",
- " umtool share <project> [<clip>] [--take <id>] [--site <id>] [--json] a clip's share line: its platform",
- " page at the moment and its archive moment (a Rumble folder id mapped to the embed id)",
- // The inspector's twins (umtool redesign L6): lib/report/inspectorCli.mjs.
- " umtool provenance <project> [ls] | set [--site-origin URL] [--channel-slug S] [--channel \"Name\"] [--json]",
- " the project's provenance (where its QRs open, the channel its clips are from); \"\" removes one",
- " umtool title <project> [\"<title>\"] [--subtitle \"…\" | --no-subtitle] [--json] the project's title and subtitle",
- " umtool still <project> <clip> --at <source s> [--take <id>] [--json] | ls a frame of the clip's fetched",
- " window into shots/ (Play's Still button)",
- " umtool timeline <project> teaser-insert [--at start|end | --after <id>] [--id ID] [--beat S] --line \"…\" [--break \"…\"]",
- " [--hold S] [--line …] a teaser or closing card inserted (default at the end)",
- " umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json] the published Rumble embed id (siteVideo)",
- " on every clip citing a URL-slug folder; no network",
- " 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] [--section N]",
- " [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S]",
- " [--cite-url U] a clip, then its attribution, in the manifest's convention (deck: onscreen.title)",
- " 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 timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo] a take's timeline:",
- " the writes go into its patch (takes/<id>/take.json), each with an undo point of its own",
- " 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] [--thread] [--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); --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 posts narrate <project> [--import | --list | <item> [--script \"…\"] [--take [--note \"…\"]] [--pick n] [--approve] [k=v …]",
- " | --all --draft-scripts | --all --take | --cut k=v …] a post read aloud (its takes: the editor's tts or yours)",
- " umtool posts narrate <project> <item> --take --thread [--parents 0|all] [--skip-parent <id>]… [--no-quoted]",
- " [--voice-for <handle>=<voice>]… [--dry-run] [--json] a THREAD READ: its context and his words in date",
- " order, each in its author's voice, parts cached, one take saved and picked (exit 0 / 1)",
- " umtool posts set-item | roles | narrate | reread | fx … --in-take <take> the same edit on a TAKE of the project:",
- " its manifest read as the take's, the write in takes/<take>/take.json's patch (an undo point of the take's,",
- " `umtool timeline <p> --take <take> undo`), the project's manifest untouched; set-item/roles/reread/fx",
- " take --take <take> for it too (narrate's --take is a new read)",
- " umtool posts say <project> ls | add <word> \"<spoken>\" [--case] [--item <id>] | remove <word> | try \"<text>\" | stale",
- " the PRONUNCIATION LEXICON every synthesized read applies (stale: picked reads that say it the old way)",
- " umtool posts voices <project> ls | set <handle|*> <voice> | remove <handle> the voice map a thread read uses",
- " umtool posts fit <project> [--all | <item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part",
- " umtool posts avatar <project> [<handle> <image>|off] · avatars <project> the authors' pictures on the cards",
- " umtool posts redact <project> ls | add \"<term>\" [--substring] [--note \"…\"] | remove <n> words blanked from",
- " what is published (a bar on the card, left out of a synthesized read); the data never rewritten",
- " umtool posts repeats <project> [--match id|file|audio] [--json] the attachments played more than once (the combo counter)",
- " umtool posts combo <project> [k=v …] · <item> off|on|k=v … the combo badge's knobs (the cut's, one item's)",
- " umtool posts attach <project> [<item> … | --all] [--dry-run] a capture's media onto post items that carry none",
- " umtool candidates <project> [ls] [--all] [--json] | import <sweep.md> [--dry-run] | add <json|@file>",
- " the candidates inbox: a sweep's or an agent's proposed clips -> <project>/candidates.json;",
- " Insert into a section or a group, and Not this, are the Cut tab's Candidates panel's",
- " the Posts table's writer (updatePosts); <post> is x-<postId> or the bare <postId>",
- "",
- `reading ${REPORTS_ROOT} (set REPORTS_DIR to move it)`,
- "",
- "Run `check` before every build. It is what catches a manifest with no",
- "siteOrigin — the defect that shipped 19 QR codes reading `undefined/?v=…`.",
- ].join("\n"),
+ usageText({
+ reportsRoot: REPORTS_ROOT,
+ chainSteps: CHAIN_STEP_NAMES.join(", "),
+ draftAllSteps: chainStepsOf("draft-all").map((s) => s.name).join(", "),
+ }),
);
}
@@ -1266,6 +980,8 @@ const COMMANDS = {
posts: async () => process.exit(await (await import("../lib/report/postsCli.mjs")).postsCommand(argv.slice(argv.indexOf("posts") + 1))),
// The candidates inbox (UI notes item 14): proposals only -- lib/report/candidatesCli.mjs.
candidates: async () => process.exit(await (await import("../lib/report/candidatesCli.mjs")).candidatesCommand(argv.slice(argv.indexOf("candidates") + 1))),
+ // One recording's life cycle (lane L5, the ingredient rail): lib/ingredients/cli.mjs.
+ ingredient: async () => process.exit(await (await import("../lib/ingredients/cli.mjs")).ingredientCommand(argv.slice(argv.indexOf("ingredient") + 1))),
inbox: cmdInbox,
schedule: () => tsxScript("schedule"),
refresh: () => tsxScript("refresh"),
diff --git a/umtool/components/ingredients/IngredientRail.tsx b/umtool/components/ingredients/IngredientRail.tsx
@@ -0,0 +1,528 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { clipBenchHref, createHref, ingredientHref, playHref, projectHref } from "@/lib/hrefs";
+import { researchCasePipelineHref, researchHref } from "@/lib/research/hrefs";
+import type {
+ CheckedStage,
+ ClockStage,
+ DownloadedStage,
+ FoundStage,
+ Ingredient,
+ Pill,
+ PublishedStage,
+ RenderedStage,
+ TranscribedStage,
+ UsedStage,
+ WindowsStage,
+} from "@/lib/ingredients";
+
+// THE INGREDIENT RAIL (lane L5): one recording's nine stages across the top, the selected stage's panel below.
+// Each pill is ✓, a count, ! or —; each panel reads its stage's files (lib/ingredients/stages.mjs) and offers
+// its one action, which says what it costs and which queue it lands on before it runs.
+
+const GLYPH = (p: Pill) => (p.kind === "ok" ? "✓" : p.kind === "count" ? String(p.n ?? "") : p.kind === "warn" ? "!" : "—");
+const PILL_CLASS: Record<Pill["kind"], string> = {
+ ok: "border-seam-2 text-kept",
+ count: "border-seam-2 text-meter",
+ warn: "border-doubt text-doubt",
+ none: "border-seam text-muted-2",
+};
+
+const hms = (sec: number | null | undefined) => {
+ if (sec === null || sec === undefined || !Number.isFinite(sec)) return "?";
+ const t = Math.max(0, Math.floor(sec));
+ const h = Math.floor(t / 3600);
+ const m = Math.floor((t % 3600) / 60);
+ const s = String(t % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${m}:${s}`;
+};
+const span = (a: number | null | undefined, b: number | null | undefined) => `${hms(a)}–${hms(b)}`;
+const mb = (n: number | null | undefined) => (n === null || n === undefined ? "?" : n >= 1e9 ? `${(n / 1e9).toFixed(1)} GB` : `${(n / 1e6).toFixed(1)} MB`);
+const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 16).replace("T", " ") : "—");
+
+export default function IngredientRail({ data, initialStage, editorUrl }: { data: Ingredient; initialStage: string; editorUrl: string | null }) {
+ const [sel, setSel] = useState(initialStage);
+ const choose = (key: string) => {
+ setSel(key);
+ try {
+ const u = new URL(window.location.href);
+ u.searchParams.set("stage", key);
+ window.history.replaceState(null, "", u.toString());
+ } catch {
+ // The address is a convenience.
+ }
+ };
+ const [found, downloaded, transcribed, clock, windows, used, checked, rendered, published] = data.stages;
+ const stage = data.stages.find((s) => s.key === sel) ?? data.stages[0];
+ const ingredient = { ch: data.ch, id: data.dirId };
+
+ return (
+ <div className="space-y-3" data-ingredient={`${data.ch}/${data.dirId}`}>
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-[12.5px]" data-ingredient-head="">
+ <span className="font-mono text-[13px] font-medium text-text">
+ {data.ch}/{data.dirId}
+ </span>
+ {data.siteId && (
+ <span className="font-mono text-[12px] text-text-2" data-ingredient-site-id={data.siteId} title="a Rumble recording has two ids: its folder (the URL slug) and the embed id the archive serves">
+ archive id {data.siteId}
+ </span>
+ )}
+ {data.platform && <span className="text-muted-2">{data.platform}</span>}
+ {data.duration !== null && <span className="text-muted-2">{hms(data.duration)}</span>}
+ {data.uploadDate && <span className="text-muted-2">{data.uploadDate.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3")}</span>}
+ <span className="ml-auto flex flex-wrap items-center gap-x-3 gap-y-1">
+ {data.webpageUrl && (
+ <a href={data.webpageUrl} target="_blank" rel="noreferrer" className="ink-link">
+ its page ↗
+ </a>
+ )}
+ {editorUrl && data.exists && (
+ <a href={`${editorUrl}/channels/${encodeURIComponent(data.ch)}/videos/${encodeURIComponent(data.dirId)}`} target="_blank" rel="noreferrer" className="ink-link" data-ingredient-editor="">
+ in the editor ↗
+ </a>
+ )}
+ <Link href={createHref({ from: `${data.ch}/${data.dirId}` })} prefetch={false} className="ink-link">
+ make a video from it
+ </Link>
+ </span>
+ </div>
+ {data.notes.map((n) => (
+ <p key={n} className="m-0 text-[12px] text-doubt-text" data-ingredient-note="">
+ {n}
+ </p>
+ ))}
+ {data.focus && (
+ <p className="m-0 flex flex-wrap items-center gap-2 text-[12px] text-text-2" data-ingredient-focus={data.focus.name}>
+ Window <span className="font-mono">{data.focus.name}</span>
+ {data.focus.found ? "" : " — no such window on disk"}
+ <span className="text-muted-2">· the stages after Windows show the clips it plays</span>
+ <Link href={ingredientHref(data.ch, data.id)} prefetch={false} className="ink-link">
+ the whole recording
+ </Link>
+ </p>
+ )}
+
+ <ol className="grid grid-cols-3 gap-1 md:grid-cols-9" role="tablist" aria-label="Life cycle" data-ingredient-rail="">
+ {data.stages.map((s, i) => (
+ <li key={s.key} className="relative flex">
+ {i > 0 && <span aria-hidden="true" className="absolute -left-1 top-1/2 hidden h-px w-1 bg-seam-2 md:block" />}
+ <button
+ type="button"
+ role="tab"
+ aria-selected={s.key === stage.key}
+ data-stage={s.key}
+ data-pill={s.pill.kind}
+ data-pill-text={GLYPH(s.pill)}
+ onClick={() => choose(s.key)}
+ title={s.line}
+ className={cn(
+ "flex w-full items-center justify-between gap-1 rounded-[3px] border px-1.5 py-1.5 text-left text-[12px] transition-[color,background-color,border-color]",
+ s.key === stage.key ? "border-muted bg-panel-2 text-text" : "border-seam bg-panel text-text-2 hover:border-seam-2 hover:text-text",
+ )}
+ >
+ <span className="truncate font-medium">{s.label}</span>
+ <span className={cn("min-w-[1.3rem] shrink-0 rounded-[3px] border px-1 text-center text-[11.5px] font-semibold tabular-nums leading-[18px]", PILL_CLASS[s.pill.kind])}>{GLYPH(s.pill)}</span>
+ </button>
+ </li>
+ ))}
+ </ol>
+
+ <section className="rounded-[3px] border border-seam bg-panel px-4 py-3" role="tabpanel" data-stage-panel={stage.key} aria-label={stage.label}>
+ <div className="mb-2 flex flex-wrap items-baseline gap-x-3 gap-y-1">
+ <h2 className="micro">{stage.label}</h2>
+ <p className="m-0 text-[12.5px] text-text" data-stage-line="">
+ {stage.line}
+ </p>
+ </div>
+ {stage.key === "found" && <FoundPanel s={found} ch={data.ch} />}
+ {stage.key === "downloaded" && <DownloadedPanel s={downloaded} ingredient={ingredient} platform={data.platform} />}
+ {stage.key === "transcribed" && <TranscribedPanel s={transcribed} ingredient={ingredient} exists={data.exists} />}
+ {stage.key === "clock" && <ClockPanel s={clock} />}
+ {stage.key === "windows" && <WindowsPanel s={windows} ingredient={ingredient} ch={data.ch} id={data.id} />}
+ {stage.key === "used" && <UsedPanel s={used} />}
+ {stage.key === "checked" && <CheckedPanel s={checked} ingredient={ingredient} />}
+ {stage.key === "rendered" && <RenderedPanel s={rendered} />}
+ {stage.key === "published" && <PublishedPanel s={published} ingredient={ingredient} />}
+ </section>
+ </div>
+ );
+}
+
+// ── the action: plan, confirm, start ─────────────────────────────────────────
+
+type Plan = { action: string; what: string; cost: "network" | "gpu" | "disk" | null; queue: string; unreachable?: string; start: { route: string; body: Record<string, unknown> } | null };
+const COST: Record<string, string> = { network: "costs network", gpu: "costs GPU", disk: "deletes a cached file" };
+
+function Action({ label, body, testid }: { label: string; body: Record<string, unknown>; testid: string }) {
+ const router = useRouter();
+ const [plan, setPlan] = useState<Plan | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [result, setResult] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const post = async (route: string, b: Record<string, unknown>) => {
+ const res = await fetch(route, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(b) });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok || j?.error) throw new Error(String(j?.error ?? `HTTP ${res.status}`));
+ return j;
+ };
+ const ask = async () => {
+ setBusy(true);
+ setError(null);
+ setResult(null);
+ try {
+ setPlan((await post("/api/ingredients/action", { ...body, step: "plan" })) as Plan);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+ const start = async () => {
+ if (!plan?.start) return;
+ setBusy(true);
+ setError(null);
+ try {
+ const j = await post(plan.start.route, plan.start.body);
+ setResult(String(j?.message ?? (j?.ok ? "done" : "started")) + (j?.fixed?.length ? ` — ${j.fixed.length} link(s) fixed` : ""));
+ setPlan(null);
+ router.refresh();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <div className="space-y-1.5" data-action={testid}>
+ <button type="button" disabled={busy || !!plan} onClick={ask} className={buttonVariants({ variant: "outline", size: "sm" })} data-action-ask={testid}>
+ {label}…
+ </button>
+ {plan && (
+ <div
+ className="max-w-[760px] space-y-1.5 rounded-[3px] border border-seam-2 bg-panel-2 px-3 py-2 text-[12px]"
+ data-action-confirm={testid}
+ data-action-cost={plan.cost ?? "none"}
+ data-action-unreachable={plan.unreachable ? "1" : undefined}
+ >
+ <p className={cn("m-0", plan.unreachable ? "text-doubt-text" : "text-text")}>{plan.what}</p>
+ {!plan.unreachable && (
+ <p className="m-0 text-text-2">
+ {plan.cost && <span className="mr-2 font-medium text-doubt-text">{COST[plan.cost]}</span>}
+ lands on <span className="font-mono" data-action-queue="">{plan.queue}</span>
+ </p>
+ )}
+ <div className="flex gap-2">
+ {plan.start && (
+ <button type="button" disabled={busy} onClick={start} className={buttonVariants({ variant: "outline", size: "sm" })} data-action-start={testid}>
+ Start
+ </button>
+ )}
+ <button type="button" disabled={busy} onClick={() => setPlan(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}>
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+ {result && (
+ <p className="m-0 text-[12px] text-text-2" role="status" data-action-result={testid}>
+ {result}
+ </p>
+ )}
+ {error && (
+ <p className="m-0 text-[12px] text-reject-text" role="alert" data-action-error={testid}>
+ {error}
+ </p>
+ )}
+ </div>
+ );
+}
+
+// ── the panels ───────────────────────────────────────────────────────────────
+
+const Empty = ({ children }: { children: React.ReactNode }) => <p className="m-0 text-[12px] text-muted-2">{children}</p>;
+const Rows = ({ children, ...p }: React.ComponentProps<"ul">) => (
+ <ul className="m-0 max-h-[calc(100vh-330px)] min-h-0 list-none space-y-1 overflow-y-auto p-0 text-[12px]" {...p}>
+ {children}
+ </ul>
+);
+const Facts = ({ rows }: { rows: [string, React.ReactNode][] }) => (
+ <dl className="m-0 grid grid-cols-[max-content_1fr] gap-x-4 gap-y-0.5 text-[12px]">
+ {rows.map(([k, v]) => (
+ <div key={k} className="contents">
+ <dt className="text-muted-2">{k}</dt>
+ <dd className="m-0 min-w-0 truncate text-text-2">{v}</dd>
+ </div>
+ ))}
+ </dl>
+);
+
+function FoundPanel({ s, ch }: { s: FoundStage; ch: string }) {
+ return (
+ <div className="space-y-2">
+ {!s.findClips && !s.marks.length && !s.candidates.length && <Empty>No search mark, case window or clip-finder run names it.</Empty>}
+ <Rows data-found="">
+ {s.findClips && (
+ <li data-found-row="find-clips">
+ The clip finder ({day(s.findClips.at)}): {s.findClips.segments} segment{s.findClips.segments === 1 ? "" : "s"} —{" "}
+ <Link href={projectHref(s.findClips.project)} prefetch={false} className="ink-link">
+ {s.findClips.project}
+ </Link>
+ </li>
+ )}
+ {s.marks.map((m) => (
+ <li key={m.session} data-found-row="mark">
+ Research: <span className="text-text">{m.state}</span> in “{m.query ?? m.session}” ({day(m.at)}) —{" "}
+ <Link href={researchHref({ q: m.query ?? undefined, channels: [ch] })} prefetch={false} className="ink-link">
+ open in Research
+ </Link>
+ </li>
+ ))}
+ {s.candidates.map((c) => (
+ <li key={`${c.case}:${c.key}`} data-found-row="candidate">
+ Case {c.case}: window {span(c.from, c.to)} ({c.hits} hit{c.hits === 1 ? "" : "s"}) —{" "}
+ <Link href={researchCasePipelineHref(c.case, "candidates")} prefetch={false} className="ink-link">
+ its candidates
+ </Link>
+ </li>
+ ))}
+ </Rows>
+ <Link href={researchHref({ channels: [ch] })} prefetch={false} className={buttonVariants({ variant: "outline", size: "sm" })} data-found-open="">
+ Find in Research
+ </Link>
+ </div>
+ );
+}
+
+function DownloadedPanel({ s, ingredient, platform }: { s: DownloadedStage; ingredient: { ch: string; id: string }; platform: string | null }) {
+ return (
+ <div className="flex flex-wrap gap-x-8 gap-y-3">
+ <div className="min-w-[320px] flex-1">
+ <Facts
+ rows={[
+ ["metadata", s.meta ? `${s.meta.title ?? s.meta.id ?? "?"} (${mb(s.meta.bytes)}, its head read)` : "none"],
+ ["download", s.outcome ? `${s.outcome.status}, ${s.outcome.attempts} attempt${s.outcome.attempts === 1 ? "" : "s"}${s.outcome.finishedAt ? `, ${day(s.outcome.finishedAt)}` : ""}` : "no outcome recorded"],
+ ["availability", s.availability ? `${s.availability.availability} (checked ${day(s.availability.checkedAt)})` : "never checked"],
+ ["history", s.history ? `${s.history.count} metadata rewrite${s.history.count === 1 ? "" : "s"}, last ${day(s.history.lastAt)} by ${s.history.lastBy ?? "?"}` : "none"],
+ ["saved video", s.saved ? `${s.saved.file}${s.saved.height ? ` (${s.saved.height}p)` : ""}${s.saved.reachable ? "" : " — NOT ANSWERING"}` : "not saved"],
+ ["imported", s.imported ? `${s.imported.count} landing${s.imported.count === 1 ? "" : "s"} (${s.imported.via ?? "?"}), ${day(s.imported.lastAt)}` : "—"],
+ ["captions", s.captions?.length ? s.captions.join(", ") : "none"],
+ ]}
+ />
+ </div>
+ <div className="min-w-[260px] flex-1 space-y-2">
+ <p className="micro m-0">Media</p>
+ {s.media.length ? (
+ <Rows data-media="">
+ {s.media.map((m) => (
+ <li key={m.name} className="font-mono">
+ {m.name} {mb(m.bytes)}
+ {m.link ? (m.reachable ? " → media tier" : " → media tier, NOT ANSWERING") : ""}
+ </li>
+ ))}
+ </Rows>
+ ) : (
+ <Empty>No audio or source video in the video dir.</Empty>
+ )}
+ <Action label={platform === "rumble" ? "Persist the whole recording" : "Persist source video"} testid="persist" body={{ action: "persist", ...ingredient }} />
+ </div>
+ </div>
+ );
+}
+
+function TranscribedPanel({ s, ingredient, exists }: { s: TranscribedStage; ingredient: { ch: string; id: string }; exists: boolean }) {
+ return (
+ <div className="flex flex-wrap gap-x-8 gap-y-3">
+ <div className="min-w-[320px] flex-1">
+ <Facts
+ rows={[
+ ["cues", s.cues ? `${s.cues.source ?? "?"}${s.cues.format ? ` (${s.cues.format})` : ""}, ${mb(s.cues.bytes)}` : "none"],
+ ["reach", s.cues ? `last cue ends ${hms(s.cues.lastEnd)} of ${hms(s.cues.duration)}${s.cues.coverage !== null ? ` (${Math.round(s.cues.coverage * 100)}%)` : ""}` : "—"],
+ ["made by", s.outcome ? `${s.outcome.worker ?? "?"}, ${day(s.outcome.at)}${s.outcome.salvaged ? " — a SALVAGE: gaps where the audio did not decode" : ""}` : "—"],
+ ["timed words", s.words ? `words.json (${mb(s.words.bytes)})` : "none"],
+ ["pinned", s.pin ? "transcript-pin.json" : "no"],
+ ["caption files", s.captions?.length ? s.captions.join(", ") : "none"],
+ ]}
+ />
+ </div>
+ {exists && (
+ <div className="min-w-[260px] flex-1">
+ <Action label={s.cues ? "Transcribe again" : "Transcribe"} testid="transcribe" body={{ action: "transcribe", ...ingredient }} />
+ </div>
+ )}
+ </div>
+ );
+}
+
+function ClockPanel({ s }: { s: ClockStage }) {
+ if (!s.clock) return <Empty>A Rumble recording gets one when its whole recording is saved and a window is cut from it.</Empty>;
+ return (
+ <Facts
+ rows={[
+ ["map", `${s.clock.id}: ${s.clock.ok ? "ok" : "NOT ok"}, ${s.clock.segments} segment${s.clock.segments === 1 ? "" : "s"}${s.clock.steps ? `, ${s.clock.steps} step${s.clock.steps === 1 ? "" : "s"}` : ""}`],
+ ["between", `${s.clock.source ?? "?"} (the cues' clock) → ${s.clock.target ?? "?"}`],
+ ["residual", s.clock.residualMs !== null ? `${s.clock.residualMs} ms` : "?"],
+ ["guarantee", "umtool quote-check, per clip"],
+ ]}
+ />
+ );
+}
+
+function WindowsPanel({ s, ingredient, ch, id }: { s: WindowsStage; ingredient: { ch: string; id: string }; ch: string; id: string }) {
+ const byProject = new Map<string, string[]>();
+ for (const u of s.uncovered) byProject.set(u.project, [...(byProject.get(u.project) ?? []), u.clipId]);
+ return (
+ <div className="space-y-2">
+ {s.windows.length === 0 && !s.uncovered.length && <Empty>No windows cut yet.</Empty>}
+ {s.windows.length > 0 && (
+ <Rows data-windows="">
+ {s.windows.map((w) => (
+ <li
+ key={w.file}
+ data-window={w.name}
+ data-window-focused={w.focused ? "1" : undefined}
+ className={cn("flex flex-wrap items-center gap-x-3 gap-y-1 rounded-[3px] border px-2 py-1", w.focused ? "border-signal" : "border-seam")}
+ >
+ <Link href={ingredientHref(ch, id, w)} prefetch={false} className="font-mono text-text hover:underline">
+ {span(w.from, w.to)}
+ </Link>
+ <span className="text-muted-2">{mb(w.bytes)}</span>
+ {w.desynced && <span className="text-doubt-text">set aside: its picture runs off its sound</span>}
+ {w.sidecar && (
+ <span className="text-text-2">
+ for {w.sidecar.clipId ?? "?"} ({w.sidecar.requestedBy ?? "?"}){w.sidecar.source ? `, from the ${w.sidecar.source}` : ""}
+ {w.sidecar.clock ? `, through clock ${w.sidecar.clock.id}${w.sidecar.clock.certain ? "" : " (NOT certain)"}` : ""}
+ {w.sidecar.syncOk === false ? ", sync NOT ok" : ""}
+ </span>
+ )}
+ <span className="text-text-2">
+ {w.serves.length ? `cuts ${w.serves.map((x) => `${x.project.split("/").pop()} ${x.clipId}`).join(", ")}` : w.orphan ? "no project uses it now" : "cuts no clip"}
+ </span>
+ <span className="ml-auto">
+ <Action label="Evict" testid={`evict-${w.file}`} body={{ action: "evict", ...ingredient, window: w.file }} />
+ </span>
+ </li>
+ ))}
+ </Rows>
+ )}
+ {s.uncovered.length > 0 && (
+ <div className="space-y-1.5" data-uncovered="">
+ <p className="m-0 text-[12px] text-text-2">
+ Not fetched: {s.uncovered.map((u) => `${u.project} ${u.clipId} (${span(u.from, u.to)})`).join(", ")}
+ </p>
+ {[...byProject.entries()].map(([project, clips]) => (
+ <Action key={project} label={`Fetch ${clips.length === 1 ? clips[0] : `${clips.length} windows`} for ${project.split("/").pop()}`} testid={`fetch-${project}`} body={{ action: "fetch", ...ingredient, project, clips }} />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function UsedPanel({ s }: { s: UsedStage }) {
+ if (!s.rows.length) return <Empty>No project cuts from it.</Empty>;
+ return (
+ <Rows data-used="">
+ {s.rows.map((r) => (
+ <li key={`${r.project}#${r.clipId}`} data-used-row={`${r.project}#${r.clipId}`} className="flex flex-wrap items-baseline gap-x-3">
+ <Link href={projectHref(r.project)} prefetch={false} className="text-text hover:underline">
+ {r.project}
+ </Link>
+ <Link href={clipBenchHref(r.project, r.clipId)} prefetch={false} className="ink-link font-mono" data-used-open="">
+ {r.clipId}
+ </Link>
+ <span className="font-mono text-text-2">
+ {span(r.start, r.end)}
+ {r.cutStart !== null || r.cutEnd !== null ? ` (cut ${span(r.cutStart ?? r.start, r.cutEnd ?? r.end)})` : ""}
+ </span>
+ <span className="text-muted-2">{[r.inDraft ? "draft" : null, ...r.versions.map((v) => v.id)].filter(Boolean).join(", ")}</span>
+ {r.quote && <span className="min-w-0 flex-1 truncate text-muted-2">“{r.quote}”</span>}
+ </li>
+ ))}
+ </Rows>
+ );
+}
+
+function CheckedPanel({ s, ingredient }: { s: CheckedStage; ingredient: { ch: string; id: string } }) {
+ if (!s.clips.length) return <Empty>No clip uses it, so there is no quote to check.</Empty>;
+ const byProject = new Map<string, string[]>();
+ for (const c of s.clips) if (c.hasQuote) byProject.set(c.project, [...(byProject.get(c.project) ?? []), c.clipId]);
+ return (
+ <div className="space-y-2">
+ <Rows data-checked="">
+ {s.clips.map((c) => (
+ <li key={`${c.project}#${c.clipId}`} data-checked-row={`${c.project}#${c.clipId}`} data-status={c.status ?? ""} className="flex flex-wrap gap-x-3">
+ <span className="text-text">{c.project}</span>
+ <span className="font-mono">{c.clipId}</span>
+ <span className={cn(c.current && c.status !== "ok" ? "text-doubt-text" : "text-text-2")}>
+ {!c.hasQuote ? "no quote" : c.status ? `${c.status}${c.offset !== null && c.status !== "ok" ? ` (${c.offset > 0 ? "+" : ""}${c.offset.toFixed(1)} s)` : ""}${c.current ? "" : " — stale: the cut changed since"}` : "not checked"}
+ </span>
+ </li>
+ ))}
+ </Rows>
+ {[...byProject.entries()].map(([project, clips]) => (
+ <Action key={project} label={`Check quotes in ${project.split("/").pop()}`} testid={`quote-check-${project}`} body={{ action: "quote-check", ...ingredient, project, clips }} />
+ ))}
+ </div>
+ );
+}
+
+function RenderedPanel({ s }: { s: RenderedStage }) {
+ if (!s.renders.length) return <Empty>Not in any saved version yet.</Empty>;
+ return (
+ <Rows data-rendered="">
+ {s.renders.map((r) => (
+ <li key={`${r.project}#${r.clipId}@${r.version ?? "draft"}`} data-rendered-row={`${r.project}#${r.clipId}@${r.version ?? "draft"}`} className="flex flex-wrap gap-x-3">
+ <span className="text-text">{r.project}</span>
+ <span className="font-mono">{r.clipId}</span>
+ <span className="text-text-2">
+ {r.version ? `version ${r.version}${r.label ? ` (${r.label})` : ""}` : "the draft's segment"}: {r.state ?? "not rendered"}
+ {r.seconds !== null ? `, ${hms(r.seconds)}` : ""}
+ {r.cut ? `, cut ${span(r.cut.from, r.cut.to)}` : ""}
+ </span>
+ <Link href={playHref(r.project, r.version ? { take: r.version, clip: r.clipId } : { clip: r.clipId })} prefetch={false} className="ink-link" data-rendered-play="">
+ play it at this clip
+ </Link>
+ </li>
+ ))}
+ </Rows>
+ );
+}
+
+function PublishedPanel({ s, ingredient }: { s: PublishedStage; ingredient: { ch: string; id: string } }) {
+ if (!s.links.length) return <Empty>Not in any cut, so nothing links to it.</Empty>;
+ const projects = [...new Set(s.links.map((l) => l.project))];
+ return (
+ <div className="space-y-2">
+ <Rows data-published="">
+ {s.links.map((l) => (
+ <li key={`${l.project}#${l.clipId}`} data-published-row={`${l.project}#${l.clipId}`} data-state={l.state ?? ""} className="flex flex-wrap gap-x-3">
+ <span className="text-text">{l.project}</span>
+ <span className="font-mono">{l.clipId}</span>
+ <span className={cn(l.state === "dead" ? "text-reject-text" : "text-text-2")}>{l.state ?? "never checked"}</span>
+ {l.url && (
+ <a href={l.url} target="_blank" rel="noreferrer" className="ink-link min-w-0 truncate">
+ {l.url}
+ </a>
+ )}
+ {l.fix && <span className="text-muted-2">fix: {l.fix}</span>}
+ </li>
+ ))}
+ </Rows>
+ <div className="flex flex-wrap gap-3">
+ {projects.map((p) => (
+ <Action key={p} label={`Check links in ${p.split("/").pop()}`} testid={`links-${p}`} body={{ action: "links", ...ingredient, project: p }} />
+ ))}
+ {projects
+ .filter((p) => s.links.some((l) => l.project === p && l.state === "dead" && l.fix))
+ .map((p) => (
+ <Action key={`fix-${p}`} label={`Fix dead links in ${p.split("/").pop()}`} testid={`links-fix-${p}`} body={{ action: "links", ...ingredient, project: p, fix: true }} />
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/umtool/components/projects/bench/BenchShell.tsx b/umtool/components/projects/bench/BenchShell.tsx
@@ -71,6 +71,7 @@ export function BenchTop({
note,
phone = "shown",
slot = false,
+ life = null,
}: {
/** The piece this bench belongs to: "← <its name>". */
back: BenchLink;
@@ -94,6 +95,8 @@ export function BenchTop({
* portal a control into (the clip bench's "Back to the cut"). Hidden while empty.
*/
slot?: boolean;
+ /** The source's life cycle (lane L5, /ingredients/<ch>/<id>): a small link beside the bench's kind. */
+ life?: BenchLink | null;
}) {
return (
<header
@@ -128,6 +131,11 @@ export function BenchTop({
<span className="micro" data-bench-kind="">
{kind}
</span>
+ {life && (
+ <Link href={life.href} prefetch={false} data-bench-life="" className="text-[11.5px] text-muted-2 hover:text-text" {...life.attrs}>
+ {life.label}
+ </Link>
+ )}
{pos && (
<span data-bench-pos={`${pos.index}/${pos.total}`} className="font-mono text-[12.5px] font-medium text-text-2">
{pos.index} of {pos.total}
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -7,7 +7,7 @@ import { buttonVariants } from "@/components/ui/button";
import { useSharedNotes } from "@/components/notes/NotesProvider";
import { NoteThread } from "@/components/notes/NoteThread";
import type { Anchor, CutAsk, Note } from "@/lib/annotations/types";
-import { clipBenchHref, openInDraftHref, postBenchHref } from "@/lib/hrefs";
+import { clipBenchHref, ingredientHref, openInDraftHref, postBenchHref } from "@/lib/hrefs";
import { cn } from "@/lib/utils";
import { footageAt } from "@/lib/report/footage-move.mjs";
import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs";
@@ -117,6 +117,8 @@ export type PlayEntry = {
dateLabel?: string | null;
section?: unknown;
channel?: string | null;
+ /** The channel it cuts from (its own, else the provenance's): the life cycle's address (lane L5). */
+ sourceChannel?: string | null;
quote?: string | null;
video?: string;
start?: number;
@@ -1401,6 +1403,18 @@ export default function PlayCut({
</button>
{/* The frame on screen kept as a picture in shots/ (umtool still): never a write to the cut. */}
{item?.clip && <StillButton project={project} take={take ?? null} source={stillSource} />}
+ {/* The clip's source across its life cycle (lane L5): found, downloaded, … published. */}
+ {item?.clip && entry?.video && entry.sourceChannel && (
+ <Link
+ href={ingredientHref(entry.sourceChannel, entry.video)}
+ prefetch={false}
+ data-play-life=""
+ className="text-[11.5px] text-muted-2 hover:text-text"
+ title="this clip's recording across its life cycle: found, downloaded, transcribed, its windows, every cut that uses it, checked, rendered, published"
+ >
+ Life cycle
+ </Link>
+ )}
<span className="ml-auto flex flex-wrap items-center gap-x-2 text-[11.5px] text-muted" data-play-hud="">
{tally.length > 0 && <span className="sr-only" data-play-tally={tally.map((r) => `${r.verdict}:${r.count}`).join(",")} />}
{schedule?.factcheck && (
diff --git a/umtool/components/shell/CommandForm.tsx b/umtool/components/shell/CommandForm.tsx
@@ -0,0 +1,322 @@
+"use client";
+
+import { useEffect, useMemo, useRef, useState } from "react";
+import { buildArgv, cliLine, confirmOf } from "@/lib/cli/argv.mjs";
+import { cn } from "@/lib/utils";
+
+// ---------------------------------------------------------------------------
+// ONE VERB AS A FORM (⌘K Commands, lane palette L8a): a row of the verb
+// registry (lib/cli/verbs.mjs, served by GET /api/cli) drawn as its args, the
+// page's project and selection filled in; the exact command line under it
+// (Copy as CLI -- built by the same lib/cli/argv.mjs the server builds argv
+// with); Run posts { verb, values } to /api/cli and follows what it started:
+// the app job's live log, or the queued step's. A row with `confirm` (no undo:
+// it deletes, evicts or kills) asks a second press, "Yes, <what it does>",
+// and the server wants that confirm too. What Run started is handed up
+// (onStarted), so the palette lists it under Runs after an Escape.
+// ---------------------------------------------------------------------------
+
+export type CliArg = { name: string; type: string; required?: boolean; choices?: string[]; default?: unknown; help?: string; repeat?: boolean; context?: string };
+export type CliVerb = { verb: string; summary: string; target: string; queue: boolean; confirm?: { what: string; when?: string[]; unless?: string[] } | null; args: CliArg[] };
+export type CliContext = { project: string | null; clip: string | null; post: string | null; take: string | null };
+export type Value = string | boolean;
+/** A run the palette keeps: its form's values and what it started. */
+export type CliRun = { verb: string; values: Record<string, Value>; kind: "job" | "queued"; id: string; line: string; at: number };
+
+type Run =
+ | { kind: "job"; id: string; state: string; log: string[]; next: number; error: string | null; exitCode: number | null }
+ | { kind: "queued"; qid: string; state: string; log: string[]; error: string | null; exitCode: number | null; runnerUp: boolean };
+
+const TEXTAREA = new Set(["pairs", "flagpairs", "list", "text", "json"]);
+const TERMINAL = new Set(["done", "failed", "cancelled", "blocked"]);
+
+/** What the page tells the form: the project for a project arg, the selection for one that asks. */
+function initialValues(row: CliVerb, ctx: CliContext): Record<string, Value> {
+ const v: Record<string, Value> = {};
+ for (const a of row.args) {
+ if (a.type === "project" && a.name === "project" && ctx.project) v[a.name] = ctx.project;
+ else if (a.context === "clip" && ctx.clip) v[a.name] = ctx.clip;
+ else if (a.context === "post" && ctx.post) v[a.name] = ctx.post;
+ else if (a.context === "take" && ctx.take && a.required) v[a.name] = ctx.take;
+ else if (a.default !== undefined) v[a.name] = typeof a.default === "boolean" ? a.default : String(a.default);
+ }
+ return v;
+}
+
+export default function CommandForm({
+ row,
+ ctx,
+ onBack,
+ resume = null,
+ onStarted,
+}: {
+ row: CliVerb;
+ ctx: CliContext;
+ onBack: () => void;
+ /** A run started before (the palette's Runs): its values, and it is followed again. */
+ resume?: CliRun | null;
+ onStarted?: (run: CliRun) => void;
+}) {
+ const [values, setValues] = useState<Record<string, Value>>(() => (resume ? resume.values : initialValues(row, ctx)));
+ const [run, setRun] = useState<Run | null>(() =>
+ resume
+ ? resume.kind === "job"
+ ? { kind: "job", id: resume.id, state: "running", log: [], next: 0, error: null, exitCode: null }
+ : { kind: "queued", qid: resume.id, state: "queued", log: [], error: null, exitCode: null, runnerUp: true }
+ : null,
+ );
+ const [asking, setAsking] = useState<string | null>(null);
+ const [posting, setPosting] = useState(false);
+ const [refused, setRefused] = useState<string | null>(null);
+ const [copied, setCopied] = useState(false);
+ const first = useRef<HTMLElement | null>(null);
+ const logRef = useRef<HTMLPreElement>(null);
+
+ useEffect(() => {
+ first.current?.focus();
+ }, []);
+
+ const built = useMemo(() => buildArgv(row, values), [row, values]);
+ const line = built.ok ? cliLine(built.argv) : null;
+ const going = posting || (run !== null && !TERMINAL.has(run.state));
+
+ // Follow what Run started.
+ useEffect(() => {
+ if (!run || TERMINAL.has(run.state)) return;
+ let live = true;
+ const t = setTimeout(async () => {
+ try {
+ if (run.kind === "job") {
+ const r = await fetch(`/api/cli?job=${encodeURIComponent(run.id)}&since=${run.next}`, { cache: "no-store" });
+ const j = (await r.json()) as { job?: { state: string; log: string[]; next: number; error: string | null; exitCode: number | null } };
+ if (!live) return;
+ if (!j.job) {
+ setRun((cur) => (cur ? { ...cur, state: "failed", error: "the app no longer knows this job (it restarted): see Settings · system" } : cur));
+ return;
+ }
+ const job = j.job;
+ setRun((cur) => (cur && cur.kind === "job" ? { ...cur, state: job.state, log: [...cur.log, ...job.log].slice(-400), next: job.next, error: job.error, exitCode: job.exitCode } : cur));
+ } else {
+ const r = await fetch(`/api/cli?qid=${encodeURIComponent(run.qid)}`, { cache: "no-store" });
+ const j = (await r.json()) as { step?: { state: string; error: string | null; exitCode: number | null }; log?: string[]; runner?: { enabled: boolean; armed: boolean } };
+ if (!live) return;
+ if (!j.step) {
+ setRun((cur) => (cur ? { ...cur, state: "failed", error: "no such step in the queue" } : cur));
+ return;
+ }
+ const step = j.step;
+ setRun((cur) => (cur && cur.kind === "queued" ? { ...cur, state: step.state, log: j.log ?? [], error: step.error, exitCode: step.exitCode, runnerUp: !!j.runner?.armed } : cur));
+ }
+ } catch {
+ /* the next turn tries again */
+ }
+ }, 700);
+ return () => {
+ live = false;
+ clearTimeout(t);
+ };
+ }, [run]);
+
+ useEffect(() => {
+ const el = logRef.current;
+ if (el) el.scrollTop = el.scrollHeight;
+ }, [run?.log.length]);
+
+ const set = (name: string, v: Value) => setValues((cur) => ({ ...cur, [name]: v }));
+
+ const submit = async (confirmed = false) => {
+ if (!built.ok || going) return;
+ const what = confirmOf(row, values);
+ if (what && !confirmed) {
+ setAsking(what);
+ return;
+ }
+ setAsking(null);
+ setPosting(true);
+ setRefused(null);
+ try {
+ const r = await fetch("/api/cli", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ verb: row.verb, values, ...(confirmed ? { confirm: true } : {}) }),
+ });
+ const j = (await r.json().catch(() => ({}))) as {
+ error?: string;
+ line?: string;
+ confirm?: string;
+ job?: { id: string; state: string; log: string[]; next: number; error: string | null; exitCode: number | null };
+ queued?: { qid: string };
+ queue?: { armed: boolean };
+ };
+ if (!r.ok) {
+ if (j.confirm) setAsking(j.confirm);
+ else setRefused(j.error ?? `HTTP ${r.status}`);
+ } else if (j.job) {
+ setRun({ kind: "job", id: j.job.id, state: j.job.state, log: j.job.log, next: j.job.next, error: j.job.error, exitCode: j.job.exitCode });
+ onStarted?.({ verb: row.verb, values, kind: "job", id: j.job.id, line: j.line ?? line ?? "", at: Date.now() });
+ } else if (j.queued) {
+ setRun({ kind: "queued", qid: j.queued.qid, state: "queued", log: [], error: null, exitCode: null, runnerUp: !!j.queue?.armed });
+ onStarted?.({ verb: row.verb, values, kind: "queued", id: j.queued.qid, line: j.line ?? line ?? "", at: Date.now() });
+ }
+ } catch (e) {
+ setRefused(e instanceof Error ? e.message : String(e));
+ } finally {
+ setPosting(false);
+ }
+ };
+
+ const copy = async () => {
+ if (!line) return;
+ try {
+ await navigator.clipboard.writeText(line);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ } catch {
+ setRefused("the clipboard refused: select the line and copy it");
+ }
+ };
+
+ const field = (a: CliArg, i: number) => {
+ const id = `cli-arg-${i}`;
+ const v = values[a.name];
+ const ref = i === 0 ? (el: HTMLElement | null) => void (first.current = el) : undefined;
+ const bad = !built.ok && built.field === a.name;
+ const control =
+ a.type === "boolean" ? (
+ <input id={id} ref={ref} type="checkbox" checked={v === true} onChange={(e) => set(a.name, e.target.checked)} className="h-3.5 w-3.5 accent-[var(--color-signal)]" />
+ ) : a.type === "choice" ? (
+ <select id={id} ref={ref} value={typeof v === "string" ? v : ""} onChange={(e) => set(a.name, e.target.value)} className="h-7 min-w-0 flex-1 rounded-[3px] border border-seam bg-panel-2 px-1.5 text-[12.5px]">
+ <option value="">{a.required ? "choose…" : "—"}</option>
+ {(a.choices ?? []).map((c) => (
+ <option key={c} value={c}>
+ {c}
+ </option>
+ ))}
+ </select>
+ ) : TEXTAREA.has(a.type) ? (
+ <textarea
+ id={id}
+ ref={ref}
+ rows={a.type === "text" || a.type === "json" ? 3 : 2}
+ value={typeof v === "string" ? v : ""}
+ placeholder={a.help ?? ""}
+ spellCheck={false}
+ onChange={(e) => set(a.name, e.target.value)}
+ className="min-w-0 flex-1 resize-y rounded-[3px] border border-seam bg-panel-2 px-1.5 py-1 font-mono text-[12px] text-text outline-none focus:border-signal"
+ />
+ ) : (
+ <input
+ id={id}
+ ref={ref}
+ value={typeof v === "string" ? v : ""}
+ inputMode={a.type === "number" ? "decimal" : undefined}
+ placeholder={a.help ?? (a.type === "number" ? "a number" : "")}
+ spellCheck={false}
+ onChange={(e) => set(a.name, e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ void submit();
+ }
+ }}
+ className="h-7 min-w-0 flex-1 rounded-[3px] border border-seam bg-panel-2 px-1.5 font-mono text-[12px] text-text outline-none focus:border-signal"
+ />
+ );
+ return (
+ <div key={a.name} data-cli-arg={a.name} className={cn("flex items-start gap-2 py-1", bad && "text-reject-text")}>
+ <label htmlFor={id} className="w-[132px] shrink-0 truncate pt-1 font-mono text-[11.5px] text-muted" title={a.help ?? a.name}>
+ {a.name}
+ {a.required && <span className="text-signal"> *</span>}
+ </label>
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ {control}
+ {a.help && a.type !== "boolean" && !TEXTAREA.has(a.type) && a.type !== "string" && a.type !== "number" && <span className="text-[11px] text-muted-2">{a.help}</span>}
+ {a.help && a.type === "boolean" && <span className="text-[11px] text-muted-2">{a.help}</span>}
+ </div>
+ </div>
+ );
+ };
+
+ return (
+ <div data-cli-form={row.verb} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex items-baseline gap-3 border-b border-seam px-3.5 py-2.5">
+ <button type="button" data-cli-back="" onClick={onBack} className="font-mono text-[12px] text-muted hover:text-text">
+ ← Commands
+ </button>
+ <span className="font-mono text-[14px] text-text">umtool {row.verb}</span>
+ <span className="ml-auto min-w-0 truncate text-[12px] text-muted-2">{row.summary}</span>
+ </div>
+ <form
+ className="min-h-0 flex-1 overflow-y-auto px-3.5 py-1.5"
+ onSubmit={(e) => {
+ e.preventDefault();
+ void submit();
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
+ e.preventDefault();
+ void submit();
+ }
+ }}
+ >
+ {row.args.length ? row.args.map(field) : <p className="py-2 text-[12.5px] text-text-2">No arguments.</p>}
+ </form>
+ <div className="border-t border-seam px-3.5 py-2">
+ {line ? (
+ <code data-cli-line="" className="block select-all break-all font-mono text-[11.5px] text-text-2">
+ {line}
+ </code>
+ ) : (
+ <p data-cli-invalid="" className="text-[12px] text-reject-text">
+ {built.ok ? "" : built.error}
+ </p>
+ )}
+ <div className="mt-2 flex items-center gap-2">
+ <button type="button" data-cli-run="" disabled={!built.ok || going} onClick={() => void submit()} className="rounded-[3px] bg-signal px-3 py-1 text-[12.5px] font-medium text-on-signal disabled:opacity-40">
+ {row.queue ? "Queue it" : "Run"}
+ </button>
+ <button type="button" data-cli-copy="" disabled={!line} onClick={() => void copy()} className="rounded-[3px] border border-seam-2 px-3 py-1 text-[12.5px] text-text disabled:opacity-40">
+ {copied ? "Copied" : "Copy as CLI"}
+ </button>
+ <span className="text-[11.5px] text-muted-2">
+ {row.queue ? "renders: the durable queue runs it" : row.target === "draft" ? "writes the working draft (an undo point)" : row.target === "corpus" ? "not one project" : "a project's files"}
+ </span>
+ {run && (
+ <span data-cli-state={run.state} className={cn("ml-auto font-mono text-[12px]", run.state === "done" ? "text-kept-text" : TERMINAL.has(run.state) ? "text-reject-text" : "text-muted")}>
+ {run.kind === "queued" ? `${run.qid} · ` : ""}
+ {run.state}
+ {run.exitCode !== null && run.state !== "done" ? ` (exit ${run.exitCode})` : ""}
+ </span>
+ )}
+ </div>
+ {asking && (
+ <div data-cli-asking="" className="mt-2 flex flex-wrap items-center gap-2 rounded-[3px] border border-reject px-2 py-1.5">
+ <span className="text-[12px] text-text">This has no undo.</span>
+ <button type="button" data-cli-confirm="" onClick={() => void submit(true)} className="rounded-[3px] bg-reject px-2.5 py-1 text-[12px] font-medium text-on-signal">
+ Yes, {asking}
+ </button>
+ <button type="button" data-cli-cancel="" onClick={() => setAsking(null)} className="rounded-[3px] border border-seam-2 px-2.5 py-1 text-[12px] text-text">
+ Not now
+ </button>
+ </div>
+ )}
+ {refused && (
+ <p data-cli-refused="" className="mt-1.5 text-[12px] text-reject-text">
+ {refused}
+ </p>
+ )}
+ {run && (
+ <>
+ {run.kind === "queued" && !run.runnerUp && run.state === "queued" && (
+ <p className="mt-1.5 text-[11.5px] text-muted-2">the queue's runner is not up in this app: the step waits (umtool queue ls)</p>
+ )}
+ {run.error && run.state !== "done" && <p className="mt-1.5 text-[12px] text-reject-text">{run.error}</p>}
+ <pre ref={logRef} data-cli-log="" className="mt-1.5 max-h-[22vh] overflow-auto whitespace-pre-wrap break-all rounded-[3px] bg-panel-2 px-2 py-1.5 font-mono text-[11px] leading-[1.45] text-text-2">
+ {run.log.join("\n") || "…"}
+ </pre>
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/umtool/components/shell/JumpPalette.tsx b/umtool/components/shell/JumpPalette.tsx
@@ -23,6 +23,7 @@ import {
} from "@/lib/hrefs";
import { MODES } from "@/lib/types";
import { cn } from "@/lib/utils";
+import CommandForm, { type CliContext, type CliRun, type CliVerb } from "./CommandForm";
// ---------------------------------------------------------------------------
// ⌘K: jump to any piece, place, tool or create action (plans/umtool-redesign.md,
@@ -34,11 +35,24 @@ import { cn } from "@/lib/utils";
// The places, tools and create actions are fixed and listed here. The pieces
// are fetched the first time it opens (GET /api/jump) and kept for the page.
// The rail's "Jump to…" opens it with an event, `umtool:jump`.
+//
+// COMMANDS (lane palette, L8a): every umtool verb the registry offers as a
+// form (lib/cli/verbs.mjs, GET /api/cli), matched on its verb and summary once
+// something is typed (`>` first: commands only, all of them with nothing
+// after it). Choosing one opens its form in place (CommandForm), the page's
+// project and selection filled in -- GET /api/cli?path= says what the page is
+// about, asked each time the palette opens (and reset first, so a quick pick never
+// gets the last page's project: the form is keyed on the context and remounts when
+// it arrives). What a form's Run started stays under Runs (nothing typed) for
+// the page's life, so an Escape mid-run loses nothing.
// ---------------------------------------------------------------------------
export const JUMP_EVENT = "umtool:jump";
-type Item = { id: string; section: "Places" | "Tools" | "Create" | "Pieces"; label: string; hint: string; href: string };
+type Item = { id: string; section: "Runs" | "Places" | "Tools" | "Create" | "Pieces" | "Commands"; label: string; hint: string; href: string; verb?: string; run?: CliRun };
+
+const NO_CONTEXT: CliContext = { project: null, clip: null, post: null, take: null };
+const clock = (ms: number) => new Date(ms).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
type PieceRow = { id: string; title: string; href: string; kind: string; site: string | null; stage: string; lifecycle: string };
const FIXED: Item[] = [
@@ -73,6 +87,29 @@ const FIXED: Item[] = [
const words = (q: string) => q.toLowerCase().split(/\s+/).filter(Boolean);
+/** Each letter of `w` in `s`, in order: "tlins" finds "timeline insert". */
+const subsequence = (w: string, s: string) => {
+ let i = 0;
+ for (const ch of s) if (ch === w[i]) i += 1;
+ return i === w.length;
+};
+
+/** How well a verb answers the words typed: 0 is not at all. */
+function commandScore(v: CliVerb, w: string[]): number {
+ const verb = v.verb.toLowerCase();
+ const hay = `${verb} ${v.summary.toLowerCase()}`;
+ let score = 0;
+ for (const x of w) {
+ if (verb.startsWith(x)) score += 4;
+ else if (verb.split(" ").some((part) => part.startsWith(x))) score += 3;
+ else if (verb.includes(x)) score += 2;
+ else if (hay.includes(x)) score += 1;
+ else if (x.length >= 3 && subsequence(x, verb.replace(/[ -]/g, ""))) score += 0.5;
+ else return 0;
+ }
+ return score;
+}
+
export default function JumpPalette() {
const router = useRouter();
const dialog = useRef<HTMLDialogElement>(null);
@@ -85,10 +122,18 @@ export default function JumpPalette() {
const [error, setError] = useState<string | null>(null);
// Set once the chord is listened for, so a test (or a script) can wait for it.
const [ready, setReady] = useState(false);
+ const [verbs, setVerbs] = useState<CliVerb[] | null>(null);
+ const [ctx, setCtx] = useState<CliContext>(NO_CONTEXT);
+ const [form, setForm] = useState<CliVerb | null>(null);
+ const [resume, setResume] = useState<CliRun | null>(null);
+ const [runs, setRuns] = useState<CliRun[]>([]);
const show = useCallback(() => {
setQ("");
setAt(0);
+ setForm(null);
+ setResume(null);
+ setCtx(NO_CONTEXT);
setOpen(true);
}, []);
@@ -139,7 +184,33 @@ export default function JumpPalette() {
};
}, [open, pieces]);
+ // The verbs, and what this page is about, each time it opens (the page may have changed).
+ useEffect(() => {
+ if (!open) return;
+ let live = true;
+ const path = `${window.location.pathname}${window.location.search}`;
+ fetch(`/api/cli?path=${encodeURIComponent(path)}`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
+ .then((j: { verbs: CliVerb[]; context: CliContext }) => {
+ if (!live) return;
+ setVerbs(j.verbs);
+ setCtx(j.context);
+ })
+ .catch(() => live && setVerbs((v) => v ?? []));
+ return () => {
+ live = false;
+ };
+ }, [open]);
+
const items = useMemo(() => {
+ const commandsOnly = q.trimStart().startsWith(">");
+ const cw = words(commandsOnly ? q.trimStart().slice(1) : q);
+ const commands = (verbs ?? [])
+ .map((v) => ({ v, s: cw.length ? commandScore(v, cw) : 1 }))
+ .filter((x) => x.s > 0)
+ .sort((a, b) => b.s - a.s || a.v.verb.localeCompare(b.v.verb))
+ .map(({ v }): Item => ({ id: `cmd:${v.verb}`, section: "Commands", label: v.verb, hint: v.summary, href: "", verb: v.verb }));
+ if (commandsOnly) return commands.slice(0, 80);
const all: Item[] = [
...FIXED,
...(pieces ?? []).map(
@@ -153,7 +224,11 @@ export default function JumpPalette() {
),
];
const w = words(q);
- if (!w.length) return all.filter((it) => it.section !== "Pieces").concat(all.filter((it) => it.section === "Pieces").slice(0, 8));
+ const recent = runs.map(
+ (r): Item => ({ id: `run:${r.id}`, section: "Runs", label: r.verb, hint: `${r.kind === "queued" ? "queued " : ""}${r.id} · ${clock(r.at)}`, href: "", verb: r.verb, run: r }),
+ );
+ if (!w.length) return [...recent, ...all.filter((it) => it.section !== "Pieces"), ...all.filter((it) => it.section === "Pieces").slice(0, 8)];
+ const cmds = commands.slice(0, 12);
const hay = (it: Item) => `${it.label} ${it.hint}`.toLowerCase();
const hits = all.filter((it) => w.every((x) => hay(it).includes(x)));
// A label that starts with what was typed first, then the rest, each in
@@ -162,8 +237,10 @@ export default function JumpPalette() {
return [
...hits.filter((it) => it.label.toLowerCase().startsWith(first)),
...hits.filter((it) => !it.label.toLowerCase().startsWith(first)),
- ].slice(0, 60);
- }, [q, pieces]);
+ ]
+ .slice(0, 60)
+ .concat(cmds);
+ }, [q, pieces, verbs, runs]);
useEffect(() => {
list.current?.querySelector<HTMLElement>(`[data-jump-index="${at}"]`)?.scrollIntoView({ block: "nearest" });
@@ -171,6 +248,14 @@ export default function JumpPalette() {
const go = (it: Item | undefined) => {
if (!it) return;
+ if (it.verb) {
+ const v = verbs?.find((x) => x.verb === it.verb);
+ if (v) {
+ setResume(it.run ?? null);
+ setForm(v);
+ }
+ return;
+ }
setOpen(false);
router.push(it.href);
};
@@ -182,9 +267,30 @@ export default function JumpPalette() {
data-ready={ready ? "" : undefined}
aria-label="Jump to"
onClose={() => setOpen(false)}
- className="ui-dialog mx-auto mb-auto mt-[12vh] w-[min(640px,calc(100vw-32px))] rounded-[3px] border border-seam-2 bg-panel p-0 text-text shadow-2xl"
+ className={cn(
+ "ui-dialog mx-auto mb-auto mt-[12vh] rounded-[3px] border border-seam-2 bg-panel p-0 text-text shadow-2xl",
+ form ? "w-[min(780px,calc(100vw-32px))]" : "w-[min(640px,calc(100vw-32px))]",
+ )}
>
- {open && (
+ {open && form && (
+ <div className="flex h-[76vh] max-h-[76vh] flex-col">
+ <CommandForm
+ key={`${form.verb}|${resume?.id ?? ""}|${ctx.project ?? ""}|${ctx.clip ?? ""}|${ctx.post ?? ""}|${ctx.take ?? ""}`}
+ row={form}
+ ctx={ctx}
+ resume={resume}
+ onStarted={(r) => {
+ setRuns((cur) => [r, ...cur.filter((x) => x.id !== r.id)].slice(0, 8));
+ }}
+ onBack={() => {
+ setForm(null);
+ setResume(null);
+ setTimeout(() => input.current?.focus(), 0);
+ }}
+ />
+ </div>
+ )}
+ {open && !form && (
<div className="flex max-h-[70vh] flex-col">
<div className="flex items-center gap-2 border-b border-seam px-3.5 py-2.5">
<span aria-hidden="true" className="font-mono text-muted-2">
@@ -199,7 +305,7 @@ export default function JumpPalette() {
aria-controls="jump-list"
aria-activedescendant={items[at] ? `jump-${at}` : undefined}
aria-label="Jump to a piece, place, tool or create action"
- placeholder="Jump to a piece, place, tool…"
+ placeholder="Jump to a piece, place, tool… or > a command"
onChange={(e) => {
setQ(e.target.value);
setAt(0);
@@ -239,7 +345,7 @@ export default function JumpPalette() {
i === at && "bg-panel-2 text-text before:absolute before:inset-y-1 before:left-0 before:w-[3px] before:bg-signal before:content-['']",
)}
>
- <span className="min-w-0 truncate">{it.label}</span>
+ <span className={cn("min-w-0 truncate", it.verb && "font-mono text-[12.5px]")}>{it.verb ? `umtool ${it.label}` : it.label}</span>
<span className="ml-auto min-w-0 shrink truncate font-mono text-[11px] text-muted-2">{it.hint}</span>
</div>
</li>
@@ -253,6 +359,9 @@ export default function JumpPalette() {
<span>
<kbd>enter</kbd> open
</span>
+ <span>
+ <kbd>></kbd> commands
+ </span>
{pieces === null && <span>reading pieces…</span>}
{error && <span className="text-reject-text">{error}</span>}
</div>
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -12,6 +12,7 @@ It reads the **same** `lib/projects/*.mjs` the app does, so `umtool ls` and
`/projects` cannot disagree about what a project is, and `umtool check` and the
Inbox cannot disagree about what is wrong with one.
+<!-- verbs:begin (generated by umtool/lib/cli/docs.mjs from lib/cli/verbs.mjs and groups.mjs -- edit those, not this) -->
## Commands
| | |
@@ -19,31 +20,40 @@ Inbox cannot disagree about what is wrong with one.
| `ls [--kind --template --state --open --blocking --q --sort --json]` | the index, as text or JSON |
| `show <project> [--json]` | one project: summary, the cut, per-clip status, decisions |
| `check [<project>] [--json]` | **exit 1 on anything blocking** — including an `out/`, `clips/` or `share-*/` link whose drive is not there (`storage-unreachable`) |
+| `links <project> --embed-ids [--clips a,b] [--dry-run] [--json]` | the **published embed id**: every clip citing a Rumble URL-slug folder the archive does not serve gets `siteVideo` (the folder's `metadata.info.json` id, shareLine.mjs `siteVideoFor`), a citeUrl naming the folder moved with it; no network, one write, one undo point. The Cut tab's Project › Rumble cites ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
+| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) |
+| `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write |
+| `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for |
+| `cast audition <character\|@handle> --voices a,b,… [--project <p>] [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json] [--progress ndjson]` | **AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local) |
+| `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) |
+| `quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status` | **is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) |
+| `check-joins <project> --take <id> [--json] [--all] [--limit <n>]` | do a rendered take's **post joins carry on**: every boundary of its master where the next post item draws a post the one before showed, its planned join, the SSIM across it and the largest frame-to-frame step (read-only, ffmpeg) -- worst first ([report-video.md](report-video.md#thread-scenes-whole-threads-the-join-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)) |
+| `link-policy <project> [--via <site id \| https://…>] [--direct <slug,…>] [--clear] [--fix] [--json]` | the project's **link policy** (`provenance.linkPolicy`): cite via site X, these channels direct. With no flag, prints it and every clip whose QR breaks it; `--fix` rewrites each one that has a fix through the window writer; new clips are written by it. **Exit 1** when a clip still breaks it ([knobs.md](knobs.md#the-link-policy)) |
+| `patch-markers <project> [<file>.patch.json] [--fix] [--json]` | take patches whose deck markers name a clip not in the cut (a take made with one is refused); `--fix` gives each the `after` of the cut's marker of the same label; **exit 1** when one is left ([knobs.md](knobs.md#take-patches-follow-a-removal)) |
| `decisions [--json]` | the inbox |
| `inbox [--all] [--json]` | the decisions grouped and ranked by piece (`a:<site>/<report>`, `p:<project>`): Your call, Review, Blocking, Notes, Open, Ready to finish, Quiet — one card per piece and kind, and how many sit hidden on parked or done pieces (`--all` lists them). Every decision, songs' and articles' included; runs `bin/inbox.ts` through tsx |
+| `schedule list \| show <id> [--json]` | the recurring reports, read-only ([recurring.md](recurring.md)) |
| `folders [--json]` · `kinds [--json]` | the tree, the registry |
+| `link <project> <site>/<report>` · `link <project> --clear` | the manifest names the article it is the video of (settles `link-ambiguous`) |
| `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window |
| `window <project> <clip> --start S --end E --move-stamp first\|nearest\|<s>` · `--clear-stamp` · `--move-mute nearest` · `--clear-mute` | a window edit refused because a stamp's second (`claim.at`, a mark's `at`) or the mute mark would fall outside it, with the fix in the same write: the stamp to the first second that plays, the nearest, or `<s>`, or its `at` cleared; the mute mark to the nearest second, or cleared (never inside a gap). A refused `window` names these flags ([clip-bench.md](clip-bench.md#saving)) |
| `window <project> <clip> --verdict confirmed\|incorrect [--correction T]` · `window <project> <clip> --reject <why> [--note T]` | what the walk said: `--reject` is the walk's **Reject ▾** kept in place (`not-matching`/`wrong-speaker`: incorrect, the note its correction; `irrelevant`/`repeats`/`weak`/`privacy`/`other`: rejected, the note its `rejectNote`); `umtool timeline <p> reject` takes it out ([report-video.md](report-video.md#verdict--what-the-walk-said)) |
| `window <project> <clip> --walk-note T` · `--star` / `--no-star` · `--repeat-of <clip>` | what the walk said that is not a verdict: an editorial note (not a correction) and the ★ favourite, a trailer candidate (`trailer <project> --candidates [--json]` lists them as beats); a deliberate repeat ([knobs.md](knobs.md#a-clip)) |
-| `tighten <project> [--json] [--all] [--no-measure]` · `tighten <project> --apply <clip>[,<clip>…]` | the Cut tab's **Propose tight windows**: each clip to its sentence (the sentences its cut touches, else the whole ones inside its window) and each edge into its pause (the build's measured silences and the gaps between the recording's timed words, ≤ 1 s, inside the cached window) — before → after with the seconds, the clips that would change (`--all`: every clip); prints only. `--apply` writes the named rows through the window writer (the token, the cite that follows the edge); a lock is kept (it is against `resolve-windows`, not a person) ([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)) |
-| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) |
-| `link-policy <project> [--via <site id \| https://…>] [--direct <slug,…>] [--clear] [--fix] [--json]` | the project's **link policy** (`provenance.linkPolicy`): cite via site X, these channels direct. With no flag, prints it and every clip whose QR breaks it; `--fix` rewrites each one that has a fix through the window writer; new clips are written by it. **Exit 1** when a clip still breaks it ([knobs.md](knobs.md#the-link-policy)) |
-| `patch-markers <project> [<file>.patch.json] [--fix] [--json]` | take patches whose deck markers name a clip not in the cut (a take made with one is refused); `--fix` gives each the `after` of the cut's marker of the same label; **exit 1** when one is left ([knobs.md](knobs.md#take-patches-follow-a-removal)) |
-| `quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status` | **is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays)) |
| `window <project> <clip> --align` · `--quote-ruled` / `--no-quote-ruled` | the cut snapped to the quote as HEARD (0.15 s before its first word, 0.3 s after its last, the extent widened to hold it, `lockCut`); a person's ruling on the quote check (a take renders a ruled clip) |
| `window <project> <clip> --take <take> …` | a **take's** clip (walk a take): the same fields, written into the take's patch (`takes/<take>/take.json`) with an undo point first; the project's manifest is untouched ([clip-bench.md](clip-bench.md#walking-a-take)) |
-| `present <project> [--take <take> \| --cut] [--json] [--public] [--open] [--url <origin>]` | **present mode**: the cut as slides, navigated like a deck (`/projects/<p>/present`) — prints the address and every slide (its kind, id — a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>` — date, words and censor counts); `--json` the payload (each post's card as Play draws it and its censor data by kind, each clip's spans, the dividers); `--public` the payload a public page would carry (censored, no reveal data); `--open` opens it; `<address>#<slide id>` opens a slide ([knobs.md](knobs.md#present-mode-the-cut-as-slides-navigated-like-a-deck)) |
| `walk <project> [--take <take>] [--all] [--json]` | the clip bench's **walk**: every clip in walk order with its window, verdict and whether a fetched file holds it, and (→) the ones the walk visits — fetched and needing a verdict; `--all` every fetched one; `--take` walks a take (a draft too); the bench's address to start at. The intro (`render.intro`) is listed first, watched, not judged (`intro`, `stops` in `--json`) |
-| `intro <project> [key=value …] [--off] [--json]` · `intro <project> --take <take> --off\|--on` | **the intro** the cut opens on (`render.intro`): with no key, prints it as written, what the cut opens with (a `title-card`'s words resolved) and each version's on/off; `key=value` writes it through the look writer (`style` `seconds` 3.5–8 `mark` `ground` `sound` (`false` silent) `site` `title` `lines` (`a\|b`, ≤ 3) and the brand's keys; `key=` clears one; a new intro starts as `boot-dark`); `--off` takes it off the cut; `--take <t> --off` that version opens on no intro (its patch's `render.intro: null`), `--on` on the cut's again. **Exit 1** on a value the build refuses ([knobs.md](knobs.md#the-intro-played-and-edited)) |
-| `link <project> <site>/<report>` · `link <project> --clear` | the manifest names the article it is the video of (settles `link-ambiguous`) |
+| `present <project> [--take <take> \| --cut] [--json] [--public] [--open] [--url <origin>]` | **present mode**: the cut as slides, navigated like a deck (`/projects/<p>/present`) — prints the address and every slide (its kind, id — a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>` — date, words and censor counts); `--json` the payload (each post's card as Play draws it and its censor data by kind, each clip's spans, the dividers); `--public` the payload a public page would carry (censored, no reveal data); `--open` opens it; `<address>#<slide id>` opens a slide ([knobs.md](knobs.md#present-mode-the-cut-as-slides-navigated-like-a-deck)) |
| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); `key=` clears one ([knobs.md](knobs.md#marks)) |
+| `intro <project> [key=value …] [--off] [--json]` · `intro <project> --take <take> --off\|--on` | **the intro** the cut opens on (`render.intro`): with no key, prints it as written, what the cut opens with (a `title-card`'s words resolved) and each version's on/off; `key=value` writes it through the look writer (`style` `seconds` 3.5–8 `mark` `ground` `sound` (`false` silent) `site` `title` `lines` (`a\|b`, ≤ 3) and the brand's keys; `key=` clears one; a new intro starts as `boot-dark`); `--off` takes it off the cut; `--take <t> --off` that version opens on no intro (its patch's `render.intro: null`), `--on` on the cut's again. **Exit 1** on a value the build refuses ([knobs.md](knobs.md#the-intro-played-and-edited)) |
| `look <project> key=value … [--unset render.<key>]…` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2** |
| `variants <project> [--take <t>] [--list] [--json]` | **Make variants**: the encode ladder of the build (or of a take's); `--list` what was made and the build's sync report, each clip's lag (past a frame flagged) ([knobs.md](knobs.md)) |
+| `corrections <project>` | what the report got wrong (the clip bench's sixth field) and the walk's coverage, as markdown for the next pass |
| `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain |
| `build <project> --run [--url URL] [--replace] [--preset P] [--only ID] [--skip-fetch]` | **runs** it as the app's build job (POST `/api/report/build` on `--url`, else `UMTOOL_URL`, else `http://localhost:3050`), prints its log as it grows, **Ctrl-C** cancels the job (twice leaves it running); `--replace` stamps a deliverable newer than the manifest aside; exit 1 unless the job is done (release 36) |
+| `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything) |
| `index [--rebuild] [--prune] [--since MS] [--json]` | the cache |
| `new <slug> [--from <report.md>\|<share URL>\|<channel>/<id>] [--site-origin URL] [--seed chapters\|frames [--target S]]` · `new <folder>/<slug> …` · `new <slug> --folder <folder> …` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO\|auto [--segment sN]] [--no-analyze]` | scaffold; `<folder>/<slug>` (or `--folder`) makes it in a folder of the reports tree — its id `<folder>/<slug>`, routed `/projects/<folder>/<slug>` (a spin-off beside its parent); a folder that is itself a project, the reserved `at`, or one past the walk's four levels is refused |
+| `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters |
| `doctor [--json]` | which tools are on this machine and where the roots are; **exit 1** if the report pipeline is missing one, or `UMTOOL_MEDIA_DIR` is set and not there |
| `storage [<project>] [--json]` | where each project's `out/` lives: dir, link, DANGLING, none — and a report's deliverables (`clips/`, `share-*/`) and its switch |
| `storage move-out\|move-back <project>\|--all [--dry-run] [--json]` | `out/` to the media root (a link left behind) and back — copied, mirrored, verified first; run when nothing is building |
@@ -53,11 +63,10 @@ Inbox cannot disagree about what is wrong with one.
| `export <project> --format toc-bbcode\|toc-markdown\|description\|chapters [--variant V] [--first TITLE]` | the posting artifacts, from the build's chapter offsets. A deck with markers: `chapters` are its top-level sections (subsections left out) at the second each section's first segment starts, YouTube's rules kept (0:00 first, each ≥ 10 s, at least three; what was merged is said on stderr); the opening is titled `deck.sectionTitle.first`, or `--first TITLE`, else the first section takes 0:00 |
| `export <project> <clip> [--take T] [--open] [--json]` · `--context N` · `--raw [--from S --to S]` · `--fetch` · `--progress ndjson` | **one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip)) |
| `check-sources [<project>…]` | **prints** the re-check chain; with no args, the never-checked and >30 d projects |
-| `corrections <project>` | what the report got wrong (the clip bench's sixth field) and the walk's coverage, as markdown for the next pass |
-| `chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]` | an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything) |
-| `refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]` · `refresh --check [<article>] [--force]` | the refresh's plan, `--yes` starts it; the daily check now ([refresh.md](refresh.md)) |
-| `schedule list \| show <id> [--json]` | the recurring reports, read-only ([recurring.md](recurring.md)) |
| `notes …` | operator notes: list, read, reply, resolve ([notes.md](notes.md)) |
+| `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) |
+| `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project> [--replace] [--json]` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`; built in: `plain-deck` `huck-deck` `ember-deck` `archive-catalog` `basic`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build (a basic cut's chrome is not checked); `--replace` also clears the manifest's own value of every key the preset sets, after an undo point (`revisions/…-auto-before-preset-replace`), and prints what went ([knobs.md](knobs.md#look-presets)) |
+| `lint <project> [--take <take>] [--variant sourced\|full] [--final] [--json]` | **the manifest lint** (`report-to-video/lint.mjs`, what a build runs before it renders a frame) from umtool: the project's manifest, or with `--take` the take's (its patches applied, written beside the project's manifest for the lint as its render's is, then removed) -- plus the **files its post items name**: a picked read, an attachment or a context post's media not in the project is an ERROR, another kept take a warning. Run it after an import and before queueing the render. `--json`: `{ok, entries, errors, warnings}`. **Exit 0 no error · 1 an error · 2 usage** |
| `take <project> --id <id> --label L [--group G] [--kind similar\|different] [--summary S] [--style NAME] [--patch FILE \| --patch-json JSON \| --set path=value …] [--effect NAME] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then an overlay effect's (`--effect`, release 35), then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes)) |
| `take <project> --id <id> --label L [--patch F \| …] --draft` (`--no-render`) · `take <project> --id <id> [--full \| --at S --dur S]` · `take <project> --id <id> --rebuild [--full \| --at S --dur S]` · `take <project> --id <id> --promote [--anyway] [--json]` | a **draft** take: recorded with nothing rendered, to be walked first; a draft named with no patch flags is rendered from its stored (walked) patch, and `--rebuild` takes a window flag; **make it the cut**: the take's patch applied to the manifest now, one undo point (`revisions/…-auto-before-promote-take`), refused (exit 1) when its timeline would replace a cut that changed since, until `--anyway` ([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut)) |
| `take <project> --id <id> … --uncensored` · build-video `--uncensored` | the **uncensored cut** ([knobs.md](knobs.md#the-slur-filter-slurs-masked-in-what-is-published-off-for-the-uncensored-cut)): the same cut with the post items' slur filter off -- `render.posts.slurs.on: false` in the take's patch (a `--rebuild` keeps it; a censored take is not rebuilt uncensored, **exit 2**: make a take of its own), its label gains "(uncensored)", take.json's `slurs` records `censored` or `uncensored`. The redaction of private words and censored attachments stay on |
@@ -65,8 +74,11 @@ Inbox cannot disagree about what is wrong with one.
| `take <project> --id <id> --preview [--from <take>] [--at S --dur S \| --full] [--priority] [--json]` | the take's **preview**: the take as stored (a draft too, from its walked patch) composed exactly as its render is -- the same 1920×1080 layout, segments, chrome frames and sound -- with only its final picture encoded smaller and faster (`render.preview`: 1280×720, x264 veryfast, crf 26) into `takes/<id>/out/<slug>.preview.mp4`; its build, schedule and record (`render.json`, `render.log`) in `takes/<id>/out/preview/`. The full render (`preview.mp4`, `out/<slug>.mp4`, `out/sourced/`, `take.json`, `render.json`) is never touched. Reuses this take's own full render, and `--from`'s full render and preview ([report-video.md](report-video.md#fast-feedback-preview-and-changes-renders), [knobs.md](knobs.md#fast-feedback-a-preview-and-a-reel-of-the-changes)) |
| `take <project> --id <id> --changes [--from <take>] [--pad 3] [--no-preview] [--priority] [--json]` | the take's **changes reel**: only what changed against `--from` (default: the take's own `from`, or the take a draft was made from) -- each added, re-read, re-picked, re-voiced, trimmed, held, fx'd, … item with a neighbour either side, rendered in one build (`takes/<id>/out/changes/`), cut to the item ± `--pad` s, a label burned in (`21:19 · p-2116831815466193102 · re-voiced`: its time in the FULL cut), joined into `takes/<id>/out/<slug>.changes.mp4`; a removed item shows as the join it leaves. `takes/<id>/changes.json` lists the pieces with their full-cut times and how exact they are (`times.basis`: `measured` -- the base's measured schedule plus the changed items' measured lengths -- or `estimate`). Preview quality unless `--no-preview`. Nothing changed: no reel, and the list says so |
| `take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | **items of another project into a take** (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\|updated\|unchanged\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage** |
-| `lint <project> [--take <take>] [--variant sourced\|full] [--final] [--json]` | **the manifest lint** (`report-to-video/lint.mjs`, what a build runs before it renders a frame) from umtool: the project's manifest, or with `--take` the take's (its patches applied, written beside the project's manifest for the lint as its render's is, then removed) -- plus the **files its post items name**: a picked read, an attachment or a context post's media not in the project is an ERROR, another kept take a warning. Run it after an import and before queueing the render. `--json`: `{ok, entries, errors, warnings}`. **Exit 0 no error · 1 an error · 2 usage** |
| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") |
+| `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render |
+| `queue add [--after <qid>\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>` | a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself |
+| `queue ls [--all] [--json]` · `queue status <qid> [--json]` · `queue wait <qid> [--timeout <s>]` · `queue log <qid> [--tail N]` · `queue cancel <qid>` · `queue retry <qid>` | the queue: `ls` the runner (is the app running it) and the steps not finished or finished in the last 24 h; `status` one step (**exit 0 done · 3 queued or running · 1 failed, blocked or cancelled**); `wait` the same after up to `<s>` seconds (default 90); `log` its FULL log (`logs/<qid>.log`; earlier attempts kept as `<qid>.<n>.log`); `cancel` a queued or blocked step at once, a running one stopped (its process group); `retry` a failed or cancelled step back in the queue with every step blocked behind it. A step that was running when the app died reads **failed** ("the step's process is gone"), its log kept — it is never re-run on its own |
+| `jobs [--json]` | every running and recent **take render** across projects (their records), every queue step not finished or finished in the last 24 h, and the umtool app's own jobs (`GET /api/jobs` at `--url` / `UMTOOL_URL`, when it answers). The page is **/jobs** (the rail's *Running* links it) |
| `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed |
| `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--pin \| --unpin] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway`; `--pin` keeps the pick when newer takes are built (each whole-cut take of the manifest is otherwise its group's pick once built), `--unpin` lets go ([report-video.md](report-video.md#takes-alternative-renders-judged-side-by-side)) |
| `takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]` | **take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): first the working cut's line (`Latest: draft-22 · 28:03 · +N edits since`, and the edits in words; `--json`: `working`), then the takes with latest / picked (pinned) / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) |
@@ -74,6 +86,7 @@ Inbox cannot disagree about what is wrong with one.
| `takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]` | **take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare)) |
| `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels)) |
| `trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok>` · `xfade <s>` · `intro on\|off\|'<render.intro JSON>'` · `outro on\|off\|none\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\|note\|clear` · `title <text>\|none` · `take <t>\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\|remove <s>\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source)) |
+| `tighten <project> [--json] [--all] [--no-measure]` · `tighten <project> --apply <clip>[,<clip>…]` | the Cut tab's **Propose tight windows**: each clip to its sentence (the sentences its cut touches, else the whole ones inside its window) and each edge into its pause (the build's measured silences and the gaps between the recording's timed words, ≤ 1 s, inside the cached window) — before → after with the seconds, the clips that would change (`--all`: every clip); prints only. `--apply` writes the named rows through the window writer (the token, the cite that follows the edge); a lock is kept (it is against `resolve-windows`, not a person) ([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)) |
| `ledger <project> [ls] [--scope S] [--population P] [--json]` · `ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis "…" [--<key> V …] [--row '{…}']` · `ledger <project> set <id> --<key> V … [--unset k,k]` · `ledger <project> rm <id>` | a **measure ledger's rows** (`ledgerSchema.kind "measure"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) |
| `measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]` | the **measure slice** the instruments draw from (`render.chrome.deck.measure`; the flags override it): each row in scope the cut shows at the cut second its figure is said, the hidden rows, and the totals -- the odometer's runs, NET, the goals, the diets, the promises. The take's built `schedule.json` with `--take`, else an estimate; `--json` prints the slice. Reads only ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments)) |
| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
@@ -83,15 +96,23 @@ Inbox cannot disagree about what is wrong with one.
| `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in |
| `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)) |
-| `speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list` | which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices)) |
-| `check-joins <project> --take <id> [--json] [--all] [--limit <n>]` | do a rendered take's **post joins carry on**: every boundary of its master where the next post item draws a post the one before showed, its planned join, the SSIM across it and the largest frame-to-frame step (read-only, ffmpeg) -- worst first ([report-video.md](report-video.md#thread-scenes-whole-threads-the-join-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)) |
| `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) |
+| `refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]` · `refresh --check [<article>] [--force]` | the refresh's plan, `--yes` starts it; the daily check now ([refresh.md](refresh.md)) |
+| `clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]` | **quick clip**: a basic-mode project (`quick-clips/<slug>`, the footage alone), its window asked of the editor (fetch-windows, followed to its end; Rumble fetched whole), `--snap words` its edges snapped to the words heard (the editor's transcribe op), rendered as the take `clip` (`take <p> --id clip --full`: the heavy slot), then the mp4's path and the share line. `--json`: `{project, output, share: {platform, archive, text}, snapped?}`; `--progress ndjson`: events, the last `quick-clip` (the app's `POST /api/report/quick-clip` job). **Exit 0 · 1 failed (the editor, the render) · 2 usage** ([knobs.md](knobs.md#basic-output-the-footage-alone)) |
+| `provenance <project> [ls] [--json]` · `provenance <project> set [--site-origin URL] [--channel-slug S] [--channel "…"] [--json]` | the project's **provenance**: `siteOrigin` (the archive its QRs open), `channelSlug` (a clip with no channel is from it; `check` blocks without it), `channel` (the display name); `""` removes one. One write, one undo point; the Cut tab's Project › Provenance. The link policy is `link-policy` ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
+| `title <project> ["<title>"] [--subtitle "…" \| --no-subtitle] [--json]` | the project's **title and subtitle** (the manifest's `title`/`subtitle`); no words prints them. One write to the draft, one undo point; the Cut tab's Project › Title ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
+| `still <project> <clip> --at <source s> [--take <take>] [--json]` · `still <project> ls [--json]` | a **still at second N**: one frame of the clip's fetched window at that source second into `shots/still-<clip>-<s>s.png` (nothing fetched; the cut not written); `ls` the project's shots. Play's **Still** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
+| `share <project> [<clip>] [--take <t>] [--site <id>] [--json]` | a clip's **share line** (the clip named, else the first): its platform page at the first second it plays and its archive moment, a Rumble folder id as the embed id the archive serves — the twin of **Copy share line** (`GET /api/report/share-line`). `--json`: `{clip, seconds, platform, archive, text}` |
+| `timeline <project> teaser-insert [--at start\|end \| --after <id> \| --before <id>] [--id ID] [--beat S] --line "…" [--break "…"] [--hold S] [--line …] \| --lines-json <json\|@file> [--json]` | a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) |
| `timeline <project> insert (--to-section N \| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` | a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) |
-| `candidates <project> [ls] [--all] [--json]` · `candidates <project> import <sweep.md> [--dry-run] [--json]` · `candidates <project> add <json\|@file> [--json]` | the **candidates inbox** (`<project>/candidates.json`): proposals only — `import` reads a sweep's bullets (`- [verdict] [title @ time](link) (date) "quote" — why`, under their headings; a Top N section marks what it restates; a bullet with no verdict or link is skipped and said), `add` an agent's (`{channel?, video, t, quote?, why?, verdict?, score?, section?}` or `{link, …}`); the same moment again changes nothing it holds. Insert and Not this are the Cut tab's Candidates panel's ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) |
| `timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\|@file\|id…>` | **claim groups** (`groups` beside the timeline; the Cut tab's group bars): runs of clips inside one section making one claim — `ls` by section, each group's id, claim and clips (`--json` with the token); `import` a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`) in ONE write — the cut re-ordered to it, its groups the cut's, the markers following; a file section is the deck section of its name, else the one most of its clips are in; **exit 1** for an id the cut lacks (`--skip-missing`) or a section left with no clip (`--drop-empty` removes its marker); `set` (the clips already together), `label`, `remove` (ungroup), `move` the whole group (before the group at that index, or after one, in its section), `promote` (a level-2 marker at its first clip titled with its claim — the one group edit the render sees; `--label` when the claim is over 24); `order` the named entries in the places they hold (every clip keeping its section). A clip moved out of its group's run leaves it; moved alone into the middle of one, it joins. Every write an undo point (`undo`) ([knobs.md](knobs.md#claim-groups-runs-of-clips-that-make-one-claim)) |
| `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo \| insert <spec> --after <id>\|-]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it. `insert` puts a clip (`<channel>/<video>@<start>-<end>`) into the take only (`takeEdit.mjs insertTakeEntry`) -- the app's **+ Add a clip to <take> only** on the take walk page, and Play's **+ Add a clip here** on a take with its own timeline |
| `timeline <project> sections [--json]` · `section-move <id>… --to-section N [--start]` · `section-add --after <id> [--label L] [--color C]` · `section-boundary <marker> --after <id>` · `section-remove <marker>` · `section-set <marker> [--label L] [--color C]` · `split <id> <second>` · `flash-forward <id> <from>-<to> (--after <id\|-> \| --to-section N [--start]) [--move] [--quote Q] [--id ID]` | **sections as sections** (the deck's markers; the Cut tab's section bars and row menus): clips moved to a section with every marker following, a section opened, a boundary moved, relabelled, removed — no section emptied, no boundary crossed (**exit 1**) — and every take patch in step synced; **split** (each half's quote from the words, the second half's cite and QR at its second, a marker after the clip following its second half); **flash-forward** a tight copy of a span elsewhere with the clip's attribution and locks, as `repeatOf` the clip (`--move`: out of the clip) ([knobs.md](knobs.md#sections-split-and-flash-forward-editing-the-cut)) |
+| `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) |
+| `timeline <project> [--take <t>] add-video <src> [--from S] [--to S] [--fit contain\|cover] [--bass dB] [--gain dB] [--enter cut\|<out>,<in>] [--hold S] [--title T] [--id ID] [--after <id>\|-] [--dry-run] [--json]` · `timeline <project> [--take <t>] set-video <id> <key>=<value>…` | **a video entry** ([report-video.md](report-video.md#a-video-entry)): a file of the project (`src`, relative; probed, its `fileSeconds` written) played FULL FRAME with its own sound, nothing drawn over it, at the end unless `--after` (`-`: the start), into the cut or the take's timeline only (`--take`, an undo point of the take's); `set-video` sets `from= to= fit= audio.bass= audio.gain= enter=cut\|<out>,<in> enter.out= enter.in= holdLast= deck=hidden\|shown title= note= src=` (`key=` clears). `--dry-run`: the entry and its place, nothing written. `--json`: `{ok, op, take?, inserted\|updated {id, at, entry}, revision?}`. **Exit 0 · 1 refused (no such file, take or entry; the build would not take it) · 2 usage** |
+| `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one |
+| `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post-json:<json>\|post-json:@<file> [--id ID]` | **a post item made by hand** — a post no archive holds (one kept only as a picture): `{post: "<channel>/<postId>", author, handle, date, text, media: ["posts-media/…"], parents?, quoted?, subjects?, redact?}`, its media measured, its id `p-<postId>` unless `--id`; refused in the build's words (**exit 1**). Its avatar: `posts avatar <project> <handle> <file>` |
| `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) |
| `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [crop=<px>\|off] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** |
| `posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]` | a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `"thread": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)) |
@@ -104,15 +125,11 @@ Inbox cannot disagree about what is wrong with one.
| `posts reread <project> <item> --pause "<word>[#<n>]=<seconds>\|@<take s>=<seconds>[,…]" [--target post\|parent:0\|quoted\|linked:0] [--dry-run] [--json]` | **pauses put in after words** of a narrated read, no TTS (`lib/report/postPause.mjs`; operator, 5 Nov: a countdown "20 10 4 0" read without a breath): the picked take cut just after each word named (half way into the quiet before the next word, at most 0.1 s past its end) and that much silence (0.05–3 s) put in -- each cut moved to the quietest 10 ms its word allows (40 ms before its timed end up to the next word, ±40 ms when they run together) when that is clearly quieter (~3 dB) than the timing's own, and each side of the silence faded over 10 ms, so a pause in normally paced speech does not click -- everything after moved on -- its words (by index), its parts (one a pause falls in grows), its length -- so word zooms, captions, slams, beeps and the read-follow stay on their words; an effect with a set `at` does not move (the plan counts them). A word is matched as a word zoom's is (case and edge punctuation aside; a phrase pauses after its last word; `#n` its n-th time in the read; `--target` counts only the words of the parts reading that piece). A derived take (`steps: [{op: "pause", pauses: [{word, w, at, seconds}]}]`) picked in ONE write. **Absolute**, like a tempo: on a take whose last step is a pause it re-cuts from the take before (the pauses it had kept, a word named again takes the new seconds, `=0` takes one away). `--in-take <t>` puts it in a take's read. No word timings (**exit 1**, naming `posts narrate <p> <item> --words`), a word not read, an occurrence not there, nothing to change: **exit 1**; a malformed spec, seconds outside 0.05–3, `--pause` with another reread form: **exit 2** |
| `posts reread <project> <item> --revoice "<phrase>[#<n>]" --say "<what to say instead>" [--target <piece>] [--voice <v>\|auto] [--xfade 0.03] [--splice <from>-<to>] [--dry-run] [--json]` | **one phrase of an approved read re-voiced**, the rest untouched (`lib/report/postRevoice.mjs`; operator, 5 Nov: the countdown gabbled, and pauses cut into it "choppy"): the phrase found in the picked take's word timings as `--pause` finds a word (`#n`, `--target`; inside one part), the original cut from just before its first word to just after its last -- each cut at the quietest 10 ms within ±40 ms of the boundary, and when that is still speech within ±0.15 s (never inside the phrase as timed; a nearer quiet preferred) -- **`--say` alone synthesized by the editor's TTS** (narrate-via-editor; the engine of the root take, the voice of the part the phrase is in, `--voice` overrides; the project's lexicon, redaction and slur filter applied; kept in `narration/parts-cache/` like a thread read's parts, so asking again is free), its lead and tail of silence trimmed, loudness-matched to the speech in the 2 s either side (±6 dB) and spliced in with equal-power crossfades (`--xfade`, 0–0.2 s) at both joins, at the take's rate and layout. The length is exact: the take − the span cut + the piece. Everything after moves by the difference (its words, the part holding the span, the later parts) so zooms, captions, slams, beeps and the read-follow stay on their words; the new words are timed from the piece's speech and marked `estimated` (a later `posts narrate … --words` refines them); the part's text and the script say `--say`. A derived take (`steps: [{op: "revoice", revoice: {word, count, words, phrase, say, said, voice, engine, from, to, seconds, gain, xfade, key}}]`) picked in ONE write; re-voicing exactly the words a re-voice put in re-cuts from the take before. `--dry-run`: the span (words, seconds), each cut and its level, what is said and in which voice, the length change when the piece is cached -- no TTS. A cut still in speech is warned of (the word timings off there): `--splice 65.03-66.00` sets the cuts (either side may be left out). `--in-take <t>` puts it in a take's read. No word timings (naming `posts narrate <p> <item> --words`), the phrase not read or across two parts, a recorded read, the TTS failing: **exit 1**; no `--say`, a bad voice, crossfade or splice, `--revoice` with another reread form: **exit 2** |
| `posts progress <project> [auto\|on\|off\|default] [--json]` | the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it |
-| `timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]` | **the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said) |
| `posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]` | a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**) |
| `posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script "…"] [--pick <n>] [--approve\|--unapprove] [--off\|--on] [lead= tail= ramp= linger= clip=read\|full wet= lowpass= duck=on\|off short=hold\|loop attach=under\|after lufs= pace=fast\|normal]` · `<item> --take [--note "…"] [--voice v] [--engine e] [--speed s] [--script "…"]` · `<item> --derive <n> --op enhance\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…` | a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; "not installed" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said "at <handle>", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans. |
| `posts narrate <project> <item> --take --thread [--parents 0\|all\|none\|<n>] [--skip-parent <id\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--note "…"] [--force] [--no-hold] [--dry-run] [--json]` | a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the project's voice map, `posts voices`; his own: the narrator's), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2** |
| `posts say <project> [ls] [--item <id>]` · `add <word\|phrase> "<spoken>" [--case] [--item <id>] [--note "…"]` · `remove <word\|n> [--item <id>]` · `try "<text>" [--item <id>]` · `stale` `[--json]` | **THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2** |
| `posts voices <project> [ls] \| set <handle\|*> <voice> \| remove <handle\|*> [--json]` | **THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2** |
-| `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write |
-| `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for |
-| `cast audition <character\|@handle> --voices a,b,… [--project <p>] [--text "…" \| --item <id> \| --line <n> \| --stock] [--no-score \| --score-only] [--json] [--progress ndjson]` | **AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local) |
| `posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label l]` | **a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked |
| `posts fx <project> <item> add caption --match "…" --text "…" [--target post\|quoted\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\|above\|side]` · `add clock [--rewind auto\|on\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]` | a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**) |
| `posts clock <project> [on\|off\|default] [--zone <IANA zone>] [--json]` | the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times |
@@ -127,23 +144,226 @@ Inbox cannot disagree about what is wrong with one.
| `posts repeats <project> [--match id\|file\|audio] [--json]` | the **combo counter**'s repeats ([report-video.md](report-video.md#the-combo-counter)): every attachment the cut's post items play more than once -- the same X media id (the capture's url), else the same file (the capture's sha256 when its bytes agree, else hashed; cached by path, size and mtime), else (`--match audio`) the same sound (fpcalc, else a coarse ffmpeg hash) -- its posts in the cut's ORDER with their dates, the tier that matched and the badge each draws (`×2` from the second use, `(×n)` counted but not drawn); a post whose CAPTURE holds the same file but whose entry carries no attachment is listed too, `NOT ATTACHED`, with the `posts attach` that brings it in. Reads only |
| `posts attach <project> [<item> … \| --all] [--dry-run] [--json]` | a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words |
| `posts combo <project> [on=on\|off] [label=L] [position=top-right\|top-left\|bottom-right\|bottom-left\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\|hit\|coin] [minCount=2-20] [match=id\|file\|audio] [--json]` · `posts combo <project> <item> off\|on\|auto\|label=…\|position=…\|color=…\|scale=…\|sfx=… [--json]` | the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**) |
-| `new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]` | a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: "original"`), then `posts reel` with the same filters |
-| `timeline <project> [--take <t>] add-video <src> [--from S] [--to S] [--fit contain\|cover] [--bass dB] [--gain dB] [--enter cut\|<out>,<in>] [--hold S] [--title T] [--id ID] [--after <id>\|-] [--dry-run] [--json]` · `timeline <project> [--take <t>] set-video <id> <key>=<value>…` | **a video entry** ([report-video.md](report-video.md#a-video-entry)): a file of the project (`src`, relative; probed, its `fileSeconds` written) played FULL FRAME with its own sound, nothing drawn over it, at the end unless `--after` (`-`: the start), into the cut or the take's timeline only (`--take`, an undo point of the take's); `set-video` sets `from= to= fit= audio.bass= audio.gain= enter=cut\|<out>,<in> enter.out= enter.in= holdLast= deck=hidden\|shown title= note= src=` (`key=` clears). `--dry-run`: the entry and its place, nothing written. `--json`: `{ok, op, take?, inserted\|updated {id, at, entry}, revision?}`. **Exit 0 · 1 refused (no such file, take or entry; the build would not take it) · 2 usage** |
-| `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post:<channel>/<postId> [--id ID]` | **one post item** among the cut's entries, made as `posts reel` makes one |
-| `timeline <project> insert (--after <id\|-> \| --to-section N \| --group G) post-json:<json>\|post-json:@<file> [--id ID]` | **a post item made by hand** — a post no archive holds (one kept only as a picture): `{post: "<channel>/<postId>", author, handle, date, text, media: ["posts-media/…"], parents?, quoted?, subjects?, redact?}`, its media measured, its id `p-<postId>` unless `--id`; refused in the build's words (**exit 1**). Its avatar: `posts avatar <project> <handle> <file>` |
-| `modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]` | the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets)) |
-| `preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\|none> <project> [--replace] [--json]` | the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`; built in: `plain-deck` `huck-deck` `ember-deck` `archive-catalog` `basic`): a render block a manifest stands on (`"preset": "<name>"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build (a basic cut's chrome is not checked); `--replace` also clears the manifest's own value of every key the preset sets, after an undo point (`revisions/…-auto-before-preset-replace`), and prints what went ([knobs.md](knobs.md#look-presets)) |
-| `clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]` | **quick clip**: a basic-mode project (`quick-clips/<slug>`, the footage alone), its window asked of the editor (fetch-windows, followed to its end; Rumble fetched whole), `--snap words` its edges snapped to the words heard (the editor's transcribe op), rendered as the take `clip` (`take <p> --id clip --full`: the heavy slot), then the mp4's path and the share line. `--json`: `{project, output, share: {platform, archive, text}, snapped?}`; `--progress ndjson`: events, the last `quick-clip` (the app's `POST /api/report/quick-clip` job). **Exit 0 · 1 failed (the editor, the render) · 2 usage** ([knobs.md](knobs.md#basic-output-the-footage-alone)) |
-| `share <project> [<clip>] [--take <t>] [--site <id>] [--json]` | a clip's **share line** (the clip named, else the first): its platform page at the first second it plays and its archive moment, a Rumble folder id as the embed id the archive serves — the twin of **Copy share line** (`GET /api/report/share-line`). `--json`: `{clip, seconds, platform, archive, text}` |
-| `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render |
-| `queue add [--after <qid>\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>` | a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself |
-| `queue ls [--all] [--json]` · `queue status <qid> [--json]` · `queue wait <qid> [--timeout <s>]` · `queue log <qid> [--tail N]` · `queue cancel <qid>` · `queue retry <qid>` | the queue: `ls` the runner (is the app running it) and the steps not finished or finished in the last 24 h; `status` one step (**exit 0 done · 3 queued or running · 1 failed, blocked or cancelled**); `wait` the same after up to `<s>` seconds (default 90); `log` its FULL log (`logs/<qid>.log`; earlier attempts kept as `<qid>.<n>.log`); `cancel` a queued or blocked step at once, a running one stopped (its process group); `retry` a failed or cancelled step back in the queue with every step blocked behind it. A step that was running when the app died reads **failed** ("the step's process is gone"), its log kept — it is never re-run on its own |
-| `jobs [--json]` | every running and recent **take render** across projects (their records), every queue step not finished or finished in the last 24 h, and the umtool app's own jobs (`GET /api/jobs` at `--url` / `UMTOOL_URL`, when it answers). The page is **/jobs** (the rail's *Running* links it) |
-| `title <project> ["<title>"] [--subtitle "…" \| --no-subtitle] [--json]` | the project's **title and subtitle** (the manifest's `title`/`subtitle`); no words prints them. One write to the draft, one undo point; the Cut tab's Project › Title ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
-| `provenance <project> [ls] [--json]` · `provenance <project> set [--site-origin URL] [--channel-slug S] [--channel "…"] [--json]` | the project's **provenance**: `siteOrigin` (the archive its QRs open), `channelSlug` (a clip with no channel is from it; `check` blocks without it), `channel` (the display name); `""` removes one. One write, one undo point; the Cut tab's Project › Provenance. The link policy is `link-policy` |
-| `timeline <project> teaser-insert [--at start\|end \| --after <id> \| --before <id>] [--id ID] [--beat S] --line "…" [--break "…"] [--hold S] [--line …] \| --lines-json <json\|@file> [--json]` | a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** |
-| `links <project> --embed-ids [--clips a,b] [--dry-run] [--json]` | the **published embed id**: every clip citing a Rumble URL-slug folder the archive does not serve gets `siteVideo` (the folder's `metadata.info.json` id, shareLine.mjs `siteVideoFor`), a citeUrl naming the folder moved with it; no network, one write. The Cut tab's Project › Rumble cites |
-| `still <project> <clip> --at <source s> [--take <take>] [--json]` · `still <project> ls [--json]` | a **still at second N**: one frame of the clip's fetched window at that source second into `shots/still-<clip>-<s>s.png` (nothing fetched; the cut not written); `ls` the project's shots. Play's **Still** |
+| `candidates <project> [ls] [--all] [--json]` · `candidates <project> import <sweep.md> [--dry-run] [--json]` · `candidates <project> add <json\|@file> [--json]` | the **candidates inbox** (`<project>/candidates.json`): proposals only — `import` reads a sweep's bullets (`- [verdict] [title @ time](link) (date) "quote" — why`, under their headings; a Top N section marks what it restates; a bullet with no verdict or link is skipped and said), `add` an agent's (`{channel?, video, t, quote?, why?, verdict?, score?, section?}` or `{link, …}`); the same moment again changes nothing it holds. Insert and Not this are the Cut tab's Candidates panel's ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) |
+| `ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json]` | **one recording's life cycle**, the twin of `/ingredients/<channel>/<video>` ([knobs.md](knobs.md#an-ingredients-life-cycle-the-rail)): nine stages — found, downloaded, transcribed, clock, windows, used in, checked, rendered, published — each **✓**, a count, **!** or **—**, and its line, then every project clip that cuts from it (the draft and each saved version, from the usage index `<REPORTS_ROOT>/.umtool/usage-index.json`). A Rumble recording answers to its folder slug or its embed id; both are printed. `--window`: one clip window, the stages after it narrowed to the clips it plays. `--used-in`: the clips alone. `--json`: the page's object. Read-only over the corpus. **Exit 0 · 1 failed · 2 usage** |
+
+### Every verb
+
+Every verb `umtool` dispatches, a sub-verb its own row (`umtool/lib/cli/verbs.mjs`, the registry the ⌘K palette's
+**Commands** are built from). **form**: the palette offers it as a form (its arguments below, the page's project
+and selection filled in; **Copy as CLI**; Run is `POST /api/cli`, which runs only these). **queued**: Run adds it to
+the durable queue (it renders, or holds the heavy slot). Otherwise why it has none. *draft*: it writes the working
+draft (the project's manifest); *project*: a project's other files, or reads; *corpus*: no one project.
+
+| Verb | What it does | ⌘K |
+|---|---|---|
+| `ls [--kind KIND] [--template TEMPLATE] [--state STATE] [--open] [--blocking] [--q Q] [--sort recent\|name]` | every project, as text | form · *corpus* |
+| `show <project>` | one project: summary, the cut, per-clip status, decisions | form · *project* |
+| `check [<project>] [--all-severities]` | what blocks a build (exit 1 on anything blocking) | form · *project* |
+| `links <project> [--fix] [--embed-ids] [--clips CLIPS] [--dry-run]` | do the clip QRs open on their sites (out/links.json) | form · *project* |
+| `provenance <project> ls` | the project's provenance: site origin, channel slug, channel, link policy | form · *project* |
+| `provenance <project> set [--site-origin SITE-ORIGIN] [--channel-slug CHANNEL-SLUG] [--channel CHANNEL]` | the project's site origin, channel slug and channel name ("" removes one) | form · *draft* |
+| `title <project> [<title>] [--subtitle SUBTITLE] [--no-subtitle]` | the project's title and subtitle (no words: print them) | form · *draft* |
+| `still <project> <clip> --at N [--take TAKE]` | one frame of a clip's fetched window at a source second, into shots/ | form · *project* |
+| `still <project> ls` | the pictures in the project's shots/ | form · *project* |
+| `cast ls` | the characters' voices across projects | form · *corpus* |
+| `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--narrator]` | a character: name, stock voice, handles | form · *corpus* |
+| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--narrator] [--no-narrator]` | change a character | form · *corpus* |
+| `cast rm <id>` | a character out of the cast (an undo point) | form · *corpus* |
+| `cast undo` | the cast as it was before its last write | form · *corpus* |
+| `cast project <project>` | the project's characters, their voices and drift | form · *project* |
+| `cast audition <character> --voices VOICES [--project PROJECT] [--text TEXT] [--item ITEM] [--line N] [--stock] [--no-score] [--score-only]` | one line read by 2-6 candidate voices, scored against the real voice | form · queued · *project* |
+| `cast use <project> <character> <voice> [--everywhere]` | the voice a character reads in, here or everywhere | form · *draft* |
+| `cast reread <project> <character> [--dry-run]` | the items that say a character in another voice, read again | form · queued · *project* |
+| `speaker-check <project> [--clip CLIP…] [--list] [--set SET] [--remove REMOVE]` | which named voice each clip is (speaker-check.json) | form · queued · *project* |
+| `quote-check <project> [--clips CLIPS] [--pad N] [--status]` | is each clip's quote in the seconds it plays | form · queued · *project* |
+| `check-joins <project> --take TAKE [--all] [--limit N]` | do a rendered take's post joins carry on | form · queued · *project* |
+| `link-policy <project> [--via VIA] [--direct DIRECT] [--clear] [--fix]` | cite via site X, these channels direct | form · *draft* |
+| `patch-markers <project> [<file>] [--fix]` | take patches whose deck markers name a clip not in the cut | form · *draft* |
+| `decisions` | every decision waiting, by project | form · *corpus* |
+| `inbox [--all]` | the decisions grouped and ranked as the Inbox shows them | form · *corpus* |
+| `schedule list` | the recurring reports | form · *corpus* |
+| `schedule show <id>` | one recurring report: chip, editions, tick log | form · *corpus* |
+| `folders` | the reports tree's folders | form · *corpus* |
+| `kinds` | the project kinds the registry knows | form · *corpus* |
+| `link <project> [<article>] [--clear]` | the manifest names the article it is the video of | form · *draft* |
+| `window <project> <clip> [--start N] [--end N] [--lock] [--lock-end] [--no-lock-end] [--cut-start N] [--cut-end N] [--lock-cut] [--align] [--title TITLE] [--date DATE] [--cite N] [--cite-url CITE-URL] [--quote QUOTE] [--repeat-of REPEAT-OF] [--verdict confirmed\|incorrect] [--correction CORRECTION] [--reject not-matching\|wrong-speaker\|irrelevant\|repeats\|weak\|privacy\|other] [--note NOTE] [--walk-note WALK-NOTE] [--star] [--no-star] [--quote-ruled] [--no-quote-ruled] [--move-stamp MOVE-STAMP] [--clear-stamp] [--move-mute nearest] [--clear-mute] [--gap GAP…] [--gap-remove N] [--gaps GAPS] [--take TAKE]` | a clip's window, cut, attribution and verdict | form · *draft* |
+| `walk <project> [--take TAKE] [--all]` | the clip bench's walk: clips in walk order, verdicts, fetched | form · *project* |
+| `present <project> [--take TAKE] [--cut] [--public]` | present mode's address and slides | form · *project* |
+| `set <project> <clip> key=value… [--mark MARK] [--take TAKE]` | a clip's knobs: claim, marks, audio, blur, fx … | form · *draft* |
+| `intro <project> [key=value…] [--off] [--take TAKE] [--on]` | the intro the cut opens on (render.intro) | form · *draft* |
+| `look <project> key=value… [--unset UNSET…]` | the cut's knobs: mode, deck, fact-check stamps, variants … | form · *draft* |
+| `migrate <project> [--dry-run]` | the manifest's settings into the video modules' homes | form · *draft* |
+| `variants <project> [--take TAKE] [--list]` | make the encode ladder of a build | form · queued · *project* |
+| `corrections <project>` | what the report got wrong, as markdown | form · *project* |
+| `build <project> [--preset preview\|fast\|final] [--only ONLY] [--dry]` | the build's chain, printed (the Cut tab's Build runs it) | form · *project* |
+| `chain <article> <n> [--from FROM] [--dry] [--final] [--site-origin SITE-ORIGIN] [--draft-all] [--model MODEL] [--deck]` | an article iteration's pipeline to a video | form · queued · *corpus* |
+| `index [--rebuild] [--prune] [--since N]` | the project index (the cache) | form · *corpus* |
+| `new <slug> [--folder FOLDER] [--from FROM] [--site-origin SITE-ORIGIN] [--seed chapters\|frames\|phrase\|reactions] [--target N] [--phrase PHRASE] [--channels CHANNELS] [--prefer PREFER] [--exclude EXCLUDE] [--max N] [--from-posts FROM-POSTS] [--brand BRAND]` | a new project (scaffold) | form · *corpus* |
+| `doctor` | the tools and the roots on this machine | form · *corpus* |
+| `storage status [<project>]` | where each project's out/ lives | form · *corpus* |
+| `storage move-out` | out/ to the media root, a link left | none: moves a project's out/ between drives: a terminal's, run when nothing builds (the page cannot see a hand-run writer) |
+| `storage move-back` | out/ back into the project | none: moves a project's out/ between drives: a terminal's, run when nothing builds |
+| `storage deliverables` | clips/ and share-*/ to the media root and back | none: moves deliverables between drives, then the switch: a terminal's, run when nothing builds |
+| `snapshot <project> [--label LABEL]` | copy the manifest into revisions/ | form · *project* |
+| `diff <project> <snapshot>` | what changed since a snapshot | form · *project* |
+| `export <project> [<clip>] [--format toc-bbcode\|toc-markdown\|description\|chapters] [--variant VARIANT] [--first FIRST] [--context N] [--raw] [--from N] [--to N] [--fetch] [--take TAKE]` | the posting artifacts, or one clip clean into exports/ | form · queued · *project* |
+| `check-sources [<projects>…]` | the re-check chain, printed | form · *corpus* |
+| `notes [<target>] [--all] [--resolved] [--all-status]` | the operator's notes, as markdown | form · *corpus* |
+| `notes reply <id> <text> [--resolve]` | answer a note | form · *corpus* |
+| `notes resolve <id>` | a note resolved | form · *corpus* |
+| `notes wontfix <id>` | a note closed as won't fix | form · *corpus* |
+| `notes reopen <id>` | a note open again | form · *corpus* |
+| `notes source <target> [--draft DRAFT] [--generator GENERATOR] [--how HOW]` | the source a target's notes name (the draft to edit) | form · *corpus* |
+| `modules list` | the video modules | form · *corpus* |
+| `modules apply <project> [--config CONFIG] [--dry-run] [--take TAKE] [--label LABEL] [--at N] [--dur N] [--full] [--quick] [--force] [--from FROM]` | a module-config.json onto the cut, or as a take's patch | form · queued · *draft* |
+| `preset list` | the look presets | form · *corpus* |
+| `preset show <name>` | one look preset | form · *corpus* |
+| `preset save <name> --from FROM [--description DESCRIPTION] [--force]` | a project's look as a preset | form · *corpus* |
+| `preset apply <name> <project> [--replace]` | a preset under the cut (none: off it) | form · *draft* |
+| `take <project> --id ID [--label LABEL] [--group GROUP] [--kind similar\|different] [--summary SUMMARY] [--style STYLE] [--patch PATCH] [--patch-json JSON] [--set SET…] [--effect EFFECT] [--at N] [--dur N] [--full] [--quick] [--force] [--from FROM] [--keep-frames] [--priority] [--uncensored] [--draft] [--rebuild] [--preview] [--changes] [--pad N] [--no-preview] [--promote] [--anyway] [--import-item IMPORT-ITEM…] [--after AFTER] [--before BEFORE] [--as AS] [--dry-run]` | one take: rendered, drafted, previewed or promoted | form · queued · *project* |
+| `lint <project> [--take TAKE] [--variant sourced\|full] [--final]` | the manifest lint a build runs first | form · *project* |
+| `take status <project> [--id ID] [--log] [--tail N]` | a take's render record | form · *project* |
+| `queue add` | a step of the durable queue: a umtool command's argv | none: takes a raw argv -- a page never sends one (app/api/queue/route.ts); a form's Run on a heavy verb queues the step itself |
+| `queue ls [--all]` | the queue's steps and its runner | form · *corpus* |
+| `queue status <qid>` | one step: state, exit code, error, log | form · *corpus* |
+| `queue wait` | wait for a step to finish | none: blocks a terminal until a step ends: a form's Run follows its own step |
+| `queue log <qid> [--tail N]` | a step's full log | form · *corpus* |
+| `queue cancel <qid>` | a step cancelled (a running one stopped) | form · *corpus* |
+| `queue retry <qid>` | a failed or cancelled step back in the queue | form · *corpus* |
+| `jobs` | every running and recent render, step and app job | form · *corpus* |
+| `takes make <project> [--recipe RECIPE] [--only ONLY] [--force] [--all-styles] [--group GROUP] [--at N] [--dur N] [--full] [--quick] [--priority]` | a recipe's takes, or one per montage style | form · queued · *project* |
+| `takes styles` | the montage styles | form · *corpus* |
+| `takes pick <project> <take> [--anyway] [--pin] [--unpin]` | use this take: its manifest over the project's | form · *project* |
+| `takes effects <project>` | the overlay effects this cut offers | form · *project* |
+| `takes ls <project>` | the working cut, then each take | form · *project* |
+| `takes relabel <project> <take> <label>` | a take's label | form · *project* |
+| `takes supersede <project> <take> [--by BY] [--clear]` | a take folded away in the list (or back) | form · *project* |
+| `takes save <project> [--label LABEL] [--force]` | the working draft frozen as the next version (v<N>) | form · *project* |
+| `takes open <project> <take>` | a saved version into the draft (the draft saved first) | form · *draft* |
+| `takes freeze <project> [<takes>…] [--all] [--apply]` | legacy takes given a frozen base (a dry run unless --apply) | form · *project* |
+| `takes delete` | a take's directory, whole | none: deletes a take's directory whole, past undo: the Takes panel's Delete asks first; a terminal's --dry-run shows what goes |
+| `takes cancel <project> <take>` | stop a take's render | form · *project* |
+| `takes fork <project> <take> [--name NAME]` | the take as a variant project beside this one | form · *project* |
+| `takes compare <project> <a> <b>` | two takes side by side | form · *project* |
+| `render-mode on [--for FOR] [--note NOTE]` | render mode: a render gets the machine, for a window | form · *corpus* |
+| `render-mode off [--force]` | render mode off | form · *corpus* |
+| `render-mode status` | is render mode on, for what, until when | form · *corpus* |
+| `pool stats [--since SINCE]` | the render pool: what it holds | form · *corpus* |
+| `pool prune [--max-gb N] [--dry-run]` | the render pool pruned to its cap | form · *corpus* |
+| `pool verify [--sample N] [--all]` | the render pool's files checked | form · queued · *corpus* |
+| `trailer <project> [--take TAKE] [--reel REEL] [--beats BEATS] [--beats-json JSON] [--intro] [--finale N] [--xfade N] [--no-snap] [--out OUT] [--dry-run] [--candidates] [--vertical] [--layout reframe]` | a trailer or beat reel cut from a take's master | form · queued · *project* |
+| `vertical <project> --take TAKE [--reel REEL] [--beats BEATS] [--items ITEMS] [--clip full\|framed\|quote] [--post card\|stack\|media] [--side split\|overlay] [--hook HOOK] [--captions l\|xl] [--lines 1\|2] [--loudness N] [--max N] [--name NAME] [--reframe] [--dry-run] [--intro] [--no-intro] [--no-outro]` | a vertical short (1080x1920) of a take's items | form · queued · *project* |
+| `trailer-beats <project> ls [--reel REEL]` | a reel's beats against its limit | form · *project* |
+| `trailer-beats <project> add <clip> [<span>] [--at N] [--label LABEL] [--take TAKE] [--reel REEL]` | a clip beat | form · *project* |
+| `trailer-beats <project> add-raw <at> <dur> [--at N] [--label LABEL] [--reel REEL]` | a beat of master seconds | form · *project* |
+| `trailer-beats <project> set <n> <span> [--label LABEL] [--reel REEL]` | beat n's source seconds | form · *project* |
+| `trailer-beats <project> gap <n> add\|remove\|clear [<value>] [--reel REEL]` | seconds cut out of beat n's middle | form · *project* |
+| `trailer-beats <project> remove <n> [--reel REEL]` | a beat out | form · *project* |
+| `trailer-beats <project> move <n> --to N [--reel REEL]` | a beat to another place | form · *project* |
+| `trailer-beats <project> order [--reel REEL]` | the beats in the cut's order | form · *project* |
+| `trailer-beats <project> limit <limit> [--reel REEL]` | the running length's limit | form · *project* |
+| `trailer-beats <project> xfade <seconds> [--reel REEL]` | the crossfade's seconds | form · *project* |
+| `trailer-beats <project> intro <value> [--reel REEL]` | the reel's intro | form · *project* |
+| `trailer-beats <project> outro <value> [--reel REEL]` | the card the reel ends on | form · *project* |
+| `trailer-beats <project> candidates [--add] [--reel REEL]` | the walk's ★ clips not yet beats | form · *project* |
+| `trailer-beats <project> verdict <n> confirmed\|note\|clear [--reel REEL]` | the walk's word on beat n | form · *project* |
+| `trailer-beats <project> title <text> [--reel REEL]` | the reel's name | form · *project* |
+| `trailer-beats <project> take <take> [--reel REEL]` | the take the reel is cut from | form · *project* |
+| `trailer-beats <project> undo [--reel REEL]` | the reel as it was before its last write | form · *project* |
+| `trailer-beats <project> status [--take TAKE] [--reel REEL]` | each beat against the take the reel plays now | form · *project* |
+| `trailer-beats <project> anchor [<beats>…] --take TAKE [--reel REEL]` | beats anchored to a take's master | form · *project* |
+| `trailer-beats <project> clamp <n> [--take TAKE] [--reel REEL]` | a clipped beat pulled inside its clip | form · *project* |
+| `trailer-beats <project> repoint <n> <clip> [--take TAKE] [--reel REEL]` | an orphan beat's seconds on another clip | form · *project* |
+| `trailer-beats <project> history [--reel REEL]` | every write to the reel | form · *project* |
+| `trailer-beats <project> reels [--reel REEL]` | the project's reels | form · *project* |
+| `trailer-beats <project> new-reel <name> [--from FROM] [--title TITLE] [--reel REEL]` | a new reel, empty or a copy | form · *project* |
+| `tighten <project> [--all] [--no-measure] [--apply APPLY]` | each clip to its sentence, each edge into its pause | form · *draft* |
+| `ledger <project> ls [--scope SCOPE] [--population POPULATION]` | a measure ledger's rows | form · *project* |
+| `ledger <project> add <id> [--key value…] [--date DATE] [--scope SCOPE] [--population POPULATION] [--value VALUE] [--scopeBasis SCOPEBASIS] [--row JSON]` | a ledger row, checked against its schema | form · *draft* |
+| `ledger <project> set <id> --key value… [--unset UNSET]` | a ledger row's keys | form · *draft* |
+| `ledger <project> rm <id>` | a ledger row removed (refused while something names it) | form · *draft* |
+| `measure <project> [--take TAKE] [--scopes SCOPES] [--scale SCALE] [--as-of AS-OF]` | the measure slice the instruments draw from | form · *project* |
+| `rulings <project> show` | each montage clip and its ruling | form · *project* |
+| `rulings <project> import [--dry-run]` | the earlier rulings in the seed's edits.json | form · *draft* |
+| `rulings <project> set <clip> keep\|cut\|not-him\|read-aloud [--reason REASON] [--match MATCH]` | a montage clip's ruling | form · *draft* |
+| `rulings <project> clear <clip>` | a montage clip's ruling cleared | form · *draft* |
+| `fetch <project> [--dry-run] [--wait] [--status] [--body] [--reason REASON] [--refetch REFETCH] [--refetch-video REFETCH-VIDEO] [--take TAKE]` | the clip windows, asked of the editor | form · *project* |
+| `prep <project> [--clips CLIPS] [--wait] [--status] [--take TAKE]` | the bench's excerpts and waveforms, before the walk | form · queued · *project* |
+| `prune [<project>] [--all] [--take TAKE] [--anyway] [--keep N] [--older-than OLDER-THAN] [--idle-work IDLE-WORK] [--versions] [--idle IDLE] [--grace GRACE] [--yes]` | takes' work files freed by policy (a dry run unless --yes) | form · *project* |
+| `fallback <project> [--dry-run] [--clip CLIP…] [--restore RESTORE]` | stand-ins for refused montage windows | form · *draft* |
+| `phrases <phrases>… --channels CHANNELS [--prefer PREFER] [--exclude EXCLUDE] [--words] [--regex] [--samples N] [--no-cache] [--full]` | how often each phrase was said, by year | form · *corpus* |
+| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video REFERENCE-VIDEO…] [--reference-channel REFERENCE-CHANNEL…] [--instances INSTANCES] [--span phrase\|cut] [--pad N] [--likely N] [--unlikely N] [--dry]` | a speaker-similarity score per montage clip | form · queued · *project* |
+| `clips analyze <project> [--from FROM] [--rescan] [--no-laughs] [--no-voices] [--target N] [--laugh-min N] [--merge-gap N] [--setup-max N] [--clip-max N] [--words WORDS] [--keep-cut] [--scope SCOPE] [--segment SEGMENT]` | the clip finder's scans on a long recording, then proposals | form · queued · *draft* |
+| `clips propose <project> [--from FROM] [--host N] [--target N] [--laugh-min N] [--merge-gap N] [--setup-max N] [--clip-max N] [--words WORDS] [--keep-cut] [--dry]` | the clip finder's proposals again, from what is there | form · *draft* |
+| `clips show <project>` | the speakers, the laughs, what is in the cut | form · *project* |
+| `clips segments <project>` | the narrated-video spans auto-scope finds | form · *project* |
+| `refresh [<article>] [--iteration N] [--no-fetch] [--yes] [--check] [--force]` | re-fetch an article's scope: the plan, and --yes starts it | form · *corpus* |
+| `clip <spec> [--snap words] [--title TITLE] [--site SITE] [--folder FOLDER]` | quick clip: one moment to a basic-mode mp4 and its share line | form · queued · *corpus* |
+| `share <project> [<clip>] [--take TAKE] [--site SITE]` | a clip's share line | form · *project* |
+| `timeline <project> ls [--take TAKE]` | the cut: index, id, type, video, start–end | form · *project* |
+| `timeline <project> insert <spec> [--after AFTER] [--to-section N] [--group GROUP] [--id ID] [--section N] [--lock] [--lock-end] [--title TITLE] [--stream-title STREAM-TITLE] [--date DATE] [--quote QUOTE] [--cite N] [--cite-url CITE-URL] [--take TAKE]` | a clip (or a post item) into the cut | form · *draft* |
+| `timeline <project> move <id> --to N [--take TAKE]` | an entry to an index | form · *draft* |
+| `timeline <project> place <ids>… --before BEFORE [--section N]` | entries before another (Play's drag) | form · *draft* |
+| `timeline <project> remove <id> [--at N] [--take TAKE]` | an entry out of the cut | form · *draft* |
+| `timeline <project> duplicate <id> [--at N]` | an entry twice | form · *draft* |
+| `timeline <project> reject <id> not-matching\|wrong-speaker\|irrelevant\|repeats\|weak\|privacy\|other [--note NOTE]` | an entry rejected and removed, on the record | form · *draft* |
+| `timeline <project> wrong-speaker <id> [--correction CORRECTION]` | an entry removed: the wrong speaker | form · *draft* |
+| `timeline <project> post <post>` | a post added, or the one with its id replaced | form · *draft* |
+| `timeline <project> post-remove <id>` | a post out of the cut | form · *draft* |
+| `timeline <project> teaser <id> <patch>` | a teaser's lines, beat, dip, tail | form · *draft* |
+| `timeline <project> teaser-insert [--at end\|start] [--after AFTER] [--before BEFORE] [--id ID] [--beat N] [--line LINE…] [--lines-json JSON]` | a teaser or closing card inserted (default at the end) | form · *draft* |
+| `timeline <project> undo [--take TAKE]` | the newest automatic snapshot back | form · *draft* |
+| `timeline <project> sections` | the deck's sections and their clips | form · *project* |
+| `timeline <project> section-move <ids>… --to-section N [--start]` | clips to the end (or start) of section N | form · *draft* |
+| `timeline <project> section-add --after AFTER [--label LABEL] [--color COLOR] [--level 1\|2]` | a new section after a clip | form · *draft* |
+| `timeline <project> section-boundary <marker> --after AFTER` | a section boundary dragged | form · *draft* |
+| `timeline <project> section-remove <marker>` | a section's marker removed | form · *draft* |
+| `timeline <project> section-set <marker> [--label LABEL] [--color COLOR] [--level 1\|2]` | a section's label, colour or level | form · *draft* |
+| `timeline <project> split <id> <second>` | a clip in two at a source second | form · *draft* |
+| `timeline <project> flash-forward <id> <span> [--after AFTER] [--to-section N] [--start] [--move] [--quote QUOTE] [--id ID]` | a tight copy of a span elsewhere, as a repeat | form · *draft* |
+| `timeline <project> order <order>…` | the cut's order in one write | form · *draft* |
+| `timeline <project> threads [--write] [--conversation CONVERSATION]` | the cut's conversations (and --write gathers them) | form · *draft* |
+| `timeline <project> groups` | the claim groups, by section | form · *project* |
+| `timeline <project> groups import <file> [--skip-missing] [--drop-empty]` | a claim-groups file in one write | form · *draft* |
+| `timeline <project> groups set <gid> <ids>… [--claim CLAIM]` | a group is these clips | form · *draft* |
+| `timeline <project> groups label <gid> <claim>` | a group's claim | form · *draft* |
+| `timeline <project> groups remove <gid>` | a group dissolved (its clips stay) | form · *draft* |
+| `timeline <project> groups move <gid> --to TO` | a whole group to another place | form · *draft* |
+| `timeline <project> groups promote <gid> [--label LABEL]` | a group opens a subsection | form · *draft* |
+| `timeline <project> add-video <src> [--from N] [--to N] [--fit contain\|cover] [--bass N] [--gain N] [--enter ENTER] [--hold N] [--title TITLE] [--id ID] [--after AFTER] [--dry-run] [--take TAKE]` | a video entry: a project file full frame | form · *draft* |
+| `timeline <project> set-video <id> key=value… [--take TAKE]` | a video entry's knobs | form · *draft* |
+| `scenes <project> <clip> [--black-min N] [--threshold N] [--pix-th N] [--pad N] [--from N] [--to N]` | scene cuts and black spans in a clip's fetched window | form · *project* |
+| `posts add <project> <post> [--attach ATTACH] [--flag FLAG] [--author AUTHOR] [--id ID] [--thread] [--crop N] [--dry-run]` | a post card from the posts archive | form · *draft* |
+| `posts set <project> <post> key=value…` | the Posts table's writer: thread, hide, attach, crop | form · *draft* |
+| `posts reel <project> --channel CHANNEL… [--since SINCE] [--until UNTIL] [--own] [--with-media] [--replies include\|only\|exclude] [--order chrono\|reverse] [--limit N] [--after AFTER] [--dry-run]` | post items from posts channels, in one write | form · *draft* |
+| `posts set-item <project> <item> key=value… [--in-take IN-TAKE]` | a post item's knobs | form · *draft* |
+| `posts narrate <project> [<item>] [key=value…] [--script SCRIPT] [--take] [--note NOTE] [--voice VOICE] [--engine ENGINE] [--speed N] [--pick N] [--approve] [--unapprove] [--off] [--on] [--thread] [--parents PARENTS] [--words] [--import] [--list] [--all] [--draft-scripts] [--limit N] [--force] [--recording RECORDING] [--as AS] [--dry-run] [--in-take IN-TAKE]` | a post item's narration: script, takes, pick, approve, mix | form · queued · *draft* |
+| `posts say <project> ls\|add\|remove\|try\|stale [<word>] [<spoken>] [--case] [--item ITEM] [--note NOTE]` | the pronunciation lexicon | form · *draft* |
+| `posts voices <project> ls\|set\|remove [<handle>] [<voice>]` | the voice map a thread read uses | form · *draft* |
+| `posts fit <project> [<items>…] [--all] [--linger N] [--dry-run]` | narrated posts' videos cut to their best part | form · queued · *draft* |
+| `posts fx <project> <item> ls\|add\|set\|remove [<what>] [--key value…] [--in-take IN-TAKE]` | a post item's word zooms, captions, clock, slams | form · *draft* |
+| `posts clock <project> [on\|off\|default] [--zone ZONE]` | the cut's clock default | form · *draft* |
+| `posts progress <project> [auto\|on\|off\|default]` | the cut's progress bar default | form · *draft* |
+| `posts avatar <project> [<handle>] [<image>]` | an author's picture on the cards | form · *draft* |
+| `posts avatars <project> [--dry-run]` | the authors' pictures from the archive | form · *draft* |
+| `posts redact <project> ls\|add\|remove [<value>] [--substring] [--note NOTE]` | words blanked from what is published | form · *draft* |
+| `posts slurs <project> ls\|on\|off\|level\|visual\|voice\|add\|except\|remove\|edges [<value>] [--off]` | the slur filter | form · *draft* |
+| `posts context <project> [--dry-run]` | each post item's context from its capture | form · *draft* |
+| `posts repeats <project> [--match id\|file\|audio]` | the attachments played more than once | form · *project* |
+| `posts combo <project> [<item>] [key=value…]` | the combo badge's knobs (the cut's, or one item's) | form · *draft* |
+| `posts attach <project> [<items>…] [--all] [--dry-run]` | a capture's media onto post items that carry none | form · *draft* |
+| `posts scenes <project> [on\|off]` | the media scenes (and the cut's on/off) | form · *draft* |
+| `posts picture-reply <project> [key=value…] [--in-take IN-TAKE]` | the cut's picture-only rule | form · *draft* |
+| `posts roles <project> [<items>…] [--write] [--set SET] [--in-take IN-TAKE]` | a read's pieces, stored or inferred | form · *draft* |
+| `posts reread <project> <item> [--without WITHOUT] [--drop-parts DROP-PARTS] [--drop-urls] [--tempo-for TEMPO-FOR] [--tempo N] [--parts PARTS] [--stretch atempo\|rubberband] [--yell-caps] [--yell-gain N] [--yell-style raise\|shout\|loud] [--pause PAUSE] [--target TARGET] [--revoice REVOICE] [--say SAY] [--voice VOICE] [--xfade N] [--splice SPLICE] [--dry-run] [--in-take IN-TAKE]` | a read re-joined, re-timed, paused or a phrase re-voiced | form · queued · *draft* |
+| `posts yell <project> [<items>…] [--all] [--yell-gain N] [--yell-style raise\|shout\|loud] [--dry-run]` | the caps he wrote, yelled in the read | form · queued · *draft* |
+| `candidates <project> ls [--all]` | the proposed clips waiting on the Candidates panel | form · *project* |
+| `candidates <project> import <file> [--dry-run]` | a sweep's bullets as candidates | form · *project* |
+| `candidates <project> add <proposal>` | an agent's proposal(s) as candidates | form · *project* |
+| `ingredient <recording> [--window WINDOW] [--used-in]` | one recording's (or clip window's) life cycle: found to published | form · *corpus* |
+| `help` | every command | none: prints the command list: the palette's Commands are the same list |
+<!-- verbs:end -->
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
@@ -377,6 +377,40 @@ The Rumble mapping is ONE helper (`lib/report/shareLine.mjs` `siteVideoFor`, ove
`citeUrl` that was the dead link moves with it); and `umtool timeline insert <rumble-channel>/<folder>@…`, which
writes the inserted clip with its `siteVideo`. A clip that pins `siteVideo` is never looked up.
+## An ingredient's life cycle (the rail)
+
+`/ingredients/<channel>/<video>` is one recording of the corpus across its whole life: nine stages across the top,
+each a pill — **✓** (done), **a count**, **!** (needs you) or **—** (nothing yet) — and the selected stage's panel
+below. `?window=<from>-<to>` (a clip window's own name) focuses one window: it is lit, and the stages after it
+(Used in, Checked, Rendered, Published) narrow to the clips it plays. A Rumble recording answers to its folder slug
+or its embed id, and the head shows both. Every stage reads files that already exist, read-only over the corpus
+(`lib/ingredients/stages.mjs`: `metadata.info.json` and `transcript.cues.json` by their ends, never whole):
+
+| Stage | Read from | Its action | From a terminal | Route |
+|---|---|---|---|---|
+| Found | `find-clips.json`; research sessions' marks; research cases' `candidates.jsonl` | Find in Research; the case's candidates | `umtool ingredient <ch>/<id>` | — |
+| Downloaded | the metadata's head, `metadata.history.json`, `download-outcome.json`, `availability.json`, `saved-video.json`, `media-import.json`, the media files and their links | **Persist source video** (Rumble: the whole recording) | `pnpm ops persist-videos --json '{"items":[{"slug":…,"id":…}]}'` | `POST /api/ops/persist-videos` (editor) |
+| Transcribed | the cues' head and tail (source, reach), the `.vtt` files, `transcript-pin.json`, `transcribe-outcome.json`, `words.json` | **Transcribe** (the GPU) | `pnpm ops transcribe-one --json '{"slug":…,"id":…}'` | `POST /api/ops/transcribe-one` (editor) |
+| Clock | `clock.json` (`describeClock`) | — | `umtool ingredient <ch>/<id>` | — |
+| Windows | `clips/<from>-<to>.*` and their sidecars, cross-checked against the usage index: a draft clip no window holds, a window asked for a clip no project uses | **Fetch** the clips no window holds (the project's own fetch body, narrowed to them); **Evict** one window | `umtool fetch <p>` · `pnpm ops evict-clips --json '{"slug":…,"id":…,"windows":["<from>-<to>"]}'` | `POST /api/ops/fetch-windows` · `POST /api/ops/evict-clips` (editor) |
+| Used in | the usage index: every project clip that cuts from it, in the draft and in each saved version | each clip opens its bench | `umtool ingredient <ch>/<id> --used-in [--json]` | — |
+| Checked | each project's `quote-check.json` rows for those clips (a row the cut has moved past reads stale) | **Check quotes** (the GPU) | `umtool quote-check <p> --clips a,b` | `POST /api/ingredients/action` (a umtool job) |
+| Rendered | each version's `render.json` (else its preview), `out/segments/<clip>.cut.json` | play the version at that clip | `umtool take status <p> --id <v>` | — |
+| Published | each project's `out/links.json` rows for those clips, the archive moment | **Check links**; **Fix dead links** | `umtool links <p> [--fix]` | `POST /api/report/links {project, fix?}` |
+
+Every action ASKS first: `POST /api/ingredients/action {action, ch, id, step: "plan", project?, clips?, window?}`
+answers what it will do, what it costs (network, the GPU, a deleted cache file) and the queue it lands on — the
+editor's own dry run for fetch-windows and persist-videos — and nothing starts until **Start** posts the plan's
+`start` (`step: "start"`). The editor decides the queue, the pacing and a whole-recording download.
+
+THE USAGE INDEX (`lib/ingredients/usedIn.mjs`) is `<REPORTS_ROOT>/.umtool/usage-index.json` (`UMTOOL_USAGE_INDEX_FILE`
+moves it): every report-video project's `video.manifest.json` (the draft) and each take's frozen form
+(`takes/<id>/base.manifest.json`, a saved version, or a legacy rendered take's `takes/<id>/video.manifest.json`),
+rebuilt incrementally by each manifest's mtime and size; a project deleted drops out. A clip citing a Rumble embed id
+and one citing the folder slug are one ingredient, keyed by the folder (`resolveVideoDirId`, its answer kept in the
+index). The way in: the clip bench's head (**Life cycle**), Play's row for the clip on screen (**Life cycle**), and the
+editor's video page (**Open in umtool**).
+
## Sections, split and flash-forward (editing the cut)
Under the deck a cut's **sections are its markers** (`render.chrome.deck.markers`): §0 runs to the first marker's
@@ -1705,6 +1739,46 @@ The files: `<out>/<slug>.<name>.mp4` and `<out>/variants.json`; `<out>` is the p
`preview.mp4`); a take with only its `preview.mp4` is encoded from that (`--source`). A flagged clip is fixed with its `audio.offset` (the sign: a clip whose sound is early, a
negative lag, needs a positive offset), then a build.
+## ⌘K commands (every verb a form)
+
+The other way round: every `umtool` verb the registry (`umtool/lib/cli/verbs.mjs`) marks `ui: "form"` is a form in
+the ⌘K palette, so a verb with no button of its own still has a UI path.
+
+| What | In umtool | From a terminal | Over HTTP |
+|---|---|---|---|
+| the verbs | ⌘K, type (`>` first: commands only); each row `umtool <verb>` and what it does | `umtool help`; [cli.md](cli.md), "Every verb" | `GET /api/cli` (`verbs`) |
+| one verb's form | choose it: its arguments, the page's project (and the clip, post or take its address names) filled in | the line under the form, **Copy as CLI** | — |
+| run it | **Run** (a verb that renders: **Queue it**, the durable queue): its state and live log under the form | that line | `POST /api/cli {verb, values}` from the app's own page only; `GET /api/cli?job=<id>` / `?qid=<qid>` |
+
+The server builds the argv from the row's schema (`lib/cli/argv.mjs`, the same function the Copy as CLI line comes
+from) and refuses a verb with no form (`ui: "none"`, its reason in cli.md), a value its schema refuses, a page of
+another site, and a body carrying a raw argv -- `app/api/queue/route.ts` still never adds a step from a page. A new
+verb gets its row there (`verbs.test.mjs` fails, naming it, until it has one) and its help lines in
+`lib/cli/groups.mjs`; `node umtool/lib/cli/docs.mjs` rewrites cli.md's generated section.
+
+What a form may name, and what it asks first:
+
+- **Files.** An output (`trailer --out`, a take's `--id`, a reel, `--name`) is a bare name, never a directory or
+ `..`; the CLI writes it where it writes its own. An input file (`take --patch`, `trailer --beats`, `modules apply
+ --config`, `candidates import`, `timeline groups import`, `posts narrate --recording`, …) is a file of the
+ project, relative to its directory: the server runs it only when its realpath (symlinks followed) is inside the
+ project's, as that absolute path (`lib/cli/confine.mjs`). `@file`, and a key=value whose value is `@…`, `/…`,
+ `~/…` or climbs out with `..`, are a terminal's; `new --from` takes a share URL or `<channel>/<id>`, never a
+ report.md. `vertical --out` and `voice-match --out` (any path) are terminal-only.
+- **No undo.** A verb that deletes, evicts or kills (`prune --yes`, `pool prune`, `index --prune`, `takes freeze
+ --apply`, `takes make --force`, `take --force`, `queue cancel`, `takes cancel`, `render-mode off --force`, `notes
+ resolve`/`wontfix`, `notes reply --resolve`, `ledger rm`, `fetch --refetch`, `refresh --yes`, `speaker-check
+ --remove`, `preset save --force`) asks a second press, **Yes, <what it does>**; `POST /api/cli` wants
+ `confirm: true` and answers 409 without it.
+- **This machine only.** A write from a page (`POST /api/cli`, and the draft's **Save version** / **Open in
+ draft**: `lib/report/sameOrigin.mjs`) is refused when its Host, its X-Forwarded-Host or its Origin is not this
+ machine -- `localhost`, `*.localhost`, `127.x`, `::1` -- so a page whose DNS name is re-pointed at 127.0.0.1 (DNS
+ rebinding) cannot drive it. `UMTOOL_ALLOWED_HOSTS=name,name` (host names, no ports) adds the names a proxy in front
+ of umtool serves it as. `POST /api/cli` also refuses a request with no Origin and no `Sec-Fetch-Site` (a terminal
+ runs the command itself).
+- **Runs.** What a form started stays under **Runs** in the palette (nothing typed) for the page's life: an Escape
+ mid-run loses nothing. The same queued command sent twice within 5 s is the one step.
+
## Reading them back
`umtool show <p>` prints a **knobs** block — each clip's claim knobs, audio and blur (which clip stamps), the stamp's
diff --git a/umtool/e2e/fixtures/editor-stub-fetch-windows.mjs b/umtool/e2e/fixtures/editor-stub-fetch-windows.mjs
@@ -23,7 +23,8 @@ import path from "node:path";
// spec's cache lookup finds — specs must stay order-independent. And the
// article chain's `windows` step relies on that 404 to stop (article-iterations.spec).
// basicyt: the quick-clip job's recording (basic-mode-fixture.mjs), a channel of its own for the same reason.
-export const FETCH_WINDOWS_CHANNELS = new Set(["opsrumble", "opsyt", "basicyt"]);
+// railchan: the ingredient rail's recording (ingredient-rail-fixture.mjs), which no other spec reads.
+export const FETCH_WINDOWS_CHANNELS = new Set(["opsrumble", "opsyt", "basicyt", "railchan"]);
const fwJobs = new Map();
let next = 1;
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -1313,7 +1313,9 @@ const server = http.createServer((req, res) => {
// THE CASE PIPELINE'S GAP BUTTONS (release 38 lane A, case-pipeline.spec.ts): the editor's own actions,
// recorded and answered as queued -- download-missing, transcribe-bucket, persist-videos (its dryRun answers
// the buckets) and channel-priority's focus.
- if (req.method === "POST" && ["/api/ops/download-missing", "/api/ops/transcribe-bucket", "/api/ops/persist-videos", "/api/ops/channel-priority"].includes(url.pathname)) {
+ // The ingredient rail's (lane L5, ingredient-rail.spec.ts): transcribe-one and a targeted evict-clips, recorded and
+ // answered as queued the same way -- nothing is transcribed and no window is deleted.
+ if (req.method === "POST" && ["/api/ops/download-missing", "/api/ops/transcribe-bucket", "/api/ops/persist-videos", "/api/ops/channel-priority", "/api/ops/transcribe-one", "/api/ops/evict-clips"].includes(url.pathname)) {
let raw = "";
req.on("data", (c) => (raw += c));
req.on("end", () => {
diff --git a/umtool/e2e/fixtures/ingredient-rail-fixture.mjs b/umtool/e2e/fixtures/ingredient-rail-fixture.mjs
@@ -0,0 +1,83 @@
+// What ingredient-rail.spec.ts reads (lane L5, the ingredient life-cycle rail): one recording of the
+// fixture corpus used by TWO projects, and a Rumble recording cited by its embed id.
+//
+// channels/railchan/ a YouTube channel of its own (fetch-windows serves it: editor-stub-fetch-windows.mjs)
+// data/railvid/ metadata.info.json (its webpage_url past a 64 KB formats array: the head reader never sees it),
+// transcript.cues.json (300 s, 50 cues), transcript.en.vtt, download-outcome.json, availability.json,
+// metadata.history.json, find-clips.json (the clip finder found it: rail-a),
+// clips/10.00-40.00.mp4 (+ sidecar: asked for rail-a's ra1), clips/200.00-230.00.mp4 (+ sidecar:
+// asked for a clip no project has now -- the orphan)
+// channels/railrumble/ platform rumble: data/v7rslug1/ is the URL slug, its metadata's id the
+// embed id v7rembd1, which rail-r cites
+//
+// reports/rail-a ra1 railvid 12-20 (quote; ok in quote-check.json), ra2 railvid 100-110 (quote; no window holds it)
+// takes/v1: a saved version (base.manifest.json) holding ra1, rendered (render.json done, preview.mp4)
+// reports/rail-b rb1 railvid 15-25, its QR link checked ok (out/links.json)
+// reports/rail-r rr1 railrumble/v7rembd1 30-40
+//
+// The site the QRs link is http://127.0.0.1:9 (cut-integrity-fixture's placeholder): a link check there is
+// refused at once, on this machine. The spec WRITES (a link check rewrites rail-b's out/links.json; a quote
+// check may write rail-a's quote-check.json): these projects are its own.
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const RAIL_SITE = "http://127.0.0.1:9";
+
+const write = (dir, name, doc) => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n");
+};
+
+/** @param {{ reports: string, channels: string, manifest: Function, cachedWindow: string }} o */
+export function makeIngredientRailFixture({ reports, channels, manifest, cachedWindow }) {
+ // ── the corpus ──
+ const ch = path.join(channels, "railchan");
+ write(ch, "config.json", { platform: "youtube" });
+ const v = path.join(ch, "data", "railvid");
+ const formats = Array.from({ length: 1500 }, (_, i) => ({ format_id: String(i), url: `https://media.example/${"x".repeat(40)}/${i}` }));
+ write(v, "metadata.info.json", JSON.stringify({ id: "railvid", title: "The Rail Recording", formats, webpage_url: "https://www.youtube.com/watch?v=railvid", duration: 300 }));
+ const cues = Array.from({ length: 50 }, (_, i) => ({ start: i * 6, end: i * 6 + 5.5, text: `the rail recording says line ${i}.` }));
+ write(v, "transcript.cues.json", JSON.stringify({ version: 2, source: "vtt", vttFile: "transcript.en.vtt", transcriptFormat: "vtt", id: "railvid", channelSlug: "railchan", title: "The Rail Recording", uploadDate: "20261101", duration: 300, platform: "youtube", cues }));
+ write(v, "transcript.en.vtt", "WEBVTT\n\n00:00:00.000 --> 00:00:05.500\nthe rail recording says line 0.\n");
+ write(v, "download-outcome.json", { videoId: "railvid", webpageUrl: "https://www.youtube.com/watch?v=railvid", status: "ok", startedAt: "2026-11-01T10:00:00.000Z", finishedAt: "2026-11-01T10:00:20.000Z", attempts: [{ n: 0, kind: "primary" }] });
+ write(v, "availability.json", { checkedAt: "2026-11-02T00:00:00.000Z", availability: "public", history: [] });
+ write(v, "metadata.history.json", { entries: [{ at: "2026-11-03T00:00:00.000Z", by: "refresh", from: { sha256: "a", bytes: 1 }, to: { sha256: "b", bytes: 2 }, changed: {}, added: {}, removed: {}, counters: {}, volatile: [] }] });
+ write(v, "find-clips.json", { version: 1, at: "2026-11-04T00:00:00.000Z", jobId: "job-1", project: "reports/rail-a", url: "/projects/reports/rail-a/clip-editor", created: true, segments: [{ id: "s1", from: 0, to: 120 }], steps: [] });
+ mkdirSync(path.join(v, "clips"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(v, "clips", "10.00-40.00.mp4"));
+ write(path.join(v, "clips"), "10.00-40.00.json", { requestedBy: "umtool:reports/rail-a", clipId: "ra1", reason: "The Rail A Fixture", fetchedAt: "2026-11-05T00:00:00.000Z", bytes: 1 });
+ copyFileSync(cachedWindow, path.join(v, "clips", "200.00-230.00.mp4"));
+ write(path.join(v, "clips"), "200.00-230.00.json", { requestedBy: "umtool:reports/gone", clipId: "gone1", fetchedAt: "2026-11-05T00:00:00.000Z" });
+
+ const rch = path.join(channels, "railrumble");
+ write(rch, "config.json", { platform: "rumble" });
+ const rv = path.join(rch, "data", "v7rslug1");
+ write(rv, "metadata.info.json", JSON.stringify({ id: "v7rembd1", title: "The Rumble Rail Recording", webpage_url: "https://rumble.com/v7rslug1-the-rumble-rail-recording.html" }));
+ write(rv, "transcript.cues.json", JSON.stringify({ version: 2, source: "whisper", id: "v7rembd1", title: "The Rumble Rail Recording", duration: 120, cues: [{ start: 0, end: 4, text: "rumble." }] }));
+
+ // ── the projects ──
+ const origin = { siteOrigin: RAIL_SITE, channelSlug: "railchan" };
+ const a = manifest("rail-a", "The Rail A Fixture", origin, [
+ { type: "clip", id: "ra1", video: "railvid", start: 12, end: 20, cite: 12, section: 0, quote: "the rail recording says line 2." },
+ { type: "clip", id: "ra2", video: "railvid", start: 100, end: 110, cite: 100, section: 0, quote: "the rail recording says line 17." },
+ ]);
+ const aDir = path.join(reports, "rail-a");
+ write(aDir, "video.manifest.json", a);
+ const base = manifest("rail-a", "The Rail A Fixture", origin, [a.timeline[0]]);
+ const take = path.join(aDir, "takes", "v1");
+ write(take, "base.manifest.json", base);
+ write(take, "take.json", { id: "v1", group: "takes", order: 1, label: "Version 1", kind: "different", preview: "preview.mp4", window: "full", style: null, patch: null, version: true, draft: true, seconds: 8, builtAt: "2026-11-06T00:00:00.000Z" });
+ copyFileSync(cachedWindow, path.join(take, "preview.mp4"));
+ write(take, "render.json", { version: 1, state: "done", project: "reports/rail-a", take: "v1", mp4: "preview.mp4", seconds: 8, startedAt: "2026-11-06T00:00:00.000Z", endedAt: "2026-11-06T00:01:00.000Z", exitCode: 0, stage: "done", percent: 100 });
+ write(aDir, "quote-check.json", { version: 1, checkedAt: "2026-11-06T12:00:00.000Z", clips: { ra1: { status: "ok", offset: 0.02, against: "cues", cut: { from: 12, to: 20 }, quote: "the rail recording says line 2." } } });
+
+ const bDir = path.join(reports, "rail-b");
+ write(bDir, "video.manifest.json", manifest("rail-b", "The Rail B Fixture", origin, [{ type: "clip", id: "rb1", video: "railvid", start: 15, end: 25, cite: 15, section: 0 }]));
+ write(path.join(bDir, "out"), "links.json", { version: 1, checkedAt: "2026-11-07T00:00:00.000Z", fetched: 1, origins: {}, links: [{ clip: "rb1", url: `${RAIL_SITE}/?v=railchan%2Frailvid&t=15`, state: "ok", origin: RAIL_SITE }] });
+
+ const rDir = path.join(reports, "rail-r");
+ write(rDir, "video.manifest.json", manifest("rail-r", "The Rail Rumble Fixture", { siteOrigin: RAIL_SITE, channelSlug: "railrumble" }, [{ type: "clip", id: "rr1", video: "v7rembd1", start: 30, end: 40, cite: 30, section: 0 }]));
+ return { aDir, bDir, rDir };
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -68,6 +68,7 @@ import { makeMediaScenesFixture } from "./media-scenes-fixture.mjs";
import { makeInstrumentsFixture } from "./instruments-fixture.mjs";
import { makeIntroPlayFixture } from "./intro-play-fixture.mjs";
import { makeInspectorFixtures } from "./inspector-fixture.mjs";
+import { makeIngredientRailFixture } from "./ingredient-rail-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song"));
@@ -2090,6 +2091,10 @@ writeFileSync(ptFile, JSON.stringify(pt, null, 2) + "\n");
// sound of its own, and a whole-cut version v1 the spec switches the intro off and on in. WRITABLE, its own.
makeIntroPlayFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), makePlayCutFixture });
+// THE INGREDIENT RAIL (ingredient-rail.spec.ts, lane L5): one recording (railchan/railvid) used by two projects,
+// its windows, a saved version, a quote check and a link check; a Rumble recording cited by its embed id. WRITABLE, its own.
+makeIngredientRailFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
+
// The measure's instruments (instruments.spec.ts): the Play cut with the dial, the odometer and
// the trail on, and a built schedule carrying a measure slice (instruments-fixture.mjs).
await makeInstrumentsFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), makePlayCutFixture });
diff --git a/umtool/e2e/ingredient-rail.spec.ts b/umtool/e2e/ingredient-rail.spec.ts
@@ -0,0 +1,224 @@
+import { test, expect, type Page } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// THE INGREDIENT LIFE-CYCLE RAIL (umtool redesign, lane L5; operator, 9 Nov 2026: "the stage rail could be good
+// for viewing a downloaded clip or other video ingredient to see its entire life cycle"): /ingredients/<ch>/<id>
+// shows one recording across nine stages -- found, downloaded, transcribed, clock, windows, used in, checked,
+// rendered, published -- each a pill (✓, a count, ! or —) and a panel, and each stage's action says what it
+// costs and where it lands before it posts to the editor's (stubbed) or umtool's own route.
+//
+// Fixture: e2e/fixtures/ingredient-rail-fixture.mjs -- railchan/railvid used by reports/rail-a (ra1, ra2; a saved
+// version v1 holding ra1, rendered) and reports/rail-b (rb1); railrumble/v7rslug1 (embed id v7rembd1) cited by
+// reports/rail-r. WRITES (rail-b's links.json, maybe rail-a's quote-check.json): its own.
+//
+// INGREDIENT_SHOTS (a directory): the page's screenshots at 1366×768 go there too.
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial" });
+
+const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song");
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const SHOTS = process.env.INGREDIENT_SHOTS ?? null;
+const RAIL = urls.ingredientHref("railchan", "railvid");
+
+type StubRequest = { route?: string; slug?: string; id?: string; items?: { slug: string; id: string; clipId?: string }[]; dryRun?: boolean; windows?: string[] };
+const stubLog = (): StubRequest[] => {
+ try {
+ return JSON.parse(readFileSync(STUB_LOG, "utf8")) as StubRequest[];
+ } catch {
+ return [];
+ }
+};
+const railAsks = (route: string) =>
+ stubLog().filter((r) => r.route === route && (r.slug === "railchan" || (r.items ?? []).some((i) => i.slug === "railchan")));
+
+const shot = async (page: Page, name: string) => {
+ await page.screenshot({ path: test.info().outputPath(name) });
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, name) });
+};
+
+const pill = (page: Page, key: string) => page.locator(`[data-ingredient-rail] [data-stage="${key}"]`);
+const openStage = async (page: Page, key: string) => {
+ await pill(page, key).click();
+ await expect(page.locator(`[data-stage-panel="${key}"]`)).toBeVisible();
+};
+
+/** Ask, read the confirmation (cost, queue), Start, and wait for the answer. */
+async function runAction(page: Page, id: string, { cost, queue }: { cost: string; queue?: RegExp }) {
+ await page.locator(`[data-action-ask="${id}"]`).click();
+ const confirm = page.locator(`[data-action-confirm="${id}"]`);
+ await expect(confirm).toBeVisible({ timeout: 20_000 });
+ await expect(confirm).toHaveAttribute("data-action-cost", cost);
+ if (queue) await expect(confirm.locator("[data-action-queue]")).toHaveText(queue);
+ await confirm.locator(`[data-action-start="${id}"]`).click();
+ await expect(page.locator(`[data-action-result="${id}"]`)).toBeVisible({ timeout: 30_000 });
+ await expect(page.locator(`[data-action-error="${id}"]`)).toHaveCount(0);
+}
+
+test.beforeEach(async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 768 });
+});
+
+test("all nine pills render: ✓, a count, ! or — from the files that exist, and the page fits 1366×768", async ({ page }) => {
+ await page.goto(RAIL);
+ await expect(page.locator("[data-ingredient]")).toHaveAttribute("data-ingredient", "railchan/railvid");
+ const rail = page.locator("[data-ingredient-rail] [data-stage]");
+ await expect(rail).toHaveCount(9);
+ await expect(rail).toHaveText([/Found/, /Downloaded/, /Transcribed/, /Clock/, /Windows/, /Used in/, /Checked/, /Rendered/, /Published/]);
+ const want: Record<string, [string, string]> = {
+ found: ["count", "1"],
+ downloaded: ["ok", "✓"],
+ transcribed: ["ok", "✓"],
+ clock: ["none", "—"],
+ windows: ["warn", "!"],
+ used: ["count", "3"],
+ checked: ["count", "1"],
+ rendered: ["count", "1"],
+ published: ["count", "1"],
+ };
+ for (const [key, [kind, text]] of Object.entries(want)) {
+ await expect(pill(page, key), key).toHaveAttribute("data-pill", kind);
+ await expect(pill(page, key), key).toHaveAttribute("data-pill-text", text);
+ }
+ // The first stage that warns is the one open: two windows, one clip no window holds.
+ await expect(page.locator('[data-stage-panel="windows"]')).toBeVisible();
+ await expect(page.locator("[data-stage-line]")).toHaveText("2 windows, 1 clip not fetched");
+ await expect(page.locator('[data-window="200.00-230.00"]')).toContainText("no project uses it now");
+ await expect(page.locator("[data-uncovered]")).toContainText("reports/rail-a ra2");
+ // The stage with no data says so in one line.
+ await openStage(page, "clock");
+ await expect(page.locator("[data-stage-line]")).toContainText("No time map");
+ // Downloaded read the metadata's head only: its title, not the webpage_url past the formats.
+ await openStage(page, "downloaded");
+ await expect(page.locator('[data-stage-panel="downloaded"]')).toContainText("The Rail Recording");
+ await expect(page.locator('[data-stage-panel="downloaded"]')).toContainText("1 metadata rewrite");
+ await openStage(page, "transcribed");
+ await expect(page.locator("[data-stage-line]")).toContainText("vtt, 100% of 5:00");
+ // App-like: no page scroll at 1366×768.
+ expect(await page.evaluate(() => document.documentElement.scrollHeight <= window.innerHeight + 1)).toBe(true);
+ await openStage(page, "windows");
+ await shot(page, "ingredient-rail.png");
+});
+
+test("Used in lists both projects, each clip a link to its bench, the saved version beside the draft", async ({ page }) => {
+ await page.goto(RAIL);
+ await openStage(page, "used");
+ const rows = page.locator("[data-used-row]");
+ await expect(rows).toHaveCount(3);
+ await expect(page.locator('[data-used-row="reports/rail-a#ra1"]')).toContainText("draft, v1");
+ await expect(page.locator('[data-used-row="reports/rail-a#ra2"]')).toContainText("draft");
+ await expect(page.locator('[data-used-row="reports/rail-b#rb1"]')).toContainText("reports/rail-b");
+ await expect(page.locator('[data-used-row="reports/rail-a#ra1"] [data-used-open]')).toHaveAttribute("href", urls.clipBenchHref("reports/rail-a", "ra1"));
+ await expect(page.locator("[data-stage-line]")).toHaveText("3 clips in 2 projects");
+ await shot(page, "ingredient-used.png");
+ // Rendered: the version v1 holds ra1, rendered; Play opens it at that clip.
+ await openStage(page, "rendered");
+ await expect(page.locator('[data-rendered-row="reports/rail-a#ra1@v1"]')).toContainText("version v1");
+ await expect(page.locator('[data-rendered-row="reports/rail-a#ra1@v1"] [data-rendered-play]')).toHaveAttribute("href", urls.playHref("reports/rail-a", { take: "v1", clip: "ra1" }));
+ // Checked and Published read the projects' own files.
+ await openStage(page, "checked");
+ await expect(page.locator('[data-checked-row="reports/rail-a#ra1"]')).toHaveAttribute("data-status", "ok");
+ await expect(page.locator('[data-checked-row="reports/rail-a#ra2"]')).toContainText("not checked");
+ await openStage(page, "published");
+ await expect(page.locator('[data-published-row="reports/rail-b#rb1"]')).toHaveAttribute("data-state", "ok");
+ await expect(page.locator('[data-published-row="reports/rail-a#ra1"]')).toContainText("never checked");
+});
+
+test("?window= focuses one window: it is lit, and the stages after it narrow to the clips it plays", async ({ page }) => {
+ await page.goto(urls.ingredientHref("railchan", "railvid", { from: 10, to: 40 }));
+ await expect(page.locator("[data-ingredient-focus]")).toHaveAttribute("data-ingredient-focus", "10.00-40.00");
+ await expect(page.locator('[data-stage-panel="windows"]')).toBeVisible();
+ await expect(page.locator("[data-window-focused]")).toHaveCount(1);
+ await expect(page.locator('[data-window="10.00-40.00"]')).toHaveAttribute("data-window-focused", "1");
+ await expect(page.locator('[data-window="10.00-40.00"]')).toContainText("cuts rail-a ra1, rail-b rb1");
+ await expect(pill(page, "used")).toHaveAttribute("data-pill-text", "2");
+ await openStage(page, "used");
+ await expect(page.locator("[data-used-row]")).toHaveCount(2);
+ await expect(page.locator('[data-used-row="reports/rail-a#ra2"]')).toHaveCount(0);
+ await expect(page.locator("[data-stage-line]")).toHaveText("2 clips in 2 projects (of 3 from this recording)");
+ await expect(page.locator("[data-checked-row]")).toHaveCount(0); // the checked panel is not open
+ await openStage(page, "checked");
+ await expect(page.locator("[data-checked-row]")).toHaveCount(2);
+ await shot(page, "ingredient-window.png");
+});
+
+test("Rumble: the folder slug and the embed id open the same recording, and the page shows both", async ({ page }) => {
+ for (const id of ["v7rembd1", "v7rslug1"]) {
+ await page.goto(urls.ingredientHref("railrumble", id));
+ await expect(page.locator("[data-ingredient]")).toHaveAttribute("data-ingredient", "railrumble/v7rslug1");
+ await expect(page.locator("[data-ingredient-site-id]")).toHaveAttribute("data-ingredient-site-id", "v7rembd1");
+ await expect(pill(page, "used")).toHaveAttribute("data-pill-text", "1");
+ }
+ await openStage(page, "used");
+ await expect(page.locator('[data-used-row="reports/rail-r#rr1"]')).toBeVisible();
+ await openStage(page, "downloaded");
+ await expect(page.locator('[data-action-ask="persist"]')).toHaveText("Persist the whole recording…");
+});
+
+test("the entry points: the clip bench's Life cycle and Play's clip row link the clip's recording", async ({ page }) => {
+ await page.goto(urls.clipBenchHref("reports/rail-a", "ra1"));
+ await expect(page.locator("[data-bench-top] [data-bench-life]")).toHaveAttribute("href", RAIL);
+ await page.goto(urls.playHref("reports/rail-a", { clip: "ra1" }));
+ await expect(page.locator("[data-play-life]")).toHaveAttribute("href", RAIL, { timeout: 30_000 });
+});
+
+test("each action asks first -- what it costs, the queue it lands on -- then posts to the right route", async ({ page, request }) => {
+ await page.goto(RAIL);
+ // Downloaded: persist-videos, the editor's dry run first.
+ await openStage(page, "downloaded");
+ const persists = railAsks("persist-videos").length;
+ await runAction(page, "persist", { cost: "network", queue: /railchan channel's download queue/ });
+ const persist = railAsks("persist-videos").slice(persists);
+ expect(persist.map((r) => !!r.dryRun)).toEqual([true, false]);
+ expect(persist[1].items).toEqual([{ slug: "railchan", id: "railvid" }]);
+
+ // Transcribed: transcribe-one, on the GPU.
+ await openStage(page, "transcribed");
+ const transcribes = railAsks("transcribe-one").length;
+ await runAction(page, "transcribe", { cost: "gpu", queue: /transcribe-one:railchan:railvid/ });
+ expect(railAsks("transcribe-one").slice(transcribes)).toMatchObject([{ slug: "railchan", id: "railvid" }]);
+
+ // Windows: fetch-windows for the clip no window holds (rail-a's own body, narrowed to it), then a targeted evict.
+ await openStage(page, "windows");
+ const fetches = railAsks("fetch-windows").length;
+ await runAction(page, "fetch-reports/rail-a", { cost: "network", queue: /clips:youtube/ });
+ const fetch = railAsks("fetch-windows").slice(fetches);
+ expect(fetch.map((r) => !!r.dryRun)).toEqual([true, false]);
+ expect(fetch[1].items?.map((i) => `${i.slug}/${i.id}#${i.clipId}`)).toEqual(["railchan/railvid#ra2"]);
+ const evicts = railAsks("evict-clips").length;
+ await runAction(page, "evict-200.00-230.00.mp4", { cost: "disk" });
+ expect(railAsks("evict-clips").slice(evicts)).toMatchObject([{ slug: "railchan", id: "railvid", windows: ["200.00-230.00"] }]);
+
+ // Published: umtool's own link check (/api/report/links) -- the site refuses at once, so the link is unverified.
+ await openStage(page, "published");
+ const links = page.waitForRequest((r) => r.url().endsWith("/api/report/links") && r.method() === "POST");
+ await runAction(page, "links-reports/rail-b", { cost: "network" });
+ expect((await links).postDataJSON()).toEqual({ project: "reports/rail-b" });
+ await expect(page.locator('[data-published-row="reports/rail-b#rb1"]')).toHaveAttribute("data-state", "unverified", { timeout: 15_000 });
+
+ // Checked: a quote check, a umtool job (its transcriptions the editor's); it is let finish before the next spec.
+ await openStage(page, "checked");
+ await runAction(page, "quote-check-reports/rail-a", { cost: "gpu", queue: /umtool's job runner/ });
+ await expect(page.locator('[data-action-result="quote-check-reports/rail-a"]')).toContainText("quote check started");
+ await expect
+ .poll(async () => ((await (await request.get("/api/jobs")).json()) as { running: unknown }).running, { timeout: 90_000 })
+ .toBeNull();
+});
+
+test("another site's page may not start an action: a foreign Origin is refused, and so is a body that is not JSON", async ({ request }) => {
+ const body = { action: "transcribe", ch: "railchan", id: "railvid", step: "plan" };
+ const foreign = await request.post("/api/ingredients/action", { data: body, headers: { origin: "http://evil.example", "sec-fetch-site": "cross-site" } });
+ expect(foreign.status()).toBe(403);
+ const form = await request.post("/api/ingredients/action", { data: JSON.stringify(body), headers: { "content-type": "text/plain" } });
+ expect(form.status()).toBe(415);
+ // A start without the plan's key is refused before the editor is asked.
+ const asked = railAsks("transcribe-one").length;
+ const keyless = await request.post("/api/ingredients/action", { data: { ...body, step: "start" } });
+ expect(keyless.status()).toBe(400);
+ expect(railAsks("transcribe-one").length).toBe(asked);
+});
diff --git a/umtool/e2e/palette.spec.ts b/umtool/e2e/palette.spec.ts
@@ -0,0 +1,259 @@
+import { test, expect, type Page } from "@playwright/test";
+import { readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// ⌘K COMMANDS (umtool redesign, lane palette L8a): the verb registry's forms in
+// the palette. ⌘K on a project's page, "look" -> the `umtool look` form, the
+// project filled in from the page -> mode=basic -> Copy as CLI is the exact
+// line -> Run: the job's log, done, and the manifest changed. On a clip bench
+// the clip is filled in too. POST /api/cli refuses a ui:"none" verb (absent
+// from the palette), a raw argv, a value its schema refuses and a request no
+// page of this app made; a verb that renders goes through the durable queue.
+// Fixture: e2e/fixtures/basic-mode-fixture.mjs (basic-fixture, a deck cut);
+// the spec puts its manifest back. E2E_PALETTE_SHOTS=<dir>: screenshots there (1366x768).
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PROJECT = "reports/basic-fixture";
+const MANIFEST = path.join(HERE, "..", ".e2e-song", "reports", "basic-fixture", "video.manifest.json");
+const SHOTS = process.env.E2E_PALETTE_SHOTS ?? "";
+const original = readFileSync(MANIFEST, "utf8");
+const manifest = () => JSON.parse(readFileSync(MANIFEST, "utf8"));
+const shot = async (page: Page, name: string) => {
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, `${name}.png`) });
+};
+const palette = (page: Page) => page.locator("dialog[data-jump]");
+const open = async (page: Page) => {
+ await expect(page.locator("dialog[data-jump][data-ready]")).toBeAttached({ timeout: 60_000 });
+ await page.keyboard.press("Control+k");
+ await expect(palette(page)).toBeVisible();
+};
+
+test.beforeEach(() => writeFileSync(MANIFEST, original));
+test.afterAll(() => writeFileSync(MANIFEST, original));
+
+test("⌘K → look → its form, the project from the page → Copy as CLI → Run: the manifest changed", async ({ page, context }) => {
+ test.setTimeout(180_000);
+ await context.grantPermissions(["clipboard-read", "clipboard-write"]);
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await page.goto(urls.section(PROJECT, "build"));
+ await open(page);
+
+ // Typed words find the verb among the places; > is commands only.
+ await page.keyboard.type("look");
+ const row = palette(page).locator("[data-jump-item='cmd:look']");
+ await expect(row).toBeVisible({ timeout: 30_000 });
+ await expect(row).toContainText("umtool look");
+ // A verb with no form is not offered.
+ await page.locator("[data-jump-input]").fill(">help");
+ await expect(palette(page).locator("[data-jump-item='cmd:help']")).toHaveCount(0);
+ await page.locator("[data-jump-input]").fill(">teaser");
+ await expect(palette(page).locator("[data-jump-item='cmd:timeline teaser']")).toBeVisible();
+ await page.locator("[data-jump-input]").fill(">look");
+ await expect(palette(page).locator("[role=option][aria-selected=true]")).toHaveAttribute("data-jump-item", "cmd:look");
+ await page.keyboard.press("Enter");
+
+ const form = palette(page).locator("[data-cli-form='look']");
+ await expect(form).toBeVisible();
+ await expect(form.locator("[data-cli-arg='project'] input")).toHaveValue(PROJECT);
+ // Required settings missing: no line, no Run.
+ await expect(form.locator("[data-cli-invalid]")).toContainText("settings is required");
+ await expect(form.locator("[data-cli-run]")).toBeDisabled();
+ await form.locator("[data-cli-arg='settings'] textarea").fill("mode=basic");
+ const line = `node umtool/bin/umtool.mjs look ${PROJECT} mode=basic`;
+ await expect(form.locator("[data-cli-line]")).toHaveText(line);
+ await form.locator("[data-cli-copy]").click();
+ await expect(form.locator("[data-cli-copy]")).toHaveText("Copied");
+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(line);
+ const box = await palette(page).boundingBox();
+ expect(box!.y + box!.height, "the form fits 1366×768").toBeLessThanOrEqual(768);
+ await shot(page, "palette-form");
+
+ expect(manifest().render.mode ?? "deck").not.toBe("basic");
+ await form.locator("[data-cli-run]").click();
+ await expect(form.locator("[data-cli-state]")).toHaveAttribute("data-cli-state", "done", { timeout: 90_000 });
+ await expect(form.locator("[data-cli-log]")).toContainText(`look ${PROJECT} mode=basic`);
+ expect(manifest().render.mode).toBe("basic");
+ await shot(page, "palette-run-done");
+
+ // Back to the list.
+ await form.locator("[data-cli-back]").click();
+ await expect(palette(page).locator("[data-jump-input]")).toBeFocused();
+});
+
+test("on a clip bench the clip is filled in; a refused value says why", async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await page.goto(urls.clipBenchHref(PROJECT, "c01"));
+ await open(page);
+ await page.keyboard.type(">window");
+ await expect(palette(page).locator("[role=option][aria-selected=true]")).toHaveAttribute("data-jump-item", "cmd:window", { timeout: 30_000 });
+ await page.keyboard.press("Enter");
+ const form = palette(page).locator("[data-cli-form='window']");
+ await expect(form.locator("[data-cli-arg='project'] input")).toHaveValue(PROJECT);
+ await expect(form.locator("[data-cli-arg='clip'] input")).toHaveValue("c01");
+ await form.locator("[data-cli-arg='--title'] input").fill("A palette title");
+ await expect(form.locator("[data-cli-line]")).toHaveText(`node umtool/bin/umtool.mjs window ${PROJECT} c01 --title 'A palette title'`);
+ await form.locator("[data-cli-arg='--start'] input").fill("soon");
+ await expect(form.locator("[data-cli-invalid]")).toContainText("--start: a number");
+ await shot(page, "palette-clip-form");
+});
+
+test("POST /api/cli runs only registry form verbs, from this app's pages, with values its schema allows", async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.goto(urls.homeHref());
+ const origin = new URL(page.url()).origin;
+ const post = (data: unknown, headers: Record<string, string> = { origin }) => page.request.post("/api/cli", { data, headers });
+ const said = async (r: Awaited<ReturnType<typeof post>>) => ((await r.json()) as { error?: string }).error ?? "";
+
+ // The list the palette is built from: forms only.
+ const list = (await (await page.request.get("/api/cli")).json()) as { verbs: Array<{ verb: string }> };
+ const verbs = list.verbs.map((v) => v.verb);
+ expect(verbs).toContain("look");
+ expect(verbs).toContain("timeline insert");
+ expect(verbs).not.toContain("help");
+ expect(verbs).not.toContain("queue add");
+ expect(verbs).not.toContain("takes delete");
+
+ // A ui:"none" verb.
+ let r = await post({ verb: "queue add", values: {} });
+ expect(r.status()).toBe(400);
+ expect(await said(r)).toContain("has no form");
+ // A raw argv, in any spelling.
+ for (const body of [{ argv: ["look", PROJECT, "mode=basic"] }, { verb: "look", argv: ["--json"] }, { verb: "look", values: {}, cmd: "rm -rf /" }]) {
+ r = await post(body);
+ expect(r.status(), JSON.stringify(body)).toBe(400);
+ }
+ // A value its schema refuses, an arg it does not have, a project there is not.
+ r = await post({ verb: "look", values: { project: PROJECT, settings: "--unset render.rail" } });
+ expect(r.status()).toBe(400);
+ r = await post({ verb: "look", values: { project: PROJECT, settings: "mode=basic", "--json": true } });
+ expect(r.status()).toBe(400);
+ expect(await said(r)).toContain('takes no "--json"');
+ r = await post({ verb: "show", values: { project: "reports/no-such-project" } });
+ expect(r.status()).toBe(400);
+ expect(await said(r)).toContain("no project matches");
+ // Not a page of this app: another site, and no page at all.
+ r = await post({ verb: "show", values: { project: PROJECT } }, { origin: "https://evil.example" });
+ expect(r.status()).toBe(403);
+ r = await post({ verb: "show", values: { project: PROJECT } }, {});
+ expect(r.status()).toBe(403);
+ expect(manifest().render.mode ?? "deck", "nothing refused wrote").not.toBe("basic");
+
+ // A read, as one job: its log is the command's output.
+ r = await post({ verb: "show", values: { project: PROJECT } });
+ expect(r.status()).toBe(202);
+ const { job, line } = (await r.json()) as { job: { id: string }; line: string };
+ expect(line).toBe(`node umtool/bin/umtool.mjs show ${PROJECT}`);
+ await expect
+ .poll(async () => ((await (await page.request.get(`/api/cli?job=${job.id}`)).json()) as { job: { state: string } }).job.state, { timeout: 60_000 })
+ .toBe("done");
+ const shown = (await (await page.request.get(`/api/cli?job=${job.id}`)).json()) as { job: { log: string[] } };
+ expect(shown.job.log.join("\n")).toContain("The Basic Fixture");
+
+ // A verb that renders (or holds the heavy slot) is a step of the durable queue; the same one asked
+ // again at once (a double Enter) is that step.
+ r = await post({ verb: "prep", values: { project: PROJECT, "--status": true } });
+ expect(r.status()).toBe(202);
+ const { queued } = (await r.json()) as { queued: { qid: string } };
+ expect(queued.qid).toMatch(/^q\d+$/);
+ const again = await post({ verb: "prep", values: { project: PROJECT, "--status": true } });
+ expect(again.status()).toBe(200);
+ expect(((await again.json()) as { queued: { qid: string }; deduped: boolean })).toMatchObject({ queued: { qid: queued.qid }, deduped: true });
+ await expect
+ .poll(async () => ((await (await page.request.get(`/api/cli?qid=${queued.qid}`)).json()) as { step: { state: string } }).step.state, { timeout: 90_000 })
+ .toBe("done");
+});
+
+test("POST /api/cli: files stay in the project, @file is a terminal's, no-undo verbs want confirm, and a rebound host is refused", async ({ page }) => {
+ test.setTimeout(120_000);
+ await page.goto(urls.homeHref());
+ const origin = new URL(page.url()).origin;
+ const post = (data: unknown, headers: Record<string, string> = { origin }) => page.request.post("/api/cli", { data, headers });
+ const said = async (r: Awaited<ReturnType<typeof post>>) => ((await r.json()) as { error?: string }).error ?? "";
+
+ // An output is a bare name; an input a file of the project, by its realpath; @file is refused.
+ let r = await post({ verb: "trailer", values: { project: PROJECT, "--take": "t1", "--out": "../../escape.mp4" } });
+ expect(r.status()).toBe(400);
+ expect(await said(r)).toContain("bare name");
+ for (const patch of ["../../../../etc/passwd", "/etc/passwd"]) {
+ r = await post({ verb: "take", values: { project: PROJECT, "--id": "t1", "--patch": patch, "--draft": true } });
+ expect(r.status(), patch).toBe(400);
+ expect(await said(r)).toMatch(/not a file of the project|no such file in the project/);
+ expect(await said(r)).not.toContain("root:");
+ }
+ r = await post({ verb: "candidates add", values: { project: PROJECT, proposal: "@/etc/passwd" } });
+ expect(r.status()).toBe(400);
+ expect(await said(r)).toContain("terminal only");
+ r = await post({ verb: "posts set-item", values: { project: PROJECT, item: "c01", settings: "parent.0=@/etc/passwd" } });
+ expect(r.status()).toBe(400);
+
+ // No undo: 409 until confirmed.
+ r = await post({ verb: "prune", values: { project: PROJECT, "--yes": true } });
+ expect(r.status()).toBe(409);
+ expect(((await r.json()) as { confirm?: string }).confirm).toContain("delete");
+ r = await post({ verb: "prune", values: { project: PROJECT, "--yes": true }, confirm: true });
+ expect(r.status()).toBe(202);
+ const { job } = (await r.json()) as { job: { id: string } };
+ await expect.poll(async () => ((await (await page.request.get(`/api/cli?job=${job.id}`)).json()) as { job: { state: string } }).job.state, { timeout: 60_000 }).not.toBe("running");
+
+ // DNS rebinding: a name that is not this machine, as the forwarded host or the origin.
+ const port = new URL(origin).port;
+ r = await post({ verb: "show", values: { project: PROJECT } }, { origin, "x-forwarded-host": `rebind.example:${port}` });
+ expect(r.status()).toBe(403);
+ r = await post({ verb: "show", values: { project: PROJECT } }, { origin: `http://rebind.example:${port}`, "x-forwarded-host": `rebind.example:${port}` });
+ expect(r.status()).toBe(403);
+ expect(await said(r)).toContain("UMTOOL_ALLOWED_HOSTS");
+});
+
+test("a no-undo verb asks a second press; a run outlives Escape (Runs); a client-side move leaves no stale project", async ({ page }) => {
+ test.setTimeout(180_000);
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await page.goto(urls.section(PROJECT, "build"));
+ await open(page);
+ await page.keyboard.type(">prune");
+ await expect(palette(page).locator("[role=option][aria-selected=true]")).toHaveAttribute("data-jump-item", "cmd:prune", { timeout: 30_000 });
+ await page.keyboard.press("Enter");
+ const form = palette(page).locator("[data-cli-form='prune']");
+ await expect(form.locator("[data-cli-arg='project'] input")).toHaveValue(PROJECT);
+ await form.locator("[data-cli-arg='--yes'] input").check();
+ await form.locator("[data-cli-run]").click();
+ const confirm = form.locator("[data-cli-confirm]");
+ await expect(confirm).toContainText("Yes, delete those work files");
+ await expect(form.locator("[data-cli-state]")).toHaveCount(0);
+ await shot(page, "palette-confirm");
+ await confirm.click();
+ await expect(form.locator("[data-cli-state]")).toHaveAttribute("data-cli-state", /done|failed/, { timeout: 90_000 });
+
+ // A read started, then Escape: it is under Runs, and opens on its log.
+ await form.locator("[data-cli-back]").click();
+ await page.locator("[data-jump-input]").fill(">show");
+ await expect(palette(page).locator("[role=option][aria-selected=true]")).toHaveAttribute("data-jump-item", "cmd:show");
+ await page.keyboard.press("Enter");
+ const show = palette(page).locator("[data-cli-form='show']");
+ await show.locator("[data-cli-run]").click();
+ await page.keyboard.press("Escape");
+ await expect(palette(page)).toBeHidden();
+ await page.keyboard.press("Control+k");
+ const runs = palette(page).locator("[data-jump-item^='run:job-']");
+ await expect(runs).toHaveCount(2);
+ await expect(runs.first()).toContainText("umtool show");
+ await runs.first().click();
+ await expect(show.locator("[data-cli-state]")).toHaveAttribute("data-cli-state", "done", { timeout: 60_000 });
+ await expect(show.locator("[data-cli-log]")).toContainText("The Basic Fixture");
+
+ // A jump to the Inbox (a client-side move: the palette stays mounted), then a form at once: no project.
+ await show.locator("[data-cli-back]").click();
+ await page.locator("[data-jump-input]").fill("inbox");
+ await expect(palette(page).locator("[role=option][aria-selected=true]")).toHaveAttribute("data-jump-item", "inbox");
+ await page.keyboard.press("Enter");
+ await expect(page).toHaveURL(/\/$/);
+ await page.keyboard.press("Control+k");
+ await page.keyboard.type(">look");
+ await expect(palette(page).locator("[role=option][aria-selected=true]")).toHaveAttribute("data-jump-item", "cmd:look");
+ await page.keyboard.press("Enter");
+ await expect(palette(page).locator("[data-cli-form='look'] [data-cli-arg='project'] input")).toHaveValue("");
+});
diff --git a/umtool/lib/cli/argv.mjs b/umtool/lib/cli/argv.mjs
@@ -0,0 +1,305 @@
+// A VERB ROW'S FORM, AS ARGV (lane palette, L8a): the one function that turns
+// a row of the registry (lib/cli/verbs.mjs) and a form's values into the
+// words `umtool` is run with -- on the server by POST /api/cli (which never
+// takes argv from a page), and in the palette for its "Copy as CLI" line, so
+// the line copied is the command that runs.
+//
+// Pure, no imports: the route, the page and node --test read it alike.
+
+/** How the copied line names the CLI: from the repository's root. */
+export const CLI_PREFIX = "node umtool/bin/umtool.mjs";
+
+const STRING_MAX = 2000;
+const TEXT_MAX = 50_000;
+const LIST_MAX = 200;
+const PAIR_KEY = /^[A-Za-z_*][\w.*[\]<>-]*$/;
+const FLAG_KEY = /^[A-Za-z][\w-]*$/;
+const NUMBER = /^-?(\d+\.?\d*|\.\d+)$/;
+/** A bare file or id name: no directory, no `..`, no leading dot (`--out`, a take's id, a reel's name). */
+const BARE = /^[A-Za-z0-9_][\w.+-]*$/;
+/** A `..` segment, a home or an absolute path inside a value: a page may not name a path outside the project. */
+const ESCAPES = /(^|[\\/])\.\.([\\/]|$)|^~[\\/]|^[\\/]/;
+/** An `@file` reference anywhere in a value -- `@x`, `post-json:@x`, `a=@x`, `a,@x` (review, L8a): a CLI reads it. */
+const AT_REF = /(^|[:=,;])\s*['"]?@/;
+/** A timeline entry's id (`timeline order`: an id, never a file the CLI would read from its cwd). */
+const ENTRY_ID = /^[A-Za-z0-9_][\w:-]*$/;
+/** A share URL or a <channel>/<id> (`new --from` from a page: never a file). */
+const REF = /^(https?:\/\/\S+|[a-z0-9][a-z0-9_-]*\/[A-Za-z0-9_-]+)$/;
+
+const isFlag = (a) => a.name.startsWith("--");
+const isRun = (a) => a.type === "list" || a.type === "pairs" || a.type === "flagpairs";
+
+/** A list-shaped value: an array, or lines of a textarea. */
+function linesOf(v) {
+ if (Array.isArray(v)) return v.map((x) => String(x).trim()).filter(Boolean);
+ if (typeof v === "string") return v.split(/\r?\n/).map((x) => x.trim()).filter(Boolean);
+ return null;
+}
+
+/** Whether a form value is empty (left out of argv). */
+function absent(a, v) {
+ if (v === undefined || v === null || v === false) return true;
+ if (a.type === "boolean" && (v === "false" || v === "off" || v === "")) return true;
+ if (typeof v === "string") return a.type === "text" ? v.trim() === "" : v.trim() === "";
+ if (Array.isArray(v)) return v.length === 0 || (isRun(a) && linesOf(v).length === 0);
+ return false;
+}
+
+class FormError extends Error {
+ constructor(message, field) {
+ super(message);
+ this.field = field;
+ }
+}
+
+/** One word of argv from a plain value: no NUL, bounded, and never read as a flag. */
+function word(a, raw, { what = a.name, max = STRING_MAX, strictAt = atStrict(a) } = {}) {
+ const s = String(raw);
+ if (s.includes("\0")) throw new FormError(`${what}: a NUL byte`, a.name);
+ if (s.length > max) throw new FormError(`${what}: longer than ${max} characters`, a.name);
+ // `-` alone is a value (`--after -`); a negative number is a value; anything else that starts with a
+ // dash would be read as a flag by umtool's parsers.
+ if (/^-./.test(s) && !NUMBER.test(s.trim())) throw new FormError(`${what}: a value may not start with "-" (it would be read as a flag)`, a.name);
+ // `@file` reads a file wherever it is: a terminal's, never a form's (paste what the file holds) -- at the start,
+ // or inside a value a CLI splits (`post-json:@…`, `a=@…`, `a,@…`).
+ if (strictAt && !a.allowAt && AT_REF.test(s)) throw new FormError(`${what}: @file reads a file -- from a terminal only; paste what it holds`, a.name);
+ return s;
+}
+
+/**
+ * Whether an arg's values are checked for `@file` anywhere: a positional (the CLIs that read `@file` read it from
+ * a positional or a key=value), a list's items, a row's `atFile` arg. A flag's words and a positional's free prose
+ * (`text`, not atFile) are a person's words ("@grok said …"); `allowAt` is a handle (`@grok`) or a lexicon word.
+ */
+function atStrict(a) {
+ if (a.allowAt) return false;
+ if (a.atFile) return true;
+ if (a.type === "list" || a.type === "pairs") return true;
+ return !isFlag(a) && a.type !== "text";
+}
+
+/** A timeline entry's id: no dot, no slash -- never a file name. */
+function entryId(a, raw) {
+ const s = word(a, String(raw).trim());
+ if (!ENTRY_ID.test(s)) throw new FormError(`${a.name}: "${s}" is not an entry's id`, a.name);
+ return s;
+}
+
+/** A bare name: one word, no directory. */
+function bare(a, raw, what = a.name) {
+ const s = word(a, String(raw).trim(), { what });
+ if (!BARE.test(s) || s.includes("..")) throw new FormError(`${what}: a bare name (letters, digits, . _ - +; no directory, no leading dot)`, a.name);
+ return s;
+}
+
+/** A key=value value from a page: never `@file`, never a path out of the project. */
+function pairValue(a, value, what) {
+ const v = value.trim().replace(/^['"]/, "");
+ if (AT_REF.test(v)) throw new FormError(`${what}: @file reads a file -- from a terminal only; paste what it holds`, a.name);
+ if (ESCAPES.test(v)) throw new FormError(`${what}: a path outside the project (.., ~ or /) -- from a terminal only`, a.name);
+ return value;
+}
+
+/** One key=value word. */
+function pairWord(a, line) {
+ const at = line.indexOf("=");
+ const key = at > 0 ? line.slice(0, at).trim() : "";
+ if (!PAIR_KEY.test(key)) throw new FormError(`${a.name}: "${line}" is not key=value`, a.name);
+ return word(a, `${key}=${pairValue(a, line.slice(at + 1), key)}`, { max: TEXT_MAX });
+}
+
+/** A share URL or a <channel>/<id>: never a file. */
+function refWord(a, raw) {
+ const s = word(a, raw);
+ if (!REF.test(s)) throw new FormError(`${a.name}: a share URL or <channel>/<id> (a file only from a terminal)`, a.name);
+ return s;
+}
+
+/** The words one arg's value makes, flag included. */
+function wordsOf(a, v) {
+ const flag = isFlag(a) ? [a.name] : [];
+ switch (a.type) {
+ case "boolean": {
+ if (v === true || v === "true" || v === "on") return flag;
+ throw new FormError(`${a.name}: on or off`, a.name);
+ }
+ case "number": {
+ const s = String(v).trim();
+ if (!NUMBER.test(s) || !Number.isFinite(Number(s))) throw new FormError(`${a.name}: a number`, a.name);
+ return [...flag, s];
+ }
+ case "choice": {
+ const s = String(v).trim();
+ if (!(a.choices ?? []).includes(s)) throw new FormError(`${a.name}: one of ${(a.choices ?? []).join(", ")}`, a.name);
+ return [...flag, s];
+ }
+ case "json": {
+ const s = String(v);
+ try {
+ JSON.parse(s);
+ } catch {
+ throw new FormError(`${a.name}: not JSON`, a.name);
+ }
+ return [...flag, word(a, s, { max: TEXT_MAX })];
+ }
+ case "text":
+ return [...flag, word(a, String(v), { max: TEXT_MAX })];
+ case "project":
+ case "string":
+ return [...flag, word(a, String(v).trim())];
+ case "name":
+ if (a.literals?.includes(String(v).trim())) return [...flag, String(v).trim()];
+ return [...flag, bare(a, v)];
+ case "path": {
+ // A file of the project, relative to its directory. The SERVER confines it (realpath inside the
+ // project: app/api/cli/route.ts) and runs it as the absolute path it found; here it is one word.
+ const s = word(a, String(v).trim());
+ if (a.literals?.includes(s)) return [...flag, s];
+ if (s.startsWith("@")) throw new FormError(`${a.name}: a file of the project, by its path (no @)`, a.name);
+ return [...flag, s];
+ }
+ case "ref":
+ return [...flag, refWord(a, String(v).trim())];
+ case "list":
+ case "pairs":
+ case "flagpairs": {
+ const lines = linesOf(v);
+ if (!lines) throw new FormError(`${a.name}: one value per line`, a.name);
+ if (lines.length > LIST_MAX) throw new FormError(`${a.name}: more than ${LIST_MAX} values`, a.name);
+ const out = [];
+ for (const line of lines) {
+ if (a.type === "list") {
+ const w = a.item === "id" ? entryId(a, line) : a.item === "name" ? bare(a, line) : a.item === "pair" ? pairWord(a, line) : a.item === "ref" ? refWord(a, line) : word(a, line);
+ out.push(...(isFlag(a) ? [a.name, w] : [w]));
+ continue;
+ }
+ const at = line.indexOf("=");
+ const key = at > 0 ? line.slice(0, at).trim() : "";
+ if (a.type === "pairs") {
+ out.push(pairWord(a, line));
+ } else {
+ if (!FLAG_KEY.test(key)) throw new FormError(`${a.name}: "${line}" is not key=value`, a.name);
+ out.push(`--${key}`, word(a, pairValue(a, line.slice(at + 1).trim(), `--${key}`), { what: `--${key}`, max: TEXT_MAX }));
+ }
+ }
+ return out;
+ }
+ default:
+ throw new FormError(`${a.name}: an arg of unknown type ${a.type}`, a.name);
+ }
+}
+
+/**
+ * A row and a form's values to argv (the words after `umtool`).
+ *
+ * @param {{ verb: string, args: Array<Record<string, any>>, shape?: string }} row
+ * @param {Record<string, unknown>} values name -> string | number | boolean | string[]
+ * @returns {{ ok: true, argv: string[] } | { ok: false, error: string, field?: string }}
+ */
+export function buildArgv(row, values = {}) {
+ try {
+ if (!values || typeof values !== "object" || Array.isArray(values)) throw new FormError("the values are an object of name: value");
+ const args = row.args ?? [];
+ const known = new Set(args.map((a) => a.name));
+ for (const k of Object.keys(values)) if (!known.has(k)) throw new FormError(`umtool ${row.verb} takes no "${k}"`, k);
+ for (const k of Object.keys(values)) {
+ const v = values[k];
+ const ok = v === null || ["string", "number", "boolean"].includes(typeof v) || (Array.isArray(v) && v.every((x) => typeof x === "string"));
+ if (!ok) throw new FormError(`${k}: a string, a number, on/off or a list of strings`, k);
+ }
+ const given = (a) => !absent(a, values[a.name]);
+ for (const a of args) if (a.required && !given(a)) throw new FormError(`${a.name} is required`, a.name);
+
+ // An empty optional positional before a given one would shift every word after it.
+ const positionals = args.filter((a) => !isFlag(a));
+ const plain = positionals.filter((a) => a.type !== "pairs");
+ for (let i = 0; i < plain.length; i += 1) {
+ if (!given(plain[i]) && plain.slice(i + 1).some(given)) {
+ throw new FormError(`${plain[i].name} is needed before ${plain.slice(i + 1).find(given).name}`, plain[i].name);
+ }
+ }
+
+ const argv = [];
+ const placed = new Set();
+ const shape = (row.shape ?? row.verb).split(/\s+/).filter(Boolean);
+ for (const t of shape) {
+ const m = /^<(.+)>$/.exec(t);
+ if (!m) {
+ argv.push(t);
+ continue;
+ }
+ const a = positionals.find((x) => x.name === m[1]);
+ if (!a) throw new FormError(`the shape of ${row.verb} names <${m[1]}>, which is not one of its args`);
+ placed.add(a.name);
+ if (given(a)) argv.push(...wordsOf(a, values[a.name]));
+ }
+ for (const a of positionals) if (!placed.has(a.name) && given(a)) argv.push(...wordsOf(a, values[a.name]));
+ for (const a of args) if (isFlag(a) && given(a)) argv.push(...wordsOf(a, values[a.name]));
+ return { ok: true, argv };
+ } catch (e) {
+ if (e instanceof FormError) return { ok: false, error: e.message, ...(e.field ? { field: e.field } : {}) };
+ throw e;
+ }
+}
+
+/** A word as a POSIX shell reads it back. */
+export function shellQuote(s) {
+ const v = String(s);
+ if (v !== "" && /^[\w@%+=:,./-]+$/.test(v)) return v;
+ return `'${v.replace(/'/g, `'\\''`)}'`;
+}
+
+/** The line to paste into a terminal at the repository's root. */
+export const cliLine = (argv) => [CLI_PREFIX, ...argv.map(shellQuote)].join(" ");
+
+/** The row's arguments as a usage line reads them: `<project> <clip> [--start N] [--lock]`. */
+export function synopsis(row) {
+ const args = row.args ?? [];
+ const meta = (a) =>
+ a.type === "choice" ? (a.choices ?? []).join("|") : a.type === "number" ? "N" : a.type === "json" ? "JSON" : a.name.replace(/^--/, "").toUpperCase();
+ const one = (a) => {
+ if (a.type === "pairs") return a.required ? "key=value…" : "[key=value…]";
+ if (a.type === "flagpairs") return a.required ? "--key value…" : "[--key value…]";
+ if (!isFlag(a)) {
+ const w = a.type === "choice" ? (a.choices ?? []).join("|") : `<${a.name}>`;
+ const s = a.type === "list" ? `${w}…` : w;
+ return a.required ? s : `[${s}]`;
+ }
+ const s = a.type === "boolean" ? a.name : `${a.name} ${meta(a)}${a.type === "list" ? "…" : ""}`;
+ return a.required ? s : `[${s}]`;
+ };
+ const positionals = args.filter((a) => !isFlag(a));
+ const placed = new Set();
+ const head = (row.shape ?? row.verb).split(/\s+/).filter(Boolean).map((t) => {
+ const m = /^<(.+)>$/.exec(t);
+ const a = m && positionals.find((x) => x.name === m[1]);
+ if (!a) return t;
+ placed.add(a.name);
+ return one(a);
+ });
+ return [...head, ...positionals.filter((a) => !placed.has(a.name)).map(one), ...args.filter(isFlag).map(one)].join(" ");
+}
+
+/**
+ * Whether these values make the row do something with no undo (a row's `confirm`): the sentence to
+ * confirm with, or null. `confirm: { what, when?: [arg names, any of them given], unless?: [arg names] }`;
+ * no `when`: always.
+ * @returns {string | null}
+ */
+export function confirmOf(row, values = {}) {
+ const c = row.confirm;
+ if (!c) return null;
+ const args = row.args ?? [];
+ const given = (name) => {
+ const a = args.find((x) => x.name === name);
+ return !!a && !absent(a, values?.[name]);
+ };
+ if (c.unless?.some(given)) return null;
+ if (c.when && !c.when.some(given)) return null;
+ return c.what;
+}
+
+/** The row's path args a page gave: the server confines each. */
+export function pathArgsOf(row, values = {}) {
+ return (row.args ?? []).filter((a) => a.type === "path" && !absent(a, values?.[a.name]) && !a.literals?.includes(String(values[a.name]).trim()));
+}
diff --git a/umtool/lib/cli/confine.mjs b/umtool/lib/cli/confine.mjs
@@ -0,0 +1,40 @@
+// A PATH A PAGE NAMED, KEPT INSIDE THE PROJECT (lane palette L8a, review):
+// POST /api/cli runs a registry row's `path` arg (lib/cli/verbs.mjs) only
+// when it is a file of the project the form names -- relative to the
+// project's directory, its REALPATH (every symlink followed, the project's
+// own too) inside the project's realpath. What runs is that absolute path, so
+// the CLI's own resolution (most of them path.resolve() from their cwd) cannot
+// put it anywhere else; a row whose CLI takes it relative to the project
+// (`pass: "relative"`) gets the path as typed, checked the same way.
+//
+// The refusal names the arg and never what the file holds.
+import { realpath, stat } from "node:fs/promises";
+import path from "node:path";
+
+/**
+ * @param {string} projectDir
+ * @param {string} value what the form gave
+ * @returns {Promise<{ ok: true, abs: string } | { ok: false, error: string }>}
+ */
+export async function confineToProject(projectDir, value) {
+ const v = String(value ?? "").trim();
+ if (!v) return { ok: false, error: "no file named" };
+ if (v.includes("\0")) return { ok: false, error: "a NUL byte" };
+ let root;
+ try {
+ root = await realpath(/* turbopackIgnore: true */ projectDir);
+ } catch {
+ return { ok: false, error: "the project's directory is not there" };
+ }
+ const wanted = path.resolve(/* turbopackIgnore: true */ projectDir, v);
+ let real;
+ try {
+ real = await realpath(/* turbopackIgnore: true */ wanted);
+ } catch {
+ return { ok: false, error: `${v}: no such file in the project` };
+ }
+ if (real !== root && !real.startsWith(root + path.sep)) return { ok: false, error: `${v}: not a file of the project (a form may only name files inside it)` };
+ const st = await stat(/* turbopackIgnore: true */ real).catch(() => null);
+ if (!st?.isFile()) return { ok: false, error: `${v}: not a file` };
+ return { ok: true, abs: real };
+}
diff --git a/umtool/lib/cli/docs.mjs b/umtool/lib/cli/docs.mjs
@@ -0,0 +1,107 @@
+// `umtool help` AND docs/cli.md's COMMANDS, GENERATED (lane palette, L8a)
+// from the registry: the verb rows (verbs.mjs) and their prose (groups.mjs).
+//
+// node umtool/lib/cli/docs.mjs rewrite docs/cli.md's generated section
+// node umtool/lib/cli/docs.mjs --check exit 1 when it is stale (verbs.test.mjs says the same)
+//
+// The section stands between the two markers below -- the Commands table (each
+// command's rows, as groups.mjs gives them) and "Every verb" (every row of the
+// registry, its arguments and whether ⌘K offers it as a form). Everything else
+// in cli.md is hand-written and left as it is.
+import { readFileSync, writeFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+
+import { GROUPS } from "./groups.mjs";
+import { VERBS, commandOf } from "./verbs.mjs";
+import { synopsis } from "./argv.mjs";
+
+export const DOCS_BEGIN = "<!-- verbs:begin (generated by umtool/lib/cli/docs.mjs from lib/cli/verbs.mjs and groups.mjs -- edit those, not this) -->";
+export const DOCS_END = "<!-- verbs:end -->";
+
+/** docs/cli.md, beside this checkout's umtool. */
+export const CLI_MD = fileURLToPath(new URL("../../docs/cli.md", import.meta.url));
+
+/**
+ * What `umtool help` prints.
+ * @param {{ reportsRoot: string, chainSteps?: string, draftAllSteps?: string }} fill
+ */
+export function usageText({ reportsRoot, chainSteps = "", draftAllSteps = "" }) {
+ const lines = GROUPS.flatMap((g) => g.usage).map((l) => l.replace("{chainSteps}", chainSteps).replace("{draftAllSteps}", draftAllSteps));
+ return [
+ "umtool — the project tree, from a terminal",
+ "",
+ ...lines,
+ "",
+ `reading ${reportsRoot} (set REPORTS_DIR to move it)`,
+ "",
+ "Run `check` before every build. It is what catches a manifest with no",
+ "siteOrigin — the defect that shipped 19 QR codes reading `undefined/?v=…`.",
+ "",
+ "Every verb, its arguments and its ⌘K form: umtool/docs/cli.md (\"Every verb\").",
+ ].join("\n");
+}
+
+const code = (s) => `\`${String(s).replace(/\|/g, "\\|")}\``;
+const cell = (s) => String(s).replace(/\|/g, "\\|").replace(/\n/g, " ");
+
+/** The generated section, markers included. */
+export function verbsMarkdown() {
+ const out = [DOCS_BEGIN, "## Commands", "", "| | |", "|---|---|"];
+ for (const g of GROUPS) for (const [syntax, text] of g.docs) out.push(`| ${syntax} | ${text} |`);
+ out.push(
+ "",
+ "### Every verb",
+ "",
+ "Every verb `umtool` dispatches, a sub-verb its own row (`umtool/lib/cli/verbs.mjs`, the registry the ⌘K palette's",
+ "**Commands** are built from). **form**: the palette offers it as a form (its arguments below, the page's project",
+ "and selection filled in; **Copy as CLI**; Run is `POST /api/cli`, which runs only these). **queued**: Run adds it to",
+ "the durable queue (it renders, or holds the heavy slot). Otherwise why it has none. *draft*: it writes the working",
+ "draft (the project's manifest); *project*: a project's other files, or reads; *corpus*: no one project.",
+ "",
+ "| Verb | What it does | ⌘K |",
+ "|---|---|---|",
+ );
+ for (const r of VERBS) {
+ const ui = r.ui === "form" ? `form${r.queue ? " · queued" : ""} · *${r.target}*` : `none: ${cell(r.reason)}`;
+ out.push(`| ${code(r.ui === "form" ? synopsis(r) : r.verb)} | ${cell(r.summary)} | ${ui} |`);
+ }
+ out.push(DOCS_END);
+ return out.join("\n");
+}
+
+/**
+ * cli.md with its section replaced: between the markers when they are there,
+ * else from `## Commands` to the end of its table (the first run).
+ */
+export function withVerbsSection(text) {
+ const md = verbsMarkdown();
+ const a = text.indexOf(DOCS_BEGIN);
+ const b = text.indexOf(DOCS_END);
+ if (a >= 0 && b > a) return text.slice(0, a) + md + text.slice(b + DOCS_END.length);
+ const lines = text.split("\n");
+ const h = lines.indexOf("## Commands");
+ if (h < 0) throw new Error("cli.md has neither the markers nor a `## Commands` heading");
+ let end = h + 1;
+ for (let i = h + 1; i < lines.length && !lines[i].startsWith("## "); i += 1) if (lines[i].startsWith("|")) end = i;
+ return [...lines.slice(0, h), md, ...lines.slice(end + 1)].join("\n");
+}
+
+/** The top-level commands the registry has rows for. */
+export const registryCommands = () => [...new Set(VERBS.map((r) => commandOf(r.verb)))];
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
+ const text = readFileSync(/* turbopackIgnore: true */ CLI_MD, "utf8");
+ const next = withVerbsSection(text);
+ if (process.argv.includes("--check")) {
+ if (next !== text) {
+ console.error("umtool/docs/cli.md is stale: run `node umtool/lib/cli/docs.mjs` and commit it");
+ process.exit(1);
+ }
+ console.log("umtool/docs/cli.md is current");
+ } else if (next !== text) {
+ writeFileSync(/* turbopackIgnore: true */ CLI_MD, next);
+ console.log("umtool/docs/cli.md rewritten");
+ } else {
+ console.log("umtool/docs/cli.md is current");
+ }
+}
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -0,0 +1,1061 @@
+// THE REGISTRY'S PROSE (lane palette, L8a): per top-level command, the lines
+// `umtool help` prints for it and the rows docs/cli.md's Commands table gives
+// it -- written ONCE here, so the help and the page are generated from the same
+// place as the verb rows (verbs.mjs) the ⌘K palette's forms are built from.
+//
+// `usage`: the help lines, as `umtool help` prints them (two spaces, then
+// `umtool <cmd>` padded to the column; a continuation line indented to it).
+// `{chainSteps}` and `{draftAllSteps}` are filled in when it prints (lib/cli/docs.mjs).
+// `docs`: [syntax cell, text cell] pairs, the Commands table's markdown as it stands.
+//
+// A command appears in the order `umtool help` lists it; one may appear twice
+// (take: its renders, then the lint, then its promote and status). Edit the
+// prose here, then `node umtool/lib/cli/docs.mjs` rewrites docs/cli.md's
+// generated section (the test in verbs.test.mjs fails while it is stale).
+//
+// Plain data, no imports.
+
+/** @type {Array<{ cmd: string, usage: string[], docs: Array<[string, string]> }>} */
+export const GROUPS = [
+ {
+ cmd: "ls",
+ usage: [
+ " umtool ls [--kind K] [--template T] [--state S] [--open] [--blocking]",
+ " [--q TEXT] [--sort name|recent] [--json]",
+ ],
+ docs: [
+ ["`ls [--kind --template --state --open --blocking --q --sort --json]`",
+ "the index, as text or JSON"],
+ ],
+ },
+ {
+ cmd: "show",
+ usage: [
+ " umtool show <project> [--json]",
+ ],
+ docs: [
+ ["`show <project> [--json]`",
+ "one project: summary, the cut, per-clip status, decisions"],
+ ],
+ },
+ {
+ cmd: "check",
+ usage: [
+ " umtool check [<project>] [--json] exit 1 on anything blocking",
+ ],
+ docs: [
+ ["`check [<project>] [--json]`",
+ "**exit 1 on anything blocking** — including an `out/`, `clips/` or `share-*/` link whose drive is not there (`storage-unreachable`)"],
+ ],
+ },
+ {
+ cmd: "links",
+ usage: [
+ " umtool links <project> [--json] [--fix] do the clip QRs open on their sites? (corpus.json -> slugToPage",
+ " -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead",
+ " umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json] the published Rumble embed id (siteVideo)",
+ " on every clip citing a URL-slug folder; no network, one write (the Cut tab's Project > Rumble cites)",
+ ],
+ docs: [
+ ["`links <project> --embed-ids [--clips a,b] [--dry-run] [--json]`",
+ "the **published embed id**: every clip citing a Rumble URL-slug folder the archive does not serve gets `siteVideo` (the folder's `metadata.info.json` id, shareLine.mjs `siteVideoFor`), a citeUrl naming the folder moved with it; no network, one write, one undo point. The Cut tab's Project › Rumble cites ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"],
+ ["`links <project> [--json] [--fix]`",
+ "do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on))"],
+ ],
+ },
+ {
+ cmd: "cast",
+ usage: [
+ " umtool cast [ls] | add <id> --name … --voice <engine:voice> [--handles a,b] | set <id> … | rm <id> | undo",
+ " | project <p> | audition <character> --voices a,b,c [--project <p>] [--text …] | use <p> <character> <voice>",
+ " [--everywhere] | reread <p> <character> the CAST: characters' stock voices across projects (cast.json), a",
+ " project's characters and their drift, an audition of candidate voices (scored against the real voice)",
+ ],
+ docs: [
+ ["`cast [ls] \\| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \\| set <id> … \\| rm <id> \\| undo [--json]`",
+ "**THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write"],
+ ["`cast project <project> [--json]` · `cast use <project> <character\\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]`",
+ "a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for"],
+ ["`cast audition <character\\|@handle> --voices a,b,… [--project <p>] [--text \"…\" \\| --item <id> \\| --line <n> \\| --stock] [--no-score \\| --score-only] [--json] [--progress ndjson]`",
+ "**AN AUDITION**: one line read by 2-6 stock voices through the editor's tts op, levelled to -20 LUFS in `<p>/narration/auditions/` (cached), scored for closeness to the character's real voice (`speakers.json`; TitaNet, local)"],
+ ],
+ },
+ {
+ cmd: "speaker-check",
+ usage: [
+ " umtool speaker-check <project> [--clip <id> …] [--json] which of the project's named voices (speakers.json) each",
+ " clip is: TitaNet-small, local -> speaker-check.json; --set 'Name=<clip>,<channel>/<id>,channel:<slug>' / --remove / --list",
+ ],
+ docs: [
+ ["`speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]` · `--set 'Name=<clip>,<channel>/<id>,channel:<slug>'` · `--remove <name>` · `--list`",
+ "which of the project's **named voices** (`speakers.json`) each clip is: TitaNet-small, local, against each voice's robust centroid → `<project>/speaker-check.json` (merged); the walk's **Speaker:** badge and **Check speaker** ([report-video.md](report-video.md#the-speaker-check-on-the-walk-which-of-several-voices))"],
+ ],
+ },
+ {
+ cmd: "quote-check",
+ usage: [
+ " umtool quote-check <project> [--clips a,b] [--pad S] [--json] | --status is each clip's quote in the seconds it plays?",
+ " the cut ±15 s of the source the render would use, transcribed by the editor (words on), the quote",
+ " found in it and in the cues: ok | moved (heard N s away: window --align) | not-found -> quote-check.json;",
+ " check calls moved and not-found blocking, and a take refuses them unless the clip is --quote-ruled",
+ ],
+ docs: [
+ ["`quote-check <project> [--clips a,b] [--pad S] [--json]` · `quote-check <project> --status`",
+ "**is each clip's quote in the seconds it plays?** The cut ±15 s of the source the render would cut it from, transcribed by the editor (`pnpm ops transcribe`, words on — its transcription lane), the quote found in those words and in the cues: `ok`, `moved` (heard more than 0.5 s from where the cues have it), `not-found`; rows in `quote-check.json`, stale when the cut or the quote changes; `check` blocks on `moved`/`not-found` (`clip-quote-moved`, `clip-quote-missing`), a take refuses them, `prep --status` counts them ([knobs.md](knobs.md#the-quote-check-is-the-quote-where-the-clip-plays))"],
+ ],
+ },
+ {
+ cmd: "check-joins",
+ usage: [
+ " umtool check-joins <project> --take <id> [--json] [--all] [--limit <n>] every boundary of the take's master where the",
+ " next post item draws a post the one before showed: its join, the SSIM across it, the largest jump",
+ ],
+ docs: [
+ ["`check-joins <project> --take <id> [--json] [--all] [--limit <n>]`",
+ "do a rendered take's **post joins carry on**: every boundary of its master where the next post item draws a post the one before showed, its planned join, the SSIM across it and the largest frame-to-frame step (read-only, ffmpeg) -- worst first ([report-video.md](report-video.md#thread-scenes-whole-threads-the-join-manual-threads-wide-attachments-context-media-link-visits-the-branch-map))"],
+ ],
+ },
+ {
+ cmd: "link-policy",
+ usage: [
+ " umtool link-policy <project> [--via <site id|url>] [--direct a,b] [--clear] [--fix] [--json] the link policy",
+ " (provenance.linkPolicy): cite via site X, these channels direct; --fix rewrites the clips that break it",
+ ],
+ docs: [
+ ["`link-policy <project> [--via <site id \\| https://…>] [--direct <slug,…>] [--clear] [--fix] [--json]`",
+ "the project's **link policy** (`provenance.linkPolicy`): cite via site X, these channels direct. With no flag, prints it and every clip whose QR breaks it; `--fix` rewrites each one that has a fix through the window writer; new clips are written by it. **Exit 1** when a clip still breaks it ([knobs.md](knobs.md#the-link-policy))"],
+ ],
+ },
+ {
+ cmd: "patch-markers",
+ usage: [
+ " umtool patch-markers <project> [<file>.patch.json] [--fix] [--json] take patches whose deck markers name a",
+ " clip not in the cut; --fix gives each the after of the cut's marker of the same label",
+ ],
+ docs: [
+ ["`patch-markers <project> [<file>.patch.json] [--fix] [--json]`",
+ "take patches whose deck markers name a clip not in the cut (a take made with one is refused); `--fix` gives each the `after` of the cut's marker of the same label; **exit 1** when one is left ([knobs.md](knobs.md#take-patches-follow-a-removal))"],
+ ],
+ },
+ {
+ cmd: "decisions",
+ usage: [
+ " umtool decisions [--json]",
+ ],
+ docs: [
+ ["`decisions [--json]`",
+ "the inbox"],
+ ],
+ },
+ {
+ cmd: "inbox",
+ usage: [
+ " umtool inbox [--all] [--json] the decisions, grouped and ranked as the inbox shows them",
+ " (--all: the hidden ones on parked/done pieces, and the quiet group)",
+ ],
+ docs: [
+ ["`inbox [--all] [--json]`",
+ "the decisions grouped and ranked by piece (`a:<site>/<report>`, `p:<project>`): Your call, Review, Blocking, Notes, Open, Ready to finish, Quiet — one card per piece and kind, and how many sit hidden on parked or done pieces (`--all` lists them). Every decision, songs' and articles' included; runs `bin/inbox.ts` through tsx"],
+ ],
+ },
+ {
+ cmd: "schedule",
+ usage: [
+ " umtool schedule list | show <id> [--json] the recurring reports: chip, editions, tick log (read-only;",
+ " a schedule is written through the editor: `pnpm ops report-schedule`)",
+ ],
+ docs: [
+ ["`schedule list \\| show <id> [--json]`",
+ "the recurring reports, read-only ([recurring.md](recurring.md))"],
+ ],
+ },
+ {
+ cmd: "folders",
+ usage: [
+ " umtool folders [--json]",
+ ],
+ docs: [
+ ["`folders [--json]` · `kinds [--json]`",
+ "the tree, the registry"],
+ ],
+ },
+ {
+ cmd: "kinds",
+ usage: [
+ " umtool kinds [--json]",
+ ],
+ docs: [
+ ],
+ },
+ {
+ cmd: "link",
+ usage: [
+ " umtool link <project> <site>/<report> | --clear [--json] the manifest names its article (a top-level",
+ " `article`): what settles link-ambiguous; noted for the generator on a generated manifest",
+ ],
+ docs: [
+ ["`link <project> <site>/<report>` · `link <project> --clear`",
+ "the manifest names the article it is the video of (settles `link-ambiguous`)"],
+ ],
+ },
+ {
+ cmd: "window",
+ usage: [
+ " umtool window <project> <clip> [--start S] [--end E] [--lock|--lock-end|…]",
+ " attribution too: --title, --date YYYY-MM-DD, --cite, --cite-url, --quote",
+ " --repeat-of <clip> it re-plays that clip on purpose (a callback): their overlap is not flagged or trimmed",
+ " --correction TEXT what the REPORT got wrong here (never rendered)",
+ " --walk-note TEXT an editorial note from the walk (not a correction; never rendered)",
+ " --star / --no-star the walk's favourite: a trailer candidate (umtool trailer <p> --candidates)",
+ " a window edit that leaves --cite (or the citeUrl's t=) more than 5 s before the clip, or",
+ " after it, moves it to the clip's first second; an explicit --cite moves the QR's t= with it",
+ " --verdict confirmed|incorrect what the walk said; incorrect needs --correction",
+ " --reject <why> [--note TEXT] rejected on the walk, kept in place (`umtool timeline <p> reject`",
+ " takes it out, on record): not-matching|wrong-speaker (fact errors: incorrect, the note its",
+ " correction) or irrelevant|repeats|weak|privacy|other (rejected; other needs --note)",
+ " --cut-start S --cut-end E --lock-cut the cut the video renders",
+ " --align the cut snapped to the quote as HEARD (quote-check.json: a breath before its first word,",
+ " its last let ring; the extent widened to hold it; lockCut kept) -- the per-clip fix for a moved quote",
+ " --quote-ruled / --no-quote-ruled a person heard it and rules the quote check's verdict: a take renders it",
+ " --move-stamp first|nearest|<s> | --clear-stamp with --start/--end: a stamp's second (claim.at,",
+ " a mark's at) the new window would leave outside moves to the first second that plays, the nearest,",
+ " or <s>, or loses its at -- in the same write; --move-mute nearest | --clear-mute the mute mark's",
+ " --gap FROM-TO (repeatable) cut those source seconds out of the clip's middle: it plays",
+ " as ONE segment of jump cuts (gaps.mjs; inside the cut, ≥ 0.2 s, 0.5 s kept between);",
+ " --gap-remove S the gap holding source second S · --gaps 'A-B,C-D' the whole list ('' clears)",
+ " an empty value (--title '') deletes the field",
+ " --take <id> a take's clip (walk a take): the edit goes into takes/<id>/take.json's",
+ " patch, an undo point first (`umtool timeline <p> --take <id> undo`); the manifest is untouched",
+ ],
+ docs: [
+ ["`window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]`",
+ "edit a window"],
+ ["`window <project> <clip> --start S --end E --move-stamp first\\|nearest\\|<s>` · `--clear-stamp` · `--move-mute nearest` · `--clear-mute`",
+ "a window edit refused because a stamp's second (`claim.at`, a mark's `at`) or the mute mark would fall outside it, with the fix in the same write: the stamp to the first second that plays, the nearest, or `<s>`, or its `at` cleared; the mute mark to the nearest second, or cleared (never inside a gap). A refused `window` names these flags ([clip-bench.md](clip-bench.md#saving))"],
+ ["`window <project> <clip> --verdict confirmed\\|incorrect [--correction T]` · `window <project> <clip> --reject <why> [--note T]`",
+ "what the walk said: `--reject` is the walk's **Reject ▾** kept in place (`not-matching`/`wrong-speaker`: incorrect, the note its correction; `irrelevant`/`repeats`/`weak`/`privacy`/`other`: rejected, the note its `rejectNote`); `umtool timeline <p> reject` takes it out ([report-video.md](report-video.md#verdict--what-the-walk-said))"],
+ ["`window <project> <clip> --walk-note T` · `--star` / `--no-star` · `--repeat-of <clip>`",
+ "what the walk said that is not a verdict: an editorial note (not a correction) and the ★ favourite, a trailer candidate (`trailer <project> --candidates [--json]` lists them as beats); a deliberate repeat ([knobs.md](knobs.md#a-clip))"],
+ ["`window <project> <clip> --align` · `--quote-ruled` / `--no-quote-ruled`",
+ "the cut snapped to the quote as HEARD (0.15 s before its first word, 0.3 s after its last, the extent widened to hold it, `lockCut`); a person's ruling on the quote check (a take renders a ruled clip)"],
+ ["`window <project> <clip> --take <take> …`",
+ "a **take's** clip (walk a take): the same fields, written into the take's patch (`takes/<take>/take.json`) with an undo point first; the project's manifest is untouched ([clip-bench.md](clip-bench.md#walking-a-take))"],
+ ],
+ },
+ {
+ cmd: "walk",
+ usage: [
+ " umtool walk <project> [--take <id>] [--all] [--json] the clip bench's walk: every clip in walk order,",
+ " its verdict, fetched or not, and (→) the ones the walk visits; --take walks a take (a draft too)",
+ ],
+ docs: [
+ ["`walk <project> [--take <take>] [--all] [--json]`",
+ "the clip bench's **walk**: every clip in walk order with its window, verdict and whether a fetched file holds it, and (→) the ones the walk visits — fetched and needing a verdict; `--all` every fetched one; `--take` walks a take (a draft too); the bench's address to start at. The intro (`render.intro`) is listed first, watched, not judged (`intro`, `stops` in `--json`)"],
+ ],
+ },
+ {
+ cmd: "present",
+ usage: [
+ " umtool present <project> [--take <id> | --cut] [--json] [--public] [--open] PRESENT MODE: the cut as slides,",
+ " navigated like a deck (/projects/<p>/present); prints its address and its slides (#<slide id> opens",
+ " one); --json the payload (posts with their censor data by kind, clips' spans, section/day dividers);",
+ " --public the payload a public page would carry (censored, no reveal data); --open opens it",
+ ],
+ docs: [
+ ["`present <project> [--take <take> \\| --cut] [--json] [--public] [--open] [--url <origin>]`",
+ "**present mode**: the cut as slides, navigated like a deck (`/projects/<p>/present`) — prints the address and every slide (its kind, id — a post's `<channel>/<id>`, a clip's id, `section-<n>`, `day-<YYYY-MM-DD>` — date, words and censor counts); `--json` the payload (each post's card as Play draws it and its censor data by kind, each clip's spans, the dividers); `--public` the payload a public page would carry (censored, no reveal data); `--open` opens it; `<address>#<slide id>` opens a slide ([knobs.md](knobs.md#present-mode-the-cut-as-slides-navigated-like-a-deck))"],
+ ],
+ },
+ {
+ cmd: "set",
+ usage: [
+ " umtool set <project> <clip> key=value … a clip's knobs (`key=` clears; umtool/docs/knobs.md):",
+ " claim.at (a source second: the stamp lands, the count steps) claim.hold claim.stamp",
+ " claim.count claim.label (the first mark's, or --mark <id>'s) · marks: mark.add=<verdict>[@<sec>]",
+ " mark.remove=<id> mark.verdict=<verdict> marks=<json> (≤ 8, each its own stamp and count)",
+ " · audio.offset (ms, + later) audio.gain (dB) audio.fadeIn audio.fadeOut",
+ " · hideModules=diet,streak (those modules hidden over the entry's span; any entry)",
+ " · shelfNote='words' (a line on the shelf over the entry's span; any entry)",
+ " --take <t>: the entry knobs into the take's patch, the project's manifest untouched",
+ ],
+ docs: [
+ ["`set <project> <clip> key=value …`",
+ "a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`, its picture's **blur** `blur.on=true` `blur.caption=…` `blur.strength` `blur.from` `blur.to` (`blur.on=` clears it; [knobs.md](knobs.md#a-clips-picture-blurred)), its **effects** `fx.zoom=<json>` `fx.receipts=<json>` `fx.punch=…` `fx.quote` `fx.punchIn=<json>` `fx.speakers=<json>` (`fx=<json>` all of them, `fx=` clears them; a shot is a file in the project; [knobs.md](knobs.md#effects)); `key=` clears one ([knobs.md](knobs.md#marks))"],
+ ],
+ },
+ {
+ cmd: "intro",
+ usage: [
+ " umtool intro <project> [key=value …] [--off] [--json] THE INTRO the cut opens on (render.intro): prints it,",
+ " what the cut opens with and each version's on/off; key=value writes it (style seconds mark sound",
+ " site title lines …; `key=` clears; a new one starts as boot-dark); --off takes it off;",
+ " --take <t> --off|--on: that version opens on no intro (its patch's render.intro: null) or the cut's",
+ ],
+ docs: [
+ ["`intro <project> [key=value …] [--off] [--json]` · `intro <project> --take <take> --off\\|--on`",
+ "**the intro** the cut opens on (`render.intro`): with no key, prints it as written, what the cut opens with (a `title-card`'s words resolved) and each version's on/off; `key=value` writes it through the look writer (`style` `seconds` 3.5–8 `mark` `ground` `sound` (`false` silent) `site` `title` `lines` (`a\\|b`, ≤ 3) and the brand's keys; `key=` clears one; a new intro starts as `boot-dark`); `--off` takes it off the cut; `--take <t> --off` that version opens on no intro (its patch's `render.intro: null`), `--on` on the cut's again. **Exit 1** on a value the build refuses ([knobs.md](knobs.md#the-intro-played-and-edited))"],
+ ],
+ },
+ {
+ cmd: "look",
+ usage: [
+ " umtool look <project> key=value … the cut's knobs: factcheck.stamp.scale|motion|opacity|seconds,",
+ " factcheck.verdicts.<V>.stampLabel|label|color, deck.markers=<json>, deck.markerLayout,",
+ " variants=<json>, and the look's keys (transition=0.3, …)",
+ ],
+ docs: [
+ ["`look <project> key=value … [--unset render.<key>]…`",
+ "the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\\|label\\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys — `mode=basic\\|deck` (the footage alone, [knobs.md](knobs.md#basic-output-the-footage-alone)) and `basic=<json>` (its fades) among them ([knobs.md](knobs.md)) **The deck on, legacy keys off** (`updateRenderKeys`, one write, an undo point `revisions/…auto-render-keys…` first): `chrome.layout=deck` turns the deck on (render.chrome created when the cut has none: engine hyperframes, an empty deck), `--unset render.<key>` (repeatable) drops a legacy render key -- only `rail` `chromeEngine` `railEngine` `chromeRegions` `claimSchedule` `wordmark` `title` `finale` `cut`; the deck beside the old rail is refused in the build's words unless the same command drops it; deck.* keys in the same command land after the chrome exists. Another key named: **exit 2**"],
+ ],
+ },
+ {
+ cmd: "migrate",
+ usage: [
+ " umtool migrate <project> [--dry-run] [--json] move the manifest into the video modules' homes",
+ " (the fact-check verdicts and tally become deck.counter's series); renders the same",
+ ],
+ docs: [
+ ],
+ },
+ {
+ cmd: "variants",
+ usage: [
+ " umtool variants <project> [--take <t>] [--list] [--json] make the encode ladder of a build (render.variants);",
+ " --list: what was made, and the build's sync report (each clip's lag, past a frame flagged)",
+ ],
+ docs: [
+ ["`variants <project> [--take <t>] [--list] [--json]`",
+ "**Make variants**: the encode ladder of the build (or of a take's); `--list` what was made and the build's sync report, each clip's lag (past a frame flagged) ([knobs.md](knobs.md))"],
+ ],
+ },
+ {
+ cmd: "corrections",
+ usage: [
+ " umtool corrections <project> what the report got wrong + the walk's coverage",
+ ],
+ docs: [
+ ["`corrections <project>`",
+ "what the report got wrong (the clip bench's sixth field) and the walk's coverage, as markdown for the next pass"],
+ ],
+ },
+ {
+ cmd: "build",
+ usage: [
+ " umtool build <project> [--preset preview|fast|final] [--only ID]",
+ " --run: the app's build job (UMTOOL_URL, else http://localhost:3050; --url), followed here;",
+ " Ctrl-C cancels it; --replace stamps a newer deliverable aside",
+ ],
+ docs: [
+ ["`build <project> [--preset preview\\|fast\\|final] [--only ID]`",
+ "**prints** the chain"],
+ ["`build <project> --run [--url URL] [--replace] [--preset P] [--only ID] [--skip-fetch]`",
+ "**runs** it as the app's build job (POST `/api/report/build` on `--url`, else `UMTOOL_URL`, else `http://localhost:3050`), prints its log as it grows, **Ctrl-C** cancels the job (twice leaves it running); `--replace` stamps a deliverable newer than the manifest aside; exit 1 unless the job is done (release 36)"],
+ ],
+ },
+ {
+ cmd: "chain",
+ usage: [
+ " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M] [--deck]]",
+ " an article iteration's pipeline, one step a process: {chainSteps}",
+ " (resumes at the first step not done; --dry prints it; the project is <root>/<article>/i<n>/)",
+ " --draft-all (Draft everything): {draftAllSteps} —",
+ " each draft a report-draft job on --model (else its route); a draft that fails does not stop it;",
+ " --deck adds a step before the flips: the minimal on-screen deck on a cut with none",
+ ],
+ docs: [
+ ["`chain <article> <n> [--from <step>] [--dry] [--final] [--draft-all [--model M]]`",
+ "an iteration to a video: the Iterations tab's **Make the video** (`--draft-all`: Draft everything)"],
+ ],
+ },
+ {
+ cmd: "index",
+ usage: [
+ " umtool index [--rebuild] [--prune] [--since MS] [--json]",
+ ],
+ docs: [
+ ["`index [--rebuild] [--prune] [--since MS] [--json]`",
+ "the cache"],
+ ],
+ },
+ {
+ cmd: "new",
+ usage: [
+ " umtool new <slug> [--from <report.md>|<share URL>|<channel>/<id>] [--site-origin URL] [--seed chapters|frames]",
+ " <folder>/<slug>, or --folder <folder>: the project in a folder of the reports tree (its id",
+ " <folder>/<slug>, routed /projects/<folder>/<slug>) — a spin-off beside its parent",
+ " --seed frames: a draft supercut from the video's frame scan (pnpm ops frame-scan) — the events",
+ " ranked (scoops, milestones, swings, pots, level-ups) into --target <seconds> (default 240), the",
+ " deck on with the stats region drawing frameScan.overlay over each clip",
+ " --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>]: every time",
+ " the phrase was said in those channels' transcripts, chronological, cut from the --prefer",
+ " channel's copy where it has one (a twin by date and duration); a context matching --exclude",
+ " is left out; the scan beside the manifest as phrase-scan.json; --max N keeps N instances",
+ " spread across the years in proportion (the rest: phrase-scan.json \"skippedByCap\")",
+ " --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO|auto [--segment sN]] [--no-analyze]: the clip finder on a long",
+ " 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",
+ ],
+ docs: [
+ ["`new <slug> [--from <report.md>\\|<share URL>\\|<channel>/<id>] [--site-origin URL] [--seed chapters\\|frames [--target S]]` · `new <folder>/<slug> …` · `new <slug> --folder <folder> …` · `new <slug> --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]` · `new <slug> --seed reactions --from <channel>/<id> [--target S] [--laugh-min X] [--scope FROM:TO\\|auto [--segment sN]] [--no-analyze]`",
+ "scaffold; `<folder>/<slug>` (or `--folder`) makes it in a folder of the reports tree — its id `<folder>/<slug>`, routed `/projects/<folder>/<slug>` (a spin-off beside its parent); a folder that is itself a project, the reserved `at`, or one past the walk's four levels is refused"],
+ ["`new <slug> --from-posts <channel> [--channel <more>…] [--since D] [--until D] [--own] [--with-media] [--replies …] [--order …] [--limit N]`",
+ "a **posts reel**: the scaffold with the deck on (no `siteOrigin`: each post's QR opens the post, `deck.qr.links: \"original\"`), then `posts reel` with the same filters"],
+ ],
+ },
+ {
+ cmd: "doctor",
+ usage: [
+ " 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",
+ ],
+ docs: [
+ ["`doctor [--json]`",
+ "which tools are on this machine and where the roots are; **exit 1** if the report pipeline is missing one, or `UMTOOL_MEDIA_DIR` is set and not there"],
+ ],
+ },
+ {
+ cmd: "storage",
+ usage: [
+ " umtool storage [<project>] where each project's out/ lives (dir, link, DANGLING)",
+ " umtool storage move-out|move-back <project>|--all [--dry-run]",
+ " umtool storage deliverables <project> --to media|local [--dry-run] clips/ + share-*/, then the switch",
+ " out/ to the media root (UMTOOL_MEDIA_DIR) and back; run when nothing is building",
+ ],
+ docs: [
+ ["`storage [<project>] [--json]`",
+ "where each project's `out/` lives: dir, link, DANGLING, none — and a report's deliverables (`clips/`, `share-*/`) and its switch"],
+ ["`storage move-out\\|move-back <project>\\|--all [--dry-run] [--json]`",
+ "`out/` to the media root (a link left behind) and back — copied, mirrored, verified first; run when nothing is building"],
+ ["`storage deliverables <project> --to media\\|local [--dry-run] [--json]`",
+ "`clips/` and every `share-*/` to the media root and back, then `storage.deliverables` in the manifest; refused while a build step, a cut or a share batch (by `--project` id, name or directory, as the app starts them) or the report's own scripts run in the project — a hand-run command that is none of these is not seen; **exit 1** on any failure (the switch is then left as it was)"],
+ ],
+ },
+ {
+ cmd: "snapshot",
+ usage: [
+ " umtool snapshot <project> [--label L] copy the manifest into revisions/",
+ ],
+ docs: [
+ ["`snapshot <project> [--label L]`",
+ "copy the manifest into `revisions/`"],
+ ],
+ },
+ {
+ cmd: "diff",
+ usage: [
+ " umtool diff <project> <snapshot> what changed since that snapshot",
+ ],
+ docs: [
+ ["`diff <project> <snapshot>`",
+ "added / removed / moved / window / retyped, by entry id"],
+ ],
+ },
+ {
+ cmd: "export",
+ usage: [
+ " umtool export <project> --format toc-bbcode|toc-markdown|description|chapters [--variant V] [--first TITLE]",
+ " umtool export <project> <clip> [--context N | --raw [--from S --to S]] [--fetch] [--take T] [--open] one clip,",
+ " clean, into <project>/exports/: the cut's edges, its gaps out, its mute; --context N what the cut",
+ " plays ± N s; --raw the whole fetched window, or a span (the full exchange), as recorded; --fetch",
+ " asks the editor first for what that needs; in the heavy slot; --open shows it",
+ ],
+ docs: [
+ ["`export <project> --format toc-bbcode\\|toc-markdown\\|description\\|chapters [--variant V] [--first TITLE]`",
+ "the posting artifacts, from the build's chapter offsets. A deck with markers: `chapters` are its top-level sections (subsections left out) at the second each section's first segment starts, YouTube's rules kept (0:00 first, each ≥ 10 s, at least three; what was merged is said on stderr); the opening is titled `deck.sectionTitle.first`, or `--first TITLE`, else the first section takes 0:00"],
+ ["`export <project> <clip> [--take T] [--open] [--json]` · `--context N` · `--raw [--from S --to S]` · `--fetch` · `--progress ndjson`",
+ "**one clip, clean** (no deck) into `<project>/exports/` as `<clip>[-ctx<N>\\|-raw[-<from>-<to>]]-<date>-<words>.mp4`: as the cut plays it (its edges, gaps out, its mute); `--context N` what the cut plays ± N s (1–120), as recorded; `--raw` the fetched window, or `--from/--to` a span (the full exchange), as recorded. In the heavy slot (a 600 MB estimate). `--fetch` asks the editor first (fetch-via-editor, the bench's path) for what a context or raw export needs that is not on disk; without it nothing is fetched. `--progress ndjson`: one `export` event (the app's export job reads it) ([knobs.md](knobs.md#export-one-clip))"],
+ ],
+ },
+ {
+ cmd: "check-sources",
+ usage: [
+ " umtool check-sources [<project>…] prints the re-check chain (never-checked/old when no args)",
+ ],
+ docs: [
+ ["`check-sources [<project>…]`",
+ "**prints** the re-check chain; with no args, the never-checked and >30 d projects"],
+ ],
+ },
+ {
+ cmd: "notes",
+ usage: [
+ " umtool notes [<site>/<report>|<project>|--all] the operator's notes, as markdown (open ones)",
+ " umtool notes reply <id> \"<text>\" [--resolve] answer one; resolve | wontfix | reopen <id>",
+ ],
+ docs: [
+ ["`notes …`",
+ "operator notes: list, read, reply, resolve ([notes.md](notes.md))"],
+ ],
+ },
+ {
+ cmd: "modules",
+ usage: [
+ " umtool modules list | apply <project> [--config F] [--dry-run | --take <id> [--at S --dur S | --full] …]",
+ " a module-config.json onto the cut (writers), or as a take's patch",
+ ],
+ docs: [
+ ["`modules list [--json]` · `modules apply <project> [--config FILE] [--dry-run] [--json]` · `modules apply <project> [--config FILE] --take <id> [--label L] [--at S --dur S \\| --full] [--quick] [--force] [--from TAKE] [--keep-frames] [--patch-out FILE]`",
+ "the **video modules** (release 39): `list` every module, its kind, slot and where its settings live; `apply` maps the project's `module-config.json` (the modules a video wants, in MODULES-DESIGN's vocabulary) into the manifest's homes (`report-to-video/modules/config-loader.mjs`) — the preset, the deck's subtitle and QR, the counter's series and each clip's marks, the stamps, the rail's markers, the chapters, the pairs, the status ledger, the intro, the finale — and lists every field with no home, by path. Without `--take` the manifest is rewritten through `replaceManifest` (a snapshot first); with `--take` it is that take's patch (`takes/<id>.modules-patch.json`, or `--patch-out`) and the take is made from it as `take` makes one, the manifest untouched. **Exit 1** when the result would not build (the build's sentences) ([knobs.md](knobs.md#look-presets))"],
+ ],
+ },
+ {
+ cmd: "preset",
+ usage: [
+ " umtool preset list | show <name> | save <name> --from <project> | apply <name|none> <project>",
+ " the look presets (preset → manifest → style → take patch)",
+ ],
+ docs: [
+ ["`preset list [--json]` · `preset show <name> [--json]` · `preset save <name> --from <project> [--description D] [--force]` · `preset apply <name\\|none> <project> [--replace] [--json]`",
+ "the **look presets** (`umtool/presets/<name>.json`, or `UMTOOL_PRESETS_DIR`; built in: `plain-deck` `huck-deck` `ember-deck` `archive-catalog` `basic`): a render block a manifest stands on (`\"preset\": \"<name>\"`), laid under it — preset → manifest → style → take patch. `save` keeps a project's look and leaves its content out; `apply` names the preset on the cut through `updatePreset` (nothing copied in), refused when the cut over it would not build (a basic cut's chrome is not checked); `--replace` also clears the manifest's own value of every key the preset sets, after an undo point (`revisions/…-auto-before-preset-replace`), and prints what went ([knobs.md](knobs.md#look-presets))"],
+ ],
+ },
+ {
+ cmd: "take",
+ usage: [
+ " umtool take <project> --id <id> --label L [--style S] [--patch F | --set p=v …] [--at S --dur S | --full]",
+ " one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force;",
+ " --from TAKE reuses that take's segments, chrome and batches; --keep-frames keeps the chrome)",
+ " --draft (--no-render): record the take, render nothing -- walk it, edit it, render it later",
+ " (`umtool take <p> --id <id> --full` renders a draft from its stored patch)",
+ " --priority: render mode for the take's lifetime -- every other heavy job waits for it, the",
+ " editor's transcription and download lanes are held; all let go at its end, failure or signal",
+ " --draft --from TAKE: a draft that starts from that take's patch (its timeline its own from then on)",
+ " umtool take <project> --id <id> --import-item <project>:<item>[,<item>…] [--after <entry>|--before <entry>]",
+ " [--as <id>] [--dry-run] [--json] items of ANOTHER project cloned into the take (its patch), their",
+ " narration and pick kept, the files they name hard-linked into this project; again: updated or unchanged",
+ ],
+ docs: [
+ ],
+ },
+ {
+ cmd: "lint",
+ usage: [
+ " umtool lint <project> [--take <id>] [--variant sourced|full] [--final] [--json] the manifest lint a build runs",
+ " first, on the project's manifest or a take's (its patches applied), and the files its post items",
+ " name (a picked read, an attachment not in the project: an error) -- exit 0 clean, 1 an error",
+ ],
+ docs: [
+ ["`lint <project> [--take <take>] [--variant sourced\\|full] [--final] [--json]`",
+ "**the manifest lint** (`report-to-video/lint.mjs`, what a build runs before it renders a frame) from umtool: the project's manifest, or with `--take` the take's (its patches applied, written beside the project's manifest for the lint as its render's is, then removed) -- plus the **files its post items name**: a picked read, an attachment or a context post's media not in the project is an ERROR, another kept take a warning. Run it after an import and before queueing the render. `--json`: `{ok, entries, errors, warnings}`. **Exit 0 no error · 1 an error · 2 usage**"],
+ ],
+ },
+ {
+ cmd: "take",
+ usage: [
+ " umtool take <project> --id <id> --promote [--anyway] make this the cut: the take's patch applied to the",
+ " manifest, one undo point (revisions/…-auto-before-promote-take)",
+ " umtool take status <project> [--id <id>] [--json] [--log] [--tail N] the take's render record (every render",
+ " writes takes/<id>/render.json and the full render.log): exit 0 done, 3 queued/waiting/running, 1 failed",
+ ],
+ docs: [
+ ["`take <project> --id <id> --label L [--group G] [--kind similar\\|different] [--summary S] [--style NAME] [--patch FILE \\| --patch-json JSON \\| --set path=value …] [--effect NAME] [--at S --dur S \\| --full] [--quick] [--force] [--progress ndjson]`",
+ "one **take**: the manifest with a montage style's patch, then an overlay effect's (`--effect`, release 35), then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes))"],
+ ["`take <project> --id <id> --label L [--patch F \\| …] --draft` (`--no-render`) · `take <project> --id <id> [--full \\| --at S --dur S]` · `take <project> --id <id> --rebuild [--full \\| --at S --dur S]` · `take <project> --id <id> --promote [--anyway] [--json]`",
+ "a **draft** take: recorded with nothing rendered, to be walked first; a draft named with no patch flags is rendered from its stored (walked) patch, and `--rebuild` takes a window flag; **make it the cut**: the take's patch applied to the manifest now, one undo point (`revisions/…-auto-before-promote-take`), refused (exit 1) when its timeline would replace a cut that changed since, until `--anyway` ([report-video.md](report-video.md#walking-a-take-drafts-edits-into-the-take-and-making-it-the-cut))"],
+ ["`take <project> --id <id> … --uncensored` · build-video `--uncensored`",
+ "the **uncensored cut** ([knobs.md](knobs.md#the-slur-filter-slurs-masked-in-what-is-published-off-for-the-uncensored-cut)): the same cut with the post items' slur filter off -- `render.posts.slurs.on: false` in the take's patch (a `--rebuild` keeps it; a censored take is not rebuilt uncensored, **exit 2**: make a take of its own), its label gains \"(uncensored)\", take.json's `slurs` records `censored` or `uncensored`. The redaction of private words and censored attachments stay on"],
+ ["`take <project> --id <id> --draft --from <take> [--label L] [--patch F \\| --patch-json J \\| --set p=v …]`",
+ "a **draft made from another take**: that take's style and patch (a `--patch` merged over it), its label \"<that label> (from <take>)\" unless `--label`, nothing rendered; its timeline is its own from then on, and its render's `--from` (segments reused) is a separate flag of the render ([take-scoped edits](#edit-a-take-not-the-project-items-from-other-projects-and-take-scoped-edits))"],
+ ["`take <project> --id <id> --preview [--from <take>] [--at S --dur S \\| --full] [--priority] [--json]`",
+ "the take's **preview**: the take as stored (a draft too, from its walked patch) composed exactly as its render is -- the same 1920×1080 layout, segments, chrome frames and sound -- with only its final picture encoded smaller and faster (`render.preview`: 1280×720, x264 veryfast, crf 26) into `takes/<id>/out/<slug>.preview.mp4`; its build, schedule and record (`render.json`, `render.log`) in `takes/<id>/out/preview/`. The full render (`preview.mp4`, `out/<slug>.mp4`, `out/sourced/`, `take.json`, `render.json`) is never touched. Reuses this take's own full render, and `--from`'s full render and preview ([report-video.md](report-video.md#fast-feedback-preview-and-changes-renders), [knobs.md](knobs.md#fast-feedback-a-preview-and-a-reel-of-the-changes))"],
+ ["`take <project> --id <id> --changes [--from <take>] [--pad 3] [--no-preview] [--priority] [--json]`",
+ "the take's **changes reel**: only what changed against `--from` (default: the take's own `from`, or the take a draft was made from) -- each added, re-read, re-picked, re-voiced, trimmed, held, fx'd, … item with a neighbour either side, rendered in one build (`takes/<id>/out/changes/`), cut to the item ± `--pad` s, a label burned in (`21:19 · p-2116831815466193102 · re-voiced`: its time in the FULL cut), joined into `takes/<id>/out/<slug>.changes.mp4`; a removed item shows as the join it leaves. `takes/<id>/changes.json` lists the pieces with their full-cut times and how exact they are (`times.basis`: `measured` -- the base's measured schedule plus the changed items' measured lengths -- or `estimate`). Preview quality unless `--no-preview`. Nothing changed: no reel, and the list says so"],
+ ["`take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \\| --before <entry>] [--as <id>] [--dry-run] [--json]`",
+ "**items of another project into a take** (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\\|updated\\|unchanged\\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage**"],
+ ["`take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \\| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]`",
+ "**render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, \"Render mode\")"],
+ ["`take status <project> [--id <take>] [--json] [--log] [--tail N]`",
+ "a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare \"exited 1\") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A \"running\" whose process is gone reads **failed** (\"the render process is gone\"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render"],
+ ],
+ },
+ {
+ cmd: "queue",
+ usage: [
+ " umtool queue add [--after <qid>|last] [--label T] -- <umtool subcommand argv…> a step the umtool APP runs, in",
+ " order, one at a time (it survives the session); prints the qid. ls [--all] | status <qid> | wait <qid>",
+ " [--timeout S] | log <qid> | cancel <qid> | retry <qid> [--json]; status exits 0 done, 3 going, 1 failed",
+ ],
+ docs: [
+ ["`queue add [--after <qid>\\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>`",
+ "a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself"],
+ ["`queue ls [--all] [--json]` · `queue status <qid> [--json]` · `queue wait <qid> [--timeout <s>]` · `queue log <qid> [--tail N]` · `queue cancel <qid>` · `queue retry <qid>`",
+ "the queue: `ls` the runner (is the app running it) and the steps not finished or finished in the last 24 h; `status` one step (**exit 0 done · 3 queued or running · 1 failed, blocked or cancelled**); `wait` the same after up to `<s>` seconds (default 90); `log` its FULL log (`logs/<qid>.log`; earlier attempts kept as `<qid>.<n>.log`); `cancel` a queued or blocked step at once, a running one stopped (its process group); `retry` a failed or cancelled step back in the queue with every step blocked behind it. A step that was running when the app died reads **failed** (\"the step's process is gone\"), its log kept — it is never re-run on its own"],
+ ],
+ },
+ {
+ cmd: "jobs",
+ usage: [
+ " umtool jobs [--json] every running and recent take render and queue step, across projects, and the app's jobs",
+ ],
+ docs: [
+ ["`jobs [--json]`",
+ "every running and recent **take render** across projects (their records), every queue step not finished or finished in the last 24 h, and the umtool app's own jobs (`GET /api/jobs` at `--url` / `UMTOOL_URL`, when it answers). The page is **/jobs** (the rail's *Running* links it)"],
+ ],
+ },
+ {
+ cmd: "takes",
+ usage: [
+ " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]",
+ " | ls <project> | relabel <project> <take> <label…> | supersede <project> <take> [--by <take>] [--clear]",
+ " | delete <project> <take> [--dry-run] [--force] take housekeeping: a label fixed, a take folded away",
+ " as superseded, a take deleted -- refused while a render names it",
+ ],
+ docs: [
+ ["`takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \\| --full]`",
+ "a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed"],
+ ["`takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--pin \\| --unpin] [--json]`",
+ "the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway`; `--pin` keeps the pick when newer takes are built (each whole-cut take of the manifest is otherwise its group's pick once built), `--unpin` lets go ([report-video.md](report-video.md#takes-alternative-renders-judged-side-by-side))"],
+ ["`takes ls <project> [--json]` · `takes relabel <project> <take> <label…>` · `takes supersede <project> <take> [--by <take>]` · `takes supersede <project> <take> --clear` · `takes delete <project> <take> [--dry-run] [--force]`",
+ "**take housekeeping** (the Takes page's ✎, **Mark superseded**, **Delete take**): first the working cut's line (`Latest: draft-22 · 28:03 · +N edits since`, and the edits in words; `--json`: `working`), then the takes with latest / picked (pinned) / superseded / RENDERING; a label fixed in `take.json` (an undo point of the take's own); a take folded away as superseded (verdicts.json, nothing deleted); a take deleted. Relabel and delete are refused (**exit 1**) while the take renders or a live render is made from it ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare))"],
+ ["`takes save <project> [--label L] [--force] [--json]` · `takes open <project> <take> [--json]` · `takes freeze <project> [<take>… \\| --all] [--apply] [--json]`",
+ "**the working draft and its saved versions** (Play's **Save version** and **Open in draft**): `save` freezes the draft (`video.manifest.json`) as the next `v<N>` — `takes/v<N>/base.manifest.json` byte for byte, `take.json` `version: true` — and names it the draft's parent (`takes/draft.json`); nothing is saved when the draft has no edits since its parent, unless `--force`. `open` copies a version into the draft — the draft saved first as the next `v<N>` when it has edits since its parent — with one undo point (`umtool timeline <p> undo` puts the draft and its parent back); a legacy take with its own timeline opens by its patch over the draft (as `take --promote`), another legacy take as the manifest it was rendered from (as `takes pick`). Neither touches the pick or its pin. `freeze` gives legacy takes a frozen base (the manifest each was rendered from, else the draft now) — a dry run unless `--apply`, each take's difference from how it resolves today said. Version ids are `v1`, `v2`, … — one above every `v<N>` directory under `takes/`, never reused ([knobs.md](knobs.md#the-working-draft-and-saved-versions))"],
+ ["`takes cancel <project> <take> [--json]` · `takes fork <project> <take> [--name N] [--json]` · `takes compare <project> <a> <b> [--json]`",
+ "**take housekeeping, the rest**: **Cancel render** (asked of the process rendering it, which stops its render's process group, marks the take cancelled and lets render mode go; exit 1 when it has not stopped); **Fork as variant** (a project beside this one, default `v-<take>`: the take's manifest, `variant.json`, the parent's media and assets linked, the take in it); two takes **side by side** (`<take>` or `<project>:<take>`: the facts, the cut's changes A → B, the look's differences) ([knobs.md](knobs.md#takes-relabel-supersede-cancel-delete-fork-as-variant-compare))"],
+ ],
+ },
+ {
+ cmd: "render-mode",
+ usage: [
+ " umtool render-mode on [--for 90m] [--note T] | off [--force] | status [--json] render mode: a render the",
+ " operator waits for gets the machine (other heavy jobs wait; the editor's transcription and",
+ " download lanes held); `on` is a window for a chain of renders (default 2h)",
+ " on [--for D] [--print-token] -- <cmd …>: held while <cmd> runs (its env carries the token,",
+ " the hold is its pid), released when it exits -- the form for a script; --print-token prints",
+ " the token alone on stdout",
+ ],
+ docs: [
+ ],
+ },
+ {
+ cmd: "pool",
+ usage: [
+ " umtool pool [stats] [--since 7d] | prune [--max-gb N] [--dry-run] | verify [--sample N | --all] [--json]",
+ " the render pool: every post, clip, chunk, sound and chrome frame a build made, by its key,",
+ " hard-linked into any take that needs it again (UMTOOL_RENDER_POOL=0 off; _MAX_GB its cap)",
+ ],
+ docs: [
+ ],
+ },
+ {
+ cmd: "trailer",
+ usage: [
+ " umtool trailer <project> --take <t> (--beats F | --beats-json J) [--intro] [--finale S] [--xfade 0.3] [--out NAME]",
+ " a trailer cut from the take's finished master: the master's own frames, so the deck shows the",
+ " whole timeline; beats are clip source seconds or master seconds ([--dry-run] the mapping only)",
+ " --reel <name> [--take <t>]: a beat reel's beats and settings (promo/<name>-beats.json),",
+ " written to takes/<t>/out/<slug>.<name>.mp4; no --take: its pinned, last-cut or latest master",
+ " --vertical [--layout reframe] [the vertical flags]: the reel 9:16 (umtool vertical --reel)",
+ ],
+ docs: [
+ ["`trailer <project> --take <t> (--beats FILE \\| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--no-snap] [--out NAME] [--dry-run] [--json]`",
+ "a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, each clip beat's end moved forward into the next pause (through its sentence when one ends within 1 s) and its start back into the one before, so the crossfade lands in quiet, each move said (`--no-snap`: the edges as written), crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) · `--reel <name> [--take <t>]`: a **beat reel** -- its own beats file (`promo/<name>-beats.json`), crossfade, intro (one rendered for the reel when the master has none, or the reel's own) and outro card (the title, the call to action, an image, the site's name; faded in from the last beat, held to the end), written to `<slug>.<name>.mp4`; no `--take`: its pinned take, else the one it was last cut from, else the latest finished master ([report-video.md](report-video.md#beat-reels))"],
+ ],
+ },
+ {
+ cmd: "vertical",
+ usage: [
+ " umtool vertical <project> --take <t> (--reel R | --beats F | --items a,b) [--clip full|framed|quote]",
+ " [--post card|stack|media] [--side split|overlay] [--hook title|section|<copy>] [--reframe] [--json]",
+ " a vertical short (1080x1920, -14 LUFS) of the take's items: each clip cut again in its layout,",
+ " each post drawn in a portrait box; --reframe recomposes the finished 16:9 master instead",
+ ],
+ docs: [
+ ],
+ },
+ {
+ cmd: "trailer-beats",
+ usage: [
+ " umtool trailer-beats <project> [ls] | add <clip> [<from>-<to>] [--at N] [--label L] | add-raw <at> <dur> | set <n> <from>-<to>",
+ " | remove <n> | move <n> --to <m> | order | limit <s|m:ss|x|instagram|shorts|tiktok> | xfade <s> | intro on|off",
+ " | candidates [--add] the trailer's beats (promo/trailer-beats.json, the Trailer page's file): each",
+ " beat's length, the running length against the platform limit (X 2:20), beats outside their clip",
+ " | verdict <n> confirmed|note|clear | title T | take T | undo | reels | new-reel <name> [--from R]",
+ " --reel <name>: that beat reel (promo/<name>-beats.json); every write is an undo point",
+ ],
+ docs: [
+ ["`trailer-beats <project> [ls] [--json]` · `add <clip> [<from>-<to>] [--at N] [--label L]` · `add-raw <at> <dur>` · `set <n> <from>-<to>` · `remove <n>` · `move <n> --to <m>` · `order` · `limit <s\\|m:ss\\|x\\|instagram\\|shorts\\|tiktok>` · `xfade <s>` · `intro on\\|off\\|'<render.intro JSON>'` · `outro on\\|off\\|none\\|'{title,text,image,seconds}'` · `candidates [--add]` · `verdict <n> confirmed\\|note\\|clear` · `title <text>\\|none` · `take <t>\\|none` · `undo` · `reels [--json]` · `new-reel <name> [--from <reel>] [--title T]` · `gap <n> add <from>-<to>\\|remove <s>\\|clear` · `status [--take <t>] [--json]` · `anchor [<n>…] --take <t>` · `clamp <n>` · `repoint <n> <clip>` · `history [--json]` · `--take <t>` on an edit · `--reel <name>` on any",
+ "**the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads) or another **beat reel's** (`--reel`: `promo/<name>-beats.json`): each beat's length, the running length against the platform limit (X 2:20 by default), beats outside their clip's window, the cut's order, the walk's ★ clips; the reel's own intro and its outro card (`ls`: `· outro 3.5 s`, counted in the length); every write an undo point and a history entry; a beat's gaps (two moments of one clip as one beat of jump cuts); each beat read against the take now -- what it was cut against, what changed (`status`), and the fixes ([knobs.md](knobs.md#the-trailers-beats), [reels track their source](knobs.md#reels-track-their-source))"],
+ ],
+ },
+ {
+ cmd: "tighten",
+ usage: [
+ " umtool tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence (its",
+ " cut's, else the whole ones in its window), each edge into its pause; before -> after; --apply writes",
+ ],
+ docs: [
+ ["`tighten <project> [--json] [--all] [--no-measure]` · `tighten <project> --apply <clip>[,<clip>…]`",
+ "the Cut tab's **Propose tight windows**: each clip to its sentence (the sentences its cut touches, else the whole ones inside its window) and each edge into its pause (the build's measured silences and the gaps between the recording's timed words, ≤ 1 s, inside the cached window) — before → after with the seconds, the clips that would change (`--all`: every clip); prints only. `--apply` writes the named rows through the window writer (the token, the cite that follows the edge); a lock is kept (it is against `resolve-windows`, not a person) ([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause))"],
+ ],
+ },
+ {
+ cmd: "ledger",
+ usage: [
+ " umtool ledger <project> [ls] [--scope S] [--json] | add <id> --date D --scope S --population P [--value V] --scopeBasis \"…\" [--<key> V …] | set <id> --<key> V … [--unset k,k] | rm <id>",
+ " a measure ledger's rows, checked against its ledgerSchema (incl. promise / promise_check, run, retro)",
+ ],
+ docs: [
+ ["`ledger <project> [ls] [--scope S] [--population P] [--json]` · `ledger <project> add <id> --date D --scope S --population P [--value V] --scopeBasis \"…\" [--<key> V …] [--row '{…}']` · `ledger <project> set <id> --<key> V … [--unset k,k]` · `ledger <project> rm <id>`",
+ "a **measure ledger's rows** (`ledgerSchema.kind \"measure\"`), the only writer of them: each row is checked against the schema -- a track, a form (and the promise forms `promise` / `promise_check`), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults `scopeConfidence` read, `valueKind` uttered, `flags` []; `--scopeBasis` is never defaulted), the declared fields, and the instruments' own keys: `run` (a loss claim's run), `retro` (a loss told in the past with no `asOf`: off the odometer), `promise`, `kept`, `due`, `speaker` (another party's key: her rows move none of his numbers), `paidOn`, `outcome` (a `promise_outcome`'s: kept, refunded, withdrawn); the promise forms are `promise`, `promise_check`, `promise_claim`, `promise_outcome`. `rm` refuses a row an entry pins or another row names ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments))"],
+ ],
+ },
+ {
+ cmd: "measure",
+ usage: [
+ " umtool measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]",
+ " the measure slice the instruments draw from: events at their cut seconds, hidden rows, totals",
+ ],
+ docs: [
+ ["`measure <project> [--take <t>] [--scopes a,b] [--scale MIN-MAX] [--as-of YYYY-MM-DD] [--json]`",
+ "the **measure slice** the instruments draw from (`render.chrome.deck.measure`; the flags override it): each row in scope the cut shows at the cut second its figure is said, the hidden rows, and the totals -- the odometer's runs, NET, the goals, the diets, the promises. The take's built `schedule.json` with `--take`, else an estimate; `--json` prints the slice. Reads only ([knobs.md](knobs.md#the-measure-slice-the-weight-instruments))"],
+ ],
+ },
+ {
+ cmd: "rulings",
+ usage: [
+ " umtool rulings <project> [--json] | import [--dry-run] | set <clip> keep|cut|not-him|read-aloud [--reason R] [--match M] | clear <clip>",
+ " the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out",
+ ],
+ docs: [
+ ["`rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\\|key> keep\\|cut\\|not-him\\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\\|key>`",
+ "a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips))"],
+ ],
+ },
+ {
+ cmd: "fetch",
+ usage: [
+ " umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] [--json]",
+ " the clip windows asked of the editor as one fetch-windows batch (one paced job per platform);",
+ " each run recorded in <project>/fetch-runs.json; --refetch <clipId>[,…] / --refetch-video <slug>/<id>",
+ " evict those clips' cached windows first (the editor's evict-clips), then fetch",
+ ],
+ docs: [
+ ["`fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` · `… --take <take>`",
+ "**Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. `--take <take>` asks for a TAKE's clips instead — its manifest as its walk reads it (the project's now with the take's patches; a draft's too, nothing rendered), so a clip only the take has is fetched; the run is recorded with `take`, and `--status --take` follows the take's last run (the cut's never reads a take's). Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins))"],
+ ],
+ },
+ {
+ cmd: "prep",
+ usage: [
+ " umtool prep <project> [--clips a,b] [--wait | --status] [--json]",
+ " what the clip bench makes on a clip's first open (a long recording's excerpt, the waveform),",
+ " made before the walk: queued and run in the background, one clip at a time, in the heavy slot",
+ " (a small declared estimate), under nice/ionice; --wait runs it here; a write or a fetch queues it too",
+ ],
+ docs: [
+ ["`prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` · `… --take <take>`",
+ "**Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). `--take <take>`: a TAKE's clips (the take's walk page has the same button) — its manifest as its walk reads it, a draft's too — with its own status, queue, runner and log under `out/bench-excerpts/takes/<take>/`, so a take's clip that carries the cut's id with other bounds never shares the cut's state; a save on the take's walk queues it. The plan does not depend on the directory it is run from. **Exit 1** when a clip failed (`--wait`)"],
+ ],
+ },
+ {
+ cmd: "prune",
+ usage: [
+ " umtool prune [<project> [--take X] [--anyway] | --all] [--keep N] [--older-than 3d] [--idle-work 3d] [--yes] [--json]",
+ " takes' work files (segments, chrome frames, crossfade batches, encode chunks, the rail's prerail base):",
+ " what each holds (hard links counted by inode), which takes keep theirs and why, what freeing the rest",
+ " gives back; a dry run unless --yes. A take build prunes its project after; a render prunes when disk is",
+ " low. --idle-work D: in a project untouched for D, the newest/picked takes' work goes too",
+ " umtool prune [<project> | --all] --versions [--idle 3d] [--grace 7d] [--idle-work 3d] [--yes] [--json]",
+ " whole SUPERSEDED takes, through `takes delete`: per version line (the id, digits folded:",
+ " draft-# ; letters never: v6c ≠ v6d) the highest built number is kept, older ones while it is",
+ " younger than --grace, and any take picked, judged, rendering, a base, noted on or refused;",
+ " a project touched within --idle, or whose verdicts.json cannot be read, is skipped",
+ ],
+ docs: [
+ ["`prune <project> [--take X[,Y]] [--anyway] [--keep N] [--older-than 3d] [--yes] [--json]` · `prune --all [--keep N] [--older-than 3d] [--yes] [--json]`",
+ "**the takes' work files** (the Takes page's **Free work files**): per take its work — segments, chrome frames, crossfade batches, encode chunks, raw clip copies, `work-from-*` — counted by inode (a file hard-linked into two takes is counted once and freed only when both let it go), what freeing it gives back, or why it is kept: a running build or the take one builds from (never freed), the picked or current take, a pin in `takes/prune.json`, the newest `--keep` (2) of its group, anything modified within `--older-than` (3d), the `--from` bases of those. A dry run unless `--yes`; `--take X --anyway` frees a take the policy keeps. Renders, previews, take.json and manifests are never touched. **Exit 1** when a path could not be removed ([report-video.md](report-video.md#a-takes-work-files-and-pruning-them))"],
+ ],
+ },
+ {
+ cmd: "fallback",
+ usage: [
+ " umtool fallback <project> [--dry-run | --clip <id> … | --restore <clipId>] [--json]",
+ " stand-ins for refused montage windows: the instance's public alternate (YouTube first), on the clip",
+ ],
+ docs: [
+ ["`fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>`",
+ "**stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in"],
+ ],
+ },
+ {
+ cmd: "phrases",
+ usage: [
+ " umtool phrases \"<phrase>\" [\"<phrase>\" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] [--json]",
+ " how often each phrase was said, by year, in one pass (the phrase finder's search)",
+ ],
+ docs: [
+ ["`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"],
+ ],
+ },
+ {
+ cmd: "voice-match",
+ usage: [
+ " umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …] [--instances F] [--dry] [--json]",
+ " a local speaker-similarity score per montage clip (TitaNet-small) -> <project>/voice-match.json",
+ ],
+ docs: [
+ ["`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))"],
+ ],
+ },
+ {
+ cmd: "clips",
+ usage: [
+ " umtool clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params]",
+ " umtool clips propose <project> [--host N] [params] [--dry] | show <project> | segments <project>",
+ " the clip finder: the laugh scan + voices on the recording's sound, then clips proposed",
+ " (setup → reaction → tail) into the manifest (assist: by the assistant) and reactions.json;",
+ " params --target S --laugh-min X --merge-gap S --setup-max S --clip-max S; a clip you edited is never moved",
+ ],
+ docs: [
+ ["`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)"],
+ ],
+ },
+ {
+ cmd: "refresh",
+ usage: [
+ " umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]",
+ " 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",
+ ],
+ docs: [
+ ["`refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]` · `refresh --check [<article>] [--force]`",
+ "the refresh's plan, `--yes` starts it; the daily check now ([refresh.md](refresh.md))"],
+ ],
+ },
+ {
+ cmd: "clip",
+ usage: [
+ " umtool clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--json]",
+ " QUICK CLIP: a basic-mode project (the footage alone), its window asked of the editor, its",
+ " edges snapped to the words (--snap words), rendered as a take; prints the mp4 and its share line",
+ ],
+ docs: [
+ ["`clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]`",
+ "**quick clip**: a basic-mode project (`quick-clips/<slug>`, the footage alone), its window asked of the editor (fetch-windows, followed to its end; Rumble fetched whole), `--snap words` its edges snapped to the words heard (the editor's transcribe op), rendered as the take `clip` (`take <p> --id clip --full`: the heavy slot), then the mp4's path and the share line. `--json`: `{project, output, share: {platform, archive, text}, snapped?}`; `--progress ndjson`: events, the last `quick-clip` (the app's `POST /api/report/quick-clip` job). **Exit 0 · 1 failed (the editor, the render) · 2 usage** ([knobs.md](knobs.md#basic-output-the-footage-alone))"],
+ ],
+ },
+ {
+ cmd: "provenance",
+ usage: [
+ " umtool provenance <project> [ls] | set [--site-origin URL] [--channel-slug S] [--channel \"Name\"] [--json]",
+ " the project's provenance (where its QRs open, the channel its clips are from); \"\" removes one",
+ ],
+ docs: [
+ ["`provenance <project> [ls] [--json]` · `provenance <project> set [--site-origin URL] [--channel-slug S] [--channel \"…\"] [--json]`",
+ "the project's **provenance**: `siteOrigin` (the archive its QRs open), `channelSlug` (a clip with no channel is from it; `check` blocks without it), `channel` (the display name); `\"\"` removes one. One write, one undo point; the Cut tab's Project › Provenance. The link policy is `link-policy` ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"],
+ ],
+ },
+ {
+ cmd: "title",
+ usage: [
+ " umtool title <project> [\"<title>\"] [--subtitle \"…\" | --no-subtitle] [--json] the project's title and subtitle",
+ ],
+ docs: [
+ ["`title <project> [\"<title>\"] [--subtitle \"…\" \\| --no-subtitle] [--json]`",
+ "the project's **title and subtitle** (the manifest's `title`/`subtitle`); no words prints them. One write to the draft, one undo point; the Cut tab's Project › Title ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"],
+ ],
+ },
+ {
+ cmd: "still",
+ usage: [
+ " umtool still <project> <clip> --at <source s> [--take <id>] [--json] | ls a frame of the clip's fetched",
+ " window into shots/ (Play's Still button)",
+ ],
+ docs: [
+ ["`still <project> <clip> --at <source s> [--take <take>] [--json]` · `still <project> ls [--json]`",
+ "a **still at second N**: one frame of the clip's fetched window at that source second into `shots/still-<clip>-<s>s.png` (nothing fetched; the cut not written); `ls` the project's shots. Play's **Still** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"],
+ ],
+ },
+ {
+ cmd: "share",
+ usage: [
+ " umtool share <project> [<clip>] [--take <id>] [--site <id>] [--json] a clip's share line: its platform",
+ " page at the moment and its archive moment (a Rumble folder id mapped to the embed id)",
+ ],
+ docs: [
+ ["`share <project> [<clip>] [--take <t>] [--site <id>] [--json]`",
+ "a clip's **share line** (the clip named, else the first): its platform page at the first second it plays and its archive moment, a Rumble folder id as the embed id the archive serves — the twin of **Copy share line** (`GET /api/report/share-line`). `--json`: `{clip, seconds, platform, archive, text}`"],
+ ],
+ },
+ {
+ cmd: "timeline",
+ 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] [--section N]",
+ " [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S]",
+ " [--cite-url U] a clip, then its attribution, in the manifest's convention (deck: onscreen.title)",
+ " 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 timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo] a take's timeline:",
+ " the writes go into its patch (takes/<id>/take.json), each with an undo point of its own",
+ " umtool timeline <project> teaser-insert [--at start|end | --after <id>] [--id ID] [--beat S] --line \"…\" [--break \"…\"]",
+ " [--hold S] [--line …] | --lines-json <json|@file> a teaser or closing card inserted (default at the end)",
+ ],
+ docs: [
+ ["`timeline <project> teaser-insert [--at start\\|end \\| --after <id> \\| --before <id>] [--id ID] [--beat S] --line \"…\" [--break \"…\"] [--hold S] [--line …] \\| --lines-json <json\\|@file> [--json]`",
+ "a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"],
+ ["`timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\\|@file>` · `undo`",
+ "the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits))"],
+ ["`timeline <project> insert (--to-section N \\| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]`",
+ "a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press))"],
+ ["`timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\\|@file\\|id…>`",
+ "**claim groups** (`groups` beside the timeline; the Cut tab's group bars): runs of clips inside one section making one claim — `ls` by section, each group's id, claim and clips (`--json` with the token); `import` a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`) in ONE write — the cut re-ordered to it, its groups the cut's, the markers following; a file section is the deck section of its name, else the one most of its clips are in; **exit 1** for an id the cut lacks (`--skip-missing`) or a section left with no clip (`--drop-empty` removes its marker); `set` (the clips already together), `label`, `remove` (ungroup), `move` the whole group (before the group at that index, or after one, in its section), `promote` (a level-2 marker at its first clip titled with its claim — the one group edit the render sees; `--label` when the claim is over 24); `order` the named entries in the places they hold (every clip keeping its section). A clip moved out of its group's run leaves it; moved alone into the middle of one, it joins. Every write an undo point (`undo`) ([knobs.md](knobs.md#claim-groups-runs-of-clips-that-make-one-claim))"],
+ ["`timeline <project> --take <take> [ls \\| move <id> --to <index> \\| remove <id> \\| undo \\| insert <spec> --after <id>\\|-]`",
+ "a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it. `insert` puts a clip (`<channel>/<video>@<start>-<end>`) into the take only (`takeEdit.mjs insertTakeEntry`) -- the app's **+ Add a clip to <take> only** on the take walk page, and Play's **+ Add a clip here** on a take with its own timeline"],
+ ["`timeline <project> sections [--json]` · `section-move <id>… --to-section N [--start]` · `section-add --after <id> [--label L] [--color C]` · `section-boundary <marker> --after <id>` · `section-remove <marker>` · `section-set <marker> [--label L] [--color C]` · `split <id> <second>` · `flash-forward <id> <from>-<to> (--after <id\\|-> \\| --to-section N [--start]) [--move] [--quote Q] [--id ID]`",
+ "**sections as sections** (the deck's markers; the Cut tab's section bars and row menus): clips moved to a section with every marker following, a section opened, a boundary moved, relabelled, removed — no section emptied, no boundary crossed (**exit 1**) — and every take patch in step synced; **split** (each half's quote from the words, the second half's cite and QR at its second, a marker after the clip following its second half); **flash-forward** a tight copy of a span elsewhere with the clip's attribution and locks, as `repeatOf` the clip (`--move`: out of the clip) ([knobs.md](knobs.md#sections-split-and-flash-forward-editing-the-cut))"],
+ ["`timeline <project> threads [--json]` · `timeline <project> threads --write [--conversation <id>]`",
+ "**the cut's conversations** ([report-video.md](report-video.md#thread-reads), `post-conversation.mjs`): each tree of two post items or more — its root, its items' places, whether they play as one run (one scene) or are split by other entries, a reply placed before the post it answers, an item re-reading a post its run already read (with `posts set-item <p> <item> thread.parent.<i>=context`). `--write` gathers each (or the one holding `<id>`: its root, a post, an item, a `thread.group` name) at its first item's place in TREE order (a manual thread: in DATE order) — a post after what it answers, sibling branches by date, each depth first — in ONE write (one undo point); never across a section boundary (gathered within each section, and said)"],
+ ["`timeline <project> [--take <t>] add-video <src> [--from S] [--to S] [--fit contain\\|cover] [--bass dB] [--gain dB] [--enter cut\\|<out>,<in>] [--hold S] [--title T] [--id ID] [--after <id>\\|-] [--dry-run] [--json]` · `timeline <project> [--take <t>] set-video <id> <key>=<value>…`",
+ "**a video entry** ([report-video.md](report-video.md#a-video-entry)): a file of the project (`src`, relative; probed, its `fileSeconds` written) played FULL FRAME with its own sound, nothing drawn over it, at the end unless `--after` (`-`: the start), into the cut or the take's timeline only (`--take`, an undo point of the take's); `set-video` sets `from= to= fit= audio.bass= audio.gain= enter=cut\\|<out>,<in> enter.out= enter.in= holdLast= deck=hidden\\|shown title= note= src=` (`key=` clears). `--dry-run`: the entry and its place, nothing written. `--json`: `{ok, op, take?, inserted\\|updated {id, at, entry}, revision?}`. **Exit 0 · 1 refused (no such file, take or entry; the build would not take it) · 2 usage**"],
+ ["`timeline <project> insert (--after <id\\|-> \\| --to-section N \\| --group G) post:<channel>/<postId> [--id ID]`",
+ "**one post item** among the cut's entries, made as `posts reel` makes one"],
+ ["`timeline <project> insert (--after <id\\|-> \\| --to-section N \\| --group G) post-json:<json>\\|post-json:@<file> [--id ID]`",
+ "**a post item made by hand** — a post no archive holds (one kept only as a picture): `{post: \"<channel>/<postId>\", author, handle, date, text, media: [\"posts-media/…\"], parents?, quoted?, subjects?, redact?}`, its media measured, its id `p-<postId>` unless `--id`; refused in the build's words (**exit 1**). Its avatar: `posts avatar <project> <handle> <file>`"],
+ ],
+ },
+ {
+ cmd: "scenes",
+ usage: [
+ " 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)",
+ ],
+ docs: [
+ ["`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)"],
+ ],
+ },
+ {
+ cmd: "posts",
+ usage: [
+ " umtool posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--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); --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]",
+ " the Posts table's writer (updatePosts); <post> is x-<postId> or the bare <postId>",
+ " 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 posts narrate <project> [--import | --list | <item> [--script \"…\"] [--take [--note \"…\"]] [--pick n] [--approve] [k=v …]",
+ " | --all --draft-scripts | --all --take | --cut k=v …] a post read aloud (its takes: the editor's tts or yours)",
+ " umtool posts narrate <project> <item> --take --thread [--parents 0|all] [--skip-parent <id>]… [--no-quoted]",
+ " [--voice-for <handle>=<voice>]… [--dry-run] [--json] a THREAD READ: its context and his words in date",
+ " order, each in its author's voice, parts cached, one take saved and picked (exit 0 / 1)",
+ " umtool posts set-item | roles | narrate | reread | fx … --in-take <take> the same edit on a TAKE of the project:",
+ " its manifest read as the take's, the write in takes/<take>/take.json's patch (an undo point of the take's,",
+ " `umtool timeline <p> --take <take> undo`), the project's manifest untouched; set-item/roles/reread/fx",
+ " take --take <take> for it too (narrate's --take is a new read)",
+ " umtool posts say <project> ls | add <word> \"<spoken>\" [--case] [--item <id>] | remove <word> | try \"<text>\" | stale",
+ " the PRONUNCIATION LEXICON every synthesized read applies (stale: picked reads that say it the old way)",
+ " umtool posts voices <project> ls | set <handle|*> <voice> | remove <handle> the voice map a thread read uses",
+ " umtool posts fit <project> [--all | <item> …] [--linger s] [--dry-run] narrated posts' videos cut to their best part",
+ " umtool posts avatar <project> [<handle> <image>|off] · avatars <project> the authors' pictures on the cards",
+ " umtool posts redact <project> ls | add \"<term>\" [--substring] [--note \"…\"] | remove <n> words blanked from",
+ " what is published (a bar on the card, left out of a synthesized read); the data never rewritten",
+ " umtool posts repeats <project> [--match id|file|audio] [--json] the attachments played more than once (the combo counter)",
+ " umtool posts combo <project> [k=v …] · <item> off|on|k=v … the combo badge's knobs (the cut's, one item's)",
+ " umtool posts attach <project> [<item> … | --all] [--dry-run] a capture's media onto post items that carry none",
+ ],
+ docs: [
+ ["`posts set <project> <post> thread=on\\|off [hide=on\\|off] [attach=<clipId>\\|auto] [crop=<px>\\|off] [--json]`",
+ "the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `\"thread\": true`; its own shot while there is none), `off` removes the key.; `crop=<px>` the post's own crop of its screenshot (`shotMaxHeight`, 120–1080: its top that tall, never panned; `off` removes it) ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut)). Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1**"],
+ ["`posts add <project> <archive-channel>/<postId> [--attach <clipId>] [--flag F] [--author A] [--id ID] [--thread] [--crop <px>] [--dry-run] [--json]`",
+ "a **post card** from the corpus's posts archive (`channels/<slug>/posts/*.jsonl`): its words, date, link and handle; id `x-<postId>` (`bsky-`, `post-`); the author an earlier post by the same handle carries in the cut, else the archive's. Its capture (`posts-media/<postId>/`: `shot.png`, `capture.json`, the post's pictures) is copied to the project's `posts-media/<slug>/<postId>/` — or used where it is, when that folder links the channel's captures; never copied through a link anywhere else. Then `upsertPost` (a post with the id is replaced, its `attachTo` kept). **Exit 1** with no screenshot, naming the `pnpm ops capture-posts` to run. `--thread`: the entry gets `thread: true` (a reply drawn with the post it answers; `shot-thread.png` is copied with the rest, and with none yet it prints the `\"thread\": true` capture to run). `--crop <px>`: the post's own crop (`shotMaxHeight`). A post that quotes another, reposts one or carries media is added with a `WARNING:` line (`--json`: `warnings`) — its screenshot shows them, by the post's own data. Play the cut's **Add post** runs this same write ([knobs.md](knobs.md#add-post-a-post-card-from-play-the-cut))"],
+ ["`posts reel <project> --channel <slug> [--channel <slug> …] [--since YYYY-MM-DD] [--until YYYY-MM-DD] [--own] [--with-media] [--replies include\\|only\\|exclude] [--order chrono\\|reverse] [--limit N] [--after <id\\|->] [--dry-run] [--json]`",
+ "**POST ITEMS** ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut)): each archived post an entry of the cut -- its card drawn from the archive row (snapshotted), its attachments copied into `posts-media/` and played in it. The channels are read as one archive, merged in time order, de-duplicated by post id (`--channel ObviousRises-x --channel ObviousRises-x-replies`); `--own` the accounts' own posts (their config's `socialHandle`, no reposts); `--with-media` only posts whose capture holds an attachment; `--replies` keeps, keeps only or drops replies (a reply carries the posts it answers from the archive, else the capture's thread shot, else a \"Replying to\" line; the quoted post and the parent the archive lacks come from the capture's `context`, as `posts context` fills them). A post the cut already plays (by its id, a repost's original, a repost of it) is skipped, so a **re-run adds only what is new**; the rest goes in in ONE write (one undo point: `timeline <p> undo`), at the end unless `--after`"],
+ ["`posts set-item <project> <item> [hold=<s>\\|off] [layout=sequence\\|grid] [redact=on\\|off\\|auto] [fit=read[:<linger>]] [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.trim=off] [media.<i>.mute=on\\|off] [media.<i>.crop=x,y,w,h\\|off] [media.<i>.push=on\\|off] [media.<i>.enter=post\\|item] [media.<i>.blur=on\\|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label=\"…\"\\|off] [media.<i>.blur.boxes=x,y,w,h;…\\|off] [quoted.paraphrase=\"…\"\\|off] [parent.<i>.paraphrase=\"…\"\\|off] [follow=on\\|off\\|auto] [follow.dim=<0.2-1>] [follow.ease=<s>] [thread.parent[.<i>]=auto\\|full\\|excerpt\\|context\\|carry\\|hidden] [thread.quoted=…] [thread.carry=auto\\|on\\|off] [thread.reveal=on\\|off] [thread.shrink=<0.3-1>] [thread.dim=<0.15-1>] [thread.seconds=<s>] [thread.pan=<s>] [thread=auto] [thread.group=<name>\\|off] [thread.map=auto\\|on\\|off\\|map\\|label\\|both] [panel=auto\\|side\\|top\\|bottom] [media.add=<file>] [media.<i>=off] [parent.<i>=<json ref>\\|@<file>\\|off] [parent.<i>.media=<file>[,…]\\|off] [link.add=<json ref>] [link.<i>=<json ref>\\|off] [link.<i>.media=<file>\\|off] [link.<i>.transcript=\"…\"\\|off] [pictureOnly=on\\|off\\|auto] [parent.<i>.pictureOnly=on\\|off\\|auto] [quoted.pictureOnly=on\\|off\\|auto] [--json]`",
+ "a **post item's knobs** (the post bench's writer, `updatePostItem`; [knobs.md](knobs.md#a-post-item-a-post-as-an-entry-of-the-cut)): `<item>` is its id or the post's id; refused in the build's words. `quoted.paraphrase` / `parent.<i>.paraphrase`: your retelling of a long context post (≤ 600 characters), drawn in place of its words with a \"paraphrased\" label (its text kept); `off` or empty clears it. `follow=`: its read-follow ([knobs.md](knobs.md#read-follow-the-block-being-read-lit-the-card-panned-to-it)) -- `off`, `on`, `auto` (the cut's); `follow.dim=` / `follow.ease=` over the cut's. `thread.*`: its THREAD READ ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said)) -- what each context post is on screen (`thread.parent.<i>` one parent, nearest first), the shrink, dim and their seconds, the pan's; `thread=auto` the cut's; a setting that would narrate a post the card hides is refused (**exit 1**). `media.<i>.blur…` CENSORS the attachment in the render (a real blur of the whole frame or of its boxes, labelled \"Censored\"; the file untouched; merged key by key, `blur=off` keeps the settings). THREAD SCENES ([knobs.md](knobs.md#thread-scenes-the-join-whole-threads-manual-threads-wide-attachments-context-media-link-visits-the-branch-map)): `parent.<i>=` an ancestor added / replaced / dropped (a whole-thread read), `parent.<i>.media=` its attachments, `media.add=` / `media.<i>=off` an attachment from a project file (measured), `link.add=` a post its words link to (a link visit) with its picture and transcript, `thread.group=` a manual thread, `thread.map=` the branch map, `panel=` where its attachments sit; `media.<i>.enter=` when its own attachment comes in -- with his own post's read (`post`, the default: a parent or a quote read first shows none of it) or with the item (`item`). `pictureOnly=` a PICTURE-ONLY post ([knobs.md](knobs.md#picture-only-posts-a-reply-that-is-its-picture)): its attachment drawn in its own card where its words would be, never in the slot, a context post that is one given its own beat before the read -- `auto` (a post of only @mentions and links with an attachment), `on`, `off`; `parent.<i>.pictureOnly=` / `quoted.pictureOnly=` for those"],
+ ["`posts set-item \\| roles \\| narrate \\| reread \\| fx <project> … --in-take <take>` (set-item, roles, reread, fx: `--take <take>` too)",
+ "**a take-scoped edit** (`takeScope.mjs`): the same command, on a TAKE of the project -- its manifest read as the take's (the project's now with the take's patches), every write landing in `takes/<take>/take.json`'s patch with an undo point of the take's own (`timeline <p> --take <take> undo`). The project's manifest, and any project the take's items were imported from, are untouched; a new read (`narrate --take`, `--thread`, `reread`) lands in the project's `narration/` under a take number no file or entry has. A writer not routed to the take refuses and writes nothing. `--json`: the command's own object plus `take {id, edits, revisions, undo}`. narrate's own `--take` is \"make a new read\": `narrate … --take <a take's id>` is refused (exit 2) naming `--in-take`. **Exit 1** when the take is not there or is rendering ([take-scoped edits](#edit-a-take-not-the-project-items-from-other-projects-and-take-scoped-edits))"],
+ ["`posts reread <project> <item> [--without parent:0\\|parent:1\\|quoted[,…]] [--drop-parts 3,4] [--drop-urls] [--dry-run] [--json]`",
+ "a narrated read **re-joined without a piece**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the picked take's kept parts cut out of its own file (ffmpeg) and joined with the read's pauses, measured, added as a derived take (`steps: [{op: \"rejoin\", drop}]`, its parts re-timed with their roles, its word timings moved, its slurs state kept) and picked — ONE write (one undo point). `--without` drops the parts that read the post it answers (`parent:0`), its parent (`parent:1`) or the quoted post; `--drop-parts` by number; `--drop-urls` the parts that are nothing but a link. Nothing to drop, every part dropped or a take read in one go: **exit 1**. `posts set-item … thread.parent.<i>=context\\|hidden` (or `thread.quoted=…`) on a piece the take reads runs it first (`--no-reread`: refused, as before)"],
+ ["`posts reread <project> <item> --tempo-for \"4-16=1.35,21-25=1.3\" \\| --tempo <x> --parts <runs> [--stretch atempo\\|rubberband] [--dry-run] [--json]`",
+ "a narrated read's **parts re-timed**, no TTS ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled)): the parts named time-stretched (1–1.6, pitch kept), the rest untouched, joined with the read's pauses (each stretched part padded and trimmed to its length, sample-exact), its words scaled with their part, a derived take (`steps: [{op: \"tempo\", tempo, params: {stretch}}]`) picked in ONE write. A tempo is absolute: on a re-timed take it re-cuts from the take before. `posts set-item <p> <item> narration.tempo=\"4-16=1.35\"` runs the same. A part outside the take, a tempo outside 1–1.6, nothing changed: **exit 1**"],
+ ["`posts reread <project> <item> --yell-caps [--yell-gain 5.5] [--yell-style raise\\|shout\\|loud] [--dry-run] [--json]` · `posts yell <project> --all \\| <item …> [--yell-gain …] [--yell-style …] [--dry-run] [--json]`",
+ "a narrated read's **caps yelled**, no TTS ([report-video.md](report-video.md#a-long-read-sped-up-and-its-caps-yelled), `lib/report/postYell.mjs`): his ALL-CAPS words found in the take's word timings and raised (the lift measured, its loudness within 1 LU), acronyms and masked slurs left flat, a derived take (`steps: [{op: \"yell\", spans, params}]`) picked (one undo point per item). No word timings: **exit 1** naming `posts narrate --words`; `posts yell --dry-run` lists every item's caps, the flat ones and why, and which need word timings"],
+ ["`posts reread <project> <item> --pause \"<word>[#<n>]=<seconds>\\|@<take s>=<seconds>[,…]\" [--target post\\|parent:0\\|quoted\\|linked:0] [--dry-run] [--json]`",
+ "**pauses put in after words** of a narrated read, no TTS (`lib/report/postPause.mjs`; operator, 5 Nov: a countdown \"20 10 4 0\" read without a breath): the picked take cut just after each word named (half way into the quiet before the next word, at most 0.1 s past its end) and that much silence (0.05–3 s) put in -- each cut moved to the quietest 10 ms its word allows (40 ms before its timed end up to the next word, ±40 ms when they run together) when that is clearly quieter (~3 dB) than the timing's own, and each side of the silence faded over 10 ms, so a pause in normally paced speech does not click -- everything after moved on -- its words (by index), its parts (one a pause falls in grows), its length -- so word zooms, captions, slams, beeps and the read-follow stay on their words; an effect with a set `at` does not move (the plan counts them). A word is matched as a word zoom's is (case and edge punctuation aside; a phrase pauses after its last word; `#n` its n-th time in the read; `--target` counts only the words of the parts reading that piece). A derived take (`steps: [{op: \"pause\", pauses: [{word, w, at, seconds}]}]`) picked in ONE write. **Absolute**, like a tempo: on a take whose last step is a pause it re-cuts from the take before (the pauses it had kept, a word named again takes the new seconds, `=0` takes one away). `--in-take <t>` puts it in a take's read. No word timings (**exit 1**, naming `posts narrate <p> <item> --words`), a word not read, an occurrence not there, nothing to change: **exit 1**; a malformed spec, seconds outside 0.05–3, `--pause` with another reread form: **exit 2**"],
+ ["`posts reread <project> <item> --revoice \"<phrase>[#<n>]\" --say \"<what to say instead>\" [--target <piece>] [--voice <v>\\|auto] [--xfade 0.03] [--splice <from>-<to>] [--dry-run] [--json]`",
+ "**one phrase of an approved read re-voiced**, the rest untouched (`lib/report/postRevoice.mjs`; operator, 5 Nov: the countdown gabbled, and pauses cut into it \"choppy\"): the phrase found in the picked take's word timings as `--pause` finds a word (`#n`, `--target`; inside one part), the original cut from just before its first word to just after its last -- each cut at the quietest 10 ms within ±40 ms of the boundary, and when that is still speech within ±0.15 s (never inside the phrase as timed; a nearer quiet preferred) -- **`--say` alone synthesized by the editor's TTS** (narrate-via-editor; the engine of the root take, the voice of the part the phrase is in, `--voice` overrides; the project's lexicon, redaction and slur filter applied; kept in `narration/parts-cache/` like a thread read's parts, so asking again is free), its lead and tail of silence trimmed, loudness-matched to the speech in the 2 s either side (±6 dB) and spliced in with equal-power crossfades (`--xfade`, 0–0.2 s) at both joins, at the take's rate and layout. The length is exact: the take − the span cut + the piece. Everything after moves by the difference (its words, the part holding the span, the later parts) so zooms, captions, slams, beeps and the read-follow stay on their words; the new words are timed from the piece's speech and marked `estimated` (a later `posts narrate … --words` refines them); the part's text and the script say `--say`. A derived take (`steps: [{op: \"revoice\", revoice: {word, count, words, phrase, say, said, voice, engine, from, to, seconds, gain, xfade, key}}]`) picked in ONE write; re-voicing exactly the words a re-voice put in re-cuts from the take before. `--dry-run`: the span (words, seconds), each cut and its level, what is said and in which voice, the length change when the piece is cached -- no TTS. A cut still in speech is warned of (the word timings off there): `--splice 65.03-66.00` sets the cuts (either side may be left out). `--in-take <t>` puts it in a take's read. No word timings (naming `posts narrate <p> <item> --words`), the phrase not read or across two parts, a recorded read, the TTS failing: **exit 1**; no `--say`, a bad voice, crossfade or splice, `--revoice` with another reread form: **exit 2**"],
+ ["`posts progress <project> [auto\\|on\\|off\\|default] [--json]`",
+ "the cut's **progress bar** default (`render.posts.progress`, `updatePostProgressRender`; [report-video.md](report-video.md#the-progress-bar)); bare, which items draw it"],
+ ["`posts roles <project> [<item> …] [--write] [--set <n>=<role>,…] [--json]`",
+ "a narrated read **piece by piece** ([knobs.md](knobs.md#thread-reads-every-part-of-a-read-on-screen-while-it-is-said), [report-video.md](report-video.md#thread-reads)): the text each part of the picked take reads -- `parent:<i>`, `quoted`, `post`, `media:<i>` -- stored or inferred, what the card shows for each, and the build's guard (a part read off a post the card hides is refused). `--write` stores the inferred roles on the picked takes' parts (one write; the import stores them for every new take); `<item> --set n=role,…` sets parts' roles by hand (`off`: inferred again); a part out of range or an unknown role is refused (**exit 1**)"],
+ ["`posts narrate <project> --import [--dry-run] [--json]` · `--list` · `<item> [--script \"…\"] [--pick <n>] [--approve\\|--unapprove] [--off\\|--on] [lead= tail= ramp= linger= clip=read\\|full wet= lowpass= duck=on\\|off short=hold\\|loop attach=under\\|after lufs= pace=fast\\|normal]` · `<item> --take [--note \"…\"] [--voice v] [--engine e] [--speed s] [--script \"…\"]` · `<item> --derive <n> --op enhance\\|convert [--engine e] [--voice v]` · `<item> --delete <n>` · `--all --draft-scripts [--force]` · `--all --take [--limit N]` · `--cut <k=v>…`",
+ "a **narrated post item** ([report-video.md](report-video.md#narrated-post-items), [knobs.md](knobs.md#a-narrated-post-item)): `--import` reads `narration/posts/index.json` (`[{id, entry, script, takes: [{file, engine, voice, seconds}], pick}]`, and a take's `take-<n>.parts.json`) into the cut in ONE write, measuring each take (length, loudness); a re-run adds only takes not there. `--take` asks the EDITOR for a new take (`POST /api/ops/tts`, its `out` the next `narration/posts/<postId>/take-<n>.<engine>-<voice>.wav`; a job, waited for; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and picks it, its `--note` kept with it; `--pick <n>` is the take's number as `--list` shows it. `--derive <n>` makes a NEW take from take n through the editor's `voice-enhance` / `voice-convert` op (a stock synthetic voice; \"not installed\" until the editor has the engine), the original kept; `--delete <n>` moves a take's file to the post's `.trash/`. A new script or pick takes the approval away. `--all --draft-scripts` writes every post's words as its script, VERBATIM (cleaned only to be spoken: a reply's leading @handles, links, emoji dropped -- a handle typed inside the message is kept and said \"at <handle>\", the lexicon first; `plan(s)` → plans, `w/` → with, `&` → and; paragraphs kept). `--cut` sets `render.postNarration` (and its read-follow: `follow=on\\|off`, `follow.dim=`, `follow.ease=`; its thread reads: `thread.parent=`, `thread.quoted=`, `thread.carry=`, `thread.reveal=`, `thread.shrink=`, `thread.dim=`, `thread.seconds=`, `thread.pan=`). Refused in the build's words (**exit 1**) A `--take` whose read says a slur the cut BEEPS is word-timed by the editor's transcription before it is kept -- never waited on: with the transcription lane held (as while Orpheus runs) the take is kept as read and the timing deferred (it says so, naming `posts narrate <p> <item> --words` to run after the release; the build refuses the take until then), and a timing still queued after 5 min is deferred the same way. An excerpted item (`posts set-item … excerpt=`) reads its spans."],
+ ["`posts narrate <project> <item> --take --thread [--parents 0\\|all\\|none\\|<n>] [--skip-parent <id\\|parent:i>]… [--no-quoted] [--no-linked] [--read-seen] [--voice-for <handle>=<voice>]… [--voice v] [--engine e] [--note \"…\"] [--force] [--no-hold] [--dry-run] [--json]`",
+ "a **THREAD READ** as one command ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read), `lib/report/postThreadRead.mjs`): the post it answers (`--parents all`: every ancestor; `<n>`: parents 0..n; `none`), the post it quotes and the posts it links to, then his words, in DATE order, each in its author's voice (`--voice-for`, then the project's voice map, `posts voices`; his own: the narrator's), the redaction, the slur filter (a beep is skipped: a joined read is not word-timed) and the lexicon (`posts say`) applied. A parent or quoted post the item before already shows is not read again (`--read-seen`: it is). Each part is synthesized ONCE by the editor's tts op into `narration/parts-cache/<sha1(voice\\|text)>.wav` (the transcription lane held meanwhile, only if it was not; `--no-hold`: left alone), joined (0.8 s between pieces, 0.6 between paragraphs, 0.25 inside one) into `take-<n>.<engine>-thread.wav` with `take-<n>.parts.json`, saved with its parts' roles, its lexicon and how it was asked (`read`) and PICKED — one write (one undo point). `--dry-run`: the pieces, voices and parts (cached or not), nothing asked. Already up to date (same words and voices): nothing done, **exit 0** (`--force`: again). A part not synthesized: **exit 1** (the parts made stay cached; run it again); `--json` prints `{ok: false, error}` too. A usage error: **exit 2**"],
+ ["`posts say <project> [ls] [--item <id>]` · `add <word\\|phrase> \"<spoken>\" [--case] [--item <id>] [--note \"…\"]` · `remove <word\\|n> [--item <id>]` · `try \"<text>\" [--item <id>]` · `stale` `[--json]`",
+ "**THE PRONUNCIATION LEXICON** ([knobs.md](knobs.md#pronunciation-and-voices-the-lexicon-the-voice-map-a-thread-read)): `narration/lexicon.json` in the project, a word or phrase said differently in EVERY synthesized read (a script's `--take`, each piece of a thread read, the bench's re-take); the scripts and cards keep their words. Whole words, without case unless `--case`, a phrase across any spaces, regex characters literal; `--item` for one item's reads (it wins over the project's). A masked slur and a redacted word are never replaced. `add` of a word already listed changes what is said. `try` prints what a voice would be asked to say. `stale` lists every picked read that still says an entry the old way, with the command that re-reads it. A bad entry or an unknown item: **exit 2**"],
+ ["`posts voices <project> [ls] \\| set <handle\\|*> <voice> \\| remove <handle\\|*> [--json]`",
+ "**THE VOICE MAP** (`narration/voices.json`): the stock voice a thread read gives each author (`*`: everyone it does not name; default `leo` on Orpheus); `ls` lists the map and every author the cut's items carry with the voice each would get. A bad handle or voice: **exit 2**"],
+ ["`posts narrate <project> <item> --recording <file> [--as <character>] [--no-clean] [--no-convert] [--label l]`",
+ "**a recording made a character's read**: kept (recorded), cleaned (voice-enhance), converted (voice-convert) to the character's STOCK voice, each a new take, the last picked"],
+ ["`posts fx <project> <item> add caption --match \"…\" --text \"…\" [--target post\\|quoted\\|parent:<i>] [--occurrence n] [--at s] [--lead s] [--hold s] [--place below\\|above\\|side]` · `add clock [--rewind auto\\|on\\|off] [--off]` · `set <n> [--text …] [--place …] [--rewind …]`",
+ "a post item's **caption** ([report-video.md](report-video.md#a-caption), [knobs.md](knobs.md#a-caption-a-chip-explaining-a-phrase-as-it-is-read)): a chip explaining a phrase (any script: CJK drawn), up as it is read -- `--at`, else the take's word timings, else the reading estimate -- held `--hold` s, by the phrase and never over a word read while it is up; it waits for a word zoom. Its **clock** ([knobs.md](knobs.md#the-clock-each-posts-own-time-on-its-card-run-between-items)): the post's own time on the card, run from the clock item before it (forward; a REWIND when earlier: `--rewind`), `--off` not on this item. Through `updatePostFx`, refused in the build's words (**exit 1**); a zoom's knob on a caption, or a caption's on a zoom (**exit 1**)"],
+ ["`posts clock <project> [on\\|off\\|default] [--zone <IANA zone>] [--json]`",
+ "the cut's **clock** default (`render.posts.clock`, `updatePostClock`); bare, which items show it and their times"],
+ ["`posts fx <project> <item> add slam --text \"不動心\" [--match \"…\" \\| --at s] [--whole \\| --per-glyph] [--gap s] [--hold s] [--from-scale x] [--color #rrggbb] [--outline #rrggbb] [--outline-width px] [--place over-match\\|center] [--size px] [--face jp\\|sc\\|tc\\|kr] [--sfx trailer-hit\\|off] [--volume x] [--swell \\| --no-swell] [--bar \"…\" [--bar-style dark\\|gold\\|plain]]` · `set <n> [those flags; --bar off clears it]`",
+ "a post item's **slam** ([report-video.md](report-video.md#a-slam), [knobs.md](knobs.md#a-slam-a-trailer-style-title-slam-over-a-word-as-it-is-read)): a corny trailer title slam -- each glyph huge, shrinking onto the card just above the matched words' line and HITTING (a flash, dust, the frame's punch, a trailer hit's boom: the teaser's generator, `trailer-hits.mjs`), gold with a black outline; the hits spread evenly over the words' spoken span (`--gap` spaces them, `--at` moves the first), held `--hold` s; `--bar` lands the glyphs on a translation bar (rising in at the first hit, faded with them); a caption up with it waits for it. Through `updatePostFx`, refused in the build's words (**exit 1**); a slam's knob on another effect, or another's on a slam (**exit 2**)"],
+ ["`posts fx <project> <item> [ls]` · `add word-zoom --match \"…\" [--target post\\|quoted\\|parent:<i>] [--occurrence n] [--at s] [--scale s] [--hold s] [--lead s] [--ease out\\|inOut\\|snap] [--highlight #rrggbb\\|off]` · `set <n> [those flags; default clears one]` · `remove <n>` · `posts narrate <project> <item> --words [--worker <id>]`",
+ "a post item's **word zoom** ([report-video.md](report-video.md#a-word-zoom), [knobs.md](knobs.md#a-word-zoom-a-post-items-card-pushed-in-on-a-word-as-it-is-read)): the card pushed in on a word as it is read, a highlight under it, then back out -- through `updatePostFx`, refused in the build's words (a match not in the words, a knob out of bounds; **exit 1**). Its time is `--at`, else the word's start in the picked take's word timings; `ls` prints each zoom's time and where it came from. An un-narrated post's `add` fills `at` with the reading estimate. `--words` asks the EDITOR's transcribe op (`words: true`, a job per take or per part file; `ARCHILYZER_EDITOR_URL`, `WORKER_TOKEN`) and keeps the words heard, aligned to the script, on the take (`takes[i].words`)"],
+ ["`posts fit <project> [--all \\| <item> …] [--linger <s>] [--dry-run] [--json]` · `posts set-item <project> <item> fit=read[:<linger>]`",
+ "narrated posts' video attachments cut to their **best part** for the read (lead + take + tail + linger): a scored scan of the sound (loudness, its peaks), the speech (a transcript) and the scene cuts, the start snapped to a pause or a cut, recorded with why (`narration.window`) -- ONE write; each post's old and new length printed. A video no longer than the read is left as it is"],
+ ["`posts avatar <project> [<handle> <image-file> \\| <handle> off] [--json]` · `posts avatars <project> [--dry-run] [--json]`",
+ "the **authors' pictures** (`postAvatars`): `avatar` copies a picture into `posts-media/_avatars/` for every card that draws that handle (manual; never replaced by the archive's), `off` clears it, no handle lists them; `avatars` copies the archive's (the channels' `posts-media/_avatars/avatars.json`, capture-posts') for every author the cut's cards draw unblurred that it has none of. A blurred author never shows one"],
+ ["`posts redact <project> ls \\| add \"<term>\" [--substring] [--note \"…\"] \\| remove <n> [--json]`",
+ "**REDACTED WORDS** ([knobs.md](knobs.md#redacted-words-blanked-from-what-is-published)): the project's list (`render.posts.redact`, `updatePostRedact`) of words or phrases blanked from everything the cut publishes -- a solid bar on the rendered card, left out of a synthesized read, a post's chapter line and an attachment's captions; matched without case, as whole words (`--substring`: inside words too), a phrase across any spaces or punctuation. The posts' words and the scripts are never rewritten. `ls` numbers the terms as `remove` takes them, and counts the corpus's (`transcripts/redactions.json`) and the posts marked up in the cut's channels (`posts-markup.json`). A term already listed is refused (**exit 1**)"],
+ ["`posts slurs <project> [ls] \\| on \\| off \\| level strong\\|all \\| visual blackout\\|placeholder \\| voice skip\\|beep\\|placeholder \\| add <word> \\| except <word> \\| remove <word> \\| edges <word> [--off] [--json]`",
+ "**THE SLUR FILTER** ([knobs.md](knobs.md#the-slur-filter-slurs-masked-in-what-is-published-off-for-the-uncensored-cut)): `render.posts.slurs` (`updatePostSlurs`, one undo point each), on by default -- the slurs of the shipped list (`report-to-video/slurs.json`; `level strong`: only the strong ones) and the project's own (`add`; `except` never masks one) masked in everything the cut publishes: a dark pill with its mask (`visual placeholder`, the default, \"f*****\") or a bar (`blackout`) on the card; said and beeped by the take's word timings (`voice beep`, the default), left out of a synthesized read (`skip`), or its stand-in said (`placeholder`). `edges <word>` EDGE-masks that slur (its word, id or a form names it; `render.posts.slurs.edges`): every form first letter, stars, last letter, in the case written (\"n***a\", \"f****t\"), `--off` back to the first letter; a word naming no slur is refused (**exit 2**). `ls` counts what the cut masks per slur and per post -- masks only, never the word -- and names each narrated post whose take says one with no word timings (a censored build refuses it; `posts narrate <p> <item> --words`). `off` is the uncensored cut (the redaction stays). A word already on a list, or on neither for `remove`, is refused (**exit 1**); an unknown verb or value (**exit 2**)"],
+ ["`posts context <project> [--dry-run] [--json]`",
+ "every **post item's context from its capture** (`postContext.mjs`): the post it quotes and the post it answers, as its page showed them (`capture.json`'s `context`, read by the editor's `capture-posts` -- `\"contextOnly\": true` reads it alone), filled where the archive row lacks them -- `quoted` where the entry has none (or a named one with no words, the same post), `parents` where it has none (a thread shot stays on the entry; the card draws the parents). An x.com/twitter.com **status link** in its words (or its row's links) is a quote: the post it names, from any channel's archive, fills `quoted` (`via: \"link\"`) when it has none; the row's `threadId` is snapshotted as the item's `conversation` (the thread walk reads it). What the archive gave is never replaced. ONE write for every entry (`setPostItemsContext`: one undo point, refused whole in the build's words); a re-run with nothing new writes nothing. A post whose capture read no context is listed with the call that reads it (`pnpm ops capture-posts --json '{\"slug\":…,\"ids\":[…],\"contextOnly\":true}' --wait`). The card's blur of other authors is unchanged ([report-video.md](report-video.md#post-items-a-post-as-an-entry-of-the-cut))"],
+ ["`posts picture-reply <project> [on=on\\|off] [image=<s>] [min=<s>] [max=<s>] [maxSound=<s>] [--in-take <take>] [--json]`",
+ "the cut's **PICTURE-ONLY RULE** ([knobs.md](knobs.md#picture-only-posts-a-reply-that-is-its-picture)): `render.posts.pictureReply` (`updatePostPictureReplyRender`, one undo point) -- `on` the rule at all; a beat's length: an image `image` s (2), a GIF's or a silent video's own length clamped to `min`–`max` (1.5–4 s), a video with its sound its whole length up to `maxSound` (8 s). `k=` the default again; none: the rule as it stands. `--in-take` writes it into a take's patch. Refused in the build's words (**exit 1**)"],
+ ["`posts repeats <project> [--match id\\|file\\|audio] [--json]`",
+ "the **combo counter**'s repeats ([report-video.md](report-video.md#the-combo-counter)): every attachment the cut's post items play more than once -- the same X media id (the capture's url), else the same file (the capture's sha256 when its bytes agree, else hashed; cached by path, size and mtime), else (`--match audio`) the same sound (fpcalc, else a coarse ffmpeg hash) -- its posts in the cut's ORDER with their dates, the tier that matched and the badge each draws (`×2` from the second use, `(×n)` counted but not drawn); a post whose CAPTURE holds the same file but whose entry carries no attachment is listed too, `NOT ATTACHED`, with the `posts attach` that brings it in. Reads only"],
+ ["`posts attach <project> [<item> … \\| --all] [--dry-run] [--json]`",
+ "a post item with **no attachment whose capture holds one** (captured after it went in -- `posts repeats` marks them `NOT ATTACHED`): the capture's media (its own channel's `posts-media/<postId>/`, else any channel the cut's posts come from) copied into the project's `posts-media/<slug>/<postId>/` and measured, set as the entry's `media` as `posts reel` would have made it -- nothing else of the entry changes (its paraphrases, narration, knobs kept); an item that has an attachment is never touched. ONE write (one undo point: `timeline <p> undo`), refused whole in the build's words"],
+ ["`posts combo <project> [on=on\\|off] [label=L] [position=top-right\\|top-left\\|bottom-right\\|bottom-left\\|center] [color=#rrggbb] [scale=0.4-2.5] [sfx=off\\|hit\\|coin] [minCount=2-20] [match=id\\|file\\|audio] [--json]` · `posts combo <project> <item> off\\|on\\|auto\\|label=…\\|position=…\\|color=…\\|scale=…\\|sfx=… [--json]`",
+ "the **combo badge's knobs** ([knobs.md](knobs.md#the-combo-counter)): the cut's (`render.posts.combo`, `updatePostComboRender`; no knobs prints them; `k=` the default again) or one post item's (`combo`, `updatePostCombo`): `off` draws no badge on it -- it still counts -- `on`/`auto` the cut's again. Refused in the build's words (**exit 1**)"],
+ ],
+ },
+ {
+ cmd: "candidates",
+ usage: [
+ " 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",
+ ],
+ docs: [
+ ["`candidates <project> [ls] [--all] [--json]` · `candidates <project> import <sweep.md> [--dry-run] [--json]` · `candidates <project> add <json\\|@file> [--json]`",
+ "the **candidates inbox** (`<project>/candidates.json`): proposals only — `import` reads a sweep's bullets (`- [verdict] [title @ time](link) (date) \"quote\" — why`, under their headings; a Top N section marks what it restates; a bullet with no verdict or link is skipped and said), `add` an agent's (`{channel?, video, t, quote?, why?, verdict?, score?, section?}` or `{link, …}`); the same moment again changes nothing it holds. Insert and Not this are the Cut tab's Candidates panel's ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press))"],
+ ],
+ },
+ {
+ cmd: "ingredient",
+ usage: [
+ " umtool ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json] one recording's life cycle:",
+ " found, downloaded, transcribed, clock, windows, used in, checked, rendered, published (/ingredients)",
+ ],
+ docs: [
+ ["`ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json]`",
+ "**one recording's life cycle**, the twin of `/ingredients/<channel>/<video>` ([knobs.md](knobs.md#an-ingredients-life-cycle-the-rail)): nine stages — found, downloaded, transcribed, clock, windows, used in, checked, rendered, published — each **✓**, a count, **!** or **—**, and its line, then every project clip that cuts from it (the draft and each saved version, from the usage index `<REPORTS_ROOT>/.umtool/usage-index.json`). A Rumble recording answers to its folder slug or its embed id; both are printed. `--window`: one clip window, the stages after it narrowed to the clips it plays. `--used-in`: the clips alone. `--json`: the page's object. Read-only over the corpus. **Exit 0 · 1 failed · 2 usage**"],
+ ],
+ },
+];
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -0,0 +1,480 @@
+// THE VERB REGISTRY (umtool redesign, lane palette L8a): every verb
+// `umtool` dispatches, one row each -- a sub-verb (`timeline insert`,
+// `takes pick`, `posts add`) its own row -- machine-readable, so the ⌘K
+// palette builds a FORM from a row, POST /api/cli runs only what a row
+// allows, and `umtool help` and docs/cli.md are generated (lib/cli/docs.mjs)
+// from here and from the prose beside it (lib/cli/groups.mjs).
+//
+// { verb, summary, target, ui, reason?, args, shape?, queue?, timeoutMin? }
+//
+// verb the words that name it, as typed: "timeline insert"
+// summary one line, what it does (the palette's hint)
+// target "draft" it writes the working draft: the project's manifest (and the files beside it
+// a write keeps in step), each write an undo point
+// "project" it reads a project, or writes what is not its draft (takes, renders, records)
+// "corpus" it is not about one project
+// ui "form" the palette offers it as a form; POST /api/cli runs it
+// "none" it has no form, and `reason` says why (required)
+// args what the form asks, in argv order (below)
+// shape where the verb's words and positionals go when they interleave:
+// "timeline <project> insert" -- a `<name>` is that positional arg. Absent: the verb's
+// words, then every positional in order. Positionals the shape leaves out follow it.
+// queue true: it renders (or holds the heavy slot) -- POST /api/cli adds it to the durable
+// queue (lib/queue/store.mjs), never the app's one-job runner
+// timeoutMin a job's (or a queued step's) time limit, minutes (default 15 for a job, the queue's 12 h)
+// confirm { what, when?, unless? }: it does something with no undo point (deletes, evicts, kills):
+// the form asks a second press ("Yes, <what>") and POST /api/cli wants `confirm: true`;
+// `when` the arg names that make it so (any given), `unless` those that make it a dry run
+//
+// An arg: { name, type, required?, choices?, default?, help?, repeat?, context? }
+// name "--flag" is a flag; anything else is a positional
+// type project a project id (positional; the palette fills it from the page)
+// string one word or line text a longer one (a textarea)
+// number a finite number boolean a flag present or not
+// choice one of `choices` json a string that parses as JSON
+// pairs key=value lines, each one argv word (a positional run)
+// flagpairs key=value lines, each `--key value`
+// list several values: a positional run, or (`repeat`) the flag once per value
+// (`item: "id"` each an entry id; `item: "name"` each a bare name; `item: "pair"` each key=value; `item: "ref"` each a ref)
+// name a bare name: no directory, no `..`, no leading dot (`--out`, a take's id, a reel)
+// path a file of the project, relative to its directory: POST /api/cli runs it only when
+// its realpath is inside the project's, as that absolute path (`pass: "relative"`: as typed)
+// ref a share URL or <channel>/<id>, never a file (`new --from`)
+// literals values a name or path arg also takes as words ("none", "off")
+// atFile the CLI reads `@file` here: a form may not (the file could be anywhere). Every positional, list item
+// and key=value is refused an `@file` reference anywhere in it (`post-json:@x`, `a,@x`); `allowAt`
+// exempts a handle (`@grok`) or a lexicon word; a flag's words and free prose (`text`) are a person's.
+// context "clip" | "post" | "take": filled from the page's selection (its URL: /clip/<id>,
+// /post/<id>, /takes/<id>, ?clip=, ?take=)
+//
+// A NEW VERB (or sub-verb) is a new row here, ui "form" with its args or ui "none" with its
+// reason -- verbs.test.mjs fails, naming the verb, until it has one -- and its help lines in
+// groups.mjs; then `node umtool/lib/cli/docs.mjs` rewrites docs/cli.md.
+//
+// Plain data and pure helpers: no imports, so the route, the tests and the docs read one table.
+
+// ---- the args -----------------------------------------------------------------
+
+const project = (o = {}) => ({ name: "project", type: "project", required: true, help: "an id, a directory or a unique name", ...o });
+/** A positional: required unless said. */
+const arg = (name, o = {}) => ({ name, type: "string", required: true, ...o });
+/** A valued flag. */
+const opt = (name, o = {}) => ({ name, type: "string", ...o });
+const bool = (name, help) => ({ name, type: "boolean", ...(help ? { help } : {}) });
+const num = (name, o = {}) => ({ name, type: "number", ...o });
+const pick = (name, choices, o = {}) => ({ name, type: "choice", choices, ...o });
+const pairs = (o = {}) => ({ name: "settings", type: "pairs", required: true, help: "key=value, one per line (`key=` clears one)", ...o });
+const many = (name, o = {}) => ({ name, type: "list", ...o });
+const clip = (o = {}) => arg("clip", { context: "clip", help: "the clip's id", ...o });
+const item = (o = {}) => arg("item", { context: "post", help: "the post item's id (or its post's)", ...o });
+const takeOpt = (o = {}) => opt("--take", { type: "name", context: "take", help: "a take of the project: the edit lands in its patch", ...o });
+const takeArg = (o = {}) => arg("take", { type: "name", context: "take", help: "the take's id", ...o });
+const inTake = () => opt("--in-take", { type: "name", context: "take", help: "a take of the project: the edit lands in its patch" });
+const name = (n, o = {}) => ({ name: n, type: "name", ...(n.startsWith("--") ? {} : { required: true }), ...o });
+const file = (n, o = {}) => ({ name: n, type: "path", ...(n.startsWith("--") ? {} : { required: true }), help: "a file of the project, relative to its directory", ...o });
+const dry = () => bool("--dry-run", "say what it would do; change nothing");
+const reel = () => opt("--reel", { type: "name", help: "that beat reel (promo/<name>-beats.json); default the trailer" });
+const window_ = () => [num("--at", { help: "the window's start, s" }), num("--dur", { help: "the window's length, s" }), bool("--full", "the whole cut")];
+
+// ---- the rows -------------------------------------------------------------------
+
+const form = (verb, target, summary, args, extra = {}) => ({ verb, summary, target, ui: "form", args, ...extra });
+const none = (verb, target, summary, reason, extra = {}) => ({ verb, summary, target, ui: "none", reason, args: [], ...extra });
+
+/** The heavy verbs' default time limit in the queue is its own (12 h); a job's is 15 min unless a row says. */
+const Q = { queue: true };
+
+const REJECT_WHYS = ["not-matching", "wrong-speaker", "irrelevant", "repeats", "weak", "privacy", "other"];
+
+/** @type {ReadonlyArray<Record<string, any>>} */
+export const VERBS = Object.freeze([
+ // ---- the tree ----
+ form("ls", "corpus", "every project, as text", [
+ opt("--kind"), opt("--template"), opt("--state"), bool("--open", "only projects with something open"), bool("--blocking", "only projects with something blocking"),
+ opt("--q", { help: "words the project's text holds" }), pick("--sort", ["recent", "name"]),
+ ]),
+ form("show", "project", "one project: summary, the cut, per-clip status, decisions", [project()]),
+ form("check", "project", "what blocks a build (exit 1 on anything blocking)", [project({ required: false, help: "one project; none: every project" }), bool("--all-severities", "the info rows too")]),
+ form("links", "project", "do the clip QRs open on their sites (out/links.json)", [
+ project(), bool("--fix", "rewrite the dead links it knows the fix for"),
+ bool("--embed-ids", "no check: every clip citing a Rumble URL-slug folder gets the embed id the archive serves (siteVideo), one write to the draft"),
+ opt("--clips", { help: "with --embed-ids: a,b (none: every such clip)" }), dry(),
+ ], { timeoutMin: 30 }),
+ // The inspector's twins (umtool redesign L6): the project's provenance, its title, a still at second N.
+ form("provenance ls", "project", "the project's provenance: site origin, channel slug, channel, link policy", [project()], { shape: "provenance <project> ls" }),
+ form("provenance set", "draft", "the project's site origin, channel slug and channel name (\"\" removes one)", [
+ project(), opt("--site-origin", { help: "https://… (the archive its QRs open)" }), opt("--channel-slug", { help: "the channel a clip with no channel is from" }), opt("--channel", { help: "the display name" }),
+ ], { shape: "provenance <project> set" }),
+ form("title", "draft", "the project's title and subtitle (no words: print them)", [
+ project(), arg("title", { required: false, help: "the new title (none: print them)" }), opt("--subtitle"), bool("--no-subtitle", "remove the subtitle"),
+ ]),
+ form("still", "project", "one frame of a clip's fetched window at a source second, into shots/", [
+ project(), clip(), num("--at", { required: true, help: "the SOURCE second" }), takeOpt({ help: "a take's (version's) clip" }),
+ ], { confirm: { what: "write the frame into shots/ (a file, no undo point; a still of the same second is replaced)" } }),
+ form("still ls", "project", "the pictures in the project's shots/", [project()], { shape: "still <project> ls" }),
+
+ // ---- the cast ----
+ form("cast ls", "corpus", "the characters' voices across projects", [], { shape: "cast ls" }),
+ form("cast add", "corpus", "a character: name, stock voice, handles", [
+ arg("id"), opt("--name", { required: true }), opt("--voice", { required: true, help: "engine:voice" }), opt("--handles", { help: "a,b" }), opt("--speakers", { help: "Name,…" }),
+ pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice", { help: "engine:voice" }), opt("--note"), bool("--narrator", "the recordings' default character"),
+ ]),
+ form("cast set", "corpus", "change a character", [
+ arg("id"), opt("--name"), opt("--voice", { help: "engine:voice" }), opt("--handles"), opt("--speakers"), pick("--convert-engine", ["openvoice", "seed-vc"]), opt("--convert-voice"),
+ opt("--note"), opt("--add-handle"), opt("--remove-handle"), bool("--no-convert"), bool("--narrator"), bool("--no-narrator"),
+ ]),
+ form("cast rm", "corpus", "a character out of the cast (an undo point)", [arg("id")]),
+ form("cast undo", "corpus", "the cast as it was before its last write", []),
+ form("cast project", "project", "the project's characters, their voices and drift", [project()]),
+ form("cast audition", "project", "one line read by 2-6 candidate voices, scored against the real voice", [
+ arg("character", { allowAt: true, help: "a character id or @handle" }), opt("--voices", { required: true, help: "engine:voice,engine:voice,…" }), project({ name: "--project", required: false }),
+ opt("--text", { type: "text" }), opt("--item"), num("--line"), bool("--stock"), bool("--no-score"), bool("--score-only"),
+ ], Q),
+ form("cast use", "draft", "the voice a character reads in, here or everywhere", [project(), arg("character", { allowAt: true }), arg("voice", { help: "engine:voice" }), bool("--everywhere", "the cast's voice, not this project's")], { shape: "cast use <project> <character> <voice>" }),
+ form("cast reread", "project", "the items that say a character in another voice, read again", [project(), arg("character", { allowAt: true }), dry()], Q),
+
+ form("speaker-check", "project", "which named voice each clip is (speaker-check.json)", [
+ project(), many("--clip", { repeat: true, help: "clip ids, one per line (none: every clip)" }), bool("--list", "list the named voices"),
+ opt("--set", { help: "Name=<clip>,<channel>/<id>,channel:<slug>" }), opt("--remove", { help: "a voice's name" }),
+ ], { ...Q, confirm: { what: "remove that named voice from speakers.json", when: ["--remove"] } }),
+ form("quote-check", "project", "is each clip's quote in the seconds it plays", [project(), opt("--clips", { help: "a,b (none: every clip)" }), num("--pad"), bool("--status", "the rows as they stand")], Q),
+ form("check-joins", "project", "do a rendered take's post joins carry on", [project(), takeOpt({ required: true, help: "the rendered take" }), bool("--all", "every post-to-post boundary"), num("--limit")], Q),
+ form("link-policy", "draft", "cite via site X, these channels direct", [
+ project(), opt("--via", { help: "a site id or its https address" }), opt("--direct", { help: "channel slugs, a,b" }), bool("--clear"), bool("--fix", "rewrite the clips that break it"),
+ ]),
+ form("patch-markers", "draft", "take patches whose deck markers name a clip not in the cut", [project(), arg("file", { required: false, help: "<file>.patch.json (none: every patch)" }), bool("--fix")]),
+ form("decisions", "corpus", "every decision waiting, by project", []),
+ form("inbox", "corpus", "the decisions grouped and ranked as the Inbox shows them", [bool("--all", "the hidden ones and the quiet group too")]),
+ form("schedule list", "corpus", "the recurring reports", []),
+ form("schedule show", "corpus", "one recurring report: chip, editions, tick log", [arg("id")]),
+ form("folders", "corpus", "the reports tree's folders", []),
+ form("kinds", "corpus", "the project kinds the registry knows", []),
+ form("link", "draft", "the manifest names the article it is the video of", [project(), arg("article", { required: false, help: "<site>/<report>" }), bool("--clear")]),
+
+ // ---- a clip ----
+ form("window", "draft", "a clip's window, cut, attribution and verdict", [
+ project(), clip(),
+ num("--start", { help: "the extent's start, source s" }), num("--end"), bool("--lock"), bool("--lock-end"), bool("--no-lock-end"),
+ num("--cut-start", { help: "the cut the video renders, source s" }), num("--cut-end"), bool("--lock-cut"), bool("--align", "the cut snapped to the quote as heard"),
+ opt("--title"), opt("--date", { help: "YYYY-MM-DD" }), num("--cite"), opt("--cite-url"), opt("--quote", { type: "text" }), opt("--repeat-of"),
+ pick("--verdict", ["confirmed", "incorrect"]), opt("--correction", { type: "text", help: "what the report got wrong (incorrect needs one)" }),
+ pick("--reject", REJECT_WHYS), opt("--note", { type: "text" }), opt("--walk-note", { type: "text" }), bool("--star"), bool("--no-star"),
+ bool("--quote-ruled"), bool("--no-quote-ruled"), opt("--move-stamp", { help: "first | nearest | <s>" }), bool("--clear-stamp"), pick("--move-mute", ["nearest"]), bool("--clear-mute"),
+ many("--gap", { repeat: true, help: "FROM-TO source seconds, one per line" }), num("--gap-remove"), opt("--gaps", { help: "A-B,C-D (the whole list)" }),
+ takeOpt(),
+ ]),
+ form("walk", "project", "the clip bench's walk: clips in walk order, verdicts, fetched", [project(), takeOpt({ help: "walk a take (a draft too)" }), bool("--all", "every fetched clip")]),
+ form("present", "project", "present mode's address and slides", [project(), takeOpt({ help: "that take's cut (default the latest)" }), bool("--cut", "the manifest alone"), bool("--public", "as a public page would carry it")]),
+ form("set", "draft", "a clip's knobs: claim, marks, audio, blur, fx …", [project(), clip(), pairs({ help: "key=value, one per line (claim.at=190.2, audio.gain=-3, `key=` clears)" }), opt("--mark", { help: "the mark the claim.* keys set" }), takeOpt()]),
+ form("intro", "draft", "the intro the cut opens on (render.intro)", [project(), pairs({ required: false, help: "key=value, one per line (style=boot-dark, seconds=4); none: print it" }), bool("--off", "take the intro off"), takeOpt({ help: "a version: --off opens it on no intro, --on on the cut's" }), bool("--on")]),
+ form("look", "draft", "the cut's knobs: mode, deck, fact-check stamps, variants …", [project(), pairs({ help: "key=value, one per line (mode=basic, deck.markerLayout=stagger)" }), many("--unset", { repeat: true, help: "render.<key>, a legacy key dropped" })]),
+ form("migrate", "draft", "the manifest's settings into the video modules' homes", [project(), dry()]),
+ form("variants", "project", "make the encode ladder of a build", [project(), takeOpt({ help: "a take's build" }), bool("--list", "what was made, and the sync report")], Q),
+ form("corrections", "project", "what the report got wrong, as markdown", [project()]),
+ form("build", "project", "the build's chain, printed (the Cut tab's Build runs it)", [project(), pick("--preset", ["preview", "fast", "final"]), opt("--only", { help: "one clip id" }), bool("--dry")]),
+ form("chain", "corpus", "an article iteration's pipeline to a video", [
+ arg("article"), num("n", { required: true, help: "the iteration" }), opt("--from", { help: "the step to start at" }), bool("--dry", "print it"), bool("--final"),
+ opt("--site-origin"), bool("--draft-all", "Draft everything"), opt("--model"), bool("--deck"),
+ ], Q),
+ form("index", "corpus", "the project index (the cache)", [bool("--rebuild"), bool("--prune"), num("--since", { help: "ms" })], { confirm: { what: "prune the index's rows of projects no longer on disk", when: ["--prune"] } }),
+ form("new", "corpus", "a new project (scaffold)", [
+ arg("slug", { help: "<slug> or <folder>/<slug>" }), opt("--folder"), opt("--from", { type: "ref", help: "a share URL or <channel>/<id> (a report.md: from a terminal)" }), opt("--site-origin"),
+ pick("--seed", ["chapters", "frames", "phrase", "reactions"]), num("--target", { help: "s" }), opt("--phrase", { help: "a regex (--seed phrase)" }), opt("--channels", { help: "a,b" }),
+ opt("--prefer"), opt("--exclude"), num("--max"), opt("--from-posts", { type: "name", help: "a posts channel: a posts reel" }), name("--brand"),
+ ], { timeoutMin: 30 }),
+ form("doctor", "corpus", "the tools and the roots on this machine", []),
+ form("storage status", "corpus", "where each project's out/ lives", [project({ required: false })]),
+ none("storage move-out", "project", "out/ to the media root, a link left", "moves a project's out/ between drives: a terminal's, run when nothing builds (the page cannot see a hand-run writer)"),
+ none("storage move-back", "project", "out/ back into the project", "moves a project's out/ between drives: a terminal's, run when nothing builds"),
+ none("storage deliverables", "project", "clips/ and share-*/ to the media root and back", "moves deliverables between drives, then the switch: a terminal's, run when nothing builds"),
+ form("snapshot", "project", "copy the manifest into revisions/", [project(), opt("--label")]),
+ form("diff", "project", "what changed since a snapshot", [project(), arg("snapshot", { help: "its path under revisions/" })]),
+ form("export", "project", "the posting artifacts, or one clip clean into exports/", [
+ project(), clip({ required: false, help: "one clip (none: --format)" }), pick("--format", ["toc-bbcode", "toc-markdown", "description", "chapters"]), opt("--variant"), opt("--first"),
+ num("--context", { help: "± s, as recorded" }), bool("--raw", "the fetched window as recorded"), num("--from"), num("--to"), bool("--fetch", "ask the editor first for what is not on disk"), takeOpt(),
+ ], Q),
+ form("check-sources", "corpus", "the re-check chain, printed", [many("projects", { help: "one per line (none: the never-checked and > 30 d)" })]),
+
+ // ---- notes ----
+ form("notes", "corpus", "the operator's notes, as markdown", [arg("target", { required: false, help: "<site>/<report> or a project" }), bool("--all"), bool("--resolved"), bool("--all-status")]),
+ form("notes reply", "corpus", "answer a note", [arg("id"), arg("text", { type: "text" }), bool("--resolve")], { confirm: { what: "answer the note and resolve it", when: ["--resolve"] } }),
+ form("notes resolve", "corpus", "a note resolved", [arg("id")], { confirm: { what: "resolve the operator's note" } }),
+ form("notes wontfix", "corpus", "a note closed as won't fix", [arg("id")], { confirm: { what: "close the operator's note as won't fix" } }),
+ form("notes reopen", "corpus", "a note open again", [arg("id")]),
+ form("notes source", "corpus", "the source a target's notes name (the draft to edit)", [arg("target", { help: "<site>/<report>" }), opt("--draft"), opt("--generator"), opt("--how")]),
+
+ // ---- modules, presets ----
+ form("modules list", "corpus", "the video modules", []),
+ form("modules apply", "draft", "a module-config.json onto the cut, or as a take's patch", [
+ project(), file("--config"), dry(), takeOpt({ help: "made as that take (rendered) instead" }), opt("--label"), ...window_(), bool("--quick"), bool("--force"), name("--from"),
+ ], Q),
+ form("preset list", "corpus", "the look presets", []),
+ form("preset show", "corpus", "one look preset", [name("name")]),
+ form("preset save", "corpus", "a project's look as a preset", [name("name"), project({ name: "--from" }), opt("--description"), bool("--force")], { confirm: { what: "overwrite the preset of that name", when: ["--force"] } }),
+ form("preset apply", "draft", "a preset under the cut (none: off it)", [name("name", { help: "a preset, or none" }), project(), bool("--replace", "clear the manifest's own values of its keys")]),
+
+ // ---- takes ----
+ form("take", "project", "one take: rendered, drafted, previewed or promoted", [
+ project(), name("--id", { required: true, context: "take", help: "the take's id" }), opt("--label"), opt("--group"), pick("--kind", ["similar", "different"]), opt("--summary"),
+ opt("--style"), file("--patch", { help: "a patch file of the project" }), opt("--patch-json", { type: "json" }), many("--set", { repeat: true, item: "pair", help: "path=value, one per line" }), opt("--effect"),
+ ...window_(), bool("--quick"), bool("--force", "make it again over the take there"), name("--from", { help: "a take whose built parts it reuses" }), bool("--keep-frames"), bool("--priority", "render mode for its lifetime"), bool("--uncensored"),
+ bool("--draft", "record it, render nothing"), bool("--rebuild"), bool("--preview"), bool("--changes"), num("--pad"), bool("--no-preview"),
+ bool("--promote", "make this take the cut"), bool("--anyway"),
+ many("--import-item", { repeat: true, help: "<project>:<item>[,<item>…], one per line" }), opt("--after"), opt("--before"), opt("--as"), dry(),
+ ], { ...Q, confirm: { what: "make the take again over the one there", when: ["--force"] } }),
+ form("lint", "project", "the manifest lint a build runs first", [project(), takeOpt({ help: "a take's manifest" }), pick("--variant", ["sourced", "full"]), bool("--final")]),
+ form("take status", "project", "a take's render record", [project(), name("--id", { context: "take" }), bool("--log"), num("--tail")]),
+ none("queue add", "corpus", "a step of the durable queue: a umtool command's argv", "takes a raw argv -- a page never sends one (app/api/queue/route.ts); a form's Run on a heavy verb queues the step itself"),
+ form("queue ls", "corpus", "the queue's steps and its runner", [bool("--all")]),
+ form("queue status", "corpus", "one step: state, exit code, error, log", [arg("qid")]),
+ none("queue wait", "corpus", "wait for a step to finish", "blocks a terminal until a step ends: a form's Run follows its own step"),
+ form("queue log", "corpus", "a step's full log", [arg("qid"), num("--tail")]),
+ form("queue cancel", "corpus", "a step cancelled (a running one stopped)", [arg("qid")], { confirm: { what: "cancel the step (a running one is killed)" } }),
+ form("queue retry", "corpus", "a failed or cancelled step back in the queue", [arg("qid")]),
+ form("jobs", "corpus", "every running and recent render, step and app job", []),
+ form("takes make", "project", "a recipe's takes, or one per montage style", [
+ project(), file("--recipe"), opt("--only", { help: "ID,ID" }), bool("--force", "make again the takes that exist"), bool("--all-styles"), opt("--group"), ...window_(), bool("--quick"), bool("--priority"),
+ ], { ...Q, confirm: { what: "render again over the takes that exist", when: ["--force"] } }),
+ form("takes styles", "corpus", "the montage styles", []),
+ form("takes pick", "project", "use this take: its manifest over the project's", [project(), takeArg(), bool("--anyway"), bool("--pin"), bool("--unpin")]),
+ form("takes effects", "project", "the overlay effects this cut offers", [project()]),
+ form("takes ls", "project", "the working cut, then each take", [project()]),
+ form("takes relabel", "project", "a take's label", [project(), takeArg(), arg("label")]),
+ form("takes supersede", "project", "a take folded away in the list (or back)", [project(), takeArg(), name("--by"), bool("--clear")]),
+ form("takes save", "project", "the working draft frozen as the next version (v<N>)", [project(), opt("--label"), bool("--force", "save even with no edits since its parent")]),
+ form("takes open", "draft", "a saved version into the draft (the draft saved first)", [project(), takeArg({ help: "the version (or take) to open" })]),
+ form("takes freeze", "project", "legacy takes given a frozen base (a dry run unless --apply)", [project(), many("takes", { item: "name", help: "take ids, one per line (none: --all)" }), bool("--all"), bool("--apply", "write them (else a dry run)")], { confirm: { what: "write each legacy take's frozen base (how it resolves can change)", when: ["--apply"] } }),
+ none("takes delete", "project", "a take's directory, whole", "deletes a take's directory whole, past undo: the Takes panel's Delete asks first; a terminal's --dry-run shows what goes"),
+ form("takes cancel", "project", "stop a take's render", [project(), takeArg()], { confirm: { what: "stop the take's render (killed, marked cancelled)" } }),
+ form("takes fork", "project", "the take as a variant project beside this one", [project(), takeArg(), name("--name")]),
+ form("takes compare", "project", "two takes side by side", [project(), arg("a", { help: "<take> or <project>:<take>" }), arg("b")]),
+ form("render-mode on", "corpus", "render mode: a render gets the machine, for a window", [opt("--for", { help: "90m, 2h (default 2h)" }), opt("--note")]),
+ form("render-mode off", "corpus", "render mode off", [bool("--force", "even while a render holds it")], { confirm: { what: "take render mode from the render that holds it", when: ["--force"] } }),
+ form("render-mode status", "corpus", "is render mode on, for what, until when", []),
+ form("pool stats", "corpus", "the render pool: what it holds", [opt("--since", { help: "7d" })], { shape: "pool stats" }),
+ form("pool prune", "corpus", "the render pool pruned to its cap", [num("--max-gb"), dry()], { confirm: { what: "delete render pool files past the cap", unless: ["--dry-run"] } }),
+ form("pool verify", "corpus", "the render pool's files checked", [num("--sample"), bool("--all")], Q),
+ form("trailer", "project", "a trailer or beat reel cut from a take's master", [
+ project(), takeOpt({ help: "the take whose master it is cut from" }), reel(), file("--beats", { help: "a beats file of the project" }), opt("--beats-json", { type: "json" }),
+ bool("--intro"), num("--finale", { help: "s" }), num("--xfade"), bool("--no-snap"), name("--out", { help: "a file name, written in the take's out/" }), dry(), bool("--candidates", "the walk's ★ clips as beats (prints)"), bool("--vertical"), pick("--layout", ["reframe"]),
+ ], Q),
+ form("vertical", "project", "a vertical short (1080x1920) of a take's items", [
+ project(), takeOpt({ required: true, help: "the take" }), reel(), file("--beats", { help: "a beats file of the project" }), opt("--items", { help: "id,id" }), pick("--clip", ["full", "framed", "quote"]), pick("--post", ["card", "stack", "media"]),
+ pick("--side", ["split", "overlay"]), opt("--hook", { help: "title | section | a line of the cut's own copy" }), pick("--captions", ["l", "xl"]), pick("--lines", ["1", "2"]), num("--loudness"), num("--max"),
+ name("--name"), bool("--reframe", "recompose the finished 16:9 master"), dry(), bool("--intro"), bool("--no-intro"), bool("--no-outro"),
+ ], Q),
+
+ // ---- the trailer's beats ----
+ ...trailerBeats(),
+
+ form("tighten", "draft", "each clip to its sentence, each edge into its pause", [project(), bool("--all", "every clip"), bool("--no-measure", "the words alone"), opt("--apply", { help: "clip,clip: write those rows" })]),
+ form("ledger ls", "project", "a measure ledger's rows", [project(), opt("--scope"), opt("--population")], { shape: "ledger <project> ls" }),
+ form("ledger add", "draft", "a ledger row, checked against its schema", [
+ project(), arg("id"), opt("--date"), opt("--scope"), opt("--population"), opt("--value"), opt("--scopeBasis", { type: "text" }), opt("--row", { type: "json" }),
+ { name: "more", type: "flagpairs", help: "any other key=value, one per line (each --key value)" },
+ ], { shape: "ledger <project> add <id>" }),
+ form("ledger set", "draft", "a ledger row's keys", [project(), arg("id"), { name: "keys", type: "flagpairs", required: true, help: "key=value, one per line (each --key value; null clears)" }, opt("--unset", { help: "k,k" })], { shape: "ledger <project> set <id>" }),
+ form("ledger rm", "draft", "a ledger row removed (refused while something names it)", [project(), arg("id")], { shape: "ledger <project> rm <id>", confirm: { what: "remove the ledger row" } }),
+ form("measure", "project", "the measure slice the instruments draw from", [project(), takeOpt({ help: "that take's built seconds" }), opt("--scopes", { help: "a,b" }), opt("--scale", { help: "MIN-MAX" }), opt("--as-of", { help: "YYYY-MM-DD" })]),
+ form("rulings show", "project", "each montage clip and its ruling", [project()], { shape: "rulings <project> show" }),
+ form("rulings import", "draft", "the earlier rulings in the seed's edits.json", [project(), dry()], { shape: "rulings <project> import" }),
+ form("rulings set", "draft", "a montage clip's ruling", [project(), clip({ help: "the clip or its moment key" }), pick("ruling", ["keep", "cut", "not-him", "read-aloud"], { required: true }), opt("--reason"), opt("--match")], { shape: "rulings <project> set <clip> <ruling>" }),
+ form("rulings clear", "draft", "a montage clip's ruling cleared", [project(), clip()], { shape: "rulings <project> clear <clip>" }),
+ form("fetch", "project", "the clip windows, asked of the editor", [
+ project(), dry(), bool("--wait", "follow the editor's jobs"), bool("--status", "the last run's jobs"), bool("--body", "print the request body"), opt("--reason"),
+ opt("--refetch", { help: "clipId,clipId: evict those windows first" }), opt("--refetch-video", { help: "<slug>/<id>" }), takeOpt({ help: "a take's clips" }),
+ ], { timeoutMin: 60, confirm: { what: "evict those cached windows, then fetch them again", when: ["--refetch", "--refetch-video"], unless: ["--dry-run"] } }),
+ form("prep", "project", "the bench's excerpts and waveforms, before the walk", [project(), opt("--clips", { help: "a,b" }), bool("--wait", "here, until done"), bool("--status"), takeOpt()], Q),
+ form("prune", "project", "takes' work files freed by policy (a dry run unless --yes)", [
+ project({ required: false, help: "one project (none: --all)" }), bool("--all"), opt("--take", { help: "X[,Y]" }), bool("--anyway"), num("--keep"), opt("--older-than", { help: "3d" }), opt("--idle-work", { help: "3d" }),
+ bool("--versions", "whole superseded takes"), opt("--idle"), opt("--grace"), bool("--yes", "free them (else a dry run)"),
+ ], { confirm: { what: "delete those work files (--versions: whole superseded takes)", when: ["--yes"] } }),
+ form("fallback", "draft", "stand-ins for refused montage windows", [project(), dry(), many("--clip", { repeat: true, help: "clip ids, one per line (none: every candidate)" }), opt("--restore", { help: "a switched clip's id" })]),
+ form("phrases", "corpus", "how often each phrase was said, by year", [
+ many("phrases", { required: true, help: "one phrase per line" }), opt("--channels", { required: true, help: "a,b" }), opt("--prefer"), opt("--exclude", { help: "a regex" }),
+ bool("--words"), bool("--regex"), num("--samples"), bool("--no-cache"), bool("--full"),
+ ], { timeoutMin: 30 }),
+ form("voice-match", "project", "a speaker-similarity score per montage clip", [
+ project(), pick("--reference", ["auto", "rulings", "recordings"]), many("--reference-video", { repeat: true, item: "ref", help: "<channel>/<id>, one per line" }), many("--reference-channel", { repeat: true, item: "name" }),
+ file("--instances"), pick("--span", ["phrase", "cut"]), num("--pad"), num("--likely"), num("--unlikely"), bool("--dry"),
+ ], Q),
+ form("clips analyze", "draft", "the clip finder's scans on a long recording, then proposals", [project(), opt("--from", { type: "ref", help: "<channel>/<id>" }), bool("--rescan"), bool("--no-laughs"), bool("--no-voices"), ...clipParams(), file("--words"), bool("--keep-cut"), opt("--scope"), opt("--segment")], Q),
+ form("clips propose", "draft", "the clip finder's proposals again, from what is there", [project(), opt("--from", { type: "ref", help: "<channel>/<id>" }), num("--host"), ...clipParams(), file("--words"), bool("--keep-cut"), bool("--dry")]),
+ form("clips show", "project", "the speakers, the laughs, what is in the cut", [project()]),
+ form("clips segments", "project", "the narrated-video spans auto-scope finds", [project()]),
+ form("refresh", "corpus", "re-fetch an article's scope: the plan, and --yes starts it", [arg("article", { required: false }), num("--iteration"), bool("--no-fetch"), bool("--yes", "start it"), bool("--check", "the daily suggestion check, now"), bool("--force")], { confirm: { what: "start the refresh: an editor job that fetches the article's scope again", when: ["--yes"] } }),
+ form("clip", "corpus", "quick clip: one moment to a basic-mode mp4 and its share line", [arg("spec", { help: "<channel>/<video>@<start>-<end>" }), pick("--snap", ["words"]), opt("--title"), name("--site"), name("--folder")], Q),
+ form("share", "project", "a clip's share line", [project(), clip({ required: false, help: "the clip (none: the first)" }), takeOpt({ help: "the take's cut" }), name("--site")]),
+
+ // ---- the cut's structure ----
+ ...timeline(),
+
+ form("scenes", "project", "scene cuts and black spans in a clip's fetched window", [project(), clip(), num("--black-min"), num("--threshold"), num("--pix-th"), num("--pad"), num("--from"), num("--to")]),
+
+ // ---- posts ----
+ ...posts(),
+
+ form("candidates ls", "project", "the proposed clips waiting on the Candidates panel", [project(), bool("--all", "the inserted and set aside too")], { shape: "candidates <project> ls" }),
+ form("candidates import", "project", "a sweep's bullets as candidates", [project(), file("file", { help: "a sweep's markdown, a file of the project" }), dry()], { shape: "candidates <project> import <file>" }),
+ form("candidates add", "project", "an agent's proposal(s) as candidates", [project(), arg("proposal", { type: "text", atFile: true, help: "JSON (@file: from a terminal)" })], { shape: "candidates <project> add <proposal>" }),
+ form("ingredient", "corpus", "one recording's (or clip window's) life cycle: found to published", [
+ arg("recording", { type: "ref", help: "<channel>/<video> (a Rumble folder slug or its embed id)" }), opt("--window", { help: "<from>-<to>: one clip window" }), bool("--used-in", "every project clip that cuts from it, alone"),
+ ]),
+ none("help", "corpus", "every command", "prints the command list: the palette's Commands are the same list"),
+]);
+
+function clipParams() {
+ return [num("--target", { help: "the cut's length, s" }), num("--laugh-min"), num("--merge-gap"), num("--setup-max"), num("--clip-max")];
+}
+
+function trailerBeats() {
+ const tb = (sub, summary, args, extra = {}) =>
+ form(`trailer-beats ${sub}`, "project", summary, [project(), ...args, reel()], { shape: `trailer-beats <project> ${sub}`, ...extra });
+ const n = (o = {}) => num("n", { required: true, help: "the beat's number", ...o });
+ return [
+ tb("ls", "a reel's beats against its limit", []),
+ tb("add", "a clip beat", [clip(), arg("span", { required: false, help: "<from>-<to> source s (none: the whole cut)" }), num("--at", { help: "its place" }), opt("--label"), takeOpt({ help: "the take it is anchored to" })]),
+ tb("add-raw", "a beat of master seconds", [num("at", { required: true }), num("dur", { required: true }), num("--at", { help: "its place" }), opt("--label")]),
+ tb("set", "beat n's source seconds", [n(), arg("span", { help: "<from>-<to>" }), opt("--label")]),
+ tb("gap", "seconds cut out of beat n's middle", [n(), pick("op", ["add", "remove", "clear"], { required: true }), arg("value", { required: false, help: "<from>-<to> (add), a second (remove)" })]),
+ tb("remove", "a beat out", [n()]),
+ tb("move", "a beat to another place", [n(), num("--to", { required: true })]),
+ tb("order", "the beats in the cut's order", []),
+ tb("limit", "the running length's limit", [arg("limit", { help: "s, m:ss, x, instagram, shorts, tiktok" })]),
+ tb("xfade", "the crossfade's seconds", [num("seconds", { required: true })]),
+ tb("intro", "the reel's intro", [arg("value", { help: "on | off | a render.intro JSON" })]),
+ tb("outro", "the card the reel ends on", [arg("value", { help: "on | off | none | a JSON card" })]),
+ tb("candidates", "the walk's ★ clips not yet beats", [bool("--add", "add them all")]),
+ tb("verdict", "the walk's word on beat n", [n(), pick("verdict", ["confirmed", "note", "clear"], { required: true })]),
+ tb("title", "the reel's name", [arg("text", { help: "a title, or none" })]),
+ tb("take", "the take the reel is cut from", [name("take", { context: "take", help: "a take, or none" })]),
+ tb("undo", "the reel as it was before its last write", []),
+ tb("status", "each beat against the take the reel plays now", [takeOpt({ help: "against that take" })]),
+ tb("anchor", "beats anchored to a take's master", [many("beats", { help: "beat numbers, one per line (none: all)" }), takeOpt({ required: true })]),
+ tb("clamp", "a clipped beat pulled inside its clip", [n(), takeOpt()]),
+ tb("repoint", "an orphan beat's seconds on another clip", [n(), clip(), takeOpt()]),
+ tb("history", "every write to the reel", []),
+ tb("reels", "the project's reels", []),
+ tb("new-reel", "a new reel, empty or a copy", [name("name"), name("--from", { help: "a reel to copy" }), opt("--title")]),
+ ];
+}
+
+function timeline() {
+ const tl = (sub, target, summary, args, extra = {}) =>
+ form(`timeline ${sub}`, target, summary, [project(), ...args], { shape: `timeline <project> ${sub}`, ...extra });
+ const id = (o = {}) => arg("id", { context: "clip", help: "the entry's id", ...o });
+ const gid = () => arg("gid", { help: "the group's id" });
+ const marker = () => arg("marker", { help: "the section's marker" });
+ const ids = (o = {}) => many("ids", { required: true, help: "entry ids, one per line", ...o });
+ return [
+ tl("ls", "project", "the cut: index, id, type, video, start–end", [takeOpt({ help: "a take's timeline" })]),
+ tl("insert", "draft", "a clip (or a post item) into the cut", [
+ arg("spec", { help: "<channel>/<video>@<start>-<end>, post:<channel>/<postId> or post-json:<json>" }), opt("--after", { help: "an entry id, or - (the start)" }),
+ num("--to-section"), opt("--group"), opt("--id"), num("--section"), bool("--lock"), bool("--lock-end"), opt("--title"), opt("--stream-title"), opt("--date", { help: "YYYY-MM-DD" }),
+ opt("--quote", { type: "text" }), num("--cite"), opt("--cite-url"), takeOpt(),
+ ]),
+ tl("move", "draft", "an entry to an index", [id(), num("--to", { required: true, help: "its place after the move (0 first)" }), takeOpt()]),
+ tl("place", "draft", "entries before another (Play's drag)", [ids(), opt("--before", { required: true, help: "an entry id, or - (the end)" }), num("--section")]),
+ tl("remove", "draft", "an entry out of the cut", [id(), num("--at", { help: "which of an id's twins" }), takeOpt()]),
+ tl("duplicate", "draft", "an entry twice", [id(), num("--at")]),
+ tl("reject", "draft", "an entry rejected and removed, on the record", [id(), pick("why", REJECT_WHYS, { required: true }), opt("--note", { type: "text" })]),
+ tl("wrong-speaker", "draft", "an entry removed: the wrong speaker", [id(), opt("--correction", { type: "text" })]),
+ tl("post", "draft", "a post added, or the one with its id replaced", [arg("post", { type: "text", atFile: true, help: "JSON (@file: from a terminal)" })]),
+ tl("post-remove", "draft", "a post out of the cut", [arg("id", { context: "post" })]),
+ tl("teaser", "draft", "a teaser's lines, beat, dip, tail", [id(), arg("patch", { type: "text", atFile: true, help: "a JSON patch (@file: from a terminal)" })]),
+ tl("teaser-insert", "draft", "a teaser or closing card inserted (default at the end)", [
+ pick("--at", ["end", "start"]), opt("--after", { help: "an entry's id: after it" }), opt("--before", { help: "an entry's id: before it" }), opt("--id"), num("--beat"),
+ many("--line", { repeat: true, help: "its lines, one per line (the first its title)" }),
+ opt("--lines-json", { type: "json", atFile: true, help: "the lines as JSON, each a string or {text, break?, hold?} (@file: from a terminal)" }),
+ ]),
+ tl("undo", "draft", "the newest automatic snapshot back", [takeOpt({ help: "a take's own undo" })]),
+ tl("sections", "project", "the deck's sections and their clips", []),
+ tl("section-move", "draft", "clips to the end (or start) of section N", [ids(), num("--to-section", { required: true }), bool("--start")]),
+ tl("section-add", "draft", "a new section after a clip", [opt("--after", { required: true }), opt("--label"), opt("--color"), pick("--level", ["1", "2"])]),
+ tl("section-boundary", "draft", "a section boundary dragged", [marker(), opt("--after", { required: true })]),
+ tl("section-remove", "draft", "a section's marker removed", [marker()]),
+ tl("section-set", "draft", "a section's label, colour or level", [marker(), opt("--label"), opt("--color"), pick("--level", ["1", "2"])]),
+ tl("split", "draft", "a clip in two at a source second", [id(), num("second", { required: true })]),
+ tl("flash-forward", "draft", "a tight copy of a span elsewhere, as a repeat", [id(), arg("span", { help: "<from>-<to>" }), opt("--after"), num("--to-section"), bool("--start"), bool("--move", "the span leaves the clip"), opt("--quote"), opt("--id")]),
+ tl("order", "draft", "the cut's order in one write", [many("order", { required: true, item: "id", help: "entry ids in order, one per line" })]),
+ tl("threads", "draft", "the cut's conversations (and --write gathers them)", [bool("--write"), opt("--conversation")]),
+ tl("groups", "project", "the claim groups, by section", []),
+ tl("groups import", "draft", "a claim-groups file in one write", [file("file", { help: "a claim-groups file of the project" }), bool("--skip-missing"), bool("--drop-empty")]),
+ tl("groups set", "draft", "a group is these clips", [arg("gid", { help: "a group id, or - (a new one)" }), ids(), opt("--claim")]),
+ tl("groups label", "draft", "a group's claim", [gid(), arg("claim", { type: "text" })]),
+ tl("groups remove", "draft", "a group dissolved (its clips stay)", [gid()]),
+ tl("groups move", "draft", "a whole group to another place", [gid(), opt("--to", { required: true, help: "<index>, or after <gid>" })]),
+ tl("groups promote", "draft", "a group opens a subsection", [gid(), opt("--label")]),
+ tl("add-video", "draft", "a video entry: a project file full frame", [
+ file("src", { pass: "relative", help: "a video file of the project, relative to its directory" }), num("--from"), num("--to"), pick("--fit", ["contain", "cover"]), num("--bass"), num("--gain"), opt("--enter", { help: "cut | <out>,<in>" }),
+ num("--hold"), opt("--title"), opt("--id"), opt("--after"), dry(), takeOpt(),
+ ]),
+ tl("set-video", "draft", "a video entry's knobs", [id(), pairs({ help: "from= to= fit= audio.gain= …, one per line" }), takeOpt()]),
+ ];
+}
+
+function posts() {
+ const p = (sub, target, summary, args, extra = {}) => form(`posts ${sub}`, target, summary, [project(), ...args], extra);
+ const items = () => many("items", { help: "post item ids, one per line" });
+ return [
+ p("add", "draft", "a post card from the posts archive", [arg("post", { help: "<archive-channel>/<postId>" }), opt("--attach", { help: "a clip id" }), opt("--flag"), opt("--author"), opt("--id"), bool("--thread"), num("--crop"), dry()]),
+ p("set", "draft", "the Posts table's writer: thread, hide, attach, crop", [arg("post", { context: "post", help: "x-<postId> or the bare id" }), pairs({ help: "thread=on, hide=off, attach=<clip>|auto, crop=<px>|off" })]),
+ p("reel", "draft", "post items from posts channels, in one write", [
+ many("--channel", { repeat: true, required: true, item: "name", help: "posts channels, one per line" }), opt("--since"), opt("--until"), bool("--own"), bool("--with-media"),
+ pick("--replies", ["include", "only", "exclude"]), pick("--order", ["chrono", "reverse"]), num("--limit"), opt("--after"), dry(),
+ ]),
+ p("set-item", "draft", "a post item's knobs", [item(), pairs({ help: "hold=4, layout=grid, media.0.start=2 …" }), inTake()]),
+ p("narrate", "draft", "a post item's narration: script, takes, pick, approve, mix", [
+ item({ required: false, help: "the post item (none: --list, --import, --all or --cut)" }), opt("--script", { type: "text" }), bool("--take", "a new read (the editor's tts)"), opt("--note"),
+ opt("--voice"), opt("--engine"), num("--speed"), num("--pick"), bool("--approve"), bool("--unapprove"), bool("--off"), bool("--on"),
+ bool("--thread", "with --take: a thread read"), opt("--parents"), bool("--words", "the picked take's word timings"), bool("--import"), bool("--list"), bool("--all"), bool("--draft-scripts"),
+ num("--limit"), bool("--force"), file("--recording", { help: "a person's recording (a file of the project) made the read" }), opt("--as"), dry(),
+ pairs({ required: false, help: "the mix: lead= tail= linger= rate= …, one per line" }), inTake(),
+ ], Q),
+ p("say", "draft", "the pronunciation lexicon", [pick("op", ["ls", "add", "remove", "try", "stale"], { required: true }), arg("word", { required: false, allowAt: true, help: "the word or phrase (try: the text)" }), arg("spoken", { required: false }), bool("--case"), opt("--item"), opt("--note")], { shape: "posts say <project> <op>" }),
+ p("voices", "draft", "the voice map a thread read uses", [pick("op", ["ls", "set", "remove"], { required: true }), arg("handle", { required: false, help: "a handle, or *" }), arg("voice", { required: false })], { shape: "posts voices <project> <op>" }),
+ p("fit", "draft", "narrated posts' videos cut to their best part", [items(), bool("--all"), num("--linger"), dry()], Q),
+ p("fx", "draft", "a post item's word zooms, captions, clock, slams", [
+ item(), pick("op", ["ls", "add", "set", "remove"], { required: true }), arg("what", { required: false, help: "add: word-zoom | caption | clock | slam; set/remove: n" }),
+ { name: "flags", type: "flagpairs", help: "match=…, text=…, at=…, one per line (each --key value)" }, inTake(),
+ ], { shape: "posts fx <project> <item> <op>" }),
+ p("clock", "draft", "the cut's clock default", [pick("mode", ["on", "off", "default"]), opt("--zone", { help: "an IANA zone" })]),
+ p("progress", "draft", "the cut's progress bar default", [pick("mode", ["auto", "on", "off", "default"])]),
+ p("avatar", "draft", "an author's picture on the cards", [arg("handle", { required: false, allowAt: true }), file("image", { required: false, literals: ["off"], help: "a picture file of the project, or off" })]),
+ p("avatars", "draft", "the authors' pictures from the archive", [dry()]),
+ p("redact", "draft", "words blanked from what is published", [pick("op", ["ls", "add", "remove"], { required: true }), arg("value", { required: false, help: "the term (add), its n (remove)" }), bool("--substring"), opt("--note")], { shape: "posts redact <project> <op>" }),
+ p("slurs", "draft", "the slur filter", [pick("op", ["ls", "on", "off", "level", "visual", "voice", "add", "except", "remove", "edges"], { required: true }), arg("value", { required: false }), bool("--off")], { shape: "posts slurs <project> <op>" }),
+ p("context", "draft", "each post item's context from its capture", [dry()]),
+ p("repeats", "project", "the attachments played more than once", [pick("--match", ["id", "file", "audio"])]),
+ p("combo", "draft", "the combo badge's knobs (the cut's, or one item's)", [arg("item", { required: false, context: "post" }), pairs({ required: false, help: "on=on, label=COMBO … (an item: off | on | auto first)" })]),
+ p("attach", "draft", "a capture's media onto post items that carry none", [items(), bool("--all"), dry()]),
+ p("scenes", "draft", "the media scenes (and the cut's on/off)", [pick("mode", ["on", "off"])]),
+ p("picture-reply", "draft", "the cut's picture-only rule", [pairs({ required: false, help: "on=on, image=2, min=1.5 …" }), inTake()]),
+ p("roles", "draft", "a read's pieces, stored or inferred", [items(), bool("--write"), opt("--set", { help: "<n>=<role>,…" }), inTake()]),
+ p("reread", "draft", "a read re-joined, re-timed, paused or a phrase re-voiced", [
+ item(), opt("--without", { help: "parent:0,quoted …" }), opt("--drop-parts"), bool("--drop-urls"), opt("--tempo-for"), num("--tempo"), opt("--parts"), pick("--stretch", ["atempo", "rubberband"]),
+ bool("--yell-caps"), num("--yell-gain"), pick("--yell-style", ["raise", "shout", "loud"]), opt("--pause"), opt("--target"), opt("--revoice"), opt("--say"), opt("--voice"), num("--xfade"), opt("--splice"), dry(), inTake(),
+ ], Q),
+ p("yell", "draft", "the caps he wrote, yelled in the read", [items(), bool("--all"), num("--yell-gain"), pick("--yell-style", ["raise", "shout", "loud"]), dry()], Q),
+ ];
+}
+
+// ---- reading the table ------------------------------------------------------------
+
+/** The row for a verb, or null. */
+export const verbRow = (verb) => VERBS.find((r) => r.verb === verb) ?? null;
+
+/** The rows the palette offers (ui "form"), as the page needs them: no prose. */
+export function formVerbs() {
+ return VERBS.filter((r) => r.ui === "form").map((r) => ({
+ verb: r.verb,
+ summary: r.summary,
+ target: r.target,
+ queue: !!r.queue,
+ confirm: r.confirm ?? null,
+ args: r.args,
+ }));
+}
+
+/** The top-level command a row belongs to: its first word. */
+export const commandOf = (verb) => String(verb).split(" ")[0];
diff --git a/umtool/lib/cli/verbs.test.mjs b/umtool/lib/cli/verbs.test.mjs
@@ -0,0 +1,311 @@
+// The verb registry (lib/cli/verbs.mjs) names every verb umtool dispatches,
+// each row is a form or says why it is not, and `umtool help` and
+// docs/cli.md are what it generates.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { VERBS, formVerbs, verbRow, commandOf } from "./verbs.mjs";
+import { GROUPS } from "./groups.mjs";
+import { CLI_MD, DOCS_BEGIN, DOCS_END, usageText, withVerbsSection } from "./docs.mjs";
+import { buildArgv, cliLine, confirmOf, pathArgsOf, shellQuote, synopsis } from "./argv.mjs";
+import { confineToProject } from "./confine.mjs";
+
+const UMTOOL = fileURLToPath(new URL("../../", import.meta.url));
+const read = (rel) => readFileSync(`${UMTOOL}${rel}`, "utf8");
+const ADD = "add a row to umtool/lib/cli/verbs.mjs: form(verb, target, summary, args) with its args, or none(verb, target, summary, reason) with why it has no form";
+
+/** The top-level commands bin/umtool.mjs dispatches: its COMMANDS table's keys. */
+function dispatched() {
+ const src = read("bin/umtool.mjs");
+ const a = src.indexOf("const COMMANDS = {");
+ const b = src.indexOf("\n};", a);
+ assert.ok(a >= 0 && b > a, "bin/umtool.mjs has its COMMANDS table");
+ return [...src.slice(a, b).matchAll(/^ {2}("?)([a-z][a-z-]*)\1:/gm)].map((m) => m[2]);
+}
+
+// Where each command's sub-verbs are dispatched, and the pattern that names one. A sub-verb added to one of
+// these files without a row fails "every sub-verb …" below, naming it.
+const SUBVERBS = [
+ { cmd: "takes", file: "lib/report/takeCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g },
+ { cmd: "timeline", file: "lib/report/timelineCli.mjs", re: /\bverb === "([a-z][a-z-]*)"|case "([a-z][a-z -]*)":/g },
+ { cmd: "posts", file: "lib/report/postsCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g },
+ { cmd: "trailer-beats", file: "lib/report/trailerBeatsCli.mjs", re: /\bverb === "([a-z][a-z-]*)"|case "([a-z][a-z-]*)":/g },
+ { cmd: "cast", file: "lib/report/castCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, ignore: ["help", "remove"] },
+ { cmd: "queue", file: "lib/queue/cli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g },
+ { cmd: "notes", file: "lib/annotations/cli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g, ignore: ["help"] },
+ { cmd: "rulings", file: "lib/report/rulingsCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g },
+ { cmd: "ledger", file: "lib/report/ledgerCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g },
+ { cmd: "candidates", file: "lib/report/candidatesCli.mjs", re: /\bverb === "([a-z][a-z-]*)"/g },
+ { cmd: "clips", file: "lib/report/reactions.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, ignore: ["help"] },
+ { cmd: "pool", file: "lib/report/poolCli.mjs", re: /\bsub === "([a-z][a-z-]*)"/g },
+ { cmd: "render-mode", file: "lib/report/renderMode.mjs", re: /\bsub === "([a-z][a-z-]*)"/g },
+ { cmd: "schedule", file: "bin/schedule.ts", re: /\bsub === "([a-z][a-z-]*)"/g },
+ { cmd: "storage", file: "bin/umtool.mjs", re: /\bsub === "([a-z][a-z-]*)"/g, within: ["async function cmdStorage()", "async function cmdStorageDeliverables"] },
+];
+
+/** The sub-verbs a file dispatches for a command. */
+function subverbsOf({ file, re, ignore = [], within }) {
+ let src = read(file);
+ if (within) src = src.slice(src.indexOf(within[0]), src.indexOf(within[1]));
+ const names = new Set();
+ for (const m of src.matchAll(re)) names.add((m[1] ?? m[2]).trim());
+ return [...names].filter((n) => !ignore.includes(n));
+}
+
+test("every command bin/umtool.mjs dispatches has a row (and its help lines in groups.mjs)", () => {
+ const verbs = new Set(VERBS.map((r) => commandOf(r.verb)));
+ const groups = new Set(GROUPS.map((g) => g.cmd));
+ for (const cmd of dispatched()) {
+ assert.ok(verbs.has(cmd), `\`umtool ${cmd}\` is dispatched (bin/umtool.mjs COMMANDS) but has no row -- ${ADD}`);
+ if (cmd !== "help") assert.ok(groups.has(cmd), `\`umtool ${cmd}\` has no help lines -- add a group to umtool/lib/cli/groups.mjs`);
+ }
+ const all = new Set(dispatched());
+ for (const r of VERBS) assert.ok(all.has(commandOf(r.verb)), `the row \`${r.verb}\` names a command bin/umtool.mjs does not dispatch`);
+ for (const g of GROUPS) assert.ok(all.has(g.cmd), `groups.mjs's \`${g.cmd}\` is not a command bin/umtool.mjs dispatches`);
+});
+
+test("every sub-verb the CLI modules dispatch has a row", () => {
+ const have = new Set(VERBS.map((r) => r.verb));
+ for (const s of SUBVERBS) {
+ const subs = subverbsOf(s);
+ assert.ok(subs.length, `${s.file} still dispatches ${s.cmd}'s sub-verbs the way verbs.test.mjs reads them`);
+ for (const sub of subs) {
+ const verb = `${s.cmd} ${sub}`;
+ // A group's bare name ("timeline groups") is its listing.
+ assert.ok(have.has(verb), `\`umtool ${verb}\` is dispatched (${s.file}) but has no row -- ${ADD}`);
+ }
+ }
+ for (const v of ["modules list", "modules apply", "preset list", "preset show", "preset save", "preset apply", "render-mode off", "take status", "takes save", "takes open", "takes freeze"]) {
+ assert.ok(have.has(v), `\`umtool ${v}\` has no row -- ${ADD}`);
+ }
+});
+
+test("every row is a form or says why it is not, and its args make sense", () => {
+ const TYPES = new Set(["project", "string", "text", "number", "boolean", "choice", "json", "pairs", "flagpairs", "list", "name", "path", "ref"]);
+ const seen = new Set();
+ for (const r of VERBS) {
+ assert.ok(!seen.has(r.verb), `\`${r.verb}\` has two rows`);
+ seen.add(r.verb);
+ assert.ok(r.summary?.trim(), `\`${r.verb}\` has a summary`);
+ assert.ok(["draft", "project", "corpus"].includes(r.target), `\`${r.verb}\`'s target is draft, project or corpus`);
+ assert.ok(r.ui === "form" || r.ui === "none", `\`${r.verb}\`'s ui is "form" or "none"`);
+ if (r.ui === "none") {
+ assert.ok(r.reason?.trim(), `\`${r.verb}\` has no form: say why (reason)`);
+ continue;
+ }
+ const names = new Set();
+ for (const a of r.args) {
+ assert.ok(!names.has(a.name), `\`${r.verb}\`: ${a.name} twice`);
+ names.add(a.name);
+ assert.ok(TYPES.has(a.type), `\`${r.verb}\`: ${a.name}'s type ${a.type}`);
+ if (a.type === "choice") assert.ok(a.choices?.length, `\`${r.verb}\`: ${a.name} names its choices`);
+ if (a.type === "boolean" || a.type === "flagpairs") assert.ok(a.name.startsWith("--") || a.type === "flagpairs", `\`${r.verb}\`: a boolean is a flag`);
+ }
+ for (const t of (r.shape ?? r.verb).split(" ")) {
+ const m = /^<(.+)>$/.exec(t);
+ if (m) assert.ok(r.args.some((a) => a.name === m[1] && !a.name.startsWith("--")), `\`${r.verb}\`'s shape names <${m[1]}>, a positional it has`);
+ }
+ // The shape's words are the verb's own, in order.
+ const words = (r.shape ?? r.verb).split(" ").filter((t) => !t.startsWith("<"));
+ assert.deepEqual(words, r.verb.split(" "), `\`${r.verb}\`'s shape keeps its words in order`);
+ }
+ assert.ok(formVerbs().every((r) => !("usage" in r) && !("reason" in r)), "the page's list carries no prose");
+ assert.equal(formVerbs().length, VERBS.filter((r) => r.ui === "form").length);
+});
+
+test("cli.md's generated section is current (node umtool/lib/cli/docs.mjs rewrites it)", () => {
+ const text = readFileSync(CLI_MD, "utf8");
+ assert.ok(text.includes(DOCS_BEGIN) && text.includes(DOCS_END), "the markers are in cli.md");
+ assert.equal(withVerbsSection(text), text, "umtool/docs/cli.md is stale: run `node umtool/lib/cli/docs.mjs`");
+ // Every row is in it, and the hand-written sections around it stay.
+ for (const r of VERBS) assert.ok(text.includes(r.ui === "form" ? synopsis(r).replace(/\|/g, "\\|") : `\`${r.verb}\``), `cli.md lists \`${r.verb}\``);
+ assert.ok(text.includes("## Environment") && text.includes("## `check` is the one to run before every build"));
+});
+
+test("umtool help is generated from the groups, with its fills", () => {
+ const help = usageText({ reportsRoot: "/r", chainSteps: "current, windows", draftAllSteps: "a, b" });
+ assert.match(help, /^umtool — the project tree, from a terminal\n\n {2}umtool ls /);
+ assert.match(help, /one step a process: current, windows/);
+ assert.match(help, /\(Draft everything\): a, b —/);
+ assert.match(help, /reading \/r {2}\(set REPORTS_DIR to move it\)/);
+ assert.ok(!help.includes("{chainSteps}"));
+ for (const g of GROUPS) for (const l of g.usage) assert.ok(/^ {2}umtool [a-z-]+ |^ {19}/.test(l), `${g.cmd}: "${l.slice(0, 40)}…" is a usage line`);
+});
+
+test("buildArgv: a row and a form's values to the words umtool is run with", () => {
+ const look = verbRow("look");
+ assert.deepEqual(buildArgv(look, { project: "reports/basic-fixture", settings: "mode=basic\n\n deck.markerLayout=stagger " }), {
+ ok: true,
+ argv: ["look", "reports/basic-fixture", "mode=basic", "deck.markerLayout=stagger"],
+ });
+ // The shape puts the project before the sub-verb; flags after the positionals.
+ const insert = verbRow("timeline insert");
+ assert.deepEqual(buildArgv(insert, { project: "p", spec: "yt/abc@1-5", "--after": "-", "--lock": true, "--section": 2 }).argv, [
+ "timeline", "p", "insert", "yt/abc@1-5", "--after", "-", "--section", "2", "--lock",
+ ]);
+ // A repeated flag, flag pairs.
+ assert.deepEqual(buildArgv(verbRow("look"), { project: "p", settings: ["a=1"], "--unset": ["render.rail", "render.title"] }).argv, [
+ "look", "p", "a=1", "--unset", "render.rail", "--unset", "render.title",
+ ]);
+ assert.deepEqual(buildArgv(verbRow("ledger set"), { project: "p", id: "r1", keys: "value=12\nflags=a|b" }).argv, ["ledger", "p", "set", "r1", "--value", "12", "--flags", "a|b"]);
+ // A false boolean and an empty string are left out.
+ assert.deepEqual(buildArgv(verbRow("show"), { project: "p" }).argv, ["show", "p"]);
+ assert.deepEqual(buildArgv(verbRow("check"), { project: "", "--all-severities": false }).argv, ["check"]);
+});
+
+test("buildArgv refuses what a form may not send", () => {
+ const look = verbRow("look");
+ const no = (values, re, row = look) => {
+ const r = buildArgv(row, values);
+ assert.equal(r.ok, false, JSON.stringify(values));
+ assert.match(r.error, re);
+ };
+ no({ project: "p" }, /settings is required/);
+ no({ project: "p", settings: "mode=basic", argv: ["rm", "-rf"] }, /takes no "argv"/);
+ no({ project: "--all", settings: "mode=basic" }, /may not start with "-"/);
+ no({ project: "p", settings: "--json" }, /not key=value/);
+ no({ project: "p", settings: "mode" }, /not key=value/);
+ no({ project: "p", settings: "a=\0" }, /NUL/);
+ no({ project: "p", settings: { a: 1 } }, /a string, a number/);
+ no({ project: "p", clip: "c1", "--start": "soon" }, /a number/, verbRow("window"));
+ no({ project: "p", clip: "c1", "--verdict": "maybe" }, /one of confirmed, incorrect/, verbRow("window"));
+ no({ project: "p", "--patch-json": "{nope", "--id": "t" }, /not JSON/, verbRow("take"));
+});
+
+test("an empty optional positional before a given one is refused (it would shift the words)", () => {
+ const row = { verb: "x", args: [{ name: "a", type: "string" }, { name: "b", type: "string" }] };
+ const r = buildArgv(row, { b: "2" });
+ assert.equal(r.ok, false);
+ assert.match(r.error, /a is needed before b/);
+ // Negative numbers are values, not flags.
+ assert.deepEqual(buildArgv(verbRow("window"), { project: "p", clip: "c1", "--start": "-0.5" }).argv, ["window", "p", "c1", "--start", "-0.5"]);
+});
+
+test("cliLine: the exact line to paste, quoted for a shell", () => {
+ assert.equal(cliLine(["look", "reports/basic-fixture", "mode=basic"]), "node umtool/bin/umtool.mjs look reports/basic-fixture mode=basic");
+ assert.equal(shellQuote("it's here"), `'it'\\''s here'`);
+ assert.equal(shellQuote(""), "''");
+ assert.equal(shellQuote('deck.markers=[{"after":"c01"}]'), `'deck.markers=[{"after":"c01"}]'`);
+ assert.equal(synopsis(verbRow("timeline move")), "timeline <project> move <id> --to N [--take TAKE]");
+});
+
+test("a form's flags are flags the CLI still parses (a renamed flag fails here)", () => {
+ // Best effort: every `--flag` of a form row is a string literal somewhere in the CLI's parsers. A `--no-x` is
+ // the negation idiom of `--x` (bin/umtool.mjs window); ledger takes any `--<key>` of its schema.
+ const files = [
+ ...readdirSync(`${UMTOOL}lib/report`).filter((f) => f.endsWith(".mjs") && !f.includes(".test.")).map((f) => `lib/report/${f}`),
+ "bin/umtool.mjs", "bin/schedule.ts", "bin/refresh.ts", "bin/inbox.ts", "lib/queue/cli.mjs", "lib/annotations/cli.mjs", "lib/phrase-finder/cli.mjs", "lib/ingredients/cli.mjs",
+ ];
+ const src = files.map(read).join("\n");
+ const GENERIC = new Set(["ledger"]);
+ const lost = [];
+ for (const r of VERBS) {
+ if (GENERIC.has(commandOf(r.verb))) continue;
+ for (const a of r.args) {
+ if (!a.name.startsWith("--")) continue;
+ const lit = (n) => src.includes(`"${n}"`) || src.includes(`'${n}'`);
+ const neg = a.name.startsWith("--no-") && lit(`--${a.name.slice(5)}`) && src.includes("`--no-${");
+ if (!lit(a.name) && !neg) lost.push(`${r.verb} ${a.name}`);
+ }
+ }
+ assert.deepEqual(lost, [], "a form names a flag no CLI parser does: rename it in umtool/lib/cli/verbs.mjs");
+});
+
+test("no form writes or reads a file a page names freely: outputs are bare names, inputs are project files", () => {
+ for (const r of VERBS.filter((x) => x.ui === "form")) {
+ for (const a of r.args) {
+ if (["--out", "--name", "--id", "--from", "--by", "--reel", "--folder", "--site"].includes(a.name) && a.type !== "project") {
+ assert.ok(["name", "ref", "string", "number"].includes(a.type), `${r.verb} ${a.name}: ${a.type}`);
+ }
+ if (a.name === "--out") assert.equal(a.type, "name", `${r.verb} --out is a bare name, never a path`);
+ if (a.type === "path") assert.ok(r.args.some((x) => x.name === "project" && x.type === "project"), `${r.verb}: a path arg needs the project it is inside`);
+ if (/@file/.test(a.help ?? "")) assert.ok(a.atFile, `${r.verb} ${a.name} names @file: it refuses it from a form`);
+ }
+ }
+ for (const v of ["vertical", "voice-match"]) assert.ok(!verbRow(v).args.some((a) => a.name === "--out"), `${v}: --out (a path) is a terminal's`);
+ for (const [v, n] of [["take", "--patch"], ["trailer", "--beats"], ["modules apply", "--config"], ["candidates import", "file"], ["timeline groups import", "file"], ["posts narrate", "--recording"], ["takes make", "--recipe"]]) {
+ assert.equal(verbRow(v).args.find((a) => a.name === n)?.type, "path", `${v} ${n} is a project file`);
+ }
+});
+
+test("names, paths, refs and @file: what a page may not send", () => {
+ const no = (row, values, re) => {
+ const r = buildArgv(row, values);
+ assert.equal(r.ok, false, JSON.stringify(values));
+ assert.match(r.error, re);
+ };
+ const trailer = verbRow("trailer");
+ for (const out of ["../x.mp4", "a/b.mp4", ".hidden", "/etc/x", "..", "x\\y"]) no(trailer, { project: "p", "--out": out }, /bare name|start with "-"/);
+ assert.deepEqual(buildArgv(trailer, { project: "p", "--out": "teaser-2.mp4" }).argv, ["trailer", "p", "--out", "teaser-2.mp4"]);
+ no(verbRow("take"), { project: "p", "--id": "../../evil" }, /bare name/);
+ no(verbRow("take"), { project: "p", "--id": "t", "--patch": "@/etc/passwd" }, /no @/);
+ no(verbRow("candidates add"), { project: "p", proposal: "@/etc/passwd" }, /terminal only/);
+ no(verbRow("timeline teaser"), { project: "p", id: "t1", patch: "@x.json" }, /terminal only/);
+ for (const o of ["/etc/passwd", "package.json", "@ids.txt", "../x"]) no(verbRow("timeline order"), { project: "p", order: o }, /not an entry's id|start with "-"|terminal only/);
+ assert.deepEqual(buildArgv(verbRow("timeline order"), { project: "p", order: "c01\nx-1987\nt:2" }).argv, ["timeline", "p", "order", "c01", "x-1987", "t:2"]);
+ // An @file reference anywhere a CLI splits a value (review): post-json:@…, a=@…, a,@….
+ for (const spec of ["post-json:@/etc/passwd", "post-json: @x.json", "@x", "post:@x"]) no(verbRow("timeline insert"), { project: "p", spec, "--after": "-" }, /terminal only/);
+ for (const settings of ["a=b,@/etc/passwd", "deck.markers=@m.json", "x=1;@y", "chat='@f'"]) no(verbRow("look"), { project: "p", settings }, /terminal only/);
+ no(verbRow("posts set-item"), { project: "p", item: "i1", settings: 'link.add= @/etc/passwd' }, /terminal only/);
+ no(verbRow("timeline set-video"), { project: "p", id: "v1", settings: "src=@x" }, /terminal only/);
+ // A person's words keep their @: a flag's value, free prose, a handle, a lexicon word, a pause at a take second.
+ assert.ok(buildArgv(verbRow("timeline insert"), { project: "p", spec: "yt/abc@1-5", "--quote": "@grok said, @x", "--title": "@sam" }).ok, "<channel>/<video>@<start>-<end> is not a file");
+ assert.ok(buildArgv(verbRow("notes reply"), { id: "n1", text: "@operator: done" }).ok);
+ assert.ok(buildArgv(verbRow("posts say"), { project: "p", op: "add", word: "@grok", spoken: "At grok" }).ok);
+ assert.ok(buildArgv(verbRow("posts reread"), { project: "p", item: "i1", "--pause": "@12.5=0.4" }).ok);
+ for (const v of ["@/etc/passwd", "/etc/passwd", "../../x", "~/x", "a/../../b", "'@x'"]) no(verbRow("posts set-item"), { project: "p", item: "i1", settings: `parent.0=${v}` }, /terminal only|outside the project/);
+ no(verbRow("take"), { project: "p", "--id": "t", "--set": "render.x=@f" }, /terminal only/);
+ no(verbRow("ledger add"), { project: "p", id: "r", more: "src=../../etc" }, /outside the project/);
+ for (const from of ["./report.md", "/home/x/report.md", "../r.md", "report.md"]) no(verbRow("new"), { slug: "s", "--from": from }, /share URL or <channel>\/<id>/);
+ assert.deepEqual(buildArgv(verbRow("new"), { slug: "s", "--from": "https://example.com/s/abc" }).argv.slice(-2), ["--from", "https://example.com/s/abc"]);
+ assert.deepEqual(buildArgv(verbRow("new"), { slug: "s", "--from": "thequartering/abc_123" }).argv.slice(-2), ["--from", "thequartering/abc_123"]);
+ // A handle is not a file: cast's <character|@handle> stays a value.
+ assert.ok(buildArgv(verbRow("cast use"), { project: "p", character: "@grok", voice: "kokoro:am_michael" }).ok);
+ // "false" from a form is off.
+ assert.deepEqual(buildArgv(verbRow("check"), { "--all-severities": "false" }).argv, ["check"]);
+ // The path args the server confines, literals aside.
+ assert.deepEqual(pathArgsOf(verbRow("posts avatar"), { project: "p", handle: "h", image: "off" }), []);
+ assert.deepEqual(pathArgsOf(verbRow("posts avatar"), { project: "p", handle: "h", image: "pics/a.png" }).map((a) => a.name), ["image"]);
+});
+
+test("confirm: a row that deletes, evicts or kills asks, when its args make it so", () => {
+ assert.match(String(confirmOf(verbRow("prune"), { project: "p", "--yes": true })), /delete/);
+ assert.equal(confirmOf(verbRow("prune"), { project: "p" }), null, "a dry run");
+ assert.match(String(confirmOf(verbRow("pool prune"), {})), /delete/);
+ assert.equal(confirmOf(verbRow("pool prune"), { "--dry-run": true }), null);
+ assert.match(String(confirmOf(verbRow("fetch"), { project: "p", "--refetch": "c1" })), /evict/);
+ assert.equal(confirmOf(verbRow("fetch"), { project: "p", "--refetch": "c1", "--dry-run": true }), null);
+ assert.equal(confirmOf(verbRow("fetch"), { project: "p" }), null);
+ for (const v of ["queue cancel", "notes resolve", "notes wontfix", "takes cancel", "ledger rm"]) assert.ok(confirmOf(verbRow(v), {}), v);
+ for (const [v, a] of [["index", "--prune"], ["takes freeze", "--apply"], ["render-mode off", "--force"], ["refresh", "--yes"], ["takes make", "--force"]]) {
+ assert.equal(confirmOf(verbRow(v), {}), null, `${v} bare`);
+ assert.ok(confirmOf(verbRow(v), { [a]: true }), `${v} ${a}`);
+ }
+ assert.ok(formVerbs().find((r) => r.verb === "prune")?.confirm, "the page knows to ask");
+});
+
+test("confineToProject: a file of the project by its realpath, symlinks followed", async () => {
+ const tmp = mkdtempSync(path.join(os.tmpdir(), "umtool-confine-"));
+ try {
+ const proj = path.join(tmp, "proj");
+ mkdirSync(path.join(proj, "promo"), { recursive: true });
+ writeFileSync(path.join(proj, "promo", "beats.json"), "[]");
+ writeFileSync(path.join(tmp, "secret.txt"), "the secret");
+ symlinkSync(path.join(tmp, "secret.txt"), path.join(proj, "leak.txt"));
+ symlinkSync(proj, path.join(tmp, "alias"));
+ const ok = await confineToProject(proj, "promo/beats.json");
+ assert.deepEqual(ok, { ok: true, abs: path.join(proj, "promo", "beats.json") });
+ assert.equal((await confineToProject(path.join(tmp, "alias"), "promo/beats.json")).ok, true, "a project reached through a link");
+ for (const bad of ["../secret.txt", path.join(tmp, "secret.txt"), "leak.txt", "promo", "nope.json", "promo/../../secret.txt"]) {
+ const r = await confineToProject(proj, bad);
+ assert.equal(r.ok, false, bad);
+ assert.ok(!String(r.error).includes("the secret"), "never what the file holds");
+ }
+ } finally {
+ rmSync(tmp, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs
@@ -138,3 +138,9 @@ test("Play the cut ↔ the clip bench: Edit this clip carries the way back, Back
assert.equal(H.playHref("a/b", { at: 3 }), "/projects/a/b/play");
assert.equal(H.playHref("a/b", { take: "t1", note: "n" }), "/projects/a/b/play?take=t1¬e=n");
});
+
+test("ingredientHref: /ingredients/<ch>/<id>, a window as its two-decimal name", () => {
+ assert.equal(H.ingredientHref("MommaOcco", "n8G_ysDV2bA"), "/ingredients/MommaOcco/n8G_ysDV2bA");
+ assert.equal(H.ingredientHref("MommaOcco", "n8G_ysDV2bA", { from: 1290, to: 1365 }), "/ingredients/MommaOcco/n8G_ysDV2bA?window=1290.00-1365.00");
+ assert.equal(H.ingredientHref("a b", "x/y", null), "/ingredients/a%20b/x%2Fy");
+});
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -535,3 +535,15 @@ export function toolsHref(): string {
export function songToolsHref(): string {
return "/tools/song";
}
+
+// ── ingredients (lane L5) ───────────────────────────────────────────────────
+
+/**
+ * ONE RECORDING'S LIFE CYCLE (lib/ingredients/stages.mjs): `/ingredients/<channel>/<video>`, and with `win` one
+ * of its clip windows (`?window=<from>-<to>`, the window's own two-decimal name). Either Rumble id finds it.
+ */
+export function ingredientHref(ch: string, id: string, win?: { from: number; to: number } | null): string {
+ return withQuery(`/ingredients/${encodeURIComponent(ch)}/${encodeURIComponent(id)}`, {
+ window: win && Number.isFinite(win.from) && Number.isFinite(win.to) ? `${win.from.toFixed(2)}-${win.to.toFixed(2)}` : null,
+ });
+}
diff --git a/umtool/lib/ingredients.ts b/umtool/lib/ingredients.ts
@@ -0,0 +1,134 @@
+import { CHANNELS_DIR, REPORTS_ROOT } from "./paths";
+import { loadUsageIndex } from "./ingredients/usedIn.mjs";
+import { readIngredient as readAt, STAGES as STAGE_LIST } from "./ingredients/stages.mjs";
+
+// The app's view of lib/ingredients/ (lane L5, the ingredient life-cycle rail), typed and bound to the roots.
+// The readers, the file formats and the rules are there (plain ESM, unit-tested); `umtool ingredient` prints
+// the same object. SERVER ONLY.
+//
+// The usage index is memoised for a few seconds on globalThis (every bundle shares one copy, the rail-counts
+// lesson): a rebuild is a walk and a stat per manifest, and a page asks once per render. A write here clears it.
+
+export type PillKind = "ok" | "count" | "warn" | "none";
+export type Pill = { kind: PillKind; n?: number };
+export type UseRow = {
+ project: string;
+ clipId: string;
+ start: number | null;
+ end: number | null;
+ cutStart: number | null;
+ cutEnd: number | null;
+ quote: string | null;
+ inDraft: boolean;
+ cites: string[];
+ versions: { id: string; kind: "version" | "rendered"; start: number | null; end: number | null; cutStart: number | null; cutEnd: number | null }[];
+};
+export type WindowRow = {
+ name: string;
+ file: string;
+ from: number;
+ to: number;
+ bytes: number;
+ mtime: string;
+ desynced: boolean;
+ focused: boolean;
+ orphan: boolean;
+ serves: { project: string; clipId: string }[];
+ partly: { project: string; clipId: string }[];
+ sidecar: {
+ requestedBy: string | null;
+ manifest: string | null;
+ clipId: string | null;
+ reason: string | null;
+ fetchedAt: string | null;
+ source: string | null;
+ syncOk: boolean | null;
+ clock: { id: string | null; offset: number | null; certain: boolean } | null;
+ } | null;
+};
+type Base = { key: string; label: string; pill: Pill; line: string };
+export type Stage = Base & Record<string, unknown>;
+export type FoundStage = Base & {
+ findClips: { at: string | null; project: string; url: string | null; segments: number; segment: string | null; created: boolean } | null;
+ marks: { session: string; query: string | null; state: string; at: string | null }[];
+ candidates: { case: string; key: string | null; from: number | null; to: number | null; title: string | null; hits: number }[];
+};
+export type DownloadedStage = Base & {
+ meta: { bytes: number; id: string | null; title: string | null; webpageUrl: string | null; uploadDate: string | null; extractor: string | null } | null;
+ history?: { count: number; lastAt: string | null; lastBy: string | null } | null;
+ outcome?: { status: string; finishedAt: string | null; attempts: number; webpageUrl: string | null; error: string | null } | null;
+ availability?: { availability: string; checkedAt: string | null } | null;
+ saved?: { file: string; height: number | null; reachable: boolean } | null;
+ imported?: { count: number; lastAt: string | null; via: string | null } | null;
+ media: { name: string; link: boolean; reachable: boolean; bytes: number | null }[];
+ captions?: string[];
+ problems?: string[];
+};
+export type TranscribedStage = Base & {
+ cues: { bytes: number; source: string | null; format: string | null; vttFile: string | null; engine: string | null; platform: string | null; title: string | null; uploadDate: string | null; duration: number | null; lastEnd: number | null; coverage: number | null } | null;
+ pin?: Record<string, unknown> | null;
+ outcome?: { at: string | null; worker: string | null; durationMs: number | null; salvaged: boolean } | null;
+ words?: { bytes: number } | null;
+ captions?: string[];
+};
+export type ClockStage = Base & {
+ clock: { id: string; ok: boolean; source: string | null; target: string | null; segments: number; steps: number; residualMs: number | null; measuredAt: string | null } | null;
+};
+export type WindowsStage = Base & {
+ windows: WindowRow[];
+ uncovered: { project: string; clipId: string; from: number | null; to: number | null }[];
+ savedWhole: boolean;
+ /** The saved whole recording's path when its drive does not answer, else null. */
+ savedUnreachable: string | null;
+ focus: { from: number; to: number; name: string; found: boolean } | null;
+};
+export type UsedStage = Base & { rows: UseRow[] };
+export type CheckedStage = Base & { clips: { project: string; clipId: string; hasQuote: boolean; status: string | null; offset: number | null; current: boolean; checkedAt: string | null }[] };
+export type RenderedStage = Base & {
+ renders: { project: string; clipId: string; version: string | null; kind: string; label: string | null; state: string | null; seconds: number | null; endedAt: string | null; cut: { from: number | null; to: number | null } | null }[];
+};
+export type PublishedStage = Base & { links: { project: string; clipId: string; url: string | null; state: string | null; fix: string | null; checkedAt: string | null }[] };
+
+export type Ingredient = {
+ ch: string;
+ id: string;
+ dirId: string;
+ siteId: string | null;
+ platform: string | null;
+ exists: boolean;
+ title: string | null;
+ webpageUrl: string | null;
+ duration: number | null;
+ uploadDate: string | null;
+ notes: string[];
+ focus: { from: number; to: number; name: string; found: boolean } | null;
+ stages: [FoundStage, DownloadedStage, TranscribedStage, ClockStage, WindowsStage, UsedStage, CheckedStage, RenderedStage, PublishedStage];
+};
+
+export const STAGES = STAGE_LIST as { key: string; label: string }[];
+
+const MEMO_MS = 5_000;
+const KEY = Symbol.for("umtool.usage-index");
+type Memo = { at: number; value: Promise<Record<string, unknown>> } | null;
+const store = globalThis as unknown as Record<symbol, Memo>;
+
+export function clearUsageIndex(): void {
+ store[KEY] = null;
+}
+
+export function usageIndex(): Promise<Record<string, unknown>> {
+ const m = store[KEY];
+ if (m && Date.now() - m.at < MEMO_MS) return m.value;
+ const value = loadUsageIndex({ reportsRoot: REPORTS_ROOT, channelsDir: CHANNELS_DIR }).then((r) => r.index as Record<string, unknown>);
+ const entry = { at: Date.now(), value };
+ store[KEY] = entry;
+ value.catch(() => {
+ if (store[KEY] === entry) store[KEY] = null;
+ });
+ return value;
+}
+
+/** One recording's nine stages (lib/ingredients/stages.mjs), or null for a channel or id that is not one. */
+export async function readIngredient(ch: string, id: string, window: string | null = null): Promise<Ingredient> {
+ return (await readAt({ channelsDir: CHANNELS_DIR, reportsRoot: REPORTS_ROOT, ch, id, window, index: await usageIndex() })) as Ingredient;
+}
diff --git a/umtool/lib/ingredients/actions.mjs b/umtool/lib/ingredients/actions.mjs
@@ -0,0 +1,266 @@
+// THE RAIL'S ACTIONS (lane L5): one click on a stage runs its action through an action that already exists --
+// the editor's ops for what touches the corpus, umtool's own for what touches a project. Nothing here downloads,
+// transcribes or deletes by itself: it builds the editor's body and asks.
+//
+// persist Downloaded POST /api/ops/persist-videos {items:[{slug, id}]} the channel's download queue;
+// a Rumble recording is saved whole
+// transcribe Transcribed POST /api/ops/transcribe-one {slug, id} the GPU (the editor's worker pool)
+// fetch Windows POST /api/ops/fetch-windows {items, requestedBy, …} one paced job per platform queue:
+// the project's own body (projectFetchBody), narrowed to this recording's unfetched clips
+// evict Windows POST /api/ops/evict-clips {slug, id, windows:[name]} targeted: that one window
+// quote-check Checked `umtool quote-check <project> --clips …` on the app's job runner (the route starts it)
+// links Published POST /api/report/links {project, fix?} umtool's own link check
+//
+// Two steps, always: `plan` says what the action does, what it costs (network, the GPU, the disk) and which
+// queue it lands on -- for fetch-windows and persist-videos the editor's own dry run answers -- and the page
+// asks before it `start`s. An action that costs neither still says what it does.
+//
+// Plain ESM; the route (app/api/ingredients/action) is its only caller.
+import { createHash } from "node:crypto";
+import { lstat, readlink, stat } from "node:fs/promises";
+import path from "node:path";
+import { resolveProject } from "../projects/core.mjs";
+import { askEditorOps, postFetchWindows, projectFetchBody, summarizeAnswer } from "../report/fetchWindows.mjs";
+import { audioFilesOf, present, readSavedVideoPointer } from "yt-dlp-transcript-common/lib/evidenceClip.mjs";
+import { ingredientIdentity, isChannelSlug, isVideoId, listWindows } from "./stages.mjs";
+
+export const ACTIONS = ["persist", "transcribe", "fetch", "evict", "quote-check", "links"];
+const CLIP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
+
+export class ActionError extends Error {
+ constructor(message, status = 400) {
+ super(message);
+ this.status = status;
+ }
+}
+
+const plural = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`;
+
+async function projectOf(id, reportsRoot) {
+ const r = await resolveProject(String(id ?? ""), reportsRoot);
+ if (!r?.project) throw new ActionError(`no project "${id}"`, 404);
+ return r.project;
+}
+
+function clipList(v) {
+ const list = (Array.isArray(v) ? v : String(v ?? "").split(",")).map((s) => String(s).trim()).filter(Boolean);
+ if (!list.length) throw new ActionError("name the clips (clips: [ids])");
+ for (const c of list) if (!CLIP_ID.test(c)) throw new ActionError(`"${c}" is not a clip id`);
+ return [...new Set(list)];
+}
+
+/**
+ * A KEY FOR WHAT THE PLAN SHOWED: `start` carries it back, and the action is re-read and refused when it no
+ * longer matches (a fetch body that changed, a window refetched or set aside since the page asked).
+ */
+const keyOf = (v) => createHash("sha256").update(JSON.stringify(v)).digest("hex").slice(0, 16);
+const fetchKey = (body) => keyOf(body.items.map((i) => [String(i.id), i.from, i.to, String(i.clipId ?? "")]).sort());
+const evictKey = (w, twins) => keyOf([w.file, w.bytes, w.mtime, ...twins.map((t) => [t.file, t.bytes, t.mtime])]);
+const plainKey = (action, idn) => keyOf([action, idn.ch, idn.dirId]);
+
+/**
+ * AN UNMOUNTED DRIVE IS NOT A MISSING FILE (AGENTS.md, "A channel's media may live on another drive"): a media
+ * link that does not resolve, the channel's media/ linked to a drive not answering, a saved video whose file does
+ * not answer. A plan that read those as "absent" would offer to download again what is only out of reach, so the
+ * plan says which drive, costs nothing and offers no Start, and a start is refused. null when everything answers.
+ * @param {Awaited<ReturnType<typeof ingredientIdentity>>} idn
+ * @param {{ saved?: boolean }} [o] also the saved-video store's file (persist)
+ */
+export async function unreachableOf(idn, { saved = false } = {}) {
+ const channelMedia = path.join(idn.dir, "..", "..", "media");
+ if (idn.mediaDrive === "missing") {
+ const to = await readlink(channelMedia).catch(() => null);
+ return `the channel's media drive does not answer (${idn.ch}/media -> ${to ?? "?"}): mount it, or re-point its location on /storage`;
+ }
+ if (!idn.exists) return null;
+ const dangling = [];
+ for (const a of await audioFilesOf(idn.dir)) {
+ const l = await lstat(a.path).catch(() => null);
+ if (l?.isSymbolicLink() && !(await stat(a.path).catch(() => null))) dangling.push(`${a.name} -> ${(await readlink(a.path).catch(() => null)) ?? "?"}`);
+ }
+ if (dangling.length) return `its media does not answer (${dangling.join(", ")}): the drive it lives on is not mounted`;
+ if (saved) {
+ const pointer = await readSavedVideoPointer(idn.dir);
+ if (pointer && !(await present(pointer.path))) return `its saved video does not answer (${pointer.path}): the saved-video store's drive is not mounted`;
+ }
+ return null;
+}
+
+const unreachablePlan = (action, why) => ({ action, what: `Not now: ${why}`, cost: null, queue: "—", unreachable: why, start: null });
+
+/** The fetch-windows bodies for the named clips of one project, narrowed to this recording (one per project). */
+async function fetchBodyFor(project, clips, idn) {
+ const { body, skipped } = await projectFetchBody(project, { localIds: true });
+ const want = new Set(clips);
+ const items = body.items.filter((it) => it.slug === idn.ch && String(it.id) === idn.dirId && want.has(String(it.clipId)));
+ if (!items.length) {
+ const why = skipped.filter((s) => want.has(s.clipId)).map((s) => `${s.clipId}: ${s.why}`);
+ throw new ActionError(`no window of ${idn.ch}/${idn.dirId} to fetch for ${clips.join(", ")}${why.length ? ` (${why.join("; ")})` : ""}`);
+ }
+ return { ...body, requestedBy: `${body.requestedBy} (ingredient rail)`, items };
+}
+
+/**
+ * What an action will do, before it does it.
+ *
+ * @param {{ action: string, ch: string, id: string, project?: string, clips?: string[] | string, window?: string, fix?: boolean }} req
+ * @param {{ cfg: { url: string, token: string, fetch?: typeof fetch }, reportsRoot: string, channelsDir: string }} ctx
+ * @returns {Promise<{ action: string, what: string, cost: "network" | "gpu" | "disk" | null, queue: string, start: { route: string, body: Record<string, any> }, plan?: any }>}
+ */
+export async function planAction(req, ctx) {
+ const { action } = req;
+ if (!ACTIONS.includes(action)) throw new ActionError(`action is one of ${ACTIONS.join(", ")}`);
+ if (!isChannelSlug(req.ch) || !isVideoId(req.id)) throw new ActionError("ch and id name a recording");
+ const idn = await ingredientIdentity({ channelsDir: ctx.channelsDir, ch: req.ch, id: req.id });
+ const self = (extra = {}) => ({ route: "/api/ingredients/action", body: { action, ch: idn.ch, id: idn.dirId, ...extra, step: "start" } });
+ const rumble = idn.platform === "rumble";
+
+ if (action === "persist") {
+ const away = await unreachableOf(idn, { saved: true });
+ if (away) return unreachablePlan(action, away);
+ const body = { items: [{ slug: idn.ch, id: idn.dirId }] };
+ const plan = await askEditorOps(ctx.cfg, "/api/ops/persist-videos", { method: "POST", body: { ...body, dryRun: true } });
+ // The editor's plan buckets each item: { saved: {count, items}, toFetch, noUrl, unknown, willFetch }.
+ const buckets = plan?.plan ?? plan?.buckets ?? {};
+ const count = (k) => (Array.isArray(buckets?.[k]) ? buckets[k].length : Number(buckets?.[k]?.count ?? 0) || 0);
+ const already = count("saved");
+ return {
+ action,
+ what: already
+ ? `The source video is already saved: the editor will skip it`
+ : `Download the source video to the saved-video store${rumble ? " -- on Rumble the WHOLE recording, saved once (the editor's whole-recording rule)" : ""}`,
+ cost: already ? null : "network",
+ queue: `the ${idn.ch} channel's download queue (the editor's)`,
+ plan: { saved: already, toFetch: count("toFetch"), noUrl: count("noUrl"), unknown: count("unknown") },
+ start: self({ key: plainKey(action, idn) }),
+ };
+ }
+
+ if (action === "transcribe") {
+ const away = await unreachableOf(idn);
+ if (away) return unreachablePlan(action, away);
+ const audio = idn.exists ? (await Promise.all((await audioFilesOf(idn.dir)).map(async (a) => ((await present(a.path)) ? a.name : null)))).filter(Boolean) : [];
+ return {
+ action,
+ what: audio.length
+ ? `Transcribe ${audio[0]} through the editor's worker pool (an existing transcript is replaced by the new one)`
+ : `Download the audio, then transcribe it (a YouTube video with English captions has those fetched instead)`,
+ cost: "gpu",
+ queue: audio.length ? `transcribe-one:${idn.ch}:${idn.dirId}` : `the ${idn.ch} channel's platform queue for the download, then transcribe-one:${idn.ch}:${idn.dirId}`,
+ start: self({ key: plainKey(action, idn) }),
+ };
+ }
+
+ if (action === "fetch") {
+ const project = await projectOf(req.project, ctx.reportsRoot);
+ const clips = clipList(req.clips);
+ const body = await fetchBodyFor(project, clips, idn);
+ const answer = await postFetchWindows(ctx.cfg, body, { dryRun: true });
+ const groups = Array.isArray(answer?.groups) ? answer.groups : [];
+ const queues = [...new Set(groups.map((g) => g.queueKey).filter(Boolean))];
+ const cached = Array.isArray(answer?.cached) ? answer.cached.length : Number(answer?.cached ?? 0) || 0;
+ return {
+ action,
+ what: `Fetch ${plural(body.items.length, "window")} for ${project.id} (${clips.join(", ")})${rumble ? " -- Rumble: cut from the whole recording, which the editor saves once" : ""}${cached ? `; ${cached} already on disk` : ""}`,
+ cost: "network",
+ queue: queues.length ? queues.join(", ") : "the editor's paced fetch queue for the platform",
+ plan: { summary: summarizeAnswer(answer) },
+ start: self({ project: project.id, clips, key: fetchKey(body) }),
+ };
+ }
+
+ if (action === "evict") {
+ const { w, twins } = await evictTarget(idn, req.window);
+ const mb = (b) => `${(b / 1e6).toFixed(1)} MB`;
+ return {
+ action,
+ what:
+ `Delete the cached window ${w.file} (${mb(w.bytes)})` +
+ // The editor's targeted evict names the `<from>-<to>` stem, and a set-aside twin of the span goes with it.
+ (twins.length ? `, and with it ${twins.map((t) => `${t.file} (${mb(t.bytes)})`).join(", ")}: the editor evicts a span's set-aside twin with it` : "") +
+ `. A window is a cache: it can be fetched again, and that fetch is the cost. Nothing knows whether a project still cites it`,
+ cost: "disk",
+ queue: "an evict-clips job on the editor",
+ start: self({ window: w.file, key: evictKey(w, twins) }),
+ };
+ }
+
+ if (action === "quote-check") {
+ const project = await projectOf(req.project, ctx.reportsRoot);
+ const clips = clipList(req.clips);
+ return {
+ action,
+ what: `Check ${clips.join(", ")} in ${project.id}: each clip's seconds transcribed by the editor, its quote found in them (writes ${project.id}/quote-check.json)`,
+ cost: "gpu",
+ queue: "umtool's job runner (one job at a time); the transcriptions on the editor's transcribe queue",
+ start: self({ project: project.id, clips }),
+ };
+ }
+
+ // links
+ const project = await projectOf(req.project, ctx.reportsRoot);
+ return {
+ action,
+ what: req.fix === true
+ ? `Rewrite each dead link of ${project.id} the last check knows the fix for, then check every link again`
+ : `Check that each clip QR of ${project.id} opens on its site (the archive's corpus.json, the channel's manifest, the shard's record)`,
+ cost: "network",
+ queue: "this umtool, one request at a time to the site (cached)",
+ start: { route: "/api/report/links", body: { project: project.id, ...(req.fix === true ? { fix: true } : {}) } },
+ };
+}
+
+/**
+ * Do it: the editor-bound actions (persist, transcribe, fetch, evict). quote-check is started by the route on
+ * the app's job runner; links goes to /api/report/links.
+ * @returns {Promise<{ ok: true, action: string, jobIds: string[], message: string, answer?: any }>}
+ */
+export async function startAction(req, ctx) {
+ const { action } = req;
+ if (!["persist", "transcribe", "fetch", "evict"].includes(action)) throw new ActionError(`${action} is not started here`);
+ if (!isChannelSlug(req.ch) || !isVideoId(req.id)) throw new ActionError("ch and id name a recording");
+ const idn = await ingredientIdentity({ channelsDir: ctx.channelsDir, ch: req.ch, id: req.id });
+ if (typeof req.key !== "string" || !req.key) throw new ActionError("start carries the plan's key: ask for the plan first");
+ const changed = () => new ActionError("it changed since the plan was shown: ask again", 409);
+ if (action === "persist" || action === "transcribe") {
+ const away = await unreachableOf(idn, { saved: action === "persist" });
+ if (away) throw new ActionError(`refused: ${away}`, 409);
+ if (req.key !== plainKey(action, idn)) throw changed();
+ }
+ const ids = (a) => [...new Set([...(Array.isArray(a?.jobIds) ? a.jobIds : []), ...(a?.jobId ? [a.jobId] : [])].map(String))];
+ if (action === "persist") {
+ const a = await askEditorOps(ctx.cfg, "/api/ops/persist-videos", { method: "POST", body: { items: [{ slug: idn.ch, id: idn.dirId }] } });
+ return { ok: true, action, jobIds: ids(a), message: ids(a).length ? `persist started (${ids(a).join(", ")})` : "nothing to persist: already saved", answer: a };
+ }
+ if (action === "transcribe") {
+ const a = await askEditorOps(ctx.cfg, "/api/ops/transcribe-one", { method: "POST", body: { slug: idn.ch, id: idn.dirId } });
+ return { ok: true, action, jobIds: ids(a), message: a?.instead === "captions" ? String(a.message ?? "captions fetched instead") : `transcription queued (${ids(a).join(", ")})`, answer: a };
+ }
+ if (action === "fetch") {
+ const project = await projectOf(req.project, ctx.reportsRoot);
+ const body = await fetchBodyFor(project, clipList(req.clips), idn);
+ if (req.key !== fetchKey(body)) throw changed();
+ const a = await postFetchWindows(ctx.cfg, body);
+ return { ok: true, action, jobIds: ids(a), message: ids(a).length ? `fetch started (${ids(a).join(", ")})` : "nothing to fetch: every window is on disk or in flight", answer: summarizeAnswer(a) };
+ }
+ const { w, twins } = await evictTarget(idn, req.window);
+ if (req.key !== evictKey(w, twins)) throw changed();
+ const a = await askEditorOps(ctx.cfg, "/api/ops/evict-clips", { method: "POST", body: { slug: idn.ch, id: idn.dirId, windows: [w.name] } });
+ return { ok: true, action, jobIds: ids(a), message: `evicting ${w.name} (${ids(a).join(", ")})`, answer: a };
+}
+
+/** The window a targeted evict names, EXACTLY by its file, and the set-aside twin of its span that goes with it. */
+async function evictTarget(idn, file) {
+ const f = String(file ?? "");
+ const all = idn.exists ? await listWindows(idn.dir) : [];
+ const w = all.find((x) => x.file === f);
+ if (!w) throw new ActionError(`no window file "${f}" in ${idn.ch}/${idn.dirId}/clips/`, 404);
+ return { w, twins: all.filter((x) => x !== w && x.name === w.name) };
+}
+
+/** The argv of a quote check of some of a project's clips (the route runs it on the app's job runner). */
+export function quoteCheckArgv(umtoolDir, project, clips) {
+ return [process.execPath, path.join(umtoolDir, "bin", "umtool.mjs"), "quote-check", project, "--clips", clips.join(",")];
+}
+
+export { clipList as parseClipList };
diff --git a/umtool/lib/ingredients/actions.test.mjs b/umtool/lib/ingredients/actions.test.mjs
@@ -0,0 +1,136 @@
+// node --test umtool/lib/ingredients/actions.test.mjs
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { planAction, startAction } from "./actions.mjs";
+import { readIngredient } from "./stages.mjs";
+
+/** An editor that records what it was asked and answers like the real one would, enough for these tests. */
+function editor() {
+ const asked = [];
+ const fetch = async (url, init) => {
+ const body = init?.body ? JSON.parse(init.body) : null;
+ const route = new URL(url).pathname;
+ asked.push({ route, body });
+ let answer = { ok: true, jobId: `job-${asked.length}` };
+ if (route === "/api/ops/fetch-windows") answer = body.dryRun ? { ok: true, dryRun: true, groups: [{ platform: "youtube", queueKey: "clips:youtube", items: body.items }], cached: [], inFlight: [], unresolved: [] } : { ok: true, jobs: [], jobIds: ["fw-1"], jobId: "fw-1", groups: [], cached: [], inFlight: [], unresolved: [], refused: [] };
+ if (route === "/api/ops/persist-videos" && body.dryRun) answer = { ok: true, dryRun: true, plan: { saved: { count: 0, items: [] }, toFetch: { count: 1, items: [] }, willFetch: 1 } };
+ return new Response(JSON.stringify(answer), { status: 200, headers: { "content-type": "application/json" } });
+ };
+ return { asked, cfg: { url: "http://editor.test", token: "t", fetch } };
+}
+
+async function corpus() {
+ const root = await mkdtemp(path.join(tmpdir(), "actions-"));
+ const channels = path.join(root, "channels");
+ const reports = path.join(root, "reports");
+ const v = path.join(channels, "chan", "data", "vid");
+ await mkdir(path.join(v, "clips"), { recursive: true });
+ await writeFile(path.join(channels, "chan", "config.json"), JSON.stringify({ platform: "youtube" }));
+ await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id: "vid", title: "t" }));
+ await writeFile(path.join(v, "clips", "10.00-40.00.mp4"), Buffer.alloc(100));
+ await writeFile(path.join(v, "clips", "10.00-40.00.desynced.mp4"), Buffer.alloc(70));
+ await writeFile(path.join(v, "clips", "50.00-60.00.mp4"), Buffer.alloc(10));
+ const a = path.join(reports, "f", "a");
+ await mkdir(a, { recursive: true });
+ await writeFile(path.join(a, "video.manifest.json"), JSON.stringify({ provenance: { channelSlug: "chan" }, render: { fetchPad: 3 }, timeline: [{ type: "clip", id: "a1", video: "vid", start: 100, end: 110 }] }));
+ return { root, channels, reports, v, a };
+}
+
+test("an unmounted media drive: transcribe and persist plan 'not now', name the drive, offer no Start, and a start is refused", async () => {
+ const { root, channels, reports, v } = await corpus();
+ try {
+ // The channel's media/ links to a drive that is not there; the audio is a link into it.
+ await symlink(path.join(root, "gone-drive", "chan", "media"), path.join(channels, "chan", "media"));
+ await symlink("../../media/vid/audio.mp3", path.join(v, "audio.mp3"));
+ const { cfg, asked } = editor();
+ const ctx = { cfg, reportsRoot: reports, channelsDir: channels };
+ for (const action of ["transcribe", "persist"]) {
+ const plan = await planAction({ action, ch: "chan", id: "vid" }, ctx);
+ assert.equal(plan.cost, null, action);
+ assert.equal(plan.start, null, action);
+ assert.match(plan.unreachable, /media drive does not answer .*gone-drive/, action);
+ await assert.rejects(startAction({ action, ch: "chan", id: "vid", key: "x" }, ctx), (e) => e.status === 409 && /refused: the channel's media drive/.test(e.message));
+ }
+ assert.deepEqual(asked, [], "the editor was never asked");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a dangling audio link alone (the channel's media/ fine) is 'not now' too -- never 'download the audio'", async () => {
+ const { root, channels, reports, v } = await corpus();
+ try {
+ await mkdir(path.join(channels, "chan", "media"), { recursive: true });
+ await symlink("../../media/vid/audio.mp3", path.join(v, "audio.mp3"));
+ const { cfg } = editor();
+ const plan = await planAction({ action: "transcribe", ch: "chan", id: "vid" }, { cfg, reportsRoot: reports, channelsDir: channels });
+ assert.match(plan.what, /^Not now: its media does not answer \(audio\.mp3 -> \.\.\/\.\.\/media\/vid\/audio\.mp3\)/);
+ assert.equal(plan.start, null);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("a saved video whose drive is gone: persist is 'not now', and the Windows stage says it does not answer", async () => {
+ const { root, channels, reports, v } = await corpus();
+ try {
+ await writeFile(path.join(v, "saved-video.json"), JSON.stringify({ dir: path.join(root, "gone-store", "chan"), file: "vid.mp4" }));
+ const { cfg } = editor();
+ const plan = await planAction({ action: "persist", ch: "chan", id: "vid" }, { cfg, reportsRoot: reports, channelsDir: channels });
+ assert.match(plan.unreachable, /saved video does not answer/);
+ const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "vid", indexFile: path.join(root, "state", "u.json") });
+ const win = r.stages.find((s) => s.key === "windows");
+ assert.equal(win.pill.kind, "warn");
+ assert.match(win.line, /the saved whole recording does not answer/);
+ assert.equal(win.savedWhole, false);
+ assert.equal(win.uncovered.length, 1, "nothing cuts from an unreachable recording: the clip is not covered");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("start carries the plan's key: none, or a stale one, is refused before the editor is asked", async () => {
+ const { root, channels, reports, a } = await corpus();
+ try {
+ const { cfg, asked } = editor();
+ const ctx = { cfg, reportsRoot: reports, channelsDir: channels };
+ const plan = await planAction({ action: "fetch", ch: "chan", id: "vid", project: "f/a", clips: ["a1"] }, ctx);
+ assert.equal(plan.start.body.key.length, 16);
+ await assert.rejects(startAction({ ...plan.start.body, key: undefined }, ctx), /ask for the plan first/);
+ // The clip moves after the plan was shown: the fetch would differ, so the start is refused.
+ await writeFile(path.join(a, "video.manifest.json"), JSON.stringify({ provenance: { channelSlug: "chan" }, render: { fetchPad: 3 }, timeline: [{ type: "clip", id: "a1", video: "vid", start: 200, end: 210 }] }));
+ await assert.rejects(startAction(plan.start.body, ctx), (e) => e.status === 409 && /changed since the plan was shown/.test(e.message));
+ const again = await planAction({ action: "fetch", ch: "chan", id: "vid", project: "f/a", clips: ["a1"] }, ctx);
+ const r = await startAction(again.start.body, ctx);
+ assert.deepEqual(r.jobIds, ["fw-1"]);
+ const starts = asked.filter((x) => x.route === "/api/ops/fetch-windows" && !x.body.dryRun);
+ assert.equal(starts.length, 1);
+ assert.deepEqual(starts[0].body.items.map((i) => [i.from, i.to, i.clipId]), [[197, 213, "a1"]]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("evict names one window by its FILE, says its set-aside twin goes with it, and refuses a window changed since", async () => {
+ const { root, channels, reports, v } = await corpus();
+ try {
+ const { cfg, asked } = editor();
+ const ctx = { cfg, reportsRoot: reports, channelsDir: channels };
+ await assert.rejects(planAction({ action: "evict", ch: "chan", id: "vid", window: "10.00-40.00" }, ctx), /no window file/);
+ const plan = await planAction({ action: "evict", ch: "chan", id: "vid", window: "10.00-40.00.mp4" }, ctx);
+ assert.match(plan.what, /^Delete the cached window 10\.00-40\.00\.mp4 .*and with it 10\.00-40\.00\.desynced\.mp4/);
+ const lone = await planAction({ action: "evict", ch: "chan", id: "vid", window: "50.00-60.00.mp4" }, ctx);
+ assert.doesNotMatch(lone.what, /and with it/);
+ // Refetched since (other bytes under the same name): the key no longer matches.
+ await writeFile(path.join(v, "clips", "50.00-60.00.mp4"), Buffer.alloc(99));
+ await assert.rejects(startAction(lone.start.body, ctx), (e) => e.status === 409);
+ const ok = await startAction(plan.start.body, ctx);
+ assert.equal(ok.ok, true);
+ assert.deepEqual(asked.at(-1), { route: "/api/ops/evict-clips", body: { slug: "chan", id: "vid", windows: ["10.00-40.00"] } });
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/ingredients/cli.mjs b/umtool/lib/ingredients/cli.mjs
@@ -0,0 +1,78 @@
+// `umtool ingredient <ch>/<id> [--window a-b] [--used-in] [--json]` (lane L5): one recording's life cycle --
+// the CLI twin of /ingredients/<ch>/<id> (lib/ingredients/stages.mjs reads it; the page renders the same object).
+// Either Rumble id finds the recording, and both are printed. Read-only over the corpus; the usage index it
+// brings up to date lives in umtool's state dir (<REPORTS_ROOT>/.umtool/usage-index.json).
+//
+// Plain ESM: the CLI runs it under bare node.
+import { CHANNELS_DIR, REPORTS_ROOT } from "../paths.mjs";
+import { parseWindowParam, pillGlyph, readIngredient, spanText } from "./stages.mjs";
+
+export const INGREDIENT_USAGE = [
+ "usage: umtool ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json]",
+ " a recording's life cycle, nine stages: found, downloaded, transcribed, clock, windows, used in, checked,",
+ " rendered, published -- each ✓, a count, ! or —, and its line. A Rumble recording answers to its folder",
+ " slug or its embed id. --window: one clip window (its <from>-<to> name); the stages after it narrow to",
+ " the clips it plays. --used-in: every project clip that cuts from it (draft and saved versions), alone.",
+ " --json: the page's object. The page: /ingredients/<channel>/<video>.",
+].join("\n");
+
+class CliError extends Error {}
+
+/**
+ * @param {string[]} args the words after `ingredient`
+ * @param {{ reportsRoot?: string, channelsDir?: string, out?: (s: string) => void, err?: (s: string) => void }} [o]
+ * @returns {Promise<number>}
+ */
+export async function ingredientCommand(args, { reportsRoot = REPORTS_ROOT, channelsDir = CHANNELS_DIR, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ try {
+ const words = [];
+ const flags = new Map();
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a === "--window") {
+ if (i + 1 >= args.length) throw new CliError("--window needs <from>-<to>");
+ flags.set(a, args[++i]);
+ } else if (a === "--json" || a === "--used-in" || a === "--help") flags.set(a, true);
+ else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`);
+ else words.push(a);
+ }
+ if (flags.has("--help") || words.length !== 1) {
+ (flags.has("--help") ? out : err)(INGREDIENT_USAGE);
+ return flags.has("--help") ? 0 : 2;
+ }
+ const m = /^([^/]+)\/([^/@]+)$/.exec(words[0]);
+ if (!m) throw new CliError(`"${words[0]}" is not <channel>/<video>`);
+ const win = flags.has("--window") ? parseWindowParam(flags.get("--window")) : null;
+ if (flags.has("--window") && !win) throw new CliError(`--window "${flags.get("--window")}" is not <from>-<to>`);
+ const r = await readIngredient({ channelsDir, reportsRoot, ch: m[1], id: m[2], window: win });
+ const used = r.stages.find((s) => s.key === "used");
+ if (flags.has("--used-in")) {
+ if (flags.has("--json")) out(JSON.stringify(used.rows, null, 2));
+ else if (!used.rows.length) out(used.line);
+ else for (const u of used.rows) out(useLine(u));
+ return 0;
+ }
+ if (flags.has("--json")) {
+ out(JSON.stringify(r, null, 2));
+ return 0;
+ }
+ out(`${r.ch}/${r.dirId}${r.siteId ? ` (the archive's id: ${r.siteId})` : ""}${r.platform ? ` · ${r.platform}` : ""}${r.title ? ` · ${r.title}` : ""}`);
+ if (r.focus) out(`window ${r.focus.name}${r.focus.found ? "" : " (no such window on disk)"}`);
+ for (const n of r.notes) out(`note: ${n}`);
+ for (const s of r.stages) out(`${pillGlyph(s.pill).padStart(3)} ${s.label.padEnd(12)} ${s.line}`);
+ if (used.rows.length) {
+ out("");
+ for (const u of used.rows) out(useLine(u));
+ }
+ return 0;
+ } catch (e) {
+ err(e instanceof Error ? e.message : String(e));
+ return e instanceof CliError ? 2 : 1;
+ }
+}
+
+const useLine = (u) => {
+ const play = u.cutStart != null || u.cutEnd != null ? ` (cut ${spanText(u.cutStart ?? u.start, u.cutEnd ?? u.end)})` : "";
+ const where = [u.inDraft ? "draft" : null, ...u.versions.map((v) => v.id)].filter(Boolean).join(", ");
+ return ` ${u.project} ${u.clipId} ${spanText(u.start, u.end)}${play} [${where}]`;
+};
diff --git a/umtool/lib/ingredients/heads.mjs b/umtool/lib/ingredients/heads.mjs
@@ -0,0 +1,152 @@
+// READING A BIG JSON FILE BY ITS ENDS (lane L5). `metadata.info.json` runs to
+// 600 KB+ (yt-dlp's formats), `transcript.cues.json` to megabytes; the
+// ingredient page needs a handful of top-level fields of each, and how far the
+// last cue reaches. So a file is read by its HEAD (the first bytes, scanned as
+// the top-level object's members until the buffer ends or a named key is met)
+// and its TAIL (the last bytes, searched for the last `"end"`), never whole.
+//
+// Plain ESM; the CLI runs it under bare node.
+import { open } from "node:fs/promises";
+
+export const HEAD_BYTES = 64 * 1024;
+export const TAIL_BYTES = 4 * 1024;
+
+async function readRange(file, start, length) {
+ let fh;
+ try {
+ fh = await open(file, "r");
+ const st = await fh.stat();
+ const from = start < 0 ? Math.max(0, st.size + start) : start;
+ const n = Math.max(0, Math.min(length, st.size - from));
+ const buf = Buffer.alloc(n);
+ const { bytesRead } = await fh.read(buf, 0, n, from);
+ return { text: buf.subarray(0, bytesRead).toString("utf8"), size: st.size };
+ } catch {
+ return null;
+ } finally {
+ await fh?.close().catch(() => {});
+ }
+}
+
+/**
+ * The top-level PRIMITIVE members of a JSON object, from the start of its text
+ * (a truncated text is fine: what was complete is returned). An object or
+ * array member is skipped (its key is listed in `nested`); scanning stops at
+ * `stopKey`.
+ * @param {string} text
+ * @param {{ stopKey?: string | null }} [o]
+ * @returns {{ fields: Record<string, string | number | boolean | null>, nested: string[], complete: boolean }}
+ */
+export function scanHead(text, { stopKey = null } = {}) {
+ const fields = {};
+ const nested = [];
+ let i = 0;
+ const n = text.length;
+ const ws = () => {
+ while (i < n && /\s/.test(text[i])) i += 1;
+ };
+ const str = () => {
+ // at a quote; returns the decoded string, or null when it runs off the end
+ const s = i;
+ i += 1;
+ while (i < n) {
+ const c = text[i];
+ if (c === "\\") i += 2;
+ else if (c === '"') {
+ i += 1;
+ try {
+ return JSON.parse(text.slice(s, i));
+ } catch {
+ return null;
+ }
+ } else i += 1;
+ }
+ return null;
+ };
+ const skipNested = () => {
+ let depth = 0;
+ while (i < n) {
+ const c = text[i];
+ if (c === '"') {
+ if (str() === null) return false;
+ continue;
+ }
+ if (c === "{" || c === "[") depth += 1;
+ else if (c === "}" || c === "]") {
+ depth -= 1;
+ if (depth === 0) {
+ i += 1;
+ return true;
+ }
+ }
+ i += 1;
+ }
+ return false;
+ };
+ ws();
+ if (text[i] !== "{") return { fields, nested, complete: false };
+ i += 1;
+ for (;;) {
+ ws();
+ if (i >= n) return { fields, nested, complete: false };
+ if (text[i] === "}") return { fields, nested, complete: true };
+ if (text[i] === ",") {
+ i += 1;
+ continue;
+ }
+ if (text[i] !== '"') return { fields, nested, complete: false };
+ const key = str();
+ if (key === null) return { fields, nested, complete: false };
+ ws();
+ if (text[i] !== ":") return { fields, nested, complete: false };
+ i += 1;
+ ws();
+ if (stopKey && key === stopKey) return { fields, nested: [...nested, key], complete: false };
+ const c = text[i];
+ if (c === '"') {
+ const v = str();
+ if (v === null) return { fields, nested, complete: false };
+ fields[key] = v;
+ } else if (c === "{" || c === "[") {
+ nested.push(key);
+ if (!skipNested()) return { fields, nested, complete: false };
+ } else {
+ const m = /^(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null)/.exec(text.slice(i, i + 40));
+ if (!m) return { fields, nested, complete: false };
+ // A number at the very end of a truncated text may be cut short: only a terminated one counts.
+ if (i + m[0].length >= n) return { fields, nested, complete: false };
+ fields[key] = JSON.parse(m[0]);
+ i += m[0].length;
+ }
+ }
+}
+
+/**
+ * A JSON file's head: its top-level primitive members (scanHead), and its size.
+ * @param {string} file
+ * @param {{ bytes?: number, stopKey?: string | null }} [o]
+ * @returns {Promise<{ fields: Record<string, any>, nested: string[], size: number } | null>}
+ */
+export async function readJsonHead(file, { bytes = HEAD_BYTES, stopKey = null } = {}) {
+ const r = await readRange(file, 0, bytes);
+ if (!r) return null;
+ const { fields, nested } = scanHead(r.text, { stopKey });
+ return { fields, nested, size: r.size };
+}
+
+/**
+ * The largest `"end": <seconds>` in a file's last bytes: how far a cue file's
+ * last cue reaches, without reading the cues.
+ * @param {string} file
+ * @returns {Promise<number | null>}
+ */
+export async function lastEndOf(file, { bytes = TAIL_BYTES } = {}) {
+ const r = await readRange(file, -bytes, bytes);
+ if (!r) return null;
+ let best = null;
+ for (const m of r.text.matchAll(/"end"\s*:\s*(-?\d+(?:\.\d+)?)/g)) {
+ const v = Number(m[1]);
+ if (Number.isFinite(v) && (best === null || v > best)) best = v;
+ }
+ return best;
+}
diff --git a/umtool/lib/ingredients/stages.mjs b/umtool/lib/ingredients/stages.mjs
@@ -0,0 +1,570 @@
+// ONE INGREDIENT'S WHOLE LIFE CYCLE (umtool redesign, lane L5; operator, 9 Nov 2026: "the stage rail could be
+// good for viewing a downloaded clip or other video ingredient to see its entire life cycle").
+//
+// An ingredient is one recording of the corpus, `channels/<ch>/data/<id>/`, and optionally one clip window of
+// it (`?window=<from>-<to>`). Nine stages, each read from files that already exist:
+//
+// found data/<id>/find-clips.json; research sessions' marks["ch/id"]; research cases' candidates.jsonl
+// downloaded metadata.info.json (its HEAD only), metadata.history.json, download-outcome.json,
+// availability.json, saved-video.json, media-import.json, the media files and their links
+// transcribed transcript.cues.json (its head and its tail, never the cues), the .vtt files,
+// transcript-pin.json, transcribe-outcome.json, words.json (stat only)
+// clock clock.json (recordingClock-read.mjs, describeClock)
+// windows clips/<from>-<to>.{mp4,…} and their sidecars, cross-checked against the usage index
+// used the usage index (usedIn.mjs): every project clip that cuts from it, draft and versions
+// checked <project>/quote-check.json rows for those clips (rowIsCurrent)
+// rendered <project>/takes/<id>/render.json for the versions holding them, out/segments/<clip>.cut.json
+// published <project>/out/links.json for those clips (linkVerdicts' rows), the archive moment
+//
+// READ-ONLY OVER THE CORPUS, no exceptions: nothing here writes under the channels dir (the usage index lives
+// in umtool's own state dir). Each stage answers a PILL -- `ok` (✓), `count` (a number), `warn` (!) or `none`
+// (—) -- and a one-line summary; its panel reads the rest of the stage's object.
+//
+// Plain ESM: `umtool ingredient` prints it under bare node; the page renders it.
+import { lstat, readdir, readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import { describeClock } from "yt-dlp-transcript-common/lib/recordingClock.mjs";
+import { readRecordingClock } from "yt-dlp-transcript-common/lib/recordingClock-read.mjs";
+import { audioFilesOf, present, readSavedVideoPointer, WIN_EPS } from "yt-dlp-transcript-common/lib/evidenceClip.mjs";
+import { readChannelPlatform, recordIdOfVideoDir, resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { archiveMomentUrl } from "umtool-report-to-video/site-links";
+import { readLog } from "../research/log.mjs";
+import { readQuoteCheck, rowIsCurrent } from "../report/quoteCheck.mjs";
+import { readRenderRecord } from "../report/renderRecord.mjs";
+import { listTakes } from "../report/takes.mjs";
+import { readLinkCheck } from "../report/linkCheck.mjs";
+import { lastEndOf, readJsonHead } from "./heads.mjs";
+import { loadUsageIndex, overlaps, playedOf, rowsInWindow, usesOf } from "./usedIn.mjs";
+
+export const STAGES = [
+ { key: "found", label: "Found" },
+ { key: "downloaded", label: "Downloaded" },
+ { key: "transcribed", label: "Transcribed" },
+ { key: "clock", label: "Clock" },
+ { key: "windows", label: "Windows" },
+ { key: "used", label: "Used in" },
+ { key: "checked", label: "Checked" },
+ { key: "rendered", label: "Rendered" },
+ { key: "published", label: "Published" },
+];
+
+const ID_RE = /^[\w.-]{1,128}$/;
+const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
+export const isChannelSlug = (v) => typeof v === "string" && SLUG_RE.test(v) && !v.includes("..");
+export const isVideoId = (v) => typeof v === "string" && ID_RE.test(v) && v !== "." && v !== "..";
+
+const WINDOW_NAME = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)(\.desynced)?\.(mp4|mkv|webm)$/i;
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const round2 = (x) => Math.round(Number(x) * 100) / 100;
+
+/** `?window=<from>-<to>` -> {from, to}, or null. */
+export function parseWindowParam(v) {
+ const m = /^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)$/.exec(String(v ?? "").trim());
+ if (!m) return null;
+ const from = Number(m[1]);
+ const to = Number(m[2]);
+ return to > from ? { from, to } : null;
+}
+
+/** The window's own name, `<from>-<to>` with two decimals (clipWindow.ts clipWindowName). */
+export const windowName = (from, to) => `${Number(from).toFixed(2)}-${Number(to).toFixed(2)}`;
+
+const pill = (kind, n = null) => ({ kind, ...(n !== null ? { n } : {}) });
+
+async function readJson(file) {
+ try {
+ return JSON.parse(await readFile(file, "utf8"));
+ } catch {
+ return null;
+ }
+}
+const statOf = (p) => stat(p).catch(() => null);
+const lstatOf = (p) => lstat(p).catch(() => null);
+const hms = (sec) => {
+ const t = Math.max(0, Math.floor(Number(sec) || 0));
+ const h = Math.floor(t / 3600);
+ const m = Math.floor((t % 3600) / 60);
+ const s = String(t % 60).padStart(2, "0");
+ return h ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${m}:${s}`;
+};
+export const spanText = (from, to) => (fin(from) && fin(to) ? `${hms(from)}–${hms(to)}` : "?");
+
+/**
+ * A file in the video dir: is it there, a link (the media tier), and does it resolve?
+ * @param {string} dir
+ * @param {string} name
+ */
+async function fileState(dir, name) {
+ const p = path.join(dir, name);
+ const l = await lstatOf(p);
+ if (!l) return null;
+ const link = l.isSymbolicLink();
+ const s = link ? await statOf(p) : l;
+ return { name, link, reachable: !!s, bytes: s?.size ?? null };
+}
+
+// ── identity ─────────────────────────────────────────────────────────────────
+
+/**
+ * Who the ingredient is: the directory it lives in (either Rumble id finds it), the archive's id for it, the
+ * channel's platform and the guards' facts about the channel's media (moving, a drive not answering).
+ */
+export async function ingredientIdentity({ channelsDir, ch, id }) {
+ const platform = await readChannelPlatform(channelsDir, ch);
+ const dirId = await resolveVideoDirId(channelsDir, ch, id, { platform }).catch(() => id);
+ const siteId = await recordIdOfVideoDir(channelsDir, ch, dirId, { platform }).catch(() => dirId);
+ const channelDir = path.join(channelsDir, ch);
+ const dir = path.join(channelDir, "data", dirId);
+ const exists = !!(await statOf(dir))?.isDirectory();
+ const channelExists = !!(await statOf(channelDir))?.isDirectory();
+ const notes = [];
+ if (await statOf(path.join(channelDir, ".relocating.json"))) notes.push("the channel's media is being moved (.relocating.json): its big files may not answer until the move ends");
+ const dataL = await lstatOf(path.join(channelDir, "data"));
+ if (dataL?.isSymbolicLink() && !(await statOf(path.join(channelDir, "data")))) notes.push("the channel's data/ is a link to a drive that is not mounted: an unmounted drive is not an empty channel");
+ const mediaL = await lstatOf(path.join(channelDir, "media"));
+ const mediaDrive = mediaL?.isSymbolicLink() ? ((await statOf(path.join(channelDir, "media"))) ? "linked" : "missing") : mediaL ? "local" : "none";
+ if (mediaDrive === "missing") notes.push("the channel's media/ links to a drive that is not answering: its media files read as missing, not as never downloaded");
+ return { ch, asked: id, dirId, siteId: siteId !== dirId ? siteId : null, platform, dir, exists, channelExists, mediaDrive, notes };
+}
+
+// ── found ────────────────────────────────────────────────────────────────────
+
+async function foundStage({ reportsRoot, idn }) {
+ const keys = new Set([`${idn.ch}/${idn.dirId}`, ...(idn.siteId ? [`${idn.ch}/${idn.siteId}`] : []), `${idn.ch}/${idn.asked}`]);
+ const ids = new Set([idn.dirId, idn.asked, ...(idn.siteId ? [idn.siteId] : [])]);
+ const fc = idn.exists ? await readJson(path.join(idn.dir, "find-clips.json")) : null;
+ const findClips =
+ fc && fc.version === 1 && typeof fc.project === "string"
+ ? { at: fc.at ?? null, project: fc.project, url: typeof fc.url === "string" ? fc.url : null, segments: Array.isArray(fc.segments) ? fc.segments.length : 0, segment: fc.segment ?? null, created: fc.created === true }
+ : null;
+ const research = path.join(reportsRoot, ".umtool", "research");
+ const marks = [];
+ for (const name of await readdir(path.join(research, "sessions")).catch(() => [])) {
+ if (!name.endsWith(".json")) continue;
+ const session = name.slice(0, -5);
+ const log = await readLog(reportsRoot, session);
+ for (const k of keys) {
+ const m = log.marks?.[k];
+ if (m) {
+ marks.push({ session, query: log.query ?? null, state: m.state, at: m.at || null });
+ break;
+ }
+ }
+ }
+ const candidates = [];
+ for (const c of await readdir(research, { withFileTypes: true }).catch(() => [])) {
+ if (!c.isDirectory() || c.name.startsWith(".") || c.name === "sessions") continue;
+ const text = await readFile(path.join(research, c.name, "candidates.jsonl"), "utf8").catch(() => "");
+ if (!text) continue;
+ for (const line of text.split("\n")) {
+ if (!line || ![...ids].some((x) => line.includes(`"${x}"`))) continue;
+ let w;
+ try {
+ w = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (w?.slug !== idn.ch || !ids.has(String(w.id))) continue;
+ candidates.push({ case: c.name, key: w.key ?? null, from: w.from ?? null, to: w.to ?? null, title: w.title ?? null, hits: Array.isArray(w.hits) ? w.hits.length : 0 });
+ if (candidates.length >= 200) break;
+ }
+ }
+ const n = (findClips ? 1 : 0) + marks.length + candidates.length;
+ const parts = [findClips && `the clip finder (${findClips.project})`, marks.length && `${marks.length} research mark${marks.length === 1 ? "" : "s"}`, candidates.length && `${candidates.length} case window${candidates.length === 1 ? "" : "s"}`].filter(Boolean);
+ return {
+ key: "found",
+ label: "Found",
+ pill: n ? pill("count", n) : pill("none"),
+ line: n ? `Found by ${parts.join(", ")}` : "Not found by a search, a case or the clip finder (it came in some other way)",
+ findClips,
+ marks,
+ candidates,
+ };
+}
+
+// ── downloaded ───────────────────────────────────────────────────────────────
+
+const AVAILABLE = new Set(["public", "unlisted"]);
+
+async function downloadedStage({ idn }) {
+ if (!idn.exists) {
+ return { key: "downloaded", label: "Downloaded", pill: pill("none"), line: idn.channelExists ? `Not in the corpus: no ${idn.ch}/data/${idn.dirId}/` : `No channel ${idn.ch} in the corpus`, meta: null, media: [] };
+ }
+ const dir = idn.dir;
+ const head = await readJsonHead(path.join(dir, "metadata.info.json"));
+ const meta = head
+ ? {
+ bytes: head.size,
+ id: head.fields.id ?? null,
+ title: head.fields.title ?? null,
+ webpageUrl: head.fields.webpage_url ?? null,
+ uploadDate: head.fields.upload_date ?? null,
+ extractor: head.fields.extractor_key ?? head.fields.extractor ?? null,
+ }
+ : null;
+ const hist = await readJson(path.join(dir, "metadata.history.json"));
+ const histEntries = Array.isArray(hist?.entries) ? hist.entries : [];
+ const history = histEntries.length ? { count: histEntries.length, lastAt: histEntries[histEntries.length - 1]?.at ?? null, lastBy: histEntries[histEntries.length - 1]?.by ?? null } : null;
+ const oc = await readJson(path.join(dir, "download-outcome.json"));
+ const outcome = oc ? { status: String(oc.status ?? "unknown"), finishedAt: oc.finishedAt ?? null, attempts: Array.isArray(oc.attempts) ? oc.attempts.length : 0, webpageUrl: oc.webpageUrl ?? null, error: oc.error ?? oc.message ?? null } : null;
+ const av = await readJson(path.join(dir, "availability.json"));
+ const availability = av ? { availability: String(av.availability ?? "unknown"), checkedAt: av.checkedAt ?? null } : null;
+ const pointer = await readSavedVideoPointer(dir);
+ const saved = pointer ? { file: pointer.file, height: pointer.height ?? null, reachable: await present(pointer.path) } : null;
+ const mi = await readJson(path.join(dir, "media-import.json"));
+ const miEntries = Array.isArray(mi) ? mi : Array.isArray(mi?.entries) ? mi.entries : [];
+ const imported = miEntries.length ? { count: miEntries.length, lastAt: miEntries[miEntries.length - 1]?.at ?? null, via: miEntries[miEntries.length - 1]?.via ?? null } : null;
+ const names = await readdir(dir).catch(() => []);
+ const mediaNames = [...(await audioFilesOf(dir)).map((a) => a.name), ...names.filter((n) => /^source-media\.(mp4|webm|mkv|mov|m4v)$/i.test(n))];
+ const media = [];
+ for (const n of [...new Set(mediaNames)]) {
+ const f = await fileState(dir, n);
+ if (f) media.push(f);
+ }
+ const vtts = names.filter((n) => /^transcript\..+\.vtt$/.test(n));
+ const problems = [];
+ if (outcome && !outcome.status.startsWith("ok")) problems.push(`the last download ended ${outcome.status}`);
+ if (availability && !AVAILABLE.has(availability.availability)) problems.push(`the recording reads ${availability.availability} (checked ${availability.checkedAt ?? "?"})`);
+ if (media.some((m) => m.link && !m.reachable)) problems.push("a media link does not resolve (its drive is not answering)");
+ if (saved && !saved.reachable) problems.push("the saved video's file does not answer");
+ const have = [meta && "metadata", vtts.length && "captions", media.length && `${media.length} media file${media.length === 1 ? "" : "s"}`, saved && `the saved video${saved.height ? ` (${saved.height}p)` : ""}`].filter(Boolean);
+ return {
+ key: "downloaded",
+ label: "Downloaded",
+ pill: problems.length ? pill("warn") : have.length ? pill("ok") : pill("none"),
+ line: problems.length ? problems.join("; ") : have.length ? `${have.join(", ")} on disk` : "Nothing downloaded yet",
+ meta,
+ history,
+ outcome,
+ availability,
+ saved,
+ imported,
+ media,
+ captions: vtts,
+ problems,
+ };
+}
+
+// ── transcribed ──────────────────────────────────────────────────────────────
+
+async function transcribedStage({ idn }) {
+ if (!idn.exists) return { key: "transcribed", label: "Transcribed", pill: pill("none"), line: "No recording to transcribe", cues: null };
+ const dir = idn.dir;
+ const cueFile = path.join(dir, "transcript.cues.json");
+ const head = await readJsonHead(cueFile, { stopKey: "cues" });
+ const lastEnd = head ? await lastEndOf(cueFile) : null;
+ const f = head?.fields ?? {};
+ const duration = fin(f.duration) && f.duration > 0 ? f.duration : null;
+ const cues = head
+ ? {
+ bytes: head.size,
+ source: f.source ?? null,
+ format: f.transcriptFormat ?? null,
+ vttFile: f.vttFile ?? null,
+ engine: f.engine ?? f.model ?? f.app ?? null,
+ platform: f.platform ?? null,
+ title: f.title ?? null,
+ uploadDate: f.uploadDate ?? null,
+ duration,
+ lastEnd,
+ coverage: duration && fin(lastEnd) ? Math.min(1, lastEnd / duration) : null,
+ }
+ : null;
+ const pin = await readJson(path.join(dir, "transcript-pin.json"));
+ const to = await readJson(path.join(dir, "transcribe-outcome.json"));
+ // transcribe-outcome.json is written when a transcript is FINALIZED (transcribeOutcome.ts): who made it, when, a salvage.
+ const outcome = to && typeof to === "object" ? { at: to.transcribedAt ?? null, worker: to.worker?.appId ?? to.worker?.id ?? null, durationMs: fin(to.durationMs) ? to.durationMs : null, salvaged: !!to.salvaged } : null;
+ const words = await statOf(path.join(dir, "words.json"));
+ const names = await readdir(dir).catch(() => []);
+ const vtts = names.filter((n) => /^transcript\..+\.vtt$/.test(n));
+ const line = cues
+ ? `${cues.source ?? "cues"}${cues.engine ?? outcome?.worker ? ` (${cues.engine ?? outcome?.worker})` : ""}${cues.coverage !== null ? `, ${Math.round(cues.coverage * 100)}% of ${hms(cues.duration)}` : ""}${outcome?.salvaged ? ", SALVAGED (gaps)" : ""}${words ? ", timed words" : ""}${pin ? ", pinned" : ""}`
+ : vtts.length
+ ? `${vtts.length} caption file${vtts.length === 1 ? "" : "s"}, no cues built`
+ : "Not transcribed";
+ return {
+ key: "transcribed",
+ label: "Transcribed",
+ pill: cues ? ((cues.coverage !== null && cues.coverage < 0.5) || outcome?.salvaged ? pill("warn") : pill("ok")) : pill("none"),
+ line,
+ cues,
+ pin: pin ? { ...(typeof pin === "object" ? pin : {}) } : null,
+ outcome,
+ words: words ? { bytes: words.size } : null,
+ captions: vtts,
+ };
+}
+
+// ── clock ────────────────────────────────────────────────────────────────────
+
+async function clockStage({ idn }) {
+ const clock = idn.exists ? await readRecordingClock(idn.dir) : null;
+ if (!clock) return { key: "clock", label: "Clock", pill: pill("none"), line: "No time map (clock.json): one is made when a window is cut from a saved recording", clock: null };
+ const steps = (clock.gaps ?? []).length;
+ return {
+ key: "clock",
+ label: "Clock",
+ pill: clock.ok && !steps ? pill("ok") : pill("warn"),
+ line: describeClock(clock),
+ clock: { id: clock.id, ok: clock.ok, source: clock.source?.file ?? null, target: clock.target?.file ?? null, segments: (clock.segments ?? []).length, steps, residualMs: fin(clock.residual?.rms) ? round2(clock.residual.rms * 1000) : null, measuredAt: clock.measuredAt ?? clock.at ?? null },
+ };
+}
+
+// ── windows ──────────────────────────────────────────────────────────────────
+
+/**
+ * Every clip window of the video dir, oldest-start first, each with its sidecar's provenance and the usage
+ * rows it can cut (its span holds the row's played span whole) -- the cross-check: a window asked for a clip
+ * no project uses now, and a draft clip no window holds.
+ */
+export async function listWindows(dir) {
+ const clips = path.join(dir, "clips");
+ const out = [];
+ for (const name of await readdir(clips).catch(() => [])) {
+ const m = WINDOW_NAME.exec(name);
+ if (!m) continue;
+ const from = Number(m[1]);
+ const to = Number(m[2]);
+ if (!(to > from)) continue;
+ const desynced = !!m[3];
+ const st = await statOf(path.join(clips, name));
+ if (!st?.isFile()) continue;
+ const side = await readJson(path.join(clips, `${m[1]}-${m[2]}${desynced ? ".desynced" : ""}.json`));
+ out.push({
+ name: `${m[1]}-${m[2]}`,
+ file: name,
+ from,
+ to,
+ bytes: st.size,
+ mtime: new Date(st.mtimeMs).toISOString(),
+ desynced,
+ sidecar: side && typeof side === "object"
+ ? {
+ requestedBy: side.requestedBy ?? null,
+ manifest: side.manifest ?? null,
+ clipId: side.clipId ?? null,
+ reason: side.reason ?? null,
+ fetchedAt: side.fetchedAt ?? null,
+ source: side.source ?? null,
+ syncOk: side.sync && typeof side.sync === "object" ? side.sync.ok === true : null,
+ clock: side.clock && typeof side.clock === "object" ? { id: side.clock.id ?? null, offset: side.clock.offset ?? null, certain: side.clock.certain === true } : null,
+ }
+ : null,
+ });
+ }
+ out.sort((a, b) => a.from - b.from || a.to - b.to);
+ return out;
+}
+
+const holds = (w, s) => fin(s.from) && fin(s.to) && w.from <= s.from + WIN_EPS && w.to >= s.to - WIN_EPS;
+
+function windowsStage({ idn, windows, rows, savedWhole, savedAway = null, focus }) {
+ const live = windows.filter((w) => !w.desynced);
+ const clipIds = new Set(rows.map((r) => r.clipId));
+ const annotated = windows.map((w) => {
+ const serves = w.desynced ? [] : rows.filter((r) => holds(w, playedOf(r))).map((r) => ({ project: r.project, clipId: r.clipId }));
+ const partly = w.desynced ? [] : rows.filter((r) => !holds(w, playedOf(r)) && overlaps(playedOf(r).from, playedOf(r).to, w.from, w.to)).map((r) => ({ project: r.project, clipId: r.clipId }));
+ const orphan = !!(w.sidecar?.clipId && !clipIds.has(w.sidecar.clipId)) && serves.length === 0;
+ return { ...w, serves, partly, orphan, focused: !!focus && Math.abs(w.from - focus.from) <= WIN_EPS && Math.abs(w.to - focus.to) <= WIN_EPS };
+ });
+ // A draft clip no window holds (and no saved whole recording, which cuts any span).
+ const uncovered = savedWhole ? [] : rows.filter((r) => r.inDraft && !live.some((w) => holds(w, playedOf(r)))).map((r) => ({ project: r.project, clipId: r.clipId, ...playedOf(r) }));
+ const focusedWin = focus ? annotated.find((w) => w.focused) ?? null : null;
+ const desyncedN = windows.filter((w) => w.desynced).length;
+ const bits = [
+ `${live.length} window${live.length === 1 ? "" : "s"}`,
+ desyncedN && `${desyncedN} set aside (desynced)`,
+ uncovered.length && `${uncovered.length} clip${uncovered.length === 1 ? "" : "s"} not fetched`,
+ savedWhole && "the whole recording is saved (any span cuts from it)",
+ savedAway && `the saved whole recording does not answer (${savedAway}): its drive is not mounted, so nothing cuts from it now`,
+ ].filter(Boolean);
+ return {
+ key: "windows",
+ label: "Windows",
+ pill: uncovered.length || desyncedN || savedAway ? pill("warn") : live.length ? pill("count", live.length) : savedWhole ? pill("ok") : pill("none"),
+ line: live.length || uncovered.length || desyncedN || savedWhole || savedAway ? bits.join(", ") : "No windows cut yet",
+ windows: annotated,
+ uncovered,
+ savedWhole: !!savedWhole,
+ savedUnreachable: savedAway,
+ focus: focus ? { ...focus, name: windowName(focus.from, focus.to), found: !!focusedWin } : null,
+ };
+}
+
+// ── used in ──────────────────────────────────────────────────────────────────
+
+function usedStage({ rows, allRows, focus }) {
+ const projects = new Set(rows.map((r) => r.project));
+ return {
+ key: "used",
+ label: "Used in",
+ pill: rows.length ? pill("count", rows.length) : pill("none"),
+ line: rows.length
+ ? `${rows.length} clip${rows.length === 1 ? "" : "s"} in ${projects.size} project${projects.size === 1 ? "" : "s"}${focus && allRows.length !== rows.length ? ` (of ${allRows.length} from this recording)` : ""}`
+ : focus && allRows.length
+ ? `No clip plays from this window (${allRows.length} from the recording elsewhere)`
+ : "No project cuts from it",
+ rows,
+ };
+}
+
+// ── checked ──────────────────────────────────────────────────────────────────
+
+async function checkedStage({ rows, dirOf }) {
+ const out = [];
+ const docs = new Map();
+ for (const r of rows) {
+ const dir = dirOf(r.project);
+ if (!docs.has(r.project)) docs.set(r.project, await readQuoteCheck(dir));
+ const row = docs.get(r.project)?.clips?.[r.clipId] ?? null;
+ const entry = { start: r.start, end: r.end, cutStart: r.cutStart, cutEnd: r.cutEnd, quote: r.quote ?? "" };
+ out.push({
+ project: r.project,
+ clipId: r.clipId,
+ hasQuote: !!r.quote,
+ status: row?.status ?? null,
+ offset: fin(row?.offset) ? row.offset : null,
+ current: row && r.inDraft ? rowIsCurrent(row, entry) : false,
+ checkedAt: docs.get(r.project)?.checkedAt ?? null,
+ });
+ }
+ const current = out.filter((c) => c.current);
+ const bad = current.filter((c) => c.status !== "ok");
+ const quoted = out.filter((c) => c.hasQuote).length;
+ return {
+ key: "checked",
+ label: "Checked",
+ pill: !out.length ? pill("none") : bad.length ? pill("warn") : quoted && current.length >= quoted ? pill("ok") : current.length ? pill("count", current.length) : pill("none"),
+ line: !out.length
+ ? "Nothing to check: no clip uses it"
+ : bad.length
+ ? `${bad.map((b) => `${b.clipId} ${b.status}`).join(", ")}`
+ : current.length
+ ? `${current.length} of ${quoted || out.length} quote${(quoted || out.length) === 1 ? "" : "s"} heard where the cut plays`
+ : quoted
+ ? "Not quote-checked (or the cut changed since)"
+ : "No clip carries a quote to check",
+ clips: out,
+ };
+}
+
+// ── rendered ─────────────────────────────────────────────────────────────────
+
+async function renderedStage({ rows, dirOf }) {
+ const out = [];
+ const takesOf = new Map();
+ for (const r of rows) {
+ const dir = dirOf(r.project);
+ // A take rendered before render.json existed is known by its preview (listTakes: the file and its size).
+ if (!takesOf.has(r.project)) takesOf.set(r.project, new Map(((await listTakes(dir).catch(() => null))?.takes ?? []).map((t) => [t.id, t])));
+ for (const v of r.versions) {
+ const rec = await readRenderRecord(path.join(dir, "takes", v.id)).catch(() => null);
+ const take = takesOf.get(r.project).get(v.id) ?? null;
+ const state = rec?.state ?? (take?.previewSize ? "done" : null);
+ const seconds = fin(rec?.seconds) ? rec.seconds : fin(take?.seconds) ? take.seconds : null;
+ const cut = await readJson(path.join(dir, "takes", v.id, "out", "segments", `${r.clipId}.cut.json`));
+ out.push({ project: r.project, clipId: r.clipId, version: v.id, kind: v.kind, label: take?.label ?? null, state, seconds, endedAt: rec?.endedAt ?? rec?.finishedAt ?? take?.builtAt ?? null, cut: cut && typeof cut === "object" ? { from: cut.from ?? cut.start ?? null, to: cut.to ?? cut.end ?? null } : null });
+ }
+ if (r.inDraft) {
+ const cut = await readJson(path.join(dir, "out", "segments", `${r.clipId}.cut.json`));
+ if (cut) out.push({ project: r.project, clipId: r.clipId, version: null, kind: "draft", state: "segment", seconds: null, endedAt: null, cut: { from: cut.from ?? cut.start ?? null, to: cut.to ?? cut.end ?? null } });
+ }
+ }
+ const done = out.filter((x) => x.state === "done");
+ return {
+ key: "rendered",
+ label: "Rendered",
+ pill: done.length ? pill("count", done.length) : pill("none"),
+ line: done.length
+ ? `In ${done.length} rendered version${done.length === 1 ? "" : "s"}: ${[...new Set(done.map((d) => `${d.project.split("/").pop()} ${d.version}`))].slice(0, 4).join(", ")}${done.length > 4 ? ", …" : ""}`
+ : out.length
+ ? "In versions not rendered (or not finished)"
+ : "Not in any saved version",
+ renders: out,
+ };
+}
+
+// ── published ────────────────────────────────────────────────────────────────
+
+async function publishedStage({ rows, dirOf, idn }) {
+ const out = [];
+ const byProject = new Map();
+ for (const r of rows) {
+ if (!byProject.has(r.project)) {
+ const dir = dirOf(r.project);
+ const m = await readJson(path.join(dir, "video.manifest.json"));
+ byProject.set(r.project, { links: await readLinkCheck(dir), provenance: m?.provenance ?? null, timeline: Array.isArray(m?.timeline) ? m.timeline : [] });
+ }
+ const p = byProject.get(r.project);
+ const entry = p.timeline.find((e) => e?.id === r.clipId) ?? null;
+ const origin = typeof p.provenance?.siteOrigin === "string" && /^https?:\/\//i.test(p.provenance.siteOrigin) ? p.provenance.siteOrigin.replace(/\/+$/, "") : null;
+ const url = entry?.citeUrl ?? (origin && entry ? archiveMomentUrl({ ...entry, channel: entry.channel ?? idn.ch, ...(idn.siteId && !entry.siteVideo ? { siteVideo: idn.siteId } : {}) }, p.provenance, Math.floor(fin(entry.cutStart) ? entry.cutStart : entry.start ?? 0), { origin }) : null);
+ const recorded = (p.links?.links ?? []).filter((l) => l.clip === r.clipId);
+ const now = url ? recorded.find((l) => l.url === url) ?? null : recorded[0] ?? null;
+ out.push({ project: r.project, clipId: r.clipId, url, state: now?.state ?? (recorded.length ? "changed" : null), fix: now?.fix ?? null, checkedAt: p.links?.checkedAt ?? null });
+ }
+ const dead = out.filter((o) => o.state === "dead");
+ const ok = out.filter((o) => o.state === "ok");
+ const unverified = out.filter((o) => o.state === "unverified");
+ return {
+ key: "published",
+ label: "Published",
+ pill: !out.length ? pill("none") : dead.length ? pill("warn") : ok.length === out.length ? pill("ok") : ok.length ? pill("count", ok.length) : pill("none"),
+ line: !out.length
+ ? "Not in any cut, so no link to it"
+ : out.every((o) => o.state === null)
+ ? `${out.length} link${out.length === 1 ? "" : "s"} to it, never checked`
+ : dead.length
+ ? `${dead.length} dead link${dead.length === 1 ? "" : "s"}: ${dead.map((d) => d.clipId).join(", ")}`
+ : `${ok.length} of ${out.length} link${out.length === 1 ? "" : "s"} open on the site${unverified.length ? `, ${unverified.length} unverified` : ""}${out.some((o) => o.state === null || o.state === "changed") ? ", some never checked" : ""}`,
+ links: out,
+ };
+}
+
+// ── the whole of it ──────────────────────────────────────────────────────────
+
+/**
+ * The ingredient's nine stages.
+ *
+ * @param {{ channelsDir: string, reportsRoot: string, ch: string, id: string, window?: string | { from: number, to: number } | null,
+ * index?: Record<string, any> | null, indexFile?: string, writeIndex?: boolean }} o
+ */
+export async function readIngredient({ channelsDir, reportsRoot, ch, id, window = null, index = null, indexFile, writeIndex = true }) {
+ if (!isChannelSlug(ch)) throw new Error(`"${ch}" is not a channel slug`);
+ if (!isVideoId(id)) throw new Error(`"${id}" is not a video id`);
+ const focus = typeof window === "string" ? parseWindowParam(window) : window && fin(window.from) && fin(window.to) ? window : null;
+ const idn = await ingredientIdentity({ channelsDir, ch, id });
+ const idx = index ?? (await loadUsageIndex({ reportsRoot, channelsDir, ...(indexFile ? { file: indexFile } : {}), write: writeIndex })).index;
+ const allRows = usesOf(idx, ch, idn.dirId);
+ const rows = rowsInWindow(allRows, focus);
+ const dirOf = (project) => path.join(reportsRoot, project);
+
+ const windows = idn.exists ? await listWindows(idn.dir) : [];
+ const pointer = idn.exists ? await readSavedVideoPointer(idn.dir) : null;
+ const savedWhole = pointer ? await present(pointer.path) : false;
+
+ const [found, downloaded, transcribed, clock] = await Promise.all([foundStage({ reportsRoot, idn }), downloadedStage({ idn }), transcribedStage({ idn }), clockStage({ idn })]);
+ const win = windowsStage({ idn, windows, rows: allRows, savedWhole, savedAway: pointer && !savedWhole ? pointer.path : null, focus });
+ const used = usedStage({ rows, allRows, focus });
+ const [checked, rendered, published] = await Promise.all([checkedStage({ rows, dirOf }), renderedStage({ rows, dirOf }), publishedStage({ rows, dirOf, idn })]);
+
+ const title = downloaded.meta?.title ?? transcribed.cues?.title ?? null;
+ return {
+ ch,
+ id: idn.asked,
+ dirId: idn.dirId,
+ siteId: idn.siteId,
+ platform: idn.platform,
+ exists: idn.exists,
+ title,
+ webpageUrl: downloaded.meta?.webpageUrl ?? downloaded.outcome?.webpageUrl ?? null,
+ duration: transcribed.cues?.duration ?? null,
+ uploadDate: transcribed.cues?.uploadDate ?? downloaded.meta?.uploadDate ?? null,
+ notes: idn.notes,
+ focus: win.focus,
+ stages: [found, downloaded, transcribed, clock, win, used, checked, rendered, published],
+ };
+}
+
+/** The pill as one glyph (the CLI's, and the page's text): ✓, the count, ! or —. */
+export const pillGlyph = (p) => (p?.kind === "ok" ? "✓" : p?.kind === "count" ? String(p.n) : p?.kind === "warn" ? "!" : "—");
diff --git a/umtool/lib/ingredients/stages.test.mjs b/umtool/lib/ingredients/stages.test.mjs
@@ -0,0 +1,152 @@
+// node --test umtool/lib/ingredients/stages.test.mjs
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { lastEndOf, readJsonHead, scanHead } from "./heads.mjs";
+import { parseWindowParam, pillGlyph, readIngredient, STAGES } from "./stages.mjs";
+
+test("scanHead: the top-level primitives, nested members skipped, a truncated text read as far as it is whole", () => {
+ const text = JSON.stringify({ id: "abc", title: "A \"quoted\" title", formats: [{ duration: 9, x: "}" }], duration: 120, live: false, n: null, cues: [{ end: 5 }] });
+ const all = scanHead(text);
+ assert.deepEqual(all.fields, { id: "abc", title: 'A "quoted" title', duration: 120, live: false, n: null });
+ assert.deepEqual(all.nested, ["formats", "cues"]);
+ assert.equal(all.complete, true);
+ const stopped = scanHead(text, { stopKey: "formats" });
+ assert.deepEqual(stopped.fields, { id: "abc", title: 'A "quoted" title' });
+ // Cut in the middle of the formats array: what came before is still read.
+ const cut = scanHead(text.slice(0, text.indexOf("duration") + 4));
+ assert.deepEqual(cut.fields, { id: "abc", title: 'A "quoted" title' });
+ assert.equal(cut.complete, false);
+ // A number at the very end of the buffer may be cut short: not read.
+ assert.deepEqual(scanHead('{"a": 12').fields, {});
+});
+
+test("parseWindowParam", () => {
+ assert.deepEqual(parseWindowParam("10.00-40.00"), { from: 10, to: 40 });
+ assert.equal(parseWindowParam("40-10"), null);
+ assert.equal(parseWindowParam("x"), null);
+});
+
+async function corpus() {
+ const root = await mkdtemp(path.join(tmpdir(), "stages-"));
+ const channels = path.join(root, "channels");
+ const reports = path.join(root, "reports");
+ const vdir = path.join(channels, "chan", "data", "vid");
+ await mkdir(path.join(vdir, "clips"), { recursive: true });
+ await writeFile(path.join(channels, "chan", "config.json"), JSON.stringify({ platform: "youtube" }));
+ // A metadata file whose formats push everything past the head.
+ const formats = Array.from({ length: 4000 }, (_, i) => ({ format_id: String(i), duration: 1, url: "https://x.example/" + "y".repeat(20) }));
+ await writeFile(path.join(vdir, "metadata.info.json"), JSON.stringify({ id: "vid", title: "The Recording", formats, webpage_url: "https://www.youtube.com/watch?v=vid", duration: 300 }));
+ const cues = Array.from({ length: 50 }, (_, i) => ({ start: i * 6, end: i * 6 + 5.5, text: `cue ${i}` }));
+ await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ version: 2, source: "vtt", title: "The Recording", uploadDate: "20261101", duration: 300, cues }));
+ await writeFile(path.join(vdir, "transcript.en.vtt"), "WEBVTT\n");
+ await writeFile(path.join(vdir, "download-outcome.json"), JSON.stringify({ videoId: "vid", status: "ok", attempts: [{ n: 0 }] }));
+ await writeFile(path.join(vdir, "availability.json"), JSON.stringify({ availability: "public", checkedAt: "2026-11-01T00:00:00Z" }));
+ await writeFile(path.join(vdir, "clips", "10.00-40.00.mp4"), Buffer.alloc(100));
+ await writeFile(path.join(vdir, "clips", "10.00-40.00.json"), JSON.stringify({ requestedBy: "a cut", clipId: "a1", fetchedAt: "2026-11-02T00:00:00Z" }));
+ await writeFile(path.join(vdir, "clips", "200.00-230.00.mp4"), Buffer.alloc(50));
+ await writeFile(path.join(vdir, "clips", "200.00-230.00.json"), JSON.stringify({ requestedBy: "gone cut", clipId: "zz" }));
+ const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: "vid", start, end, ...extra });
+ const m = (timeline) => ({ provenance: { channelSlug: "chan", siteOrigin: "https://site.example" }, render: {}, timeline });
+ const a = path.join(reports, "f", "a");
+ await mkdir(path.join(a, "takes", "v1"), { recursive: true });
+ await writeFile(path.join(a, "video.manifest.json"), JSON.stringify(m([clip("a1", 12, 20, { quote: "the quote" }), clip("a2", 100, 110, { quote: "another" })])));
+ await writeFile(path.join(a, "takes", "v1", "take.json"), "{}");
+ await writeFile(path.join(a, "takes", "v1", "base.manifest.json"), JSON.stringify(m([clip("a1", 12, 20, { quote: "the quote" })])));
+ await writeFile(path.join(a, "takes", "v1", "preview.mp4"), Buffer.alloc(10));
+ await writeFile(path.join(a, "takes", "v1", "render.json"), JSON.stringify({ state: "done", mp4: "preview.mp4", seconds: 8 }));
+ await writeFile(path.join(a, "quote-check.json"), JSON.stringify({ version: 1, checkedAt: "2026-11-03T00:00:00Z", clips: { a1: { status: "ok", cut: { from: 12, to: 20 }, quote: "the quote" }, a2: { status: "moved", cut: { from: 100, to: 110 }, quote: "another" } } }));
+ const b = path.join(reports, "f", "b");
+ await mkdir(path.join(b, "out"), { recursive: true });
+ await writeFile(path.join(b, "video.manifest.json"), JSON.stringify(m([clip("b1", 15, 25)])));
+ await writeFile(path.join(b, "out", "links.json"), JSON.stringify({ version: 1, checkedAt: "2026-11-04T00:00:00Z", links: [{ clip: "b1", url: "https://site.example/?v=chan%2Fvid&t=15", state: "ok" }] }));
+ return { root, channels, reports, vdir };
+}
+
+async function listTree(dir) {
+ const out = [];
+ for (const e of await readdir(dir, { withFileTypes: true, recursive: true })) out.push(path.join(e.parentPath ?? e.path, e.name));
+ const st = await Promise.all(out.map((p) => stat(p).then((s) => `${p}:${s.size}:${s.mtimeMs}`)));
+ return st.sort();
+}
+
+test("the nine stages of a recording used by two projects, read without writing to the corpus", async () => {
+ const { root, channels, reports, vdir } = await corpus();
+ try {
+ const before = await listTree(channels);
+ const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "vid", indexFile: path.join(root, "state", "usage.json") });
+ assert.deepEqual(await listTree(channels), before, "nothing under the channels dir changed");
+ assert.deepEqual(r.stages.map((s) => s.key), STAGES.map((s) => s.key));
+ const by = Object.fromEntries(r.stages.map((s) => [s.key, s]));
+ assert.equal(r.title, "The Recording");
+ assert.equal(r.webpageUrl, null, "webpage_url is past the head: not read");
+ assert.equal(by.downloaded.pill.kind, "ok");
+ assert.equal(by.downloaded.meta.id, "vid");
+ assert.equal(by.transcribed.pill.kind, "ok");
+ assert.equal(by.transcribed.cues.lastEnd, 299.5);
+ assert.ok(Math.abs(by.transcribed.cues.coverage - 299.5 / 300) < 1e-9);
+ assert.equal(pillGlyph(by.clock.pill), "—");
+ // Windows: a2 (100-110) has no window -> the stage warns; the 200-230 window's clip no project uses.
+ assert.equal(by.windows.pill.kind, "warn");
+ assert.deepEqual(by.windows.uncovered.map((u) => u.clipId), ["a2"]);
+ const w10 = by.windows.windows.find((w) => w.name === "10.00-40.00");
+ assert.deepEqual(w10.serves.map((s) => s.clipId).sort(), ["a1", "b1"]);
+ assert.equal(by.windows.windows.find((w) => w.name === "200.00-230.00").orphan, true);
+ assert.deepEqual(by.used.rows.map((u) => `${u.project}#${u.clipId}`), ["f/a#a1", "f/a#a2", "f/b#b1"]);
+ assert.equal(pillGlyph(by.used.pill), "3");
+ assert.equal(by.checked.pill.kind, "warn");
+ assert.match(by.checked.line, /a2 moved/);
+ assert.deepEqual(by.rendered.renders.filter((x) => x.state === "done").map((x) => `${x.clipId}@${x.version}`), ["a1@v1"]);
+ assert.equal(pillGlyph(by.rendered.pill), "1");
+ const b1 = by.published.links.find((l) => l.clipId === "b1");
+ assert.equal(b1.state, "ok");
+ assert.equal(b1.url, "https://site.example/?v=chan%2Fvid&t=15");
+ assert.equal(by.published.links.find((l) => l.clipId === "a1").state, null);
+ void vdir;
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("?window= focuses one window: the stages after it narrow to the clips it plays", async () => {
+ const { root, channels, reports } = await corpus();
+ try {
+ const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "vid", window: "10.00-40.00", indexFile: path.join(root, "state", "usage.json") });
+ const by = Object.fromEntries(r.stages.map((s) => [s.key, s]));
+ assert.deepEqual(r.focus, { from: 10, to: 40, name: "10.00-40.00", found: true });
+ assert.equal(by.windows.windows.filter((w) => w.focused).length, 1);
+ assert.deepEqual(by.used.rows.map((u) => u.clipId), ["a1", "b1"]);
+ assert.match(by.used.line, /of 3 from this recording/);
+ assert.deepEqual(by.checked.clips.map((c) => c.clipId), ["a1", "b1"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("an id the corpus does not hold: every stage says so, nothing throws", async () => {
+ const { root, channels, reports } = await corpus();
+ try {
+ const r = await readIngredient({ channelsDir: channels, reportsRoot: reports, ch: "chan", id: "nope", indexFile: path.join(root, "state", "usage.json") });
+ assert.equal(r.exists, false);
+ assert.equal(r.stages.length, 9);
+ assert.match(r.stages[1].line, /Not in the corpus/);
+ assert.equal(r.stages[4].line, "No windows cut yet");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("the head and tail readers read only their ends", async () => {
+ const { root, vdir } = await corpus();
+ try {
+ const h = await readJsonHead(path.join(vdir, "metadata.info.json"));
+ assert.ok(h.size > 64 * 1024);
+ assert.deepEqual(Object.keys(h.fields), ["id", "title"]);
+ assert.equal(await lastEndOf(path.join(vdir, "transcript.cues.json")), 299.5);
+ assert.equal(await lastEndOf(path.join(vdir, "nope.json")), null);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/ingredients/usedIn.mjs b/umtool/lib/ingredients/usedIn.mjs
@@ -0,0 +1,276 @@
+// WHERE AN INGREDIENT IS USED (umtool redesign, lane L5: the ingredient life-cycle rail).
+//
+// The reverse of a manifest's timeline: for one recording -- `<channel>/<video>`,
+// the corpus's `channels/<ch>/data/<video>/` -- every project clip that cuts
+// from it, in the working draft and in each saved version.
+//
+// <REPORTS_ROOT>/.umtool/usage-index.json (UMTOOL_USAGE_INDEX_FILE overrides)
+// { format: "umtool-usage-index", version: 1, builtAt,
+// files: { "<abs manifest>": { mtimeMs, size, project, version, kind, clips: [Use] } },
+// dirIds: { "<ch>/<cited id>": { dir, dataMtimeMs? } }, a Rumble/Twitch id's directory, resolved once
+// byIngredient: { "<ch>/<dir id>": [Row] } }
+//
+// Use { ch, video, siteVideo?, clipId, start, end, cutStart, cutEnd, quote? } one clip of one manifest
+// Row { project, clipId, start, end, cutStart, cutEnd, quote, inDraft,
+// versions: [{ id, kind, start, end, cutStart, cutEnd }] } one clip of one project
+//
+// WHICH MANIFESTS. A project's video.manifest.json is the draft (lane L3); each
+// take's frozen form is `takes/<id>/base.manifest.json` (a saved version) or,
+// for a legacy rendered take, the `takes/<id>/video.manifest.json` the render
+// wrote. A take with neither (a patch that follows the draft) is the draft's
+// clips again and adds nothing here.
+//
+// INCREMENTAL by each manifest's mtime and size: an unchanged file's clips are
+// read back from the cache, a changed one is parsed again, and a file the walk
+// no longer finds (a project deleted, a take pruned) is dropped with it. The
+// walk itself is walkProjects (a project is a leaf: nothing under out/ is ever
+// listed), so a rebuild with nothing changed is a readdir per folder and a stat
+// per manifest.
+//
+// ONE KEY PER RECORDING. A Rumble recording has two ids -- the folder slug the
+// corpus keeps it under and the embed id the archive serves (AGENTS.md); a clip
+// may cite either. Each clip's key is the DIRECTORY id (`resolveVideoDirId`:
+// an embed id with no directory is looked up in the channel's metadata), so
+// the two collapse to one ingredient. Every other id costs nothing to resolve.
+//
+// Never written under CHANNELS_DIR: the corpus is read, the index lives in
+// umtool's own state dir. Plain ESM: `umtool ingredient` runs it under bare node.
+import { mkdir, readdir, readFile, rename, stat, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { walkProjects } from "../projects/walk.mjs";
+
+export const USAGE_INDEX_FORMAT = "umtool-usage-index";
+export const USAGE_INDEX_VERSION = 1;
+export const USAGE_INDEX_ENV = "UMTOOL_USAGE_INDEX_FILE";
+const MANIFEST = "video.manifest.json";
+const BASE = "base.manifest.json";
+const TAKES = "takes";
+const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const num = (v) => (fin(v) ? v : null);
+
+/** The cache file for a reports root. */
+export function usageIndexPath(reportsRoot, env = process.env) {
+ const o = env?.[USAGE_INDEX_ENV];
+ if (o) return path.resolve(o);
+ return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "usage-index.json");
+}
+
+/** `<ch>/<id>`. */
+export const ingredientKey = (ch, id) => `${ch}/${id}`;
+
+/**
+ * The clips of one manifest, as uses. A clip with no recording (a local `src`
+ * file, no video) is no ingredient of the corpus.
+ * @param {Record<string, any> | null} m
+ * @returns {{ ch: string, video: string, siteVideo?: string, clipId: string, start: number | null, end: number | null, cutStart: number | null, cutEnd: number | null, quote?: string }[]}
+ */
+export function usesOfManifest(m) {
+ const out = [];
+ for (const e of Array.isArray(m?.timeline) ? m.timeline : []) {
+ if (e?.type !== "clip" || !e.id) continue;
+ const ch = typeof e.channel === "string" && e.channel ? e.channel : m?.provenance?.channelSlug;
+ const video = e.video == null ? "" : String(e.video);
+ if (!ch || !video || e.src) continue;
+ out.push({
+ ch: String(ch),
+ video,
+ ...(typeof e.siteVideo === "string" && e.siteVideo ? { siteVideo: e.siteVideo } : {}),
+ clipId: String(e.id),
+ start: num(e.start),
+ end: num(e.end),
+ cutStart: num(e.cutStart),
+ cutEnd: num(e.cutEnd),
+ ...(typeof e.quote === "string" && e.quote ? { quote: e.quote.slice(0, 300) } : {}),
+ });
+ }
+ return out;
+}
+
+/**
+ * The manifests a project holds: its draft, then each take's frozen form.
+ * @param {string} dir
+ * @returns {Promise<{ version: string, kind: "draft" | "version" | "rendered", file: string }[]>}
+ */
+export async function manifestFilesOf(dir) {
+ const out = [{ version: "draft", kind: /** @type {const} */ ("draft"), file: path.join(dir, MANIFEST) }];
+ const takes = await readdir(path.join(dir, TAKES), { withFileTypes: true }).catch(() => []);
+ for (const t of takes.sort((a, b) => a.name.localeCompare(b.name))) {
+ if (!TAKE_ID.test(t.name)) continue;
+ if (!t.isDirectory() && !t.isSymbolicLink()) continue;
+ const td = path.join(dir, TAKES, t.name);
+ const base = path.join(td, BASE);
+ if (await stat(base).then((s) => s.isFile(), () => false)) {
+ out.push({ version: t.name, kind: "version", file: base });
+ continue;
+ }
+ const rendered = path.join(td, MANIFEST);
+ if (await stat(rendered).then((s) => s.isFile(), () => false)) out.push({ version: t.name, kind: "rendered", file: rendered });
+ }
+ return out;
+}
+
+/**
+ * Build (or bring up to date) the index.
+ *
+ * @param {{ reportsRoot: string, channelsDir: string | null, previous?: Record<string, any> | null,
+ * walk?: (root: string) => Promise<{ id: string, dir: string, kind: string }[]>,
+ * resolveDir?: (ch: string, video: string) => Promise<string>, now?: () => Date }} o
+ * @returns {Promise<{ index: Record<string, any>, stats: { manifests: number, parsed: number, reused: number, dropped: number, projects: number } }>}
+ */
+export async function buildUsageIndex({ reportsRoot, channelsDir, previous = null, walk = walkProjects, resolveDir = null, now = () => new Date() }) {
+ const prevFiles = previous?.format === USAGE_INDEX_FORMAT && previous?.version === USAGE_INDEX_VERSION && previous.files && typeof previous.files === "object" ? previous.files : {};
+ const resolve =
+ resolveDir ??
+ (async (ch, video) => (channelsDir ? await resolveVideoDirId(channelsDir, ch, video).catch(() => video) : video));
+ // The directory ids, cached with the index: a Rumble embed id is resolved by reading the heads of the
+ // channel's metadata files (thousands on a big channel), so a resolution is kept -- for good once it found a
+ // directory (a directory is never renamed under a recording), and until the channel's data/ changes when it
+ // found none. Only a Rumble- or Twitch-shaped id ever costs a read (resolveVideoDirId).
+ const prevDirIds = previous?.format === USAGE_INDEX_FORMAT && previous?.dirIds && typeof previous.dirIds === "object" ? previous.dirIds : {};
+ const dirIds = {};
+ const memo = new Map();
+ const costly = (video) => /^v[0-9a-z]{4,9}$/.test(video);
+ const dataMtime = async (ch) => (channelsDir ? await stat(path.join(channelsDir, ch, "data")).then((s) => Math.round(s.mtimeMs), () => null) : null);
+ const dirIdOf = async (ch, video) => {
+ const k = `${ch}/${video}`;
+ if (memo.has(k)) return memo.get(k);
+ let dir = null;
+ if (costly(video)) {
+ const was = prevDirIds[k];
+ if (was && typeof was.dir === "string" && (was.dir !== video || was.dataMtimeMs === (await dataMtime(ch)))) dir = was.dir;
+ if (dir === null) dir = await resolve(ch, video);
+ dirIds[k] = { dir, ...(dir === video ? { dataMtimeMs: await dataMtime(ch) } : {}) };
+ } else dir = await resolve(ch, video);
+ memo.set(k, dir);
+ return dir;
+ };
+
+ const projects = (await walk(reportsRoot)).filter((p) => p.kind === "report-video" || p.kind === undefined);
+ const files = {};
+ let parsed = 0;
+ let reused = 0;
+ for (const p of projects) {
+ for (const mf of await manifestFilesOf(p.dir)) {
+ const st = await stat(mf.file).catch(() => null);
+ if (!st?.isFile()) continue;
+ const mtimeMs = Math.round(st.mtimeMs);
+ const was = prevFiles[mf.file];
+ if (was && was.mtimeMs === mtimeMs && was.size === st.size && was.project === p.id && was.version === mf.version && Array.isArray(was.clips)) {
+ files[mf.file] = was;
+ reused += 1;
+ continue;
+ }
+ let m = null;
+ try {
+ m = JSON.parse(await readFile(mf.file, "utf8"));
+ } catch {
+ m = null;
+ }
+ parsed += 1;
+ files[mf.file] = { mtimeMs, size: st.size, project: p.id, version: mf.version, kind: mf.kind, clips: usesOfManifest(m) };
+ }
+ }
+ const dropped = Object.keys(prevFiles).filter((f) => !(f in files)).length;
+
+ // Aggregate: one row per (ingredient, project, clip), its versions beside it.
+ /** @type {Map<string, Map<string, Record<string, any>>>} */
+ const by = new Map();
+ for (const f of Object.values(files)) {
+ for (const u of f.clips) {
+ const key = ingredientKey(u.ch, await dirIdOf(u.ch, u.video));
+ if (!by.has(key)) by.set(key, new Map());
+ const rows = /** @type {Map<string, Record<string, any>>} */ (by.get(key));
+ const rk = `${f.project}\u0000${u.clipId}`;
+ let row = rows.get(rk);
+ if (!row) {
+ row = { project: f.project, clipId: u.clipId, start: u.start, end: u.end, cutStart: u.cutStart, cutEnd: u.cutEnd, quote: u.quote ?? null, inDraft: false, versions: [], cites: [] };
+ rows.set(rk, row);
+ }
+ if (!row.cites.includes(u.video)) row.cites.push(u.video);
+ if (u.siteVideo && !row.cites.includes(u.siteVideo)) row.cites.push(u.siteVideo);
+ if (f.kind === "draft") {
+ Object.assign(row, { start: u.start, end: u.end, cutStart: u.cutStart, cutEnd: u.cutEnd, quote: u.quote ?? null, inDraft: true });
+ } else {
+ row.versions.push({ id: f.version, kind: f.kind, start: u.start, end: u.end, cutStart: u.cutStart, cutEnd: u.cutEnd });
+ }
+ }
+ }
+ /** @type {Record<string, Record<string, any>[]>} */
+ const byIngredient = {};
+ for (const [key, rows] of [...by.entries()].sort(([a], [b]) => a.localeCompare(b))) {
+ byIngredient[key] = [...rows.values()]
+ .map((r) => ({ ...r, versions: r.versions.sort((a, b) => a.id.localeCompare(b.id, undefined, { numeric: true })) }))
+ .sort((a, b) => a.project.localeCompare(b.project) || (a.start ?? 0) - (b.start ?? 0) || a.clipId.localeCompare(b.clipId));
+ }
+ const index = { format: USAGE_INDEX_FORMAT, version: USAGE_INDEX_VERSION, builtAt: now().toISOString(), files, dirIds, byIngredient };
+ return { index, stats: { manifests: Object.keys(files).length, parsed, reused, dropped, projects: projects.length } };
+}
+
+/** The cached index, or null. */
+export async function readUsageIndex(file) {
+ try {
+ const j = JSON.parse(await readFile(file, "utf8"));
+ return j?.format === USAGE_INDEX_FORMAT ? j : null;
+ } catch {
+ return null;
+ }
+}
+
+async function writeUsageIndex(file, index) {
+ await mkdir(path.dirname(file), { recursive: true });
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, JSON.stringify(index) + "\n", "utf8");
+ await rename(tmp, file);
+}
+
+/**
+ * The index, brought up to date and cached. `write: false` reads the cache but
+ * never writes it (a read-only look at somebody else's tree).
+ *
+ * @param {{ reportsRoot: string, channelsDir: string | null, file?: string, write?: boolean, walk?: any, resolveDir?: any }} o
+ */
+export async function loadUsageIndex({ reportsRoot, channelsDir, file = usageIndexPath(reportsRoot), write = true, walk, resolveDir }) {
+ const previous = await readUsageIndex(file);
+ const built = await buildUsageIndex({ reportsRoot, channelsDir, previous, ...(walk ? { walk } : {}), ...(resolveDir ? { resolveDir } : {}) });
+ // byIngredient is a function of the files' clips and the directory ids alone: with no manifest parsed or
+ // dropped and the same directory answers, it is what was written -- no need to compare the whole index.
+ const changed = !previous || built.stats.parsed > 0 || built.stats.dropped > 0 || !sameDirIds(previous.dirIds, built.index.dirIds);
+ if (write && changed) await writeUsageIndex(file, built.index).catch(() => {});
+ return { ...built, file, written: write && changed };
+}
+
+/** Do two dirIds maps agree, entry by entry? */
+function sameDirIds(a, b) {
+ const ka = Object.keys(a ?? {});
+ if (ka.length !== Object.keys(b ?? {}).length) return false;
+ return ka.every((k) => b[k] && b[k].dir === a[k]?.dir && (b[k].dataMtimeMs ?? null) === (a[k]?.dataMtimeMs ?? null));
+}
+
+/**
+ * The rows for one ingredient. `id` may be either Rumble id: it is resolved to
+ * its directory first (`dirId`, when the caller has it already).
+ * @param {Record<string, any>} index
+ * @param {string} ch
+ * @param {string} dirId
+ */
+export function usesOf(index, ch, dirId) {
+ return index?.byIngredient?.[ingredientKey(ch, dirId)] ?? [];
+}
+
+/** The span a row plays: its cut, else its extent. */
+export const playedOf = (r) => ({ from: fin(r?.cutStart) ? r.cutStart : r?.start ?? null, to: fin(r?.cutEnd) ? r.cutEnd : r?.end ?? null });
+
+/** Does [a, b] overlap [from, to]? */
+export const overlaps = (a, b, from, to) => fin(a) && fin(b) && fin(from) && fin(to) && a < to && b > from;
+
+/** Only the rows a window serves: those whose played span (in any version) overlaps it. */
+export function rowsInWindow(rows, win) {
+ if (!win) return rows;
+ return rows.filter((r) => {
+ const spans = [playedOf(r), ...r.versions.map(playedOf)];
+ return spans.some((s) => overlaps(s.from, s.to, win.from, win.to));
+ });
+}
diff --git a/umtool/lib/ingredients/usedIn.test.mjs b/umtool/lib/ingredients/usedIn.test.mjs
@@ -0,0 +1,138 @@
+// node --test umtool/lib/ingredients/usedIn.test.mjs
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { buildUsageIndex, loadUsageIndex, manifestFilesOf, rowsInWindow, usesOf, usesOfManifest } from "./usedIn.mjs";
+
+const clip = (id, video, start, end, extra = {}) => ({ type: "clip", id, video, start, end, ...extra });
+const manifest = (timeline, channelSlug = "chan") => ({ schemaVersion: 1, provenance: { channelSlug }, render: {}, timeline });
+
+async function project(root, rel, m, takes = {}) {
+ const dir = path.join(root, rel);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m));
+ for (const [id, t] of Object.entries(takes)) {
+ await mkdir(path.join(dir, "takes", id), { recursive: true });
+ await writeFile(path.join(dir, "takes", id, "take.json"), "{}");
+ if (t.base) await writeFile(path.join(dir, "takes", id, "base.manifest.json"), JSON.stringify(t.base));
+ if (t.rendered) await writeFile(path.join(dir, "takes", id, "video.manifest.json"), JSON.stringify(t.rendered));
+ }
+ return dir;
+}
+
+async function fixture() {
+ const root = await mkdtemp(path.join(tmpdir(), "usedin-"));
+ const reports = path.join(root, "reports");
+ const channels = path.join(root, "channels");
+ await mkdir(reports, { recursive: true });
+ // A Rumble channel: its folder is the URL slug v7slug1, its archive (embed) id v7emb01.
+ await mkdir(path.join(channels, "rumch", "data", "v7slug1"), { recursive: true });
+ await writeFile(path.join(channels, "rumch", "config.json"), JSON.stringify({ platform: "rumble" }));
+ await writeFile(path.join(channels, "rumch", "data", "v7slug1", "metadata.info.json"), JSON.stringify({ id: "v7emb01", title: "t" }));
+ return { root, reports, channels };
+}
+
+test("usesOfManifest: clips with a recording, the provenance's channel as the default", () => {
+ const u = usesOfManifest(manifest([clip("a", "vid", 1, 2), { type: "card", id: "k" }, clip("b", "", 1, 2), clip("c", "v2", 3, 4, { channel: "other", cutStart: 3.5 }), clip("d", "v3", 1, 2, { src: "x.mp4" })]));
+ assert.deepEqual(u.map((x) => `${x.ch}/${x.video}#${x.clipId}`), ["chan/vid#a", "other/v2#c"]);
+ assert.equal(u[1].cutStart, 3.5);
+});
+
+test("manifestFilesOf: the draft, a version's base, a legacy rendered take; a patch-only take adds nothing", async () => {
+ const { root, reports } = await fixture();
+ try {
+ const dir = await project(reports, "f/p", manifest([]), { v1: { base: manifest([]) }, a2: { rendered: manifest([]) }, b3: {} });
+ const files = await manifestFilesOf(dir);
+ assert.deepEqual(files.map((f) => `${f.version}:${f.kind}:${path.basename(f.file)}`), ["draft:draft:video.manifest.json", "a2:rendered:video.manifest.json", "v1:version:base.manifest.json"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("two projects, a version, one row per project clip with its versions", async () => {
+ const { root, reports, channels } = await fixture();
+ try {
+ await project(reports, "f/a", manifest([clip("a1", "vid", 10, 20), clip("a2", "vid", 100, 110, { cutStart: 102, cutEnd: 108 })]), {
+ v1: { base: manifest([clip("a1", "vid", 11, 19)]) },
+ });
+ await project(reports, "f/b", manifest([clip("b1", "vid", 15, 25)]));
+ const { index, stats } = await buildUsageIndex({ reportsRoot: reports, channelsDir: channels });
+ assert.equal(stats.projects, 2);
+ assert.equal(stats.manifests, 3);
+ const rows = usesOf(index, "chan", "vid");
+ assert.deepEqual(rows.map((r) => `${r.project}#${r.clipId}`), ["f/a#a1", "f/a#a2", "f/b#b1"]);
+ const a1 = rows[0];
+ assert.equal(a1.inDraft, true);
+ assert.equal(a1.start, 10);
+ assert.deepEqual(a1.versions.map((v) => `${v.id}:${v.kind}:${v.start}`), ["v1:version:11"]);
+ // A window 100-130 serves a2 only; 0-30 serves a1 and b1.
+ assert.deepEqual(rowsInWindow(rows, { from: 100, to: 130 }).map((r) => r.clipId), ["a2"]);
+ assert.deepEqual(rowsInWindow(rows, { from: 0, to: 30 }).map((r) => r.clipId), ["a1", "b1"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("incremental: an unchanged manifest is reused, a changed one parsed again, a deleted project drops out", async () => {
+ const { root, reports, channels } = await fixture();
+ const file = path.join(root, "state", "usage-index.json");
+ try {
+ const a = await project(reports, "f/a", manifest([clip("a1", "vid", 10, 20)]));
+ await project(reports, "f/b", manifest([clip("b1", "vid", 15, 25)]));
+ const first = await loadUsageIndex({ reportsRoot: reports, channelsDir: channels, file });
+ assert.equal(first.stats.parsed, 2);
+ assert.equal(first.written, true);
+
+ const again = await loadUsageIndex({ reportsRoot: reports, channelsDir: channels, file });
+ assert.deepEqual([again.stats.parsed, again.stats.reused, again.written], [0, 2, false]);
+
+ // f/a's draft changes (a new mtime): only it is read again.
+ await writeFile(path.join(a, "video.manifest.json"), JSON.stringify(manifest([clip("a1", "vid", 10, 20), clip("a9", "vid", 50, 55)])));
+ const later = new Date(Date.now() + 5000);
+ await utimes(path.join(a, "video.manifest.json"), later, later);
+ const changed = await loadUsageIndex({ reportsRoot: reports, channelsDir: channels, file });
+ assert.deepEqual([changed.stats.parsed, changed.stats.reused], [1, 1]);
+ assert.deepEqual(usesOf(changed.index, "chan", "vid").map((r) => r.clipId), ["a1", "a9", "b1"]);
+
+ // f/b is deleted: its rows go with it.
+ await rm(path.join(reports, "f", "b"), { recursive: true, force: true });
+ const gone = await loadUsageIndex({ reportsRoot: reports, channelsDir: channels, file });
+ assert.equal(gone.stats.dropped, 1);
+ assert.deepEqual(usesOf(gone.index, "chan", "vid").map((r) => `${r.project}#${r.clipId}`), ["f/a#a1", "f/a#a9"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("Rumble: a clip citing the embed id and one citing the folder slug are ONE ingredient, keyed by the folder", async () => {
+ const { root, reports, channels } = await fixture();
+ try {
+ await project(reports, "f/emb", manifest([clip("e1", "v7emb01", 10, 20)], "rumch"));
+ await project(reports, "f/slug", manifest([clip("s1", "v7slug1", 30, 40, { siteVideo: "v7emb01" })], "rumch"));
+ const { index } = await buildUsageIndex({ reportsRoot: reports, channelsDir: channels });
+ assert.deepEqual(Object.keys(index.byIngredient), ["rumch/v7slug1"]);
+ const rows = usesOf(index, "rumch", "v7slug1");
+ assert.deepEqual(rows.map((r) => `${r.project}#${r.clipId}`), ["f/emb#e1", "f/slug#s1"]);
+ assert.deepEqual(rows[0].cites, ["v7emb01"]);
+ assert.deepEqual(rows[1].cites, ["v7slug1", "v7emb01"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("write: false never writes the cache", async () => {
+ const { root, reports, channels } = await fixture();
+ const file = path.join(root, "state", "usage-index.json");
+ try {
+ await project(reports, "f/a", manifest([clip("a1", "vid", 10, 20)]));
+ const r = await loadUsageIndex({ reportsRoot: reports, channelsDir: channels, file, write: false });
+ assert.equal(r.written, false);
+ assert.equal(usesOf(r.index, "chan", "vid").length, 1);
+ const { readUsageIndex } = await import("./usedIn.mjs");
+ assert.equal(await readUsageIndex(file), null);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/benchData.ts b/umtool/lib/report/benchData.ts
@@ -1,5 +1,5 @@
import { notFound } from "next/navigation";
-import { projectsHref, clipBenchHref, playHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs";
+import { projectsHref, clipBenchHref, ingredientHref, playHref, takeClipHref, takeWalkHref, takesHref } from "@/lib/hrefs";
import type { ClipBenchData } from "@/components/projects/ClipBench";
import type { BenchKey, BenchLink } from "@/components/projects/bench/BenchShell";
import {
@@ -41,6 +41,8 @@ export type BenchTopSpec = {
next: BenchLink | null;
keys: BenchKey[];
note: string;
+ /** The clip's source, across its life cycle (lane L5). */
+ life?: BenchLink | null;
};
/**
@@ -296,6 +298,8 @@ export async function clipBenchData(
],
// Which source is playing.
note: `${entry.video}${entry.channel ? ` · ${entry.channel}` : ""}`,
+ // Its source's life cycle: found, downloaded, … published (lane L5).
+ life: entry.channel && entry.video ? { href: ingredientHref(String(entry.channel), String(entry.video)), label: "Life cycle" } : null,
};
return { data, top };
}
diff --git a/umtool/lib/report/candidatesCli.mjs b/umtool/lib/report/candidatesCli.mjs
@@ -86,12 +86,14 @@ export async function candidatesCommand(args, { root = REPORTS_ROOT, out = (s) =
if (verb === "add") {
if (!arg) throw new CliError("add needs a JSON proposal (or @file)");
- const raw = arg.startsWith("@") ? await readFile(path.resolve(arg.slice(1)), "utf8") : arg;
+ const fromFile = arg.startsWith("@");
+ const raw = fromFile ? await readFile(path.resolve(arg.slice(1)), "utf8") : arg;
let v;
try {
v = JSON.parse(raw);
} catch (e) {
- throw new CliError(`add: not JSON (${e instanceof Error ? e.message : e})`);
+ // A file's words are never quoted back (JSON.parse's message carries its head): its name only.
+ throw new CliError(fromFile ? `add: ${path.basename(arg.slice(1))} is not JSON` : `add: not JSON (${e instanceof Error ? e.message : e})`);
}
const list = (Array.isArray(v) ? v : Array.isArray(v?.candidates) ? v.candidates : [v]).map((p) => normalizeProposal(p));
const res = await addCandidates(project.dir, list, { by });
diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs
@@ -469,3 +469,6 @@ export async function followRun(cfg, projectDir, run) {
}
return states;
}
+
+/** One request to the editor's ops (`ask` above): the ingredient rail's other editor actions (lib/ingredients/actions.mjs). */
+export { ask as askEditorOps };
diff --git a/umtool/lib/report/inspectorCli.mjs b/umtool/lib/report/inspectorCli.mjs
@@ -113,12 +113,13 @@ export async function provenanceCommand(args, { root = REPORTS_ROOT, out = (s) =
return 0;
}
if (verb !== "set") throw new CliError(`unknown: provenance ${verb} — ls or set`);
- const keys = { "site-origin": "siteOrigin", "channel-slug": "channelSlug", channel: "channel" };
+ /** @type {Record<string, string>} */
+ const keys = { "--site-origin": "siteOrigin", "--channel-slug": "channelSlug", "--channel": "channel" };
const patch = {};
for (const [f, v] of flags) {
if (f === "json") continue;
- if (!(f in keys)) throw new CliError(`unknown flag --${f} (--site-origin, --channel-slug, --channel)`);
- patch[keys[/** @type {keyof typeof keys} */ (f)]] = v === true ? "" : v;
+ if (!(`--${f}` in keys)) throw new CliError(`unknown flag --${f} (--site-origin, --channel-slug, --channel)`);
+ patch[keys[`--${f}`]] = v === true ? "" : v;
}
if (!Object.keys(patch).length) throw new CliError("set needs --site-origin, --channel-slug or --channel");
const { result } = await write(project, (token) => updateProvenance(project.dir, patch, { token }));
@@ -149,7 +150,8 @@ export async function titleCommand(args, { root = REPORTS_ROOT, out = (s) => con
const project = await projectOf(projectArg, root);
const patch = {};
if (rest.length) patch.title = rest.join(" ");
- if (flags.has("subtitle")) patch.subtitle = String(flags.get("subtitle"));
+ const SUBTITLE = "--subtitle";
+ if (flags.has(SUBTITLE.slice(2))) patch.subtitle = String(flags.get(SUBTITLE.slice(2)));
if (flags.has("no-subtitle")) patch.subtitle = null;
if (!Object.keys(patch).length) {
const m = await readManifest(project.dir);
@@ -217,6 +219,9 @@ async function jsonArg(v) {
}
}
+/** The flags teaser-insert reads besides --line / --break / --hold (lib/cli/verbs.mjs's form names them). */
+const TEASER_INSERT_FLAGS = ["--json", "--at", "--after", "--before", "--id", "--beat", "--lines-json"];
+
/** `umtool timeline <p> teaser-insert …` (timelineCli.mjs hands it the words after the verb). */
export async function teaserInsertVerb(project, args, { out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
try {
@@ -235,7 +240,7 @@ export async function teaserInsertVerb(project, args, { out = (s) => console.log
const last = lines.at(-1);
if (!last || typeof last === "string") throw new CliError(`--${k} goes after the --line it belongs to`);
last[k] = k === "hold" ? Number(v) : String(v);
- } else if (!["json", "at", "after", "before", "id", "beat", "lines-json"].includes(k)) throw new CliError(`unknown flag --${k}`);
+ } else if (!TEASER_INSERT_FLAGS.includes(`--${k}`)) throw new CliError(`unknown flag --${k}`);
}
if (flags.has("lines-json")) {
if (lines.length) throw new CliError("--lines-json or --line, not both");
diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs
@@ -208,6 +208,8 @@ export async function playViewWith(project, { take = null, bare = false, postFor
dateLabel: dateKey === null ? null : /^\d{1,2}\s+[A-Za-z]{3}/.test(onscreenDate) ? onscreenDate : dateKeyLabel(dateKey),
section: e.section ?? null,
channel: typeof e.channel === "string" ? e.channel : null,
+ // The channel the clip cuts from, the provenance's when the clip names none: its life cycle's address (lane L5).
+ sourceChannel: typeof e.channel === "string" && e.channel ? e.channel : typeof selected.provenance?.channelSlug === "string" ? selected.provenance.channelSlug : null,
heading: text(e.onscreen?.title) || text(e.title) || text(e.quote) || e.id,
date: text(e.date) || text(e.onscreen?.title) || null,
quote: text(e.quote) || null,
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -910,10 +910,12 @@ const REF_KEYS = ["id", "author", "handle", "badge", "date", "text", "url", "med
/** A context post given on the command line: JSON, or `@<file>.json`. Its `media` may name project files. */
const refArg = (raw, k) => {
let j;
+ const file = raw.trim().startsWith("@") ? raw.trim().slice(1) : null;
try {
- j = JSON.parse(raw.trim().startsWith("@") ? readFileSyncText(raw.trim().slice(1)) : raw);
+ j = JSON.parse(file ? readFileSyncText(file) : raw);
} catch (e) {
- throw new CliError(`${k}= takes a post as JSON ({"id","handle","author","date","text"}) or @<file>.json -- ${e.message}`);
+ // A file's words are never quoted back (JSON.parse's message carries its head): its name only.
+ throw new CliError(`${k}= takes a post as JSON ({"id","handle","author","date","text"}) or @<file>.json -- ${file ? `${path.basename(file)} is not JSON` : e.message}`);
}
if (!j || typeof j !== "object" || Array.isArray(j)) throw new CliError(`${k}= takes a post as a JSON object`);
const bad = Object.keys(j).filter((x) => !REF_KEYS.includes(x));
diff --git a/umtool/lib/report/sameOrigin.mjs b/umtool/lib/report/sameOrigin.mjs
@@ -6,11 +6,44 @@
//
// Plain ESM so `node --test` reads it.
+// DNS REBINDING (lane palette review): a page on evil.example whose name is re-pointed at 127.0.0.1 is
+// "same-origin" with itself and sends `Host: evil.example:3050`. So the host the request names -- Host, and
+// X-Forwarded-Host when a proxy (or the page) sets one -- and the Origin's host must each be THIS machine
+// (localhost, *.localhost, 127.x, ::1) or a name listed in UMTOOL_ALLOWED_HOSTS (comma-separated host names,
+// no ports: the names a proxy in front of umtool serves it as; docs/knobs.md, "⌘K commands").
+
+const LOOPBACK = new Set(["localhost", "127.0.0.1", "::1", "::ffff:127.0.0.1"]);
+
+/** A Host-header value's name, without its port or brackets, lower case. */
+export function hostNameOf(value) {
+ const v = String(value ?? "").trim().toLowerCase();
+ if (v.startsWith("[")) return v.slice(1, v.indexOf("]") > 0 ? v.indexOf("]") : undefined);
+ return v.split(":")[0];
+}
+
+/** Whether a host name is this machine, or one the operator lists. */
+export function hostAllowed(name, env = process.env) {
+ const h = hostNameOf(name);
+ if (!h) return false;
+ if (LOOPBACK.has(h) || h.endsWith(".localhost") || /^127(\.\d{1,3}){3}$/.test(h)) return true;
+ const listed = String(env.UMTOOL_ALLOWED_HOSTS ?? "").split(",").map((x) => hostNameOf(x)).filter(Boolean);
+ return listed.includes(h);
+}
+
+const notHere = (h) => `refused: a request to ${hostNameOf(h)} -- umtool answers as localhost, or a name in UMTOOL_ALLOWED_HOSTS`;
+
/**
- * The sentence to refuse with, or null for a same-origin (or non-browser) request.
+ * The sentence to refuse with, or null for a same-origin (or non-browser) request to a host that is
+ * this machine (or listed).
* @param {{ get(name: string): string | null }} headers
+ * @param {Record<string, string | undefined>} [env]
*/
-export function crossSiteRefusal(headers) {
+export function crossSiteRefusal(headers, env = process.env) {
+ for (const k of ["host", "x-forwarded-host"]) {
+ for (const h of String(headers.get(k) ?? "").split(",").map((x) => x.trim()).filter(Boolean)) {
+ if (!hostAllowed(h, env)) return notHere(h);
+ }
+ }
const site = (headers.get("sec-fetch-site") ?? "").trim().toLowerCase();
if (site && site !== "same-origin" && site !== "none") return `refused: a ${site} request may not write here`;
const origin = (headers.get("origin") ?? "").trim();
@@ -23,5 +56,6 @@ export function crossSiteRefusal(headers) {
} catch {
return "refused: the request's origin does not parse";
}
- return host && from !== host ? `refused: a request from ${from} may not write to ${host}` : null;
+ if (host && from !== host) return `refused: a request from ${from} may not write to ${host}`;
+ return hostAllowed(from, env) ? null : notHere(from);
}
diff --git a/umtool/lib/report/sameOrigin.test.mjs b/umtool/lib/report/sameOrigin.test.mjs
@@ -13,5 +13,17 @@ test("crossSiteRefusal: same-origin and non-browser requests pass; another site,
assert.match(String(crossSiteRefusal(h({ "sec-fetch-site": "same-site", origin: "http://localhost:3001", host: "localhost:3050" }))), /same-site/);
assert.match(String(crossSiteRefusal(h({ origin: "https://evil.example", host: "localhost:3050" }))), /evil\.example/);
assert.match(String(crossSiteRefusal(h({ origin: "null", host: "localhost:3050" }))), /opaque/);
- assert.equal(crossSiteRefusal(h({ origin: "https://umtool.lan", host: "127.0.0.1:3050", "x-forwarded-host": "umtool.lan" })), null, "behind the proxy");
+ assert.equal(crossSiteRefusal(h({ origin: "https://umtool.lan", host: "127.0.0.1:3050", "x-forwarded-host": "umtool.lan" }), { UMTOOL_ALLOWED_HOSTS: "umtool.lan" }), null, "behind the proxy, its name listed");
+});
+
+test("crossSiteRefusal: DNS rebinding -- a host that is not this machine, or listed, is refused, Origin or not", () => {
+ const env = {};
+ assert.match(String(crossSiteRefusal(h({ host: "evil.example:3050", origin: "http://evil.example:3050", "sec-fetch-site": "same-origin" }), env)), /evil\.example/);
+ assert.match(String(crossSiteRefusal(h({ host: "evil.example:3050" }), env)), /evil\.example/, "no Origin: the Host alone");
+ assert.match(String(crossSiteRefusal(h({ host: "localhost:3050", "x-forwarded-host": "evil.example:3050", origin: "http://evil.example:3050" }), env)), /evil\.example/, "a forwarded host is checked too");
+ assert.match(String(crossSiteRefusal(h({ origin: "https://umtool.lan", host: "127.0.0.1:3050", "x-forwarded-host": "umtool.lan" }), env)), /umtool\.lan/, "a proxy's name, unlisted");
+ for (const host of ["localhost:3050", "127.0.0.1:3050", "[::1]:3050", "umtool.localhost:3050"]) {
+ assert.equal(crossSiteRefusal(h({ host, origin: `http://${host}`, "sec-fetch-site": "same-origin" }), env), null, host);
+ }
+ assert.equal(crossSiteRefusal(h({ host: "box.lan:3050", origin: "http://box.lan:3050" }), { UMTOOL_ALLOWED_HOSTS: "other, BOX.lan" }), null, "listed, any case, ports aside");
});
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -241,11 +241,13 @@ async function handPostItem(project, manifest, raw, { id = null } = {}) {
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;
+ const fromFile = raw.startsWith("@");
+ const text = fromFile ? 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})`);
+ // A file's words are never quoted back (JSON.parse's message carries its head): its name only.
+ throw new CliError(fromFile ? `${what}: ${path.basename(raw.slice(1))} is not JSON` : `${what}: not JSON (${e instanceof Error ? e.message : e})`);
}
}
@@ -784,20 +786,31 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
case "order": {
if (!rest.length) throw new CliError("order needs the ids in their new order, or a file of them (@file)");
let text = rest.join(" ");
+ let fromFile = null;
if (rest.length === 1) {
const f = rest[0].startsWith("@") ? rest[0].slice(1) : rest[0];
const file = path.resolve(f);
const read = await readFile(file, "utf8").catch(() => null);
- if (read !== null) text = read;
+ if (read !== null) {
+ text = read;
+ fromFile = path.basename(file);
+ }
else if (rest[0].startsWith("@")) throw new CliError(`cannot read ${file}`);
}
let ids;
try {
ids = parseOrderText(text);
} catch (e) {
- throw new CliError(`order: ${e instanceof Error ? e.message : e}`);
+ // A file's words are never quoted back: its name only.
+ throw new CliError(fromFile ? `order: ${fromFile} is not an order (ids, a JSON list, {order} or a claim-groups file)` : `order: ${e instanceof Error ? e.message : e}`);
+ }
+ try {
+ ({ result, editNotes } = await write((token) => orderEntries(project.dir, ids, { token })));
+ } catch (e) {
+ // From a file, what it held is not echoed (it could be any file): its name and its count.
+ if (!fromFile) throw e;
+ throw new CliError(`order: ${fromFile} (${ids.length} id${ids.length === 1 ? "" : "s"}) is not an order of this cut's entries`);
}
- ({ result, editNotes } = await write((token) => orderEntries(project.dir, ids, { token })));
break;
}
case "groups": {
diff --git a/umtool/lib/report/timelineCli.test.mjs b/umtool/lib/report/timelineCli.test.mjs
@@ -213,3 +213,17 @@ test("teaser, post and post-remove (JSON or @file); a generated manifest gets it
const notes = JSON.parse(await readFile(path.join(dir, "notes.json"), "utf8"));
assert.ok(notes.notes.length > 0);
});
+
+test("a file read with @ that is not JSON (or an order file that is not an order) is named, never quoted (L8a review)", async () => {
+ await project("leak");
+ const secret = path.join(ROOT, "secret.txt");
+ await writeFile(secret, "root:x:0:0:THE-SECRET-HEAD\n");
+ for (const args of [["leak", "post", `@${secret}`], ["leak", "teaser", "t1", `@${secret}`], ["leak", "insert", "--after", "-", `post-json:@${secret}`], ["leak", "order", `@${secret}`], ["leak", "order", secret]]) {
+ const { lines, run } = runner();
+ const code = await run(...args);
+ assert.notEqual(code, 0, args.join(" "));
+ const said = lines.join("\n");
+ assert.ok(!said.includes("THE-SECRET") && !said.includes("root:x"), `${args.join(" ")} quoted the file: ${said}`);
+ assert.match(said, /secret\.txt/, args.join(" "));
+ }
+});