commit d357ae7f9732035881108bcc406345246f577bd6
parent d633dc58d74c9de5aee0f7f1ed79b1818ed70a28
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 2 Nov 2026 03:50:13 -0500
Merge main (c145be79: U3 ui-editing, U5 ui-ops) into lane/ui-intake
OverviewTab.tsx: both kept -- the right column under "This video" reads the source backlog
line (U4, item 16), then U5's sites and deploys panel and the link policy panel.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
94 files changed, 7832 insertions(+), 161 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -128,7 +128,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` |
| `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` |
| `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` |
-| `sync` | 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 channel's platform queue, paced like its downloads. | `pnpm ops sync --json '{"slug":"the-quartering"}' --wait` |
+| `sync` | 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 channel's platform queue, paced like its downloads. A social channel's sync is its post fetch (fetch-posts' new posts, its guards and refusals: for X a fresh cookie jar), never the video listing; "full" is refused there (fetch-posts "full": true re-walks the timeline). | `pnpm ops sync --json '{"slug":"the-quartering"}' --wait` |
| `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. "storedUrl": "fallback" \| "only" reads each video from the media URL its record stores when the page is rate-limited (or always), one file per 20 min; with one, a held platform's run goes ahead as "only". | |
| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. A record that stores an Odysee media URL is read from that URL (as "only") until 2 such downloads are on record, then from the page. "storedUrl": "fallback" \| "only" reads each from the media URL its record stores, as on download-missing (a held platform's retry runs as "only"). "corruptHeldAudio" (held audio the audio audit found damaged) is refetched the same way, with the audio check on; the new file is audited again. | `pnpm ops retry-bucket --json '{"slug":"demo-odysee","bucket":"corruptHeldAudio"}' --wait` |
| `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | |
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -263,6 +263,7 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one
| `E2E_FIXTURE_MAX_LIFETIME_MS` | the watchdog's | How long a fake binary may live before its watchdog kills it. | editor/e2e/fixtures/bin/_watchdog.mjs |
| `E2E_OLLAMA_STUB_MODEL` | `qwen2.5:7b` | The model the ollama stub claims to serve. | editor/e2e/fixtures/ollama-stub.mjs |
| `E2E_RACK_SHOTS` | off (spec skipped) | Runs the `/channels` rack screenshot audit. | editor/e2e/channels-rack-audit.spec.ts |
+| `E2E_UI_OPS_SHOTS` | off (no screenshots) | A directory: the social Sync tests (UI notes #17) write their screenshots there, for a review. | editor/e2e/social-channel.spec.ts |
| `E2E_TWO_ORIGIN_REBUILD` | off | `1` rebuilds the two-origin suite's cached hub bundle. | export/e2e-2origin/globalSetup.ts |
| `E2E_REPORT_SITE_REUSE` | off (build again) | `1` serves the cited report-site suite's existing stage build (`.e2e-report-site/out`) instead of staging and building the fixture site again — for iterating on the specs alone; it does not see a change to the app. | export/playwright.report.config.ts |
| `E2E_SHARDS` | min(max(2, cpus/2), 8) | How many containers `pnpm e2e:sharded` splits the editor suite across (`--shards N` wins). | scripts/run-sharded-e2e.mjs |
diff --git a/WORKTREES.md b/WORKTREES.md
@@ -267,8 +267,11 @@ The pieces sit in the git common dir: `heavy-queue.lock` (the slot — held SHAR
admitted weighted job, EXCLUSIVELY by a job that runs alone, so an older checkout's copy of
the gate, which always takes it exclusively, still waits for every new-style job and is
never joined by one), `heavy-queue.lock.admit` (the line), `heavy-queue.lock.build` (the
-build slot) and `heavy-queue.lock.jobs/<pid>.json` (one ticket per running job — its
-estimate and what it is; a ticket whose process is gone is dropped). The kernel releases
+build slot), `heavy-queue.lock.jobs/<pid>.json` (one ticket per running job — its
+estimate and what it is; a ticket whose process is gone is dropped) and
+`heavy-queue.lock.waiting/<pid>.json` (one per job waiting for the slot, with where it waits:
+`render`, `line`, `slot`, `memory`, `build`, `exclusive`; dropped once it is admitted). umtool's
+take panel reads them all as its **Render queue** (`common/lib/heavyQueue.mjs`). The kernel releases
every lock when its holder's fd closes. A machine whose MemTotal is under the floor is told
so and runs one job at a time; with no usable `flock` the gate warns and runs on the floor
alone — it is a safety net, not a correctness lock.
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -260,6 +260,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "E2E_FIXTURE_MAX_LIFETIME_MS", audience: "test", default: "the watchdog's", readBy: "editor/e2e/fixtures/bin/_watchdog.mjs", doc: "How long a fake binary may live before its watchdog kills it." },
{ name: "E2E_OLLAMA_STUB_MODEL", audience: "test", default: "`qwen2.5:7b`", readBy: "editor/e2e/fixtures/ollama-stub.mjs", doc: "The model the ollama stub claims to serve." },
{ name: "E2E_RACK_SHOTS", audience: "test", default: "off (spec skipped)", readBy: "editor/e2e/channels-rack-audit.spec.ts", doc: "Runs the `/channels` rack screenshot audit." },
+ { name: "E2E_UI_OPS_SHOTS", audience: "test", default: "off (no screenshots)", readBy: "editor/e2e/social-channel.spec.ts", doc: "A directory: the social Sync tests (UI notes #17) write their screenshots there, for a review." },
{ name: "E2E_TWO_ORIGIN_REBUILD", audience: "test", default: "off", readBy: "export/e2e-2origin/globalSetup.ts", doc: "`1` rebuilds the two-origin suite's cached hub bundle." },
{ name: "E2E_REPORT_SITE_REUSE", audience: "test", default: "off (build again)", readBy: "export/playwright.report.config.ts", doc: "`1` serves the cited report-site suite's existing stage build (`.e2e-report-site/out`) instead of staging and building the fixture site again — for iterating on the specs alone; it does not see a change to the app." },
{ name: "E2E_SHARDS", audience: "test", default: "min(max(2, cpus/2), 8)", readBy: "scripts/run-sharded-e2e.mjs", doc: "How many containers `pnpm e2e:sharded` splits the editor suite across (`--shards N` wins)." },
diff --git a/common/lib/heavyQueue.mjs b/common/lib/heavyQueue.mjs
@@ -0,0 +1,178 @@
+// THE HEAVY SLOT, AS IT STANDS (UI notes 2026-10-30, #18: the render queue
+// panel). Read from the slot's own files beside its lock (scripts/queue-lock.mjs,
+// WORKTREES.md "The heavy slot") -- nothing here is guessed:
+//
+// heavy-queue.lock.jobs/<pid>.json one ticket per job RUNNING in the slot:
+// its estimate, whether it builds or runs
+// alone, its command, since when
+// heavy-queue.lock.waiting/<pid>.json one ticket per job WAITING: the same,
+// and its stage (render, line, slot,
+// memory, build, exclusive, serial)
+// heavy-queue.lock.admit.holder.json the job at the head of the line
+// heavy-queue.lock.build.holder.json the build slot's holder (one next build at a time)
+// heavy-queue.lock.render.json render mode (renderPriority.mjs)
+// <name>-queue.lock.holder.json each e2e suite's own queue
+//
+// A ticket whose process is gone (or whose pid was reused) is not counted;
+// this module never removes one -- queue-lock does that. Plain ESM: umtool's
+// route and the CLI read it under bare node.
+import fs from "node:fs";
+import path from "node:path";
+import { describeRenderPriority, holderAlive, readRenderPriority, renderPriorityFile } from "./renderPriority.mjs";
+
+/** What a waiting job waits for, in words. */
+export const STAGE_WORDS = Object.freeze({
+ door: "arriving",
+ render: "waiting for the render (render mode)",
+ line: "in line behind the job at the head",
+ slot: "at the head of the line, for the slot",
+ memory: "at the head of the line, for memory",
+ build: "for the build slot (one next build at a time)",
+ exclusive: "for a job that runs alone",
+ serial: "one job at a time (this machine is under the floor)",
+});
+
+/** A ticket's process is alive and is the one that wrote it. */
+const alive = (t, isAlive) => Number.isInteger(t?.pid) && isAlive({ pid: t.pid, pidStart: t.pidStart ?? null });
+
+function readDir(dir, isAlive) {
+ let names = [];
+ try {
+ names = fs.readdirSync(/* turbopackIgnore: true */ dir).filter((n) => n.endsWith(".json"));
+ } catch {
+ return [];
+ }
+ const out = [];
+ for (const n of names) {
+ try {
+ const t = JSON.parse(fs.readFileSync(/* turbopackIgnore: true */ path.join(dir, n), "utf8"));
+ if (alive(t, isAlive)) out.push(t);
+ } catch {
+ /* half-written by queue-lock: skipped this time */
+ }
+ }
+ return out;
+}
+
+function readHolder(file, isAlive) {
+ try {
+ const h = JSON.parse(fs.readFileSync(/* turbopackIgnore: true */ file, "utf8"));
+ return alive(h, isAlive) ? h : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * What a command is: a render (build-video.mjs; its project directory and take
+ * read from the manifest path it is given), an e2e suite, a next build, the
+ * encode ladder, or the command itself.
+ * @param {string} cmd
+ * @returns {{ kind: "render" | "e2e" | "build" | "ladder" | "other", label: string, projectDir?: string | null, take?: string | null }}
+ */
+export function classifyCommand(cmd) {
+ const c = String(cmd ?? "");
+ if (/build-video\.mjs/.test(c)) {
+ // A take's render: `build-video.mjs <project>/.take-<id>.render.json --out <project>/takes/<id>/out`
+ // (umtool/lib/report/takeRender.mjs); a project build: `build-video.mjs <project>/video.manifest.json`.
+ const after = c.slice(c.indexOf("build-video.mjs") + "build-video.mjs".length).trim();
+ const man = after.split(/\s+/)[0] ?? "";
+ const take = /(?:^|\/)\.take-([a-z0-9][a-z0-9-]*)\.render\.json$/.exec(man)?.[1] ?? /\/takes\/([a-z0-9][a-z0-9-]*)\/out(?:\s|$)/.exec(after)?.[1] ?? null;
+ const projectDir = man.includes("/") ? man.slice(0, man.lastIndexOf("/")) : null;
+ const name = projectDir ? projectDir.split("/").slice(-2).join("/") : null;
+ return { kind: "render", label: take ? `render of ${take}${name ? ` (${name})` : ""}` : `render${name ? ` of ${name}` : ""}`, projectDir, take };
+ }
+ if (/variants|ladder/.test(c) && /umtool/.test(c)) return { kind: "ladder", label: "the encode ladder (variants)" };
+ if (/playwright|run-sharded-e2e|\be2e\b/.test(c)) {
+ const suite = /--name (e2e-[a-z0-9-]+)/.exec(c)?.[1] ?? /--filter ([a-z0-9-]+)/.exec(c)?.[1] ?? null;
+ return { kind: "e2e", label: suite ? `e2e suite ${suite}` : "an e2e suite" };
+ }
+ if (/next build/.test(c)) {
+ const pkg = /--filter ([a-z0-9-]+)/.exec(c)?.[1] ?? null;
+ return { kind: "build", label: pkg ? `next build (${pkg})` : "a next build" };
+ }
+ return { kind: "other", label: c.length > 90 ? `${c.slice(0, 90)}…` : c };
+}
+
+const shape = (t, now) => {
+ const what = classifyCommand(t.cmd);
+ const started = Date.parse(t.since ?? t.startedAt ?? "");
+ return {
+ pid: t.pid,
+ what: what.label,
+ kind: what.kind,
+ ...(what.projectDir ? { projectDir: what.projectDir } : {}),
+ ...(what.take ? { take: what.take } : {}),
+ estimateMb: Number.isFinite(t.estimateMb) ? t.estimateMb : null,
+ build: Boolean(t.build),
+ alone: Boolean(t.exclusive),
+ worktree: t.worktree ? path.basename(String(t.worktree)) : null,
+ branch: t.branch ?? null,
+ cmd: String(t.cmd ?? ""),
+ since: Number.isFinite(started) ? new Date(started).toISOString() : null,
+ forSeconds: Number.isFinite(started) ? Math.max(0, Math.round((now - started) / 1000)) : null,
+ };
+};
+
+/**
+ * The slot now.
+ * @param {{ heavyLock: string, renderFile?: string, env?: Record<string, string | undefined>, now?: number, isAlive?: (h: { pid: number, pidStart: string | null }) => boolean, meminfo?: string }} o
+ */
+export function readHeavyQueue({ heavyLock, renderFile, env = process.env, now = Date.now(), isAlive = holderAlive, meminfo = "/proc/meminfo" }) {
+ const running = readDir(`${heavyLock}.jobs`, isAlive).map((t) => shape(t, now)).sort((a, b) => String(a.since).localeCompare(String(b.since)));
+ const waiting = readDir(`${heavyLock}.waiting`, isAlive)
+ .map((t) => ({
+ ...shape(t, now),
+ stage: String(t.stage ?? "door"),
+ stageWords: STAGE_WORDS[/** @type {keyof typeof STAGE_WORDS} */ (t.stage)] ?? String(t.stage ?? ""),
+ }))
+ // The head of the line first, then by arrival.
+ .sort((a, b) => Number(b.stage !== "line" && b.stage !== "render" && b.stage !== "door") - Number(a.stage !== "line" && a.stage !== "render" && a.stage !== "door") || String(a.since).localeCompare(String(b.since)));
+ const head = readHolder(`${heavyLock}.admit.holder.json`, isAlive);
+ const build = readHolder(`${heavyLock}.build.holder.json`, isAlive);
+ // An older copy of queue-lock writes no ticket, only the slot's holder file.
+ const holder = running.length ? null : readHolder(`${heavyLock}.holder.json`, isAlive);
+ const dir = path.dirname(heavyLock);
+ const suites = [];
+ try {
+ for (const n of fs.readdirSync(/* turbopackIgnore: true */ dir)) {
+ const m = /^(e2e(?:-[a-z0-9-]+)?)-queue\.lock\.holder\.json$/.exec(n);
+ if (!m) continue;
+ const h = readHolder(path.join(dir, n), isAlive);
+ if (h) suites.push({ suite: m[1], ...shape(h, now) });
+ }
+ } catch {
+ /* no lock dir yet */
+ }
+ // An e2e suite's slot ticket names only its command ("playwright test"): its
+ // name is the suite queue its process holds.
+ for (const r of [...running, ...waiting]) {
+ if (r.kind !== "e2e") continue;
+ const names = suites.filter((x) => x.pid === r.pid).map((x) => x.suite);
+ if (names.length) r.what = `e2e suite ${names[0]}${names.length > 1 ? ` (and ${names.slice(1).join(", ")})` : ""}`;
+ }
+ const rp = readRenderPriority(renderFile ?? renderPriorityFile(env, { heavyLock }));
+ let mem = null;
+ try {
+ const text = fs.readFileSync(/* turbopackIgnore: true */ meminfo, "utf8");
+ const kb = (k) => Number(new RegExp(`^${k}:\\s+(\\d+)`, "m").exec(text)?.[1] ?? NaN);
+ const a = kb("MemAvailable");
+ const t = kb("MemTotal");
+ if (Number.isFinite(a)) mem = { availableMb: Math.round(a / 1024), totalMb: Number.isFinite(t) ? Math.round(t / 1024) : null };
+ } catch {
+ mem = null;
+ }
+ const floor = Number(env.HEAVY_MIN_FREE_MB ?? 6000);
+ const promised = running.reduce((n, r) => n + (r.estimateMb ?? 0), 0);
+ return {
+ heavyLock,
+ running: holder && !running.length ? [shape(holder, now)] : running,
+ waiting,
+ head: head ? shape(head, now) : null,
+ build: build ? shape(build, now) : null,
+ suites: suites.sort((a, b) => a.suite.localeCompare(b.suite)),
+ render: rp.held && rp.state ? { held: true, what: describeRenderPriority(rp.state), since: rp.state.since ?? null, until: rp.state.until ?? null } : { held: false },
+ memory: mem ? { ...mem, floorMb: Number.isFinite(floor) ? floor : 6000, promisedMb: promised } : null,
+ heldBy: running.length ? running.map((r) => r.what).join("; ") : holder ? classifyCommand(holder.cmd).label : null,
+ };
+}
diff --git a/common/lib/heavyQueue.test.ts b/common/lib/heavyQueue.test.ts
@@ -0,0 +1,82 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { classifyCommand, readHeavyQueue } from "./heavyQueue.mjs";
+
+// The render queue panel's reader (UI notes 2026-10-30, #18): the heavy slot
+// as its own files say, never guessed. A live ticket is this process's pid; a
+// dead one a pid nothing runs as.
+
+function slot() {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "heavy-queue-"));
+ const lock = path.join(dir, "heavy-queue.lock");
+ const put = (file: string, doc: unknown) => {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, JSON.stringify(doc));
+ };
+ return { dir, lock, put, done: () => fs.rmSync(dir, { recursive: true, force: true }) };
+}
+
+const LIVE = process.pid;
+const DEAD = 2 ** 22 + 12345;
+const isAlive = (h: { pid: number }) => h.pid === LIVE || h.pid === LIVE + 1 || h.pid === LIVE + 2;
+
+test("classifyCommand: a take's render names its take and project; a suite, a build", () => {
+ assert.deepEqual(
+ classifyCommand("node /x/umtool/report-to-video/build-video.mjs /r/reports/ember/cut/.take-draft-3.render.json --out /r/reports/ember/cut/takes/draft-3/out --progress ndjson"),
+ { kind: "render", label: "render of draft-3 (ember/cut)", projectDir: "/r/reports/ember/cut", take: "draft-3" },
+ );
+ assert.equal(classifyCommand("node build-video.mjs /r/p/video.manifest.json").label, "render of r/p");
+ assert.equal(classifyCommand("playwright test a.spec.ts").kind, "e2e");
+ assert.equal(classifyCommand("systemd-run --user --scope -p MemoryMax=5G pnpm --filter export exec next build").label, "next build (export)");
+});
+
+test("readHeavyQueue: running and waiting tickets (the dead ones not), the head of the line, the suites, render mode, memory", () => {
+ const s = slot();
+ try {
+ const at = (min: number) => new Date(Date.parse("2026-11-02T10:00:00Z") + min * 60_000).toISOString();
+ s.put(`${s.lock}.jobs/${LIVE}.json`, { pid: LIVE, estimateMb: 1500, build: false, exclusive: false, worktree: "/w/lane-a", branch: "lane/a", cmd: "playwright test", startedAt: at(0) });
+ s.put(`${s.lock}.jobs/${DEAD}.json`, { pid: DEAD, estimateMb: 5000, cmd: "next build", startedAt: at(0) });
+ s.put(`${s.lock}.waiting/${LIVE + 1}.json`, { pid: LIVE + 1, estimateMb: 6020, cmd: "node build-video.mjs /r/reports/ember/cut/.take-draft-9.render.json --out /r/reports/ember/cut/takes/draft-9/out", since: at(2), stage: "memory" });
+ s.put(`${s.lock}.waiting/${LIVE + 2}.json`, { pid: LIVE + 2, estimateMb: 5120, build: true, cmd: "pnpm --filter editor exec next build", since: at(1), stage: "line" });
+ s.put(`${s.lock}.admit.holder.json`, { pid: LIVE + 1, cmd: "node build-video.mjs …", startedAt: at(2) });
+ s.put(path.join(s.dir, "e2e-umtool-queue.lock.holder.json"), { pid: LIVE, cmd: "playwright test", startedAt: at(-1) });
+ s.put(path.join(s.dir, "e2e-editor-queue.lock.holder.json"), { pid: DEAD, cmd: "playwright test", startedAt: at(-1) });
+ const mem = path.join(s.dir, "meminfo");
+ fs.writeFileSync(mem, "MemTotal: 16282624 kB\nMemAvailable: 8388608 kB\n");
+ const q = readHeavyQueue({ heavyLock: s.lock, renderFile: path.join(s.dir, "none.json"), env: {}, now: Date.parse(at(3)), isAlive, meminfo: mem });
+ assert.deepEqual(q.running.map((r) => [r.pid, r.what, r.estimateMb, r.worktree, r.forSeconds]), [[LIVE, "e2e suite e2e-umtool", 1500, "lane-a", 180]]);
+ // The head of the line first (it waits for memory), then the one behind it.
+ assert.deepEqual(q.waiting.map((w) => [w.pid, w.stage, w.what]), [
+ [LIVE + 1, "memory", "render of draft-9 (ember/cut)"],
+ [LIVE + 2, "line", "next build (editor)"],
+ ]);
+ assert.equal(q.waiting[0].stageWords, "at the head of the line, for memory");
+ assert.equal(q.waiting[0].take, "draft-9");
+ assert.equal(q.head?.pid, LIVE + 1);
+ assert.deepEqual(q.suites.map((x) => x.suite), ["e2e-umtool"]);
+ assert.deepEqual(q.render, { held: false });
+ assert.deepEqual(q.memory, { availableMb: 8192, totalMb: 15901, floorMb: 6000, promisedMb: 1500 });
+ assert.equal(q.heldBy, "e2e suite e2e-umtool");
+ // Nothing was removed: queue-lock owns the files.
+ assert.ok(fs.existsSync(`${s.lock}.jobs/${DEAD}.json`));
+ } finally {
+ s.done();
+ }
+});
+
+test("readHeavyQueue: an empty slot, and render mode holding the machine", () => {
+ const s = slot();
+ try {
+ const renderFile = path.join(s.dir, "heavy-queue.lock.render.json");
+ s.put(renderFile, { token: "t", since: "2026-11-02T10:00:00.000Z", until: "2099-01-01T00:00:00.000Z", by: "umtool take", holder: { pid: LIVE, cmd: "umtool take", project: "ember/cut", take: "draft-9" }, lanesHeld: [] });
+ const q = readHeavyQueue({ heavyLock: s.lock, renderFile, env: {}, isAlive, meminfo: path.join(s.dir, "no-meminfo") });
+ assert.deepEqual([q.running, q.waiting, q.head, q.build, q.suites, q.memory, q.heldBy], [[], [], null, null, [], null, null]);
+ assert.equal(q.render.held, true);
+ assert.match(String((q.render as { what?: string }).what), /^umtool take, since /);
+ } finally {
+ s.done();
+ }
+});
diff --git a/common/lib/montage/speakerCheck.mjs b/common/lib/montage/speakerCheck.mjs
@@ -0,0 +1,206 @@
+// THE SPEAKER CHECK (UI notes 2026-10-30, #15): which of SEVERAL named voices
+// a clip is -- "Speaker: matches Ember 0.93 / Kirsche 0.83" -- where the voice
+// match (voiceMatch.mjs, release 34) scores every clip against ONE voice, the
+// host's. Panel shows (Side Scrollers, Kirsche) were attributed this way by
+// hand in scratch projects; this is the same arithmetic as a project's own
+// file.
+//
+// The pieces are voiceMatch.mjs's, unchanged: a span decoded at 16 kHz mono on
+// the window's own clock, the voiced-frames gate (a fallback span when the
+// phrase holds too little speech), ONE embedding process for every clip and
+// every reference piece (TitaNet-small through sherpa-onnx, or the test kit's
+// fake embedder), a robust centroid per voice, the cosine to it. Each named
+// reference set ("speaker") is clips of the cut, or reference pieces of
+// recordings; a clip that is itself in a speaker's set is scored against the
+// rest of that set (leave-one-out). Deterministic for a given model and input;
+// no network; nothing rules -- the verification is still a person listening.
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+import {
+ DEFAULT_THRESHOLDS,
+ FALLBACK_SPEECH_S,
+ MIN_SPEECH_S,
+ SAMPLE_RATE,
+ VOICE_MATCH_MODEL,
+ decodeSpan,
+ embedWavs,
+ encodeWav16,
+ robustCentroid,
+ scoreAgainst,
+ voicedSamples,
+} from "./voiceMatch.mjs";
+
+export const SPEAKER_CHECK_FILE = "speaker-check.json";
+export const SPEAKER_CHECK_VERSION = 1;
+/** A best voice this far ahead of the next is a match; closer is unsure. */
+export const SPEAKER_MARGIN = 0.05;
+
+const round = (x, n = 3) => Math.round(x * 10 ** n) / 10 ** n;
+
+/**
+ * A clip's verdict from its scores (best first): `matches` (the best at or
+ * over `likely` and SPEAKER_MARGIN ahead of the next), `none` (every voice
+ * under `unlikely`: someone the reference sets do not hold), else `unsure`.
+ * @param {{ name: string, score: number }[]} scores
+ */
+export function speakerVerdict(scores, t = DEFAULT_THRESHOLDS) {
+ const [a, b] = scores;
+ if (!a) return { label: /** @type {const} */ ("unsure"), best: null, margin: null };
+ const margin = b ? round(a.score - b.score) : null;
+ if (a.score < t.unlikely) return { label: /** @type {const} */ ("none"), best: a.name, margin };
+ if (a.score >= t.likely && (margin === null || margin >= SPEAKER_MARGIN)) return { label: /** @type {const} */ ("matches"), best: a.name, margin };
+ return { label: /** @type {const} */ ("unsure"), best: a.name, margin };
+}
+
+/**
+ * Score `clips` against every named voice in `speakers`.
+ *
+ * @param {{
+ * clips: Array<{ key: string, id?: string | null, file: string | null, start: number, dur: number, fallback?: { start: number, dur: number } | null, missing?: string }>,
+ * check?: string[], the keys to score (default every clip); the rest are only reference
+ * speakers: Array<{ name: string, clipKeys?: string[], items?: Array<{ key: string, file: string, start: number, dur: number, label?: string }>, recordings?: unknown[] }>,
+ * engine: { python: string, script: string, model: string, threads?: number },
+ * scratch: string,
+ * thresholds?: { likely: number, unlikely: number },
+ * ffmpeg?: string,
+ * now?: () => Date,
+ * onProgress?: (e: { event: string, n?: number, of?: number, items?: number }) => void,
+ * }} o
+ */
+export async function runSpeakerCheck(o) {
+ const t = o.thresholds ?? DEFAULT_THRESHOLDS;
+ const emit = o.onProgress ?? (() => {});
+ const scratch = o.scratch;
+ await rm(scratch, { recursive: true, force: true });
+ await mkdir(scratch, { recursive: true });
+ const check = new Set(o.check ?? o.clips.map((c) => c.key));
+ const refClipKeys = new Set(o.speakers.flatMap((s) => s.clipKeys ?? []));
+
+ /** @type {Map<string, { seconds: number, wav: string | null, why?: string, fallback?: boolean }>} */
+ const prepared = new Map();
+ const voiced = async (file, start, dur) => voicedSamples(await decodeSpan(file, start, dur, { ffmpeg: o.ffmpeg }));
+ const prepare = async (id, file, start, dur, fallback = null) => {
+ let v;
+ let usedFallback = false;
+ try {
+ v = await voiced(file, start, dur);
+ if (fallback && v.seconds < FALLBACK_SPEECH_S) {
+ const w = await voiced(file, fallback.start, fallback.dur);
+ if (w.seconds > v.seconds) {
+ v = w;
+ usedFallback = true;
+ }
+ }
+ } catch (e) {
+ prepared.set(id, { seconds: 0, wav: null, why: `decode failed: ${e instanceof Error ? e.message : String(e)}` });
+ return;
+ }
+ if (v.seconds < MIN_SPEECH_S) {
+ prepared.set(id, { seconds: v.seconds, wav: null, why: "too little speech", fallback: usedFallback });
+ return;
+ }
+ const wav = path.join(scratch, `${prepared.size.toString().padStart(4, "0")}.wav`);
+ await writeFile(wav, encodeWav16(v.samples));
+ prepared.set(id, { seconds: v.seconds, wav, fallback: usedFallback });
+ };
+ const wanted = o.clips.filter((c) => check.has(c.key) || refClipKeys.has(c.key));
+ let k = 0;
+ for (const c of wanted) {
+ k += 1;
+ if (c.file) await prepare(`clip:${c.key}`, c.file, c.start, c.dur, c.fallback ?? null);
+ emit({ event: "decode", n: k, of: wanted.length });
+ }
+ for (const s of o.speakers) for (const r of s.items ?? []) await prepare(`ref:${s.name}:${r.key}`, r.file, r.start, r.dur);
+
+ const batch = [...prepared].filter(([, p]) => p.wav).map(([id, p]) => ({ id, wav: /** @type {string} */ (p.wav) }));
+ emit({ event: "embed", items: batch.length });
+ const emb = batch.length ? await embedWavs(batch, o.engine, scratch) : { model: path.basename(o.engine.model), version: null, dim: 0, items: new Map() };
+ const vec = (id) => emb.items.get(id)?.embedding ?? null;
+
+ // Each voice: its pieces, the outliers out.
+ const voices = o.speakers.map((s) => {
+ const all = [
+ ...(s.clipKeys ?? []).map((key) => ({ key: `clip:${key}`, clipKey: key, vector: vec(`clip:${key}`) })),
+ ...(s.items ?? []).map((r) => ({ key: `ref:${s.name}:${r.key}`, clipKey: null, vector: vec(`ref:${s.name}:${r.key}`) })),
+ ].filter((r) => r.vector);
+ const robust = robustCentroid(all.map((r) => /** @type {number[]} */ (r.vector)));
+ const kept = robust.kept.map((i) => all[i]);
+ return {
+ name: s.name,
+ kept,
+ doc: {
+ name: s.name,
+ clips: [...(s.clipKeys ?? [])],
+ recordings: s.recordings ?? [],
+ pieces: (s.clipKeys?.length ?? 0) + (s.items?.length ?? 0),
+ embedded: all.length,
+ kept: kept.length,
+ dropped: robust.dropped.map((i) => all[i].clipKey ?? all[i].key.replace(/^ref:[^:]*:/, "")),
+ },
+ };
+ });
+
+ /** @type {Record<string, Record<string, unknown>>} */
+ const clips = {};
+ for (const c of o.clips) {
+ if (!check.has(c.key)) continue;
+ const p = prepared.get(`clip:${c.key}`);
+ const v = vec(`clip:${c.key}`);
+ /** @type {Record<string, unknown>} */
+ const row = { speechSeconds: round(p?.seconds ?? 0, 2), scores: [] };
+ if (c.id) row.id = c.id;
+ if (p?.fallback) row.fallback = true;
+ if (!c.file) row.why = c.missing ?? "no window";
+ else if (!p?.wav) row.why = p?.why ?? "not decoded";
+ else if (!v) row.why = emb.items.get(`clip:${c.key}`)?.error ?? "not embedded";
+ else {
+ const scores = [];
+ for (const voice of voices) {
+ const s = scoreAgainst(v, voice.kept.map((r) => ({ key: r.key, vector: /** @type {number[]} */ (r.vector) })), { selfKey: `clip:${c.key}` });
+ if (s.score == null) continue;
+ scores.push({ name: voice.name, score: s.score, best: s.best, ...(voice.kept.some((r) => r.clipKey === c.key) ? { inReference: true } : {}) });
+ }
+ scores.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
+ row.scores = scores;
+ if (!scores.length) row.why = "no reference voice has pieces to compare with";
+ else Object.assign(row, speakerVerdict(scores, t));
+ }
+ clips[c.key] = row;
+ }
+ await rm(scratch, { recursive: true, force: true });
+ return {
+ version: SPEAKER_CHECK_VERSION,
+ model: VOICE_MATCH_MODEL,
+ engine: { file: emb.model, sherpaOnnx: emb.version, dim: emb.dim, sampleRate: SAMPLE_RATE },
+ madeAt: (o.now ? o.now() : new Date()).toISOString(),
+ thresholds: { likely: t.likely, unlikely: t.unlikely, margin: SPEAKER_MARGIN },
+ speakers: voices.map((v) => v.doc),
+ clips,
+ };
+}
+
+/** `<project>/speaker-check.json`, or null. */
+export async function readSpeakerCheck(dir) {
+ try {
+ const doc = JSON.parse(await readFile(path.join(dir, SPEAKER_CHECK_FILE), "utf8"));
+ return doc && doc.version === SPEAKER_CHECK_VERSION && doc.clips && typeof doc.clips === "object" ? doc : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Written whole (tmp + rename), MERGED into the file there: a check of one
+ * clip keeps the other clips' rows -- when they were scored against the same
+ * voices (by name and pieces); a change of the reference sets starts over.
+ */
+export async function writeSpeakerCheck(dir, doc) {
+ const file = path.join(dir, SPEAKER_CHECK_FILE);
+ const prev = await readSpeakerCheck(dir);
+ const sig = (d) => JSON.stringify((d?.speakers ?? []).map((s) => [s.name, s.clips, s.recordings]));
+ const merged = prev && sig(prev) === sig(doc) ? { ...doc, clips: { ...prev.clips, ...doc.clips } } : doc;
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, `${JSON.stringify(merged, null, 1)}\n`);
+ await rename(tmp, file);
+ return { file, doc: merged };
+}
diff --git a/common/lib/montage/speakerCheck.test.ts b/common/lib/montage/speakerCheck.test.ts
@@ -0,0 +1,75 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { encodeWav16 } from "./voiceMatch.mjs";
+import { SPEAKER_CHECK_FILE, readSpeakerCheck, runSpeakerCheck, speakerVerdict, writeSpeakerCheck } from "./speakerCheck.mjs";
+import { VOICE_A, VOICE_B, syntheticVoice } from "../../testing/audio/syntheticVoice.mjs";
+import { hasFfmpeg } from "../../testing/audio/corruptAudio.mjs";
+
+// The speaker check (UI notes 2026-10-30, #15): which of several named voices
+// a clip is. Two synthetic voices the test kit's fake embedder tells apart;
+// no python, no model.
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FAKE = path.join(HERE, "..", "..", "testing", "audio", "fakeSpeakerEmbed.mjs");
+const FAKE_ENGINE = { python: process.execPath, script: FAKE, model: "fake.onnx", threads: 1 };
+const tmp = () => mkdtempSync(path.join(os.tmpdir(), "speaker-check-"));
+const wav = (dir: string, name: string, x: Float32Array) => {
+ const f = path.join(dir, name);
+ writeFileSync(f, encodeWav16(x));
+ return f;
+};
+
+test("speakerVerdict: matches when the best is over the bar and ahead by the margin; none under the floor; else unsure", () => {
+ assert.deepEqual(speakerVerdict([{ name: "Ember", score: 0.93 }, { name: "Kirsche", score: 0.83 }]), { label: "matches", best: "Ember", margin: 0.1 });
+ assert.deepEqual(speakerVerdict([{ name: "Ember", score: 0.62 }, { name: "Kirsche", score: 0.6 }]), { label: "unsure", best: "Ember", margin: 0.02 });
+ assert.deepEqual(speakerVerdict([{ name: "Ember", score: 0.2 }]), { label: "none", best: "Ember", margin: null });
+ assert.deepEqual(speakerVerdict([]), { label: "unsure", best: null, margin: null });
+});
+
+test("runSpeakerCheck: each clip against every named voice, best first; a voice's own clip is scored against the rest of it", { skip: !hasFfmpeg() && "needs ffmpeg" }, async () => {
+ const dir = tmp();
+ try {
+ const a = [0.4, 1.1, 2.2].map((ph, i) => wav(dir, `a${i}.wav`, syntheticVoice({ ...VOICE_A, seconds: 2.5, phase: ph })));
+ const b = [0.7, 1.9].map((ph, i) => wav(dir, `b${i}.wav`, syntheticVoice({ ...VOICE_B, seconds: 2.5, phase: ph })));
+ const probe = wav(dir, "probe.wav", syntheticVoice({ ...VOICE_A, seconds: 2.5, phase: 3.3 }));
+ const clip = (key: string, file: string) => ({ key, id: key, file, start: 0, dur: 2.5 });
+ const doc = await runSpeakerCheck({
+ clips: [clip("a0", a[0]), clip("a1", a[1]), clip("p", probe)],
+ check: ["p", "a0"],
+ speakers: [
+ { name: "Host", clipKeys: ["a0", "a1"], items: [{ key: "r2", file: a[2], start: 0, dur: 2.5 }] },
+ { name: "Guest", items: b.map((f, i) => ({ key: `g${i}`, file: f, start: 0, dur: 2.5 })) },
+ ],
+ engine: FAKE_ENGINE,
+ scratch: path.join(dir, "scratch"),
+ now: () => new Date("2026-11-02T10:00:00Z"),
+ });
+ const p = doc.clips.p as { scores: { name: string; score: number }[]; label: string; best: string };
+ assert.deepEqual(p.scores.map((s) => s.name), ["Host", "Guest"]);
+ assert.equal(p.label, "matches");
+ assert.equal(p.best, "Host");
+ assert.ok(p.scores[0].score > p.scores[1].score + 0.05, JSON.stringify(p.scores));
+ // a0 is in Host's set: scored against a1 and r2, and says so.
+ const a0 = doc.clips.a0 as { scores: { name: string; inReference?: boolean }[]; label: string };
+ assert.equal(a0.scores[0].name, "Host");
+ assert.equal(a0.scores[0].inReference, true);
+ assert.equal("a1" in doc.clips, false, "a reference clip not asked for is not a row");
+ assert.deepEqual(doc.speakers.map((s: { name: string; pieces: number; kept: number }) => [s.name, s.pieces, s.kept]), [["Host", 3, 3], ["Guest", 2, 2]]);
+ // The file merges a later check of one clip into the rows there.
+ await writeSpeakerCheck(dir, doc);
+ const again = { ...doc, clips: { p: { ...p, label: "unsure" } } };
+ const { doc: merged } = await writeSpeakerCheck(dir, again);
+ assert.deepEqual(Object.keys(merged.clips).sort(), ["a0", "p"]);
+ assert.equal((await readSpeakerCheck(dir))?.clips.p && (merged.clips.p as { label: string }).label, "unsure");
+ // New reference sets start the file over.
+ const { doc: fresh } = await writeSpeakerCheck(dir, { ...again, speakers: [{ ...doc.speakers[0], name: "Renamed" }] });
+ assert.deepEqual(Object.keys(fresh.clips), ["p"]);
+ assert.ok(SPEAKER_CHECK_FILE.endsWith(".json"));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/renderPriority.mjs b/common/lib/renderPriority.mjs
@@ -100,11 +100,19 @@ function gitCommonDir(cwd) {
*/
export function renderPriorityFile(env = process.env, { heavyLock = null, root = process.cwd() } = {}) {
if (env.RENDER_PRIORITY_FILE) return env.RENDER_PRIORITY_FILE;
- const lock =
- heavyLock ??
- env.HEAVY_LOCK_FILE ??
- path.join(/* turbopackIgnore: true */ gitCommonDir(root) ?? os.tmpdir(), HEAVY_LOCK_NAME);
- return `${lock}${STATE_SUFFIX}`;
+ return `${heavyLock ?? heavyLockFile(env, { root })}${STATE_SUFFIX}`;
+}
+
+/**
+ * The heavy slot's lock, as queue-lock.mjs finds it: HEAVY_LOCK_FILE, else
+ * `heavy-queue.lock` in the git common dir of `root` (one for every
+ * worktree), a tmpdir outside a git checkout. Its running and waiting
+ * tickets sit beside it (common/lib/heavyQueue.mjs reads them).
+ * @param {Record<string, string | undefined>} [env]
+ * @param {{ root?: string }} [opts]
+ */
+export function heavyLockFile(env = process.env, { root = process.cwd() } = {}) {
+ return env.HEAVY_LOCK_FILE ?? path.join(/* turbopackIgnore: true */ gitCommonDir(root) ?? os.tmpdir(), HEAVY_LOCK_NAME);
}
/** The file's JSON, or null (missing, half-written, not ours). */
diff --git a/common/package.json b/common/package.json
@@ -47,8 +47,10 @@
"./lib/montage/phraseScan.mjs": "./lib/montage/phraseScan.mjs",
"./lib/montage/phraseSource.mjs": "./lib/montage/phraseSource.mjs",
"./lib/montage/voiceMatch.mjs": "./lib/montage/voiceMatch.mjs",
+ "./lib/montage/speakerCheck.mjs": "./lib/montage/speakerCheck.mjs",
"./lib/ports.mjs": "./lib/ports.mjs",
"./lib/renderPriority.mjs": "./lib/renderPriority.mjs",
+ "./lib/heavyQueue.mjs": "./lib/heavyQueue.mjs",
"./lib/report/drafted.mjs": "./lib/report/drafted.mjs",
"./lib/report/look.mjs": "./lib/report/look.mjs",
"./lib/report/intro.mjs": "./lib/report/intro.mjs",
diff --git a/common/views/channelRow.test.ts b/common/views/channelRow.test.ts
@@ -114,6 +114,12 @@ test("the view carries no config, only the fields a cell draws", () => {
assert.equal(bare.lastSyncedAt, null);
});
+test("social: a posts channel's row says so, so its Sync button runs fetch-posts (UI notes #17)", () => {
+ assert.equal(buildChannelRowView(input()).social, false);
+ const x = buildChannelRowView(input({ config: { handling: "youtube", url: "https://x.com/someone", sourceKind: "social" } as ChannelConfig }));
+ assert.equal(x.social, true);
+});
+
test("media: in-place is dropped; the label is the volume's unless overridden", () => {
const inPlace = buildChannelRowView(
input({ media: { status: "in-place", target: "/x", detail: "" } }),
diff --git a/common/views/channelRow.ts b/common/views/channelRow.ts
@@ -1,5 +1,5 @@
import { channelDownloadsAreManual } from "../lib/manualDownloads";
-import type { ChannelConfig } from "../lib/channelConfig";
+import { isSocialChannel, type ChannelConfig } from "../lib/channelConfig";
import type { ChannelSnapshot } from "../controller/channelSnapshot";
import type { ChannelMediaLocation } from "../lib/channelMedia";
import { mediaHoldText } from "../lib/channelMediaHold";
@@ -82,6 +82,9 @@ export type ChannelRowView = {
handling: ChannelConfig["handling"];
// Whether the channel has a URL — Sync and Download need one.
hasUrl: boolean;
+ // A social (posts) channel: its Sync runs fetch-posts, never the yt-dlp
+ // listing (UI notes 2026-10-30, #17), and the button says so.
+ social: boolean;
excludeFromBuild: boolean;
lastSyncedAt: string | null;
// The playlist file's line count; null when there is no playlist file.
@@ -195,6 +198,7 @@ export function buildChannelRowView(i: ChannelRowInput): ChannelRowView {
name: i.config.name ?? "",
handling: i.config.handling,
hasUrl: Boolean(i.config.url),
+ social: isSocialChannel(i.config),
excludeFromBuild: i.config.excludeFromBuild === true,
lastSyncedAt: i.config.lastSyncedAt ?? null,
playlistCount: i.playlistCount,
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,11 @@
# Changelog
## [Unreleased]
+- **Sync on an X, Bluesky or forum channel fetches its posts.** The Sync button on a social channel ran yt-dlp's video listing against the profile and failed. Every Sync — the channel rows', the dashboard's, a group's, Sync all, `pnpm ops sync`, a sync job's Retry — now runs the channel's post fetch (the same job as the channel page's Fetch posts: on the platform's queue, paced, and for X only on a fresh cookie jar), and a refusal is its own sentence beside the button. A full sweep is the video listing's, so a Sync never starts a social channel's whole re-walk; that is still Fetch posts → Re-fetch full history.
+- **A report video's project page names the sites its links depend on, and says when one is behind.** Each site a clip's QR opens is listed with its deploy's date (its `corpus.json`, read by Check links) and the cited videos newer than it — uploaded or transcribed after it, and not found on it — and the check's new `site-deploy-behind` row offers **Publish <site>**, which asks the editor to build and deploy it.
+- **A per-project link policy: cite via one site, these channels direct.** The Ember cut's citeUrls were rewritten by hand twice to send two channels to anilyzer and one to YouTube. A project's **Link policy** (Overview, or `umtool link-policy <p> --via <site> --direct a,b`) now says it once: new clips are written by it, and every clip that breaks it is a check row with a one-press fix (`umtool link-policy <p> --fix` for all).
+- **The take panel shows the render queue and how long a take will take.** What runs in the machine's heavy slot and what waits there — e2e suites, builds, renders, and what each waits for — read from the slot's own files ("held by e2e suite e2e-editor"), and an ETA for a whole-cut take of the project, fresh and made from the newest take, from how long its past renders took. A take now records its render's own time (`renderSeconds`).
+- **The walk checks who is speaking against several named voices.** The clip bench's verdict bar shows *Speaker: matches Ember 0.93 / Kirsche 0.83* with the reference sets it used, and **Check speaker** scores the clip (TitaNet-small, local, as a job through the heavy slot); the voices are the project's `speakers.json` (**Add to a voice**, or `umtool speaker-check <p> --set 'Ember=e01,e07'`).
- **X has a cookie banner like Rumble's, and says how fresh its jar is.** X's banner used to go up only when X answered a fetch with a challenge, so an X fetch on an old jar was simply refused with a sentence the operator saw only in a job's error. Now the fresh-jar rule's refusal (`social.x.maxCookieAgeMinutes`, an hour by default) puts an **X needs fresh cookies** banner on the dashboard — "press Refresh cookies (or Connect X account) on /settings — with the browser login, open x.com in firefox" — with the jar's age under it, read from disk: the exported jar's time, or, with the browser login, when Firefox last sent its x.com `auth_token` (read by the cookie's name from a private copy of Firefox's cookie store; its value is never read). An X fetch refused at its start is offered under **Re-run stopped jobs** once the jar is fresh. Recheck re-reads the age and asks X nothing; the banner clears by itself as soon as an X job passes the rule on a fresh jar. This banner does not itself refuse X jobs (the rule does); a real challenge or login failure from X replaces it with the one that does. gallery-dl's own words are now read more carefully: its "AuthRequired: authenticated cookies needed to access this timeline" (what X answers a logged-out timeline with), "Could not authenticate you", a 401 and an API 403 count as a **login failure** (worded so on the banner and in the refusal), a 429 or "rate limit" is pacing and never raises the banner, and a protected or blocking account, an NSFW or protected tweet and a 403 on a twimg.com media file are about that one account or file — those used to raise X's banner and stop every X job. `pnpm ops get services` now always carries `x` (the jar's source, age, limit and whether an X job could start on it). Needs a restart of the editor.
- **Rumble's cookies are checked on a timer, so the banner goes up before a sync fails.** Until now a stale Cloudflare clearance was noticed only when a Rumble sync or clip fetch failed on it. Every 3 hours (stretched a little at random, never shortened) the editor now looks by itself: when Rumble has been idle that long, it asks Rumble once for the last video it answered cleanly — a refusal is checked once more on the previous, different video a minute or more later, because a removed video refuses too, and two different videos refused put the banner up; every banner already up is rechecked once, as its Recheck button does, so it clears by itself after rumble.com was opened in Firefox; and X's jar age is re-read from disk (X jobs queued on an old jar put X's banner up before their start refuses them). Nothing is asked while a job is queued or running on Rumble's queues (its answer is the check), while Rumble is cooling down or held, or while a recheck runs, and a failed check is never retried — it waits for the next tick or a click. Each check is a **Recheck service cookies** job on /jobs. `settings.serviceCookies.recheckIntervalMinutes` (180; 30–1440; 0 turns it off) and `probeServices` (`["rumble"]`; YouTube and Odysee may be added), set with `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`; `pnpm ops get services` shows the timer's last tick under `timer`. Not on an idle boot. Needs a restart of the editor.
- **A channel can download only the videos you add.** The operator wanted Harmful Opinions downloaded by hand, with its title filter gone, and nothing said that: `syncIntervalMinutes: 0` stops the listing but the download lane still works the backlog it has — and dropping a filter re-decides every video it had settled, so the whole channel would come down — while a `paused` tier stops every lane, transcription too. Configure → Advanced → **Downloads**: Manual (`downloadMode: "manual"` in config.json; `pnpm ops channel-config --json '{"slug":"<slug>","patch":{"downloadMode":"manual"}}'`, `""` sets it back to Automatic). On a manual channel the download lane skips the channel (its backlog, retries, metadata scan and chat backlog); a sync reads only the newest page of the listing and a full sweep still refreshes the playlist and the maybe-missing set, and neither downloads the new uploads it finds; Download from playlist, Download videos (`download-missing`) and the bucket retries refuse with a notice. What you ask for still downloads — Import, `import-video`, the video page's download and persist buttons, `persist-videos`, clip windows, a whole-recording fetch — and the videos on disk are still transcribed. The channel's report keeps the listed videos it lacks as **Listed, not requested** (`manualNotRequestedIds`) rather than undownloaded work, so no lane, rack figure, dashboard count or group Download button counts them, and a video that leaves the listing unfetched is not raised as never fetched; the channel page says "Manual downloads — only videos you add are downloaded" at the top and the rack row carries a **manual dl** chip. An import still passes the channel's download filter, so set the mode first and then clear the filter. Needs a restart of the editor.
diff --git a/editor/app/api/ops/sync/route.test.ts b/editor/app/api/ops/sync/route.test.ts
@@ -0,0 +1,76 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/sync/route.test.ts"
+//
+// A SOCIAL CHANNEL'S SYNC IS ITS POST FETCH (UI notes 2026-10-30, #17): Sync on
+// an X channel ran yt-dlp against the profile and failed. Every case here is a
+// refusal answered before any job, from a temp corpus: the X channel has no
+// cookie jar, so fetch-posts' own guard refuses it in its own sentence — which
+// is how this knows the sync went to fetch-posts and not the video listing —
+// and nothing reaches X.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "sync-route-"));
+// Set before the route (and getPaths, which caches) is first imported.
+process.env.WORKER_TOKEN = "test-token";
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+const channel = async (slug: string, config: Record<string, unknown>) => {
+ await mkdir(path.join(ROOT, "channels", slug), { recursive: true });
+ await writeFile(path.join(ROOT, "channels", slug, "config.json"), JSON.stringify(config));
+};
+await channel("demo-x", {
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "twitter",
+ postFetcher: "x-gallery-dl",
+ socialHandle: "example_user",
+ name: "Example (X)",
+ url: "https://x.com/example_user",
+});
+await channel("demo-pages", {
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "webpage",
+ name: "Example pages",
+ url: "https://web.archive.org/web/2020/https://example.test/",
+});
+const { POST } = await import("./route");
+const { WAYBACK_PAGES_NOT_FETCHED } = await import("yt-dlp-transcript-common/controller/fetchPosts");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+async function post(body: Record<string, unknown>): Promise<{ status: number; error: string }> {
+ const res = await POST(
+ new Request("http://localhost/api/ops/sync", {
+ method: "POST",
+ headers: { authorization: "Bearer test-token", "content-type": "application/json" },
+ body: JSON.stringify(body),
+ }),
+ );
+ return { status: res.status, error: ((await res.json()) as { error?: string }).error ?? "" };
+}
+
+const jobs = () => readdir(path.join(ROOT, ".jobs")).catch(() => []);
+
+test("an X channel's sync is fetch-posts: refused on no cookie jar, in the post fetch's own words, before any job", async () => {
+ const res = await post({ slug: "demo-x" });
+ assert.notEqual(res.status, 200);
+ assert.match(res.error, /^No X cookie jar has been exported: press Connect X account on \/settings, then fetch again\.$/);
+ assert.deepEqual(await jobs(), []);
+});
+
+test("a Wayback pages channel's sync is its post fetch too, which says such a channel is never fetched", async () => {
+ const res = await post({ slug: "demo-pages" });
+ assert.equal(res.error, WAYBACK_PAGES_NOT_FETCHED);
+ assert.deepEqual(await jobs(), []);
+});
+
+test("a full sweep is the video listing's: a social channel's sync says where its whole re-walk is", async () => {
+ const res = await post({ slug: "demo-x", full: true });
+ assert.match(res.error, /^A social channel's Sync fetches its new posts; a full re-walk of its timeline is Fetch posts → Re-fetch full history/);
+ assert.deepEqual(await jobs(), []);
+});
diff --git a/editor/app/api/ops/sync/route.ts b/editor/app/api/ops/sync/route.ts
@@ -6,7 +6,9 @@ export const dynamic = "force-dynamic";
// POST { slug: string, full?: boolean, queueKey?: string } -> { ok: true, jobId }
//
// `full` forces the periodic whole-listing sweep now; without it the job
-// decides for itself from the configured cadence.
+// decides for itself from the configured cadence. A social channel's sync is
+// its post fetch (syncAction → fetch-posts, UI notes #17), and `full` is
+// refused there.
export async function POST(request: Request) {
return ops(request, ["slug", "full", "queueKey"], async (body) =>
jobResponse(
diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts
@@ -1,6 +1,8 @@
"use server";
import { manualDownloadsRefusal } from "yt-dlp-transcript-common/lib/manualDownloads";
+import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
+import { fetchPostsAction } from "./socialActions";
import path from "node:path";
import { safeRevalidate } from "../../lib/safeRevalidate";
import {
@@ -394,11 +396,29 @@ export async function downloadMissingAction(
// the periodic full sweep (see common/jobs/deepSync.ts). Pass fullSweep to force
// one now — the sweep is still a single `sync` job: one row, one log, one
// Cancel, and the same per-platform serialization.
+//
+// A SOCIAL CHANNEL'S SYNC IS ITS POST FETCH (UI notes 2026-10-30, #17). An X,
+// Bluesky, forum-thread or Wayback-pages channel holds posts, not a video
+// listing: Sync on one ran yt-dlp against the profile URL and failed. Every
+// Sync — the channel rows', the dashboard's, a group's, Sync all, `pnpm ops
+// sync`, a Retry of a sync job — now runs fetch-posts (socialActions.ts
+// fetchPostsAction, the same job the channel page's Fetch posts runs: the
+// platform's queue, paced, and for X a fresh cookie jar and no raised alert,
+// refused in its own sentence otherwise), never the yt-dlp listing. A full
+// sweep is the video listing's; a social channel's whole re-walk is
+// fetch-posts' `full`, asked for by name, so a Sync never starts one.
+const SOCIAL_FULL_SWEEP_REFUSAL =
+ "A social channel's Sync fetches its new posts; a full re-walk of its timeline is Fetch posts → Re-fetch full history (fetch-posts \"full\": true).";
+
export async function syncAction(
slug: string,
queueKey?: string,
fullSweep?: boolean,
): Promise<StreamActionResult> {
+ if (isSocialChannel(await readChannelConfig(getPaths(), slug))) {
+ if (fullSweep) return { ok: false, info: true, error: SOCIAL_FULL_SWEEP_REFUSAL };
+ return fetchPostsAction(slug, queueKey);
+ }
return runPipelineAction(slug, "sync", "sync", queueKey, {
forceFullSweep: fullSweep,
spec: { kind: "sync", slug, params: { queueKey, fullSweep } },
diff --git a/editor/app/channels/components/ChannelSyncButton.tsx b/editor/app/channels/components/ChannelSyncButton.tsx
@@ -9,12 +9,19 @@ type Status =
| { kind: "done"; jobId: string }
| { kind: "error"; message: string };
+// A SOCIAL channel's Sync is its post fetch (UI notes 2026-10-30, #17):
+// syncAction runs fetch-posts for it — the channel page's Fetch posts job,
+// paced on the platform's queue, and for X refused on a stale cookie jar in
+// its own sentence, which shows here — never the yt-dlp listing. `social`
+// only changes the words.
export function ChannelSyncButton({
slug,
disabled,
+ social = false,
}: {
slug: string;
disabled?: boolean;
+ social?: boolean;
}) {
const [status, setStatus] = useState<Status>({ kind: "idle" });
@@ -48,6 +55,12 @@ export function ChannelSyncButton({
onClick={handleClick}
disabled={running || disabled}
aria-label={`sync ${slug}`}
+ data-sync-runs={social ? "fetch-posts" : "sync"}
+ title={
+ social
+ ? "Fetches this account's new posts (fetch-posts, on its platform's queue) — a social channel has no video listing"
+ : "Lists the channel and downloads what is new"
+ }
className="px-2 py-1 rounded-md bg-primary text-primary-foreground text-xs font-medium hover:opacity-90 disabled:opacity-50"
>
{running ? "Syncing…" : "Sync"}
@@ -66,7 +79,7 @@ export function ChannelSyncButton({
aria-label={`sync ${slug} job`}
className="text-xs text-muted-foreground font-mono"
>
- job {status.jobId}
+ {social ? "fetching posts · " : ""}job {status.jobId}
</span>
)}
{status.kind === "done" && (
@@ -74,7 +87,7 @@ export function ChannelSyncButton({
aria-label={`sync ${slug} done`}
className="text-xs text-muted-foreground"
>
- done (job {status.jobId})
+ {social ? "posts fetched" : "done"} (job {status.jobId})
</span>
)}
</div>
diff --git a/editor/app/channels/components/channelColumns.tsx b/editor/app/channels/components/channelColumns.tsx
@@ -342,7 +342,7 @@ export const CHANNEL_COLUMNS: Record<
className: "whitespace-nowrap",
content: ctx.extras?.actions ?? (
<div className="flex items-center gap-2">
- <ChannelSyncButton slug={c.slug} disabled={!c.hasUrl} />
+ <ChannelSyncButton slug={c.slug} disabled={!c.hasUrl} social={c.social} />
<ChannelAvailabilityButton slug={c.slug} disabled={!c.hasUrl} />
<InlineActionButton variant={{ kind: "refreshReport", slug: c.slug }} />
</div>
diff --git a/editor/app/components/dashboard/DashboardCockpit.tsx b/editor/app/components/dashboard/DashboardCockpit.tsx
@@ -132,7 +132,7 @@ function DashboardChannels({
<div className="flex flex-wrap items-center gap-1.5">
{c.hasUrl ? (
<>
- <ChannelSyncButton slug={c.slug} />
+ <ChannelSyncButton slug={c.slug} social={c.social} />
{c.work.undownloaded > 0 && (
<InlineActionButton
variant={{ kind: "downloadMissing", slug: c.slug }}
diff --git a/editor/e2e/social-channel.spec.ts b/editor/e2e/social-channel.spec.ts
@@ -264,3 +264,75 @@ test("a forum thread URL makes a forum-thread channel, and saved pages import in
)
.toEqual(["xenforo 21", "xenforo 22", "xenforo 23"]);
});
+
+// A SOCIAL CHANNEL'S SYNC IS ITS POST FETCH (UI notes 2026-10-30, #17): the
+// Sync button on the /channels rack ran yt-dlp's listing against an X profile
+// and failed. It runs fetch-posts now (the fake gallery-dl here), and a
+// refusal is the post fetch's own sentence beside the button.
+const UI_OPS_SHOTS = process.env.E2E_UI_OPS_SHOTS ?? "";
+const shot = async (page: import("@playwright/test").Page, name: string) => {
+ if (!UI_OPS_SHOTS) return;
+ await mkdir(UI_OPS_SHOTS, { recursive: true });
+ await page.screenshot({ path: path.join(UI_OPS_SHOTS, `${name}.png`), fullPage: false });
+};
+
+test("Sync on a social channel runs fetch-posts, never the video listing", async ({ page }) => {
+ await resetData("empty");
+ await generateReport(page, "new");
+ await page.goto("/channels/new");
+ await page.locator('input[name="url"]').fill(X_URL);
+ await page.locator('input[name="name"]').fill("Fake Tester");
+ await page.locator('input[name="slug"]').fill("faketester");
+ await page.locator('input[name="fetchPostsNow"]').uncheck();
+ await page.getByRole("button", { name: /create|add channel|save/i }).first().click();
+ const config = `${testPaths().transcriptsDir}/channels/faketester/config.json`;
+ await expect.poll(() => pathExists(config), { timeout: 15_000 }).toBe(true);
+ await generateReport(page, "faketester");
+
+ await page.goto("/channels");
+ const sync = page.getByRole("button", { name: "sync faketester" });
+ await expect(sync).toHaveAttribute("data-sync-runs", "fetch-posts");
+ await expect(sync).toHaveAttribute("title", /fetch-posts/);
+ await sync.click();
+ // The fake gallery-dl's three tweets: the post fetch ran, not yt-dlp.
+ const archive = `${testPaths().transcriptsDir}/channels/faketester/posts-archive`;
+ await expect
+ .poll(async () => ((await pathExists(archive)) ? (await readFile(resolvePath(archive), "utf8")).split("\n").filter(Boolean).length : 0), {
+ timeout: 30_000,
+ })
+ .toBe(3);
+ await expect(page.getByLabel("sync faketester done")).toContainText(/posts fetched \(job /, { timeout: 30_000 });
+ await sync.scrollIntoViewIfNeeded();
+ await shot(page, "17-social-sync-fetch-posts");
+ // The job it ran is a fetch-posts job (its record beside its log).
+ const jobId = ((await page.getByLabel("sync faketester done").textContent()) ?? "").match(/job ([^)\s]+)/)?.[1] ?? "";
+ expect(jobId).not.toBe("");
+ const meta = await readJson<{ kind: string; channelSlug?: string }>(`${testPaths().transcriptsDir}/.jobs/${jobId}.meta.json`);
+ expect(meta.kind).toBe("fetch-posts");
+ expect(meta.channelSlug).toBe("faketester");
+});
+
+test("a social channel whose post fetch refuses: the Sync button shows the refusal's sentence", async ({ page }) => {
+ await resetData("empty");
+ const dir = resolvePath(`${testPaths().transcriptsDir}/channels/waypages`);
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, "config.json"),
+ JSON.stringify({
+ handling: "transcribe",
+ sourceKind: "social",
+ platform: "webpage",
+ name: "Wayback pages",
+ url: "https://web.archive.org/web/2020/https://example.test/",
+ }),
+ );
+ await generateReport(page, "waypages");
+ await page.goto("/channels");
+ const sync = page.getByRole("button", { name: "sync waypages" });
+ await expect(sync).toHaveAttribute("data-sync-runs", "fetch-posts");
+ await sync.click();
+ await expect(page.getByLabel("sync waypages error")).toHaveText(
+ "A Wayback pages channel is not fetched: import its captures (import-page, the channel page's Import a capture).",
+ );
+ await shot(page, "17-social-sync-refusal");
+});
diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts
@@ -91,6 +91,7 @@ import { currentSlot } from "./e2e/testPaths";
// E2E_SERIAL_LAST set below by the runner for its workers: whether
// the @serial project runs last (a whole run)
// E2E_RACK_SHOTS=1 run the /channels rack screenshot audit
+// E2E_UI_OPS_SHOTS=<dir> social-channel.spec's Sync screenshots (UI notes #17) go there
// E2E_FAKE_YTDLP_AUDIO_CHECK_MODE, E2E_FAKE_YTDLP_CHUNK_DELAY_MS,
// E2E_FAKE_YTDLP_CORRUPT_AFTER_CHUNK, E2E_FAKE_YTDLP_CORRUPT_RUNS,
// E2E_FAKE_YTDLP_DETERMINISTIC_CORRUPT, E2E_FAKE_YTDLP_RECOVER_ON_RESUME,
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1264,7 +1264,10 @@ export function usage() {
'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',
- " channel's platform queue, paced like its downloads.",
+ " channel's platform queue, paced like its downloads. A social channel's",
+ " sync is its post fetch (fetch-posts' new posts, its guards and refusals:",
+ ' for X a fresh cookie jar), never the video listing; "full" is refused',
+ ' there (fetch-posts "full": true re-walks the timeline).',
"",
'download-missing downloads every listed video the channel does not hold:',
' {"slug"}. "ignoreArchive": true drops the download archive so listed',
diff --git a/scripts/queue-lock.mjs b/scripts/queue-lock.mjs
@@ -869,6 +869,15 @@ function buildLockFor(heavyLock) {
function jobsDirFor(heavyLock) {
return `${heavyLock}.jobs`;
}
+// One ticket per job WAITING for the slot, `<pid>.json` (the render queue
+// panel's "waiting", UI notes #18): what it is, since when, and where it waits
+// -- `render` (at the door while render mode holds the machine), `line` (behind
+// the job at the head of the line), `slot` (at the head, for the slot's lock),
+// or the admission's own wait (`memory`, `build`, `exclusive`, `serial`).
+// Dropped once it is admitted (its running ticket replaces it) or exits.
+export function waitingDirFor(heavyLock) {
+ return `${heavyLock}.waiting`;
+}
// `systemd-run … -p MemoryMax=5G …` → 5120; none → null.
export function memoryCapMb(cmd = []) {
@@ -1108,6 +1117,63 @@ function writeTicket(dir, job, cmd) {
};
}
+/**
+ * The waiting ticket of this process: written now (stage `door`), its stage
+ * moved by `stage(name)`, removed by `drop()` (idempotent) and at exit.
+ * Informational, like the running tickets: a missing one never blocks.
+ */
+function writeWaitingTicket(dir, job, cmd) {
+ const file = path.join(dir, `${process.pid}.json`);
+ const since = new Date().toISOString();
+ let dropped = false;
+ const put = (stage) => {
+ if (dropped) return;
+ const info = {
+ pid: process.pid,
+ pidStart: pidStartTime(process.pid),
+ estimateMb: job.estimateMb,
+ build: Boolean(job.build),
+ exclusive: Boolean(job.exclusive),
+ worktree: gitOut(["rev-parse", "--show-toplevel"]) ?? process.cwd(),
+ branch: gitOut(["rev-parse", "--abbrev-ref", "HEAD"]) ?? "?",
+ cmd: cmd.join(" "),
+ since,
+ stage,
+ stageSince: new Date().toISOString(),
+ };
+ try {
+ fs.mkdirSync(dir, { recursive: true });
+ const tmp = `${file}.tmp`;
+ fs.writeFileSync(tmp, `${JSON.stringify(info, null, 2)}\n`);
+ fs.renameSync(tmp, file);
+ } catch {
+ /* informational only */
+ }
+ };
+ const drop = () => {
+ if (dropped) return;
+ dropped = true;
+ process.off("exit", drop);
+ try {
+ fs.rmSync(file, { force: true });
+ } catch {
+ /* best effort */
+ }
+ };
+ process.on("exit", drop);
+ let last = null;
+ put("door");
+ return {
+ stage: (name) => {
+ if (name !== last) {
+ last = name;
+ put(name);
+ }
+ },
+ drop,
+ };
+}
+
function describeTicket(t) {
const where = t.worktree ? path.basename(t.worktree) : "?";
const age = t.startedAt ? ` for ${humanAge(Date.parse(t.startedAt))}` : "";
@@ -1147,6 +1213,8 @@ export async function waitForAdmission({
log = (line) => process.stderr.write(line),
now = Date.now,
sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
+ // Told what the job waits for each time that changes (its waiting ticket's stage).
+ onWait = () => {},
}) {
const t0 = now();
let lastTick = t0;
@@ -1174,6 +1242,7 @@ export async function waitForAdmission({
}
if (d.wait !== lastWait) {
lastWait = d.wait;
+ onWait(d.wait);
log(waitLine(d, mem, minMb, describe));
} else if (now() - lastTick >= tickMs) {
lastTick = now();
@@ -1340,13 +1409,17 @@ export async function withHeavy(opts, fn) {
const deadline = timeoutMs > 0 ? Date.now() + timeoutMs : 0;
const remaining = () => (deadline ? Math.max(1000, deadline - Date.now()) : 0);
const releases = [];
+ // Seen by the render queue panel until it is admitted (waitingDirFor).
+ const waiting = writeWaitingTicket(waitingDirFor(heavyLock), job, cmd);
try {
let releaseLine = null;
// RENDER MODE first, outside the line: a job waiting for the render must
// not hold the line the render is admitted through. Looked at again once in
// line — a render that went on meanwhile sends this job back to wait.
for (;;) {
+ if (renderPriorityBlocks(readRender(), process.env, { urgent: opts.urgent === true })) waiting.stage("render");
await renderGateOrExit(readRender, { urgent: opts.urgent === true, timeoutMs: remaining() });
+ waiting.stage("line");
try {
releaseLine = await holdLock(admitLockFor(heavyLock), "heavy-line", cmd, remaining(), {
...HEAVY_LOCK,
@@ -1360,6 +1433,7 @@ export async function withHeavy(opts, fn) {
`heavy: the heavy slot is not held (${err?.message ?? err}) — the memory floor still applies\n`,
);
await memoryFloorOrExit(timeoutMs);
+ waiting.drop();
process.env[HEAVY_HELD_ENV] = "1";
return await fn();
}
@@ -1368,6 +1442,7 @@ export async function withHeavy(opts, fn) {
releaseLine = null;
}
try {
+ waiting.stage("slot");
const slotWait = { ...HEAVY_LOCK, describe: () => describeSlot(heavyLock) };
if (job.exclusive) {
releases.push(await holdLock(heavyLock, HEAVY_NAME, cmd, remaining(), slotWait));
@@ -1383,16 +1458,19 @@ export async function withHeavy(opts, fn) {
describe: () => describeSlot(heavyLock),
tryBuild: () =>
holdLock(buildLockFor(heavyLock), "heavy-build", cmd, 0, BUILD_LOCK, { nonblock: true }),
+ onWait: (w) => waiting.stage(w),
});
if (releaseBuild) releases.push(releaseBuild);
}
releases.push(writeTicket(jobsDirFor(heavyLock), job, cmd));
+ waiting.drop();
} finally {
await releaseLine();
}
process.env[HEAVY_HELD_ENV] = job.build ? "build" : "1";
return await fn();
} finally {
+ waiting.drop();
delete process.env[HEAVY_HELD_ENV];
for (const release of releases.reverse()) await release();
}
diff --git a/scripts/queue-lock.test.mjs b/scripts/queue-lock.test.mjs
@@ -1088,3 +1088,52 @@ test("render mode: the render (its token) is admitted at once, on the floor 4000
});
assert.match(own.stdout, /floor=1000/);
});
+
+// THE WAITING TICKETS (UI notes #18): the render queue panel reads who waits
+// at the slot, and for what, from the slot's own files.
+test("a job waiting for the slot has a waiting ticket naming its stage; admitted, it is a running ticket instead", async () => {
+ const dir = tmpDir();
+ const log = path.join(dir, "order.log");
+ const env = heavyEnv(dir);
+ const gate = path.join(dir, "gate");
+ const first = startLock(["--heavy", "--", ...gateCmd(log, "1", gate)], env);
+ await until(() => fs.existsSync(`${env.HEAVY_LOCK_FILE}.holder.json`));
+ const second = startLock(["--heavy", "--estimate", "700", "--", ...markerCmd(log, "2", 50)], env);
+ await second.waitFor(/waiting for/);
+ const waitingDir = `${env.HEAVY_LOCK_FILE}.waiting`;
+ await until(() => readTickets(waitingDir).some((t) => t.pid === second.child.pid && t.stage !== "door" && t.stage !== "line"));
+ const [w] = readTickets(waitingDir).filter((t) => t.pid === second.child.pid);
+ // Behind a job that runs alone: at the head of the line, for the slot.
+ assert.ok(["slot", "exclusive"].includes(w.stage), w.stage);
+ assert.equal(w.estimateMb, 700);
+ assert.match(w.cmd, /appendFileSync/);
+ assert.ok(Date.parse(w.since) <= Date.now());
+ // The one running: its ticket, not a waiting one.
+ assert.deepEqual(readTickets(`${env.HEAVY_LOCK_FILE}.jobs`).map((t) => t.pid), [first.child.pid]);
+ assert.equal(readTickets(waitingDir).some((t) => t.pid === first.child.pid), false);
+ openGate(gate);
+ assert.equal((await first.done).code, 0);
+ assert.equal((await second.done).code, 0);
+ assert.deepEqual(readTickets(waitingDir), []);
+});
+
+test("waitForAdmission tells onWait what the job waits for, each time it changes", async () => {
+ let clock = 0;
+ const waits = [];
+ const sets = [[{ estimateMb: 1500 }, { estimateMb: 1500 }], [{ estimateMb: 1500 }, { estimateMb: 1500 }], []];
+ await waitForAdmission({
+ minMb: 6000,
+ pollMs: 1000,
+ tickMs: 60_000,
+ log: () => {},
+ now: () => clock,
+ sleep: async (ms) => {
+ clock += ms;
+ },
+ job: { estimateMb: 1500, build: false, exclusive: false },
+ read: () => ({ availableMb: 8000, totalMb: 16_000 }),
+ tickets: () => sets.shift() ?? [],
+ onWait: (w) => waits.push(w),
+ });
+ assert.deepEqual(waits, ["memory"]);
+});
diff --git a/umtool/app/api/render-queue/route.ts b/umtool/app/api/render-queue/route.ts
@@ -0,0 +1,37 @@
+import { realpath } from "node:fs/promises";
+import { readHeavyQueue } from "yt-dlp-transcript-common/lib/heavyQueue.mjs";
+import { heavyLockFile, renderPriorityFile } from "yt-dlp-transcript-common/lib/renderPriority.mjs";
+import { REPO_ROOT } from "@/lib/paths.mjs";
+import { projectRef } from "@/lib/projects";
+import { projectEtas } from "@/lib/report/takeEta.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE RENDER QUEUE (UI notes 2026-10-30, #18), for the take panel: what runs
+// in the machine's heavy slot and what waits at it, and for what -- read from
+// the slot's own files beside its lock (common/lib/heavyQueue.mjs:
+// heavy-queue.lock.jobs/, .waiting/, the line's and the build slot's holders,
+// the e2e suites' queues, render mode), never guessed -- and, with a project,
+// how long a take of it renders, from its past renders (lib/report/takeEta.mjs).
+// Read only: render mode is turned on by "Give renders the machine" (a take's
+// --priority) or `umtool render-mode on`.
+//
+// GET ?project=<id> -> { queue, etas, mine } `mine`: the running and waiting renders of this project
+const noStore = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const queue = readHeavyQueue({
+ heavyLock: heavyLockFile(process.env, { root: REPO_ROOT }),
+ renderFile: renderPriorityFile(process.env, { root: REPO_ROOT }),
+ });
+ const id = url.searchParams.get("project");
+ const project = id ? await projectRef(id) : null;
+ if (!project) return Response.json({ queue, etas: null, mine: [] }, { headers: noStore });
+ const dir = await realpath(project.dir).catch(() => project.dir);
+ const same = async (d: string | undefined) => !!d && ((await realpath(d).catch(() => d)) === dir || d === project.dir);
+ const mine: { pid: number; take: string | null; state: "running" | "waiting"; forSeconds: number | null; stage?: string }[] = [];
+ for (const r of queue.running) if (r.kind === "render" && (await same(r.projectDir))) mine.push({ pid: r.pid, take: r.take ?? null, state: "running", forSeconds: r.forSeconds });
+ for (const w of queue.waiting) if (w.kind === "render" && (await same(w.projectDir))) mine.push({ pid: w.pid, take: w.take ?? null, state: "waiting", forSeconds: w.forSeconds, stage: w.stageWords });
+ return Response.json({ queue, etas: await projectEtas(project.dir), mine }, { headers: noStore });
+}
diff --git a/umtool/app/api/report/clip-export/route.ts b/umtool/app/api/report/clip-export/route.ts
@@ -1,23 +1,29 @@
+import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
import { projectRef } from "@/lib/projects";
import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
import { refuseCaller } from "@/lib/report/caller";
-import { EXPORT_KINDS, ExportRefused, exportClip } from "@/lib/report/clipExport.mjs";
+import { EXPORT_KINDS, ExportRefused, contextSeconds, exportNeeds, exportSteps, spanOf } from "@/lib/report/clipExport.mjs";
import { cannotOpen, localRequest } from "@/lib/report/openFolder.mjs";
export const dynamic = "force-dynamic";
// EXPORT ONE CLIP (umtool/docs/knobs.md, "Export one clip"): a clean mp4 of a
-// clip -- the cut's edges, its gaps out as jump cuts, its mute -- or its whole
-// fetched window (`raw`), with no deck chrome, into <project>/exports/.
+// clip, no deck chrome, into <project>/exports/ -- as the cut plays it (`cut`:
+// its edges, its gaps out as jump cuts, its mute), with N s either side
+// (`context`), or a stretch as recorded (`raw`: the fetched window, or a
+// `span` -- the full exchange).
//
-// POST { project, clip, take?, kind?: "cut" | "raw" }
-// -> { ok, name, rel, size, seconds, summary, notes, download, canOpen, openWhy? }
+// POST { project, clip, take?, kind?: "cut" | "context" | "raw", context?: N, span?: {from, to}, fetch?: true }
+// -> 202 { job } ONE umtool job on the app's runner (lib/jobs.ts: one at a
+// time, a log, Stop): `fetch: true` asks the editor first for what a
+// context or raw export needs that is not on disk (the bench's own
+// fetch-window path), then `umtool export … --progress ndjson`, which
+// runs in the machine's heavy slot. 409 when a cut's window is not on
+// disk ("fetch it first"), when a context/raw export needs a fetch and
+// `fetch` was not asked, or when another job is running.
+// GET ?job=<id> -> { job, done?: { name, rel, size, seconds, summary, notes, download, canOpen, openWhy? }, error? }
//
-// Answered when the file is written: one short clip, re-encoded once on this
-// machine (seconds, not minutes), outside the job runner and the heavy slot,
-// so it never waits behind a build. A second ask for the same file waits for
-// the first. Nothing is fetched: a clip whose window is not on disk is a 409
-// saying so. Names, never paths: a project of the scan, a clip of its cut.
+// Names, never paths: a project of the scan, a clip of its cut.
const headers = { "cache-control": "no-store" };
export async function POST(request: Request) {
@@ -31,36 +37,79 @@ export async function POST(request: Request) {
const clip = String(body.clip ?? "");
if (!clip) return Response.json({ error: "which clip?" }, { status: 400, headers });
const take = typeof body.take === "string" && body.take ? body.take : null;
- const kind = body.kind === undefined || body.kind === null || body.kind === "" ? "cut" : String(body.kind);
+ const kind = (body.kind === undefined || body.kind === null || body.kind === "" ? "cut" : String(body.kind)) as "cut" | "context" | "raw";
if (!(EXPORT_KINDS as readonly string[]).includes(kind)) {
return Response.json({ error: `kind is one of ${EXPORT_KINDS.join(", ")}` }, { status: 400, headers });
}
try {
- const r = await exportClip(project, clip, { take, kind: kind as "cut" | "raw" });
+ const context = kind === "context" ? contextSeconds(body.context) : undefined;
+ const span = kind === "raw" ? spanOf(body.span) : null;
+ const need = await exportNeeds(project, clip, { take, kind, ...(context !== undefined ? { context } : {}), span });
+ if (kind === "cut" && !need.held) {
+ throw new ExportRefused(`${clip}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)`, 409);
+ }
+ if (!need.held && body.fetch !== true) {
+ throw new ExportRefused(
+ `${clip}: what this export needs is not on disk (−${need.padBefore} s / +${need.padAfter} s around the clip) — ask again with fetch, which asks the editor first`,
+ 409,
+ );
+ }
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind}) — export when it is done`, running: jobView(running) }, { status: 409, headers });
+ let manifestPath: string | null = null;
+ if (take && !need.held) {
+ const { writePlayManifest } = await import("@/lib/report/takeManifest.mjs");
+ const { readManifest } = await import("@/lib/projects/report.mjs");
+ manifestPath = await writePlayManifest(project.dir, take, await readManifest(project.dir));
+ }
+ const steps = await exportSteps(project, clip, {
+ take,
+ kind,
+ ...(context !== undefined ? { context } : {}),
+ span,
+ fetch: need.held ? null : { padBefore: need.padBefore, padAfter: need.padAfter },
+ manifestPath,
+ });
+ const job = startJob(`export ${project.id}/${clip}`, steps, { project: project.id });
+ return Response.json({ ok: true, fetching: !need.held, job: jobView(job) }, { status: 202, headers });
+ } catch (e) {
+ const status = e instanceof ExportRefused ? e.status : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const id = url.searchParams.get("job");
+ const job = id ? getJob(id) : null;
+ if (!job) return Response.json({ error: "no such job" }, { status: 404, headers });
+ const view = jobView(job, Math.max(0, job.log.length - 12));
+ const ev = [...job.events].reverse().find((e) => e.ev === "export" || e.ev === "export-failed") as Record<string, unknown> | undefined;
+ if (ev?.ev === "export" && typeof ev.name === "string" && job.project) {
const no = cannotOpen();
const local = localRequest(request.headers);
const openWhy = no ?? (local.ok ? null : `Open folder works on the machine umtool runs on: ${local.why}`);
return Response.json(
{
- ok: true,
- clip: r.clip,
- take: r.take,
- kind: r.kind,
- name: r.name,
- rel: r.rel,
- size: r.size,
- mtimeMs: r.mtimeMs,
- seconds: r.seconds,
- summary: r.summary,
- notes: r.notes,
- download: `/api/report/exports?${new URLSearchParams({ project: project.id, name: r.name, v: String(r.mtimeMs) }).toString()}`,
- canOpen: !openWhy,
- ...(openWhy ? { openWhy } : {}),
+ job: view,
+ done: {
+ clip: ev.clip,
+ kind: ev.kind,
+ name: ev.name,
+ rel: ev.rel,
+ size: ev.size,
+ mtimeMs: ev.mtimeMs,
+ seconds: ev.seconds,
+ summary: ev.summary,
+ notes: ev.notes ?? [],
+ download: `/api/report/exports?${new URLSearchParams({ project: job.project, name: ev.name, v: String(ev.mtimeMs ?? "") }).toString()}`,
+ canOpen: !openWhy,
+ ...(openWhy ? { openWhy } : {}),
+ },
},
{ headers },
);
- } catch (e) {
- const status = e instanceof ExportRefused ? e.status : 500;
- return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
}
+ const error = ev?.ev === "export-failed" ? String(ev.error ?? "the export failed") : job.state === "failed" ? (job.error ?? "the export failed") : null;
+ return Response.json({ job: view, ...(error ? { error } : {}) }, { headers });
}
diff --git a/umtool/app/api/report/link-policy/route.ts b/umtool/app/api/report/link-policy/route.ts
@@ -0,0 +1,71 @@
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, manifestToken, updateLinkPolicy } from "@/lib/report/manifest.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { linkPolicyOf } from "@/lib/report/linkPolicy.mjs";
+import { sitesByOrigin } from "@/lib/report/siteDeploys.mjs";
+import { SITES_DIR } from "@/lib/paths.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE PROJECT'S LINK POLICY (UI notes 2026-10-30, #10; lib/report/linkPolicy.mjs):
+// "cite via site X; these channels direct", `provenance.linkPolicy`.
+//
+// GET ?project=<id> the policy, the cut's channels (with their clip counts),
+// the sites a policy may cite via (SITES_DIR, each with a
+// siteUrl), provenance.siteOrigin, the token
+// PUT { project, token, policy: { via?, direct? } | null } set it (null clears)
+//
+// Setting it rewrites no clip: what breaks it is the check's clip-link-policy
+// rows, each with its one-press fix through the window writer; new clips are
+// written by it (the inserters). `umtool link-policy <p> …` is the same writer.
+const noStore = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const m = r.manifest as { provenance?: Record<string, unknown>; timeline?: { type?: string; channel?: string }[] };
+ const counts = new Map<string, number>();
+ const fallback = typeof m.provenance?.channelSlug === "string" ? m.provenance.channelSlug : null;
+ for (const e of m.timeline ?? []) {
+ if (e?.type !== "clip") continue;
+ const c = e.channel ?? fallback;
+ if (c) counts.set(c, (counts.get(c) ?? 0) + 1);
+ }
+ return Response.json(
+ {
+ policy: linkPolicyOf(m),
+ siteOrigin: typeof m.provenance?.siteOrigin === "string" ? m.provenance.siteOrigin : null,
+ channels: [...counts].map(([slug, clips]) => ({ slug, clips })).sort((a, b) => b.clips - a.clips || a.slug.localeCompare(b.slug)),
+ sites: [...sitesByOrigin(SITES_DIR)].map(([origin, s]) => ({ origin, siteId: s.siteId, title: s.title })),
+ token: await manifestToken(r.project.dir),
+ },
+ { headers: noStore },
+ );
+}
+
+export async function PUT(request: Request) {
+ const refused = refuseCaller(request, "/api/report/link-policy");
+ if (refused) return refused;
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ if (!("policy" in body)) return Response.json({ error: "policy is required — { via?, direct? }, or null to clear it" }, { status: 400 });
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ try {
+ const { result, editNotes } = await withEditNotes(r.project, () =>
+ updateLinkPolicy(r.project.dir, body.policy ?? null, { token: typeof body.token === "string" ? body.token : null }),
+ );
+ return Response.json({ ok: true, ...result, editNotes }, { headers: noStore });
+ } catch (e) {
+ if (e instanceof StaleToken) {
+ return Response.json({ error: e.message, expected: e.expected, got: e.got, stale: true }, { status: 409 });
+ }
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/app/api/report/publish-site/route.ts b/umtool/app/api/report/publish-site/route.ts
@@ -0,0 +1,65 @@
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { readManifest } from "@/lib/projects/report.mjs";
+import { askEditor, EditorError } from "@/lib/articles/generation";
+import { refuseCaller } from "@/lib/report/caller";
+import { readLinkCheck } from "@/lib/report/linkCheck.mjs";
+import { projectSites, sitesByOrigin } from "@/lib/report/siteDeploys.mjs";
+import { SITES_DIR } from "@/lib/paths.mjs";
+
+export const dynamic = "force-dynamic";
+
+// PUBLISH A SITE THE CUT CITES (UI notes 2026-10-30, #8 and #9): the
+// project page's "Publish <site>" beside a site whose deploy is older than
+// videos the cut cites there. UMTOOL BUILDS AND DEPLOYS NOTHING: it asks the
+// editor (POST /api/ops/build-deploy {siteId}, the shared WORKER_TOKEN), whose
+// publish queue runs the build and then the deploy, one stage at a time, each
+// through the heavy slot -- so in render mode it waits for the render. The
+// editor's refusal (a private site, no Pages project, the publish lane held)
+// is answered in its own words.
+//
+// GET ?project=<id> the sites the cut's links depend on (siteDeploys.mjs)
+// POST { project, siteId } -> { ok, siteId, jobId }: only a site the cut's links open
+const headers = { "cache-control": "no-store" };
+
+async function sitesOf(dir: string) {
+ const m = await readManifest(dir);
+ return projectSites(m ?? {}, await readLinkCheck(dir), { sites: sitesByOrigin(SITES_DIR) });
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const project = await projectRef(url.searchParams.get("project") ?? "");
+ if (!project) return Response.json({ error: "no such project" }, { status: 404, headers });
+ return Response.json({ sites: await sitesOf(project.dir) }, { headers });
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/publish-site");
+ if (refused) return refused;
+ const b = (await request.json().catch(() => null)) as { project?: unknown; siteId?: unknown } | null;
+ if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const project = await projectRef(String(b.project ?? ""));
+ if (!project) return Response.json({ error: "no such project" }, { status: 404, headers });
+ if (!kindMakesTakes(project.kind)) return Response.json({ error: "publishing a cited site is a report video's" }, { status: 400, headers });
+ const siteId = String(b.siteId ?? "");
+ const sites = await sitesOf(project.dir);
+ if (!sites.some((s) => s.siteId && s.siteId === siteId)) {
+ const named = sites.map((s) => s.siteId).filter(Boolean);
+ return Response.json(
+ { error: `"${siteId}" is not a site this cut's links open${named.length ? ` (they open ${named.join(", ")})` : ""}` },
+ { status: 400, headers },
+ );
+ }
+ try {
+ const r = await askEditor<{ jobId?: string; jobs?: { siteId: string; jobId: string }[] }>("/api/ops/build-deploy", {
+ method: "POST",
+ body: { siteId },
+ });
+ const jobId = r.jobs?.find((j) => j.siteId === siteId)?.jobId ?? r.jobId ?? null;
+ return Response.json({ ok: true, siteId, jobId }, { headers });
+ } catch (e) {
+ const status = e instanceof EditorError ? e.status : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+}
diff --git a/umtool/app/api/report/speaker-check/route.ts b/umtool/app/api/report/speaker-check/route.ts
@@ -0,0 +1,84 @@
+import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { readManifest } from "@/lib/projects/report.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { addClipToSpeaker, speakerBadge, speakerCheckSteps } from "@/lib/report/speakerCheck.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE SPEAKER CHECK ON THE WALK (UI notes 2026-10-30, #15): "Speaker: matches
+// Ember 0.93 / Kirsche 0.83", with the reference sets it was measured against
+// (lib/report/speakerCheck.mjs; the voices are <project>/speakers.json).
+// "Check speaker" is ONE job on the app's runner (lib/jobs.ts: a log, the
+// NDJSON events, Cancel) running `umtool speaker-check <p> --clip <id>`
+// through the machine's heavy slot (queue-lock --heavy with its estimate:
+// beside other jobs by memory, after a render the operator is waiting for).
+// Local: TitaNet-small; no network, no LLM.
+//
+// GET ?project=<id>&clip=<id> the clip's row, the voices, and the check running, if any
+// GET ?job=<id>[&since=&sinceEvent=] that job
+// POST { project, clip } check that clip's speaker (a job)
+// POST { project, clip, addTo: "<name>" } put the clip in that voice's reference set (made when new)
+const headers = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const id = url.searchParams.get("job");
+ if (id) {
+ const job = getJob(id);
+ if (!job) return Response.json({ error: "no such job" }, { status: 404 });
+ return Response.json(jobView(job, Number(url.searchParams.get("since") ?? 0), Number(url.searchParams.get("sinceEvent") ?? 0)), { headers });
+ }
+ const project = await projectRef(String(url.searchParams.get("project") ?? ""));
+ if (!project) return Response.json({ error: "no such project" }, { status: 404 });
+ const clip = String(url.searchParams.get("clip") ?? "");
+ const m = await readManifest(project.dir);
+ const running = runningJob();
+ try {
+ return Response.json(
+ {
+ ...(await speakerBadge(project.dir, m ?? {}, clip)),
+ running: running && running.project === project.id && running.kind.startsWith("speaker-check ") ? jobView(running) : null,
+ },
+ { headers },
+ );
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
+
+export async function POST(request: Request) {
+ const url = new URL(request.url);
+ const cancel = url.searchParams.get("cancel");
+ if (cancel) {
+ const { cancelJob } = await import("@/lib/jobs");
+ return Response.json({ cancelled: cancelJob(cancel) });
+ }
+ const refused = refuseCaller(request, "/api/report/speaker-check");
+ if (refused) return refused;
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 });
+ const project = await projectRef(String(body.project ?? ""));
+ if (!project) return Response.json({ error: "no such project" }, { status: 404 });
+ if (!kindMakesTakes(project.kind)) return Response.json({ error: "speakers are checked for a report video" }, { status: 400 });
+ const clip = typeof body.clip === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(body.clip) ? body.clip : null;
+ if (!clip) return Response.json({ error: "which clip?" }, { status: 400 });
+ if (typeof body.addTo === "string") {
+ try {
+ const speakers = await addClipToSpeaker(project.dir, body.addTo, clip);
+ return Response.json({ ok: true, speakers }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+ }
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409 });
+ const plan = speakerCheckSteps(project, { clip });
+ try {
+ const job = startJob(plan.kind, plan.steps, { project: project.id });
+ return Response.json({ ok: true, job: jobView(job) }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 });
+ }
+}
diff --git a/umtool/app/api/report/takes/housekeeping/route.ts b/umtool/app/api/report/takes/housekeeping/route.ts
@@ -13,15 +13,40 @@ export const dynamic = "force-dynamic";
// refused while it renders
// POST { project, take, op: "supersede", by?: <take> } verdicts.json: folded away
// POST { project, take, op: "unsupersede" } the mark cleared
+// POST { project, take, op: "cancel" } stop its render (lib/report/takeCancel.mjs):
+// asked of the process rendering it, waited
+// for; the app's own take job is stopped by
+// the job runner when it does not answer.
+// -> { stopped, how, cancelled, renderMode, said }
+// POST { project, take, op: "fork", name? } the take as a variant: a project beside
+// this one (lib/report/variantFork.mjs)
//
-// The CLI's twins: `umtool takes relabel | supersede [--clear]`.
+// The CLI's twins: `umtool takes relabel | supersede [--clear] | cancel | fork`.
export async function POST(request: Request) {
- const body = (await request.json().catch(() => null)) as { project?: string; take?: string; op?: string; label?: string; by?: string | null } | null;
+ const body = (await request.json().catch(() => null)) as { project?: string; take?: string; op?: string; label?: string; by?: string | null; name?: string | null } | null;
if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 });
if (!isTakeId(body.take)) return Response.json({ error: "take must be a take id" }, { status: 400 });
const take = body.take;
const project = await projectRef(String(body.project ?? ""));
if (!project) return Response.json({ error: "no such project" }, { status: 404 });
+ // A first render has no take.json yet: it is cancelled by its directory.
+ if (body.op === "cancel") {
+ try {
+ const { cancelTake } = await import("@/lib/report/takeCancel.mjs");
+ const { cancelJob, runningJob } = await import("@/lib/jobs");
+ const r = await cancelTake(project, take, {
+ by: "the Takes page",
+ // The take maker did not answer: when it is the app's own take job, the job runner stops it.
+ fallback: (lock) => {
+ const job = runningJob();
+ return !!job && job.pids.includes(Number(lock.pid)) && cancelJob(job.id);
+ },
+ });
+ return Response.json({ ok: true, take, ...r }, { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 409 });
+ }
+ }
const known = (await listTakes(project.dir)).takes.map((t) => t.id);
if (!known.includes(take)) return Response.json({ error: "no such take" }, { status: 404 });
try {
@@ -34,7 +59,17 @@ export async function POST(request: Request) {
const r = await setTakeSuperseded(project.dir, take, { by, clear: body.op === "unsupersede", known });
return Response.json({ ok: true, take, ...r }, { headers: { "cache-control": "no-store" } });
}
- return Response.json({ error: "op must be relabel, supersede or unsupersede" }, { status: 400 });
+ if (body.op === "fork") {
+ const { ForkRefused, forkTakeAsVariant } = await import("@/lib/report/variantFork.mjs");
+ try {
+ const r = await forkTakeAsVariant(project, take, { name: typeof body.name === "string" ? body.name : null });
+ return Response.json({ ok: true, take: r.take, id: r.id, name: r.name, links: r.links, copied: r.copied, variant: r.variant }, { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ if (e instanceof ForkRefused) return Response.json({ error: e.message }, { status: e.status });
+ throw e;
+ }
+ }
+ return Response.json({ error: "op must be relabel, supersede, unsupersede, cancel or fork" }, { status: 400 });
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
return Response.json({ error: message, ...(/changed since/.test(message) ? { stale: true } : {}) }, { status: /rendering now|being rendered/.test(message) ? 409 : 400 });
diff --git a/umtool/app/api/report/tighten/route.ts b/umtool/app/api/report/tighten/route.ts
@@ -0,0 +1,30 @@
+import { projectRef } from "@/lib/projects";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { proposeTightWindows } from "@/lib/report/tightPropose.mjs";
+
+export const dynamic = "force-dynamic";
+
+// PROPOSE TIGHT WINDOWS (UI notes 2026-10-30, item 4; lib/report/tightPropose.mjs):
+// every clip of the cut tightened to its sentence and each edge into its pause,
+// before and after, for review. READS ONLY -- nothing is fetched and nothing
+// is written; a row is applied by its own Apply, through the window writer
+// (PUT /api/report/window with the token this answers).
+//
+// GET ?project=<id>[&clip=<id>…][&measure=0]
+// -> { token, rows: [{ id, before, after, changed, how, said, why, fetched, locked, words, clear }], counts }
+// measure=0: no silences (the words alone) -- nothing is measured
+const headers = { "cache-control": "no-store" };
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const project = await projectRef(String(url.searchParams.get("project") ?? ""));
+ if (!project) return Response.json({ error: "no such project" }, { status: 404, headers });
+ if (!kindMakesTakes(project.kind)) return Response.json({ error: "tight windows are a report video's" }, { status: 400, headers });
+ const clips = url.searchParams.getAll("clip").filter(Boolean);
+ try {
+ const got = await proposeTightWindows(project, { clips: clips.length ? clips : null, measure: url.searchParams.get("measure") !== "0" });
+ return Response.json(got, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 422, headers });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -15,6 +15,8 @@
// umtool show <project> [--json]
// umtool check [<project> | --all] [--json] exit 1 on anything blocking
// umtool links <project> [--json] [--fix] do the clip QRs open on their sites (out/links.json)
+// umtool speaker-check <project> [--clip <id> …] [--set 'Name=…'] [--list] which named voice each clip is (speaker-check.json)
+// umtool link-policy <project> [--via <site>] [--direct a,b] [--clear] [--fix] cite via site X; these channels direct
// umtool decisions [--json]
// umtool inbox [--all] [--json] the decisions grouped as the inbox ranks them
// umtool schedule list | show <id> [--json] the recurring reports (R5), read-only
@@ -55,8 +57,10 @@
// 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> [--raw] [--take T] [--open] [--json] one clip, clean, into
-// <project>/exports/: the cut's edges, gaps out, mute (--raw: the whole fetched window)
+// umtool export <project> <clip> [--context N | --raw [--from S --to S]] [--fetch] [--take T] [--open] [--json]
+// one clip, clean, into <project>/exports/: the cut's edges, gaps out, mute (--context: what
+// the cut plays ± N s, as recorded; --raw: the fetched window, or a span, as recorded; --fetch:
+// ask the editor first for what is not on disk), in the heavy slot
// umtool check-sources [<project>…] prints the re-check chain
// umtool notes [<site>/<report> | <project> | --all] [--open|--resolved|--all-status] [--json]
// umtool notes reply <id> "<text>" [--resolve] | resolve | wontfix | reopen <id>
@@ -79,6 +83,8 @@
// umtool trailer-beats <project> [ls | add <clip> [<from>-<to>] | set <n> <from>-<to> | remove <n> | move <n> --to <m>
// | order | limit <s|m:ss|x> | xfade <s> | intro on|off | candidates [--add]] the trailer's beats
// (promo/trailer-beats.json): running length against the limit, beats outside their clip
+// umtool tighten <project> [--json] [--all] [--no-measure] | --apply <clip>[,<clip>…] each clip to its sentence,
+// each edge into its pause: before -> after for review; --apply writes the named rows
// umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>]
// the clip deck's montage rulings (release 34)
// umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] the clip windows, asked of
@@ -713,14 +719,49 @@ async function cmdExport() {
}
// One clip, clean (umtool/docs/knobs.md, "Export one clip"): the cut's edges,
-// its gaps out, its mute -- or `--raw`, the whole fetched window -- with no
-// deck chrome. Runs here, with this machine's ffmpeg; nothing is fetched.
+// its gaps out, its mute -- `--context N`, what the cut plays with N s either
+// side, as recorded -- `--raw [--from S --to S]`, a stretch as recorded (the
+// full exchange) -- with no deck chrome. Runs here, with this machine's
+// ffmpeg, in the heavy slot (a small declared estimate: it runs beside others
+// when memory allows). `--fetch` asks the editor first for what a context or
+// raw export needs that is not on disk (fetch-via-editor.mjs, the bench's own
+// path); otherwise nothing is fetched. `--progress ndjson`: one `export` event
+// on stdout at the end (the app's export job reads it).
async function cmdExportClip(p, clipId) {
- const { exportClip } = await import("../lib/report/clipExport.mjs");
+ const { EXPORT_ESTIMATE_MB, exportClip, exportNeeds } = await import("../lib/report/clipExport.mjs");
+ const ndjson = val("--progress") === "ndjson";
+ const kind = has("--raw") ? "raw" : val("--context") !== undefined ? "context" : "cut";
+ const context = val("--context");
+ const from = val("--from");
+ const to = val("--to");
+ if (kind !== "raw" && (from !== undefined || to !== undefined)) die("--from/--to are a raw export's span: add --raw");
+ if ((from === undefined) !== (to === undefined)) die("a raw span is --from S --to S, both");
+ const span = from !== undefined ? { from: Number(from), to: Number(to) } : null;
+ const take = val("--take") ?? null;
+ const say = (line) => (ndjson || json ? console.error(line) : console.log(line));
+ if (has("--fetch") && kind !== "cut") {
+ let need;
+ try {
+ need = await exportNeeds(p, clipId, { take, kind, context: context === undefined ? undefined : Number(context), span });
+ } catch (e) {
+ die(e?.message ?? String(e), 1);
+ }
+ if (!need.held) {
+ say(`fetching −${need.padBefore} s / +${need.padAfter} s around ${clipId} through the editor first`);
+ const code = await runFetchViaEditor(p, clipId, need, { take });
+ if (code !== 0) die(`the fetch did not finish (exit ${code}) — nothing exported`, 1);
+ }
+ }
+ const { withRenderSlot } = await import("../report-to-video/heavy-gate.mjs");
let r;
try {
- r = await exportClip(p, clipId, { take: val("--take") ?? null, kind: has("--raw") ? "raw" : "cut" });
+ r = await withRenderSlot(
+ ["umtool", "export", p.id, clipId, kind],
+ () => exportClip(p, clipId, { take, kind, ...(context !== undefined ? { context: Number(context) } : {}), span }),
+ { estimateMb: EXPORT_ESTIMATE_MB, say },
+ );
} catch (e) {
+ if (ndjson) console.log(JSON.stringify({ ev: "export-failed", clip: clipId, kind, error: e?.message ?? String(e) }));
die(e?.message ?? String(e), 1);
}
let opened = null;
@@ -729,13 +770,32 @@ async function cmdExportClip(p, clipId) {
opened = await openFolder({ dir: path.dirname(r.abs), file: r.abs });
}
const { plan: _plan, ...view } = r;
+ if (ndjson) return console.log(JSON.stringify({ ev: "export", ...view, abs: undefined }));
if (json) return out({ ...view, ...(opened ? { opened } : {}) });
console.log(r.abs);
- console.log(` ${r.kind === "raw" ? "raw window" : "the cut's clip"}: ${r.summary} · ${(r.size / 1e6).toFixed(1)} MB`);
+ console.log(` ${r.kind === "raw" ? "raw" : r.kind === "context" ? "with context" : "the cut's clip"}: ${r.summary} · ${(r.size / 1e6).toFixed(1)} MB`);
for (const n of r.notes) console.log(` NOTE ${n}`);
if (opened) console.log(opened.ok ? ` opened ${path.dirname(r.abs)} (${opened.how})` : ` could not open the folder: ${opened.error}`);
}
+/** The bench's own fetch (driver.mjs editorFetchSteps: fetch-via-editor.mjs --fetch-only), run here with its output on stderr. */
+async function runFetchViaEditor(p, clipId, need, { take = null } = {}) {
+ const { editorFetchSteps } = await import("../lib/report/driver.mjs");
+ let manifestPath = null;
+ if (take) {
+ const { writePlayManifest } = await import("../lib/report/takeManifest.mjs");
+ manifestPath = await writePlayManifest(p.dir, take, await readManifest(p.dir));
+ }
+ const [step] = editorFetchSteps(p, clipId, { padBefore: need.padBefore, padAfter: need.padAfter }, { manifestPath });
+ const { spawn } = await import("node:child_process");
+ return new Promise((resolve) => {
+ const argvF = step.argv.filter((a, i, all) => !(a === "--progress" || all[i - 1] === "--progress"));
+ const child = spawn(process.execPath, argvF.slice(1), { cwd: step.cwd, stdio: ["ignore", "inherit", "inherit"] });
+ child.on("error", () => resolve(127));
+ child.on("close", (code) => resolve(code ?? 1));
+ });
+}
+
async function cmdCheckSources() {
// Print, never run -- the same posture as `build`. With no arguments, the
// projects the dashboard would re-check: never checked, or older than 30 d.
@@ -777,6 +837,10 @@ function usage() {
" 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 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 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]",
@@ -858,8 +922,10 @@ function usage() {
" 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> [--raw] [--take T] [--open] one clip, clean, into <project>/exports/:",
- " the cut's edges, its gaps out, its mute; --raw the whole fetched window; --open shows it",
+ " 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>",
@@ -893,6 +959,8 @@ function usage() {
" | 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",
+ " 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 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]",
@@ -1001,8 +1069,14 @@ const COMMANDS = {
trailer: async () => process.exit(await (await import("../lib/report/trailerCli.mjs")).trailerCommand(argv.slice(argv.indexOf("trailer") + 1))),
// Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs.
links: async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linksCommand(argv.slice(argv.indexOf("links") + 1))),
+ // Which named voice each clip is (UI notes #15): lib/report/speakerCheck.mjs.
+ "speaker-check": async () => process.exit(await (await import("../lib/report/speakerCheck.mjs")).speakerCheckCommand(argv.slice(argv.indexOf("speaker-check") + 1))),
+ // The project's link policy (UI notes #10): lib/report/linksCli.mjs.
+ "link-policy": async () => process.exit(await (await import("../lib/report/linksCli.mjs")).linkPolicyCommand(argv.slice(argv.indexOf("link-policy") + 1))),
// A take patch's markers back on the cut (UI notes #6): lib/report/linksCli.mjs.
"patch-markers": async () => process.exit(await (await import("../lib/report/linksCli.mjs")).patchMarkersCommand(argv.slice(argv.indexOf("patch-markers") + 1))),
+ // Tight windows: each clip to its sentence and its pauses (UI notes item 4): lib/report/tightCli.mjs.
+ tighten: async () => process.exit(await (await import("../lib/report/tightCli.mjs")).tightenCommand(argv.slice(argv.indexOf("tighten") + 1))),
// The trailer's beats, edited (UI notes item 11): lib/report/trailerBeatsCli.mjs.
"trailer-beats": async () => process.exit(await (await import("../lib/report/trailerBeatsCli.mjs")).trailerBeatsCommand(argv.slice(argv.indexOf("trailer-beats") + 1))),
// The clip deck's rulings (release 34): lib/report/rulingsCli.mjs.
diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx
@@ -19,12 +19,14 @@ import { ReaderPane, paperButtonVariants } from "@/components/ui/reader-pane";
import { citationText } from "@/lib/research/facets.mjs";
import { cn } from "@/lib/utils";
import { BenchBody, VerdictBar } from "./bench/BenchShell";
+import SpeakerBadge from "./SpeakerBadge";
import CopyCitation from "./bench/CopyCitation";
import { ClipExportButtons, ClipExportStatus, useClipExport } from "./ClipExport";
import EdgeStrip from "./bench/EdgeStrip";
import RenderGhosts, { useRenderEdges } from "./bench/RenderGhosts";
import { GapLayer, ZoomControls, ZoomOverview, ZoomRuler, useWaveZoom, type Span } from "./bench/GapsZoom";
import TakeWalkStrip from "./bench/TakeWalkStrip";
+import { TightenButtons, useEdgeTools, type BenchWord } from "./bench/TightenTools";
// The renderer's own line, imported rather than re-written. A preview that
// disagrees with the header by a character is worth less than no preview: you
// would only find out twenty minutes into a build.
@@ -551,6 +553,8 @@ export default function ClipBench({
// Export clip (ClipExport.tsx): this clip, clean, into the project's exports/ -- the take's clip on a take's walk.
const clipExport = useClipExport(data.project, takeId);
const [clip, setClip] = useState<Clip>(data.clip);
+ // Export ▾'s full exchange starts from the clip's saved extent.
+ const clipAround = useMemo(() => ({ start: clip.start, end: clip.end }), [clip.start, clip.end]);
const [windows, setWindows] = useState<Win[]>(data.windows);
const [cues, setCues] = useState<Cue[]>(data.cues);
const [proposed, setProposed] = useState(data.proposed);
@@ -1612,6 +1616,28 @@ export default function ClipBench({
[doSave],
);
+ // Tighten to the sentence, snap an edge to its pause (bench/TightenTools.tsx):
+ // written at once through `save`, with an Undo.
+ const readCues = useMemo(() => {
+ const seen = new Set<number>();
+ return [...cues, ...peek].filter((c) => (seen.has(c.start) ? false : (seen.add(c.start), true))).sort((a, b) => a.start - b.start);
+ }, [cues, peek]);
+ const edgeTools = useEdgeTools({
+ project: data.project,
+ clip,
+ video: clip.video,
+ sel,
+ playhead,
+ cues: readCues,
+ silences: renderEdges?.silences ?? null,
+ lo: fetchStart,
+ hi: clampTo,
+ save,
+ lastSaved,
+ play,
+ setNote,
+ });
+
/**
* Persist one attribution field, on blur or Enter, if it actually changed.
*
@@ -2004,7 +2030,7 @@ export default function ClipBench({
// whole window, today's view -- on every clip's arrival.
const zoom = useWaveZoom(view);
// Close in: the pauses between words, when the project has its words for this recording (the clip editor's).
- const [nearWords, setNearWords] = useState<{ key: string; words: { start: number; end: number }[] | null } | null>(null);
+ const [nearWords, setNearWords] = useState<{ key: string; words: BenchWord[] | null } | null>(null);
const close = zoom.vis.to - zoom.vis.from <= DETAIL_SPAN;
const wordsKey = close ? `${clip.id}|${Math.floor(zoom.vis.from / 10) * 10}|${Math.ceil(zoom.vis.to / 10) * 10}` : null;
useEffect(() => {
@@ -2013,7 +2039,7 @@ export default function ClipBench({
const [, a, b] = wordsKey.split("|");
const q = new URLSearchParams({ project: data.project, clip: clip.id, from: a, to: b, video: clip.video });
fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" })
- .then((r) => (r.ok ? (r.json() as Promise<{ words?: { start: number; end: number }[] | null }>) : null))
+ .then((r) => (r.ok ? (r.json() as Promise<{ words?: BenchWord[] | null }>) : null))
.then((j) => {
if (live) setNearWords({ key: wordsKey, words: j?.words ?? null });
})
@@ -2725,6 +2751,8 @@ export default function ClipBench({
>
{verdictLabel(clip)}
</span>
+ {/* Which named voice it is (UI notes #15): the speaker check's row, and Check speaker. */}
+ <SpeakerBadge project={data.project} clip={clip.id} />
</VerdictBar>
);
@@ -2770,7 +2798,7 @@ export default function ClipBench({
>
Play clip
</button>
- <ClipExportButtons exp={clipExport} clip={clip.id} surface="paper" why={cached ? null : "its window is not fetched — fetch it first"} unsaved={unsaved} />
+ <ClipExportButtons exp={clipExport} clip={clip.id} surface="paper" why={cached ? null : "its window is not fetched — fetch it first"} unsaved={unsaved} around={clipAround} align="end" />
<ClipExportStatus exp={clipExport} surface="paper" />
</>
}
@@ -3820,6 +3848,7 @@ export default function ClipBench({
</button>
)}
</span>
+ <TightenButtons tools={edgeTools} busy={!!busy} />
<span className="micro max-md:hidden">
<kbd>z</kbd> <kbd>Z</kbd> zoom (or Ctrl/⌘ + wheel), <kbd>f</kbd> fit, <kbd>F</kbd> to the selection ·{" "}
<kbd>g</kbd> (or Alt + drag) select a gap, <kbd>g</kbd> cut it, <kbd>G</kbd> put back the one at the playhead
diff --git a/umtool/components/projects/ClipExport.tsx b/umtool/components/projects/ClipExport.tsx
@@ -19,9 +19,16 @@ import { cn } from "@/lib/utils";
// the server says when it cannot, and why). The bench's reader footer and
// Play the cut both use it; Play exports the clip at the playhead, or the one
// a note points at, through one `useClipExport`.
+//
+// EXPORT ▾ (UI notes 2026-10-30, item 12): as cut (no chrome), with N s of
+// context, raw / full exchange (a span, fetched through the editor first when
+// it is not on disk). Every export is a umtool job (POST answers 202 and the
+// job; this polls it), in the machine's heavy slot. No "send to phone": no
+// share path exists in umtool -- Download is the phone's way.
// ---------------------------------------------------------------------------
-export type ClipExportKind = "cut" | "raw";
+export type ClipExportKind = "cut" | "context" | "raw";
+export type ClipExportOpts = { context?: number; span?: { from: number; to: number } | null; fetch?: boolean };
type Done = {
clip: string;
@@ -39,14 +46,14 @@ type Done = {
export type ClipExportState =
| { k: "idle" }
- | { k: "exporting"; clip: string; kind: ClipExportKind; since: number }
+ | { k: "exporting"; clip: string; kind: ClipExportKind; since: number; fetching?: boolean; line?: string | null }
| { k: "ready"; done: Done; open: { k: "idle" } | { k: "opening" } | { k: "opened"; how: string } | { k: "failed"; error: string } }
| { k: "failed"; clip: string; kind: ClipExportKind; error: string };
export type ClipExportHandle = {
state: ClipExportState;
busy: boolean;
- run: (clip: string, kind?: ClipExportKind) => Promise<void>;
+ run: (clip: string, kind?: ClipExportKind, opts?: ClipExportOpts) => Promise<void>;
openFolder: () => Promise<void>;
dismiss: () => void;
};
@@ -59,21 +66,51 @@ export function useClipExport(project: string, take: string | null = null): Clip
const seq = useRef(0);
const busy = state.k === "exporting";
const run = useCallback(
- async (clip: string, kind: ClipExportKind = "cut") => {
+ async (clip: string, kind: ClipExportKind = "cut", opts: ClipExportOpts = {}) => {
const mine = ++seq.current;
- setState({ k: "exporting", clip, kind, since: Date.now() });
+ const since = Date.now();
+ setState({ k: "exporting", clip, kind, since });
+ const fail = (error: string) => {
+ if (mine === seq.current) setState({ k: "failed", clip, kind, error });
+ };
try {
const r = await fetch("/api/report/clip-export", {
method: "POST",
headers: { "content-type": "application/json" },
- body: JSON.stringify({ project, clip, kind, ...(take ? { take } : {}) }),
+ body: JSON.stringify({
+ project,
+ clip,
+ kind,
+ ...(take ? { take } : {}),
+ ...(kind === "context" && opts.context != null ? { context: opts.context } : {}),
+ ...(kind === "raw" && opts.span ? { span: opts.span } : {}),
+ ...(opts.fetch ? { fetch: true } : {}),
+ }),
});
- const j = (await r.json().catch(() => ({}))) as Partial<Done> & { error?: string };
+ const j = (await r.json().catch(() => ({}))) as { error?: string; fetching?: boolean; job?: { id: string } };
if (mine !== seq.current) return;
- if (!r.ok || !j.name) setState({ k: "failed", clip, kind, error: String(j.error ?? `HTTP ${r.status}`) });
- else setState({ k: "ready", done: { ...(j as Done), clip, kind }, open: { k: "idle" } });
+ if (!r.ok || !j.job?.id) return fail(String(j.error ?? `HTTP ${r.status}`));
+ const job = j.job.id;
+ setState({ k: "exporting", clip, kind, since, fetching: !!j.fetching });
+ // The job: polled until its export event (or its failure) is in.
+ for (;;) {
+ await new Promise((res) => setTimeout(res, 700));
+ if (mine !== seq.current) return;
+ const g = await fetch(`/api/report/clip-export?job=${encodeURIComponent(job)}`, { cache: "no-store" });
+ const v = (await g.json().catch(() => ({}))) as { done?: Done; error?: string; job?: { state: string; stepIndex: number; steps: unknown[]; log: string[] } };
+ if (mine !== seq.current) return;
+ if (v.done) {
+ setState({ k: "ready", done: { ...v.done, clip, kind }, open: { k: "idle" } });
+ return;
+ }
+ if (v.error || !g.ok) return fail(String(v.error ?? `HTTP ${g.status}`));
+ if (v.job && v.job.state !== "running") return fail(v.job.state === "done" ? "the job ended without an export" : `the job ${v.job.state}`);
+ const fetching = !!j.fetching && (v.job?.stepIndex ?? 0) < (v.job?.steps.length ?? 1) - 1;
+ const line = v.job?.log.filter((l) => !l.startsWith("$ ") && !l.startsWith("---")).at(-1) ?? null;
+ setState({ k: "exporting", clip, kind, since, fetching, line });
+ }
} catch (e) {
- if (mine === seq.current) setState({ k: "failed", clip, kind, error: e instanceof Error ? e.message : String(e) });
+ fail(e instanceof Error ? e.message : String(e));
}
},
[project, take],
@@ -111,27 +148,34 @@ const btn = (surface: Surface, quiet = false) =>
? paperButtonVariants()
: buttonVariants({ variant: quiet ? "quiet" : "outline", size: "sm" });
-/** Export clip, and its raw choice, for `clip` (null: nothing to export here, `why` says so). */
+/** Export clip, its raw choice, and Export ▾, for `clip` (null: nothing to export here, `why` says so). */
export function ClipExportButtons({
exp,
clip,
surface = "panel",
why = null,
unsaved = false,
+ around = null,
+ align = "start",
}: {
exp: ClipExportHandle;
clip: string | null;
surface?: Surface;
- /** Why there is nothing to export (a card, a window not fetched): the buttons are off and say so. */
+ /** Why there is nothing to export (a card, a window not fetched): the cut and raw buttons are off and say so. */
why?: string | null;
/** The bench has an edit not saved yet: the export is of the SAVED clip. */
unsaved?: boolean;
+ /** The clip's extent (source seconds): the full exchange's span starts from it. */
+ around?: { start: number; end: number } | null;
+ /** Which edge of Export ▾ its options open from: "end" on the bench's reader, at the screen's right edge. */
+ align?: "start" | "end";
}) {
const hydrated = useHydrated();
const off = !hydrated || !clip || !!why || exp.busy;
const saved = unsaved ? " — of the SAVED window: save first to export your edit" : "";
return (
<>
+ <ExportMenu exp={exp} clip={clip} surface={surface} around={around} saved={saved} align={align} disabled={!hydrated || !clip || exp.busy} />
<button
type="button"
data-clip-export-go={clip ?? ""}
@@ -156,6 +200,124 @@ export function ClipExportButtons({
);
}
+const CONTEXT_DEFAULT = 5;
+const r1 = (n: number) => Math.round(n * 10) / 10;
+
+/**
+ * Export ▾: the three kinds (UI notes item 12) in one place -- as cut (no
+ * chrome), with N s of context, raw / full exchange over a span. Context and
+ * the full exchange are fetched through the editor first when what they need
+ * is not on disk (`fetch: true`; the job says so while it fetches).
+ */
+function ExportMenu({
+ exp,
+ clip,
+ surface,
+ around,
+ saved,
+ align,
+ disabled,
+}: {
+ exp: ClipExportHandle;
+ clip: string | null;
+ surface: Surface;
+ around: { start: number; end: number } | null;
+ saved: string;
+ align: "start" | "end";
+ disabled: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+ const [ctx, setCtx] = useState(String(CONTEXT_DEFAULT));
+ const [from, setFrom] = useState("");
+ const [to, setTo] = useState("");
+ const box = useRef<HTMLDivElement | null>(null);
+ // A new clip: the span starts from its extent again.
+ useEffect(() => {
+ setFrom(around ? String(r1(Math.max(0, around.start - 30))) : "");
+ setTo(around ? String(r1(around.end + 30)) : "");
+ }, [clip, around?.start, around?.end]); // eslint-disable-line react-hooks/exhaustive-deps
+ useEffect(() => {
+ if (!open) return;
+ const away = (e: PointerEvent) => {
+ if (box.current && !box.current.contains(e.target as Node)) setOpen(false);
+ };
+ const esc = (e: KeyboardEvent) => {
+ if (e.key === "Escape") setOpen(false);
+ };
+ window.addEventListener("pointerdown", away);
+ window.addEventListener("keydown", esc);
+ return () => {
+ window.removeEventListener("pointerdown", away);
+ window.removeEventListener("keydown", esc);
+ };
+ }, [open]);
+ const n = Number(ctx);
+ const ctxOk = Number.isFinite(n) && n >= 1 && n <= 120;
+ const a = Number(from);
+ const b = Number(to);
+ const spanOk = from.trim() !== "" && to.trim() !== "" && Number.isFinite(a) && Number.isFinite(b) && a >= 0 && b - a >= 0.5;
+ const go = (kind: ClipExportKind, opts: ClipExportOpts = {}) => {
+ if (!clip) return;
+ setOpen(false);
+ void exp.run(clip, kind, opts);
+ };
+ const input = "w-16 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 font-mono text-[11px] text-[var(--color-text)]";
+ const item = buttonVariants({ variant: "outline", size: "sm" });
+ return (
+ <div ref={box} className="relative inline-flex" data-clip-export-menu-box="">
+ <button
+ type="button"
+ data-clip-export-menu={clip ?? ""}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ className={btn(surface)}
+ disabled={disabled}
+ title="Export ▾: as cut (no chrome), with N s of context, raw / full exchange — each a job in the heavy slot, into exports/"
+ onClick={() => setOpen((v) => !v)}
+ >
+ Export ▾
+ </button>
+ {open && (
+ <div
+ role="menu"
+ aria-label={`export ${clip ?? ""}`}
+ data-clip-export-options=""
+ className={`absolute bottom-full ${align === "end" ? "right-0" : "left-0"} z-30 mb-1 flex w-[19rem] max-w-[calc(100vw-2rem)] flex-col gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] p-2 text-[12px] text-[var(--color-text)] shadow-lg`}
+ >
+ <div className="flex flex-col gap-0.5">
+ <button type="button" role="menuitem" data-clip-export-kind="cut" className={item} onClick={() => go("cut")} title={`the clip as the cut plays it: its edges, gaps out, its mute; no deck${saved}`}>
+ As cut (no chrome)
+ </button>
+ <span className="text-[10.5px] text-[var(--color-dim)]">its edges, gaps out as jump cuts, its mute — no rail, subtitles, QR or cards</span>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="flex flex-wrap items-center gap-1.5">
+ <button type="button" role="menuitem" data-clip-export-kind="context" className={item} disabled={!ctxOk} onClick={() => go("context", { context: n, fetch: true })}>
+ With context
+ </button>
+ <input aria-label="seconds of context either side" data-clip-export-context="" className={input} inputMode="decimal" value={ctx} onChange={(e) => setCtx(e.target.value)} />
+ <span className="text-[11px] text-[var(--color-dim)]">s either side</span>
+ </span>
+ <span className="text-[10.5px] text-[var(--color-dim)]">what the cut plays and {ctxOk ? n : "N"} s around it, as recorded (1–120; fetched first if not on disk)</span>
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="flex flex-wrap items-center gap-1.5">
+ <button type="button" role="menuitem" data-clip-export-kind="raw" className={item} disabled={!spanOk} onClick={() => go("raw", { span: { from: r1(a), to: r1(b) }, fetch: true })}>
+ Raw / full exchange
+ </button>
+ <input aria-label="from (source seconds)" data-clip-export-from="" className={input} inputMode="decimal" value={from} onChange={(e) => setFrom(e.target.value)} />
+ <span aria-hidden>–</span>
+ <input aria-label="to (source seconds)" data-clip-export-to="" className={input} inputMode="decimal" value={to} onChange={(e) => setTo(e.target.value)} />
+ </span>
+ <span className="text-[10.5px] text-[var(--color-dim)]">source seconds, as recorded (no gaps, no mute) — what is not on disk is fetched through the editor first</span>
+ </div>
+ <span className="text-[10.5px] text-[var(--color-dim)]">named <clip>-<kind>-<date>-<words>.mp4 in the project’s exports/ · Download for a phone</span>
+ </div>
+ )}
+ </div>
+ );
+}
+
/** Exporting… / the file, Download, Open folder / failed, with the reason. */
export function ClipExportStatus({ exp, surface = "panel", className }: { exp: ClipExportHandle; surface?: Surface; className?: string }) {
const s = exp.state;
@@ -172,8 +334,10 @@ export function ClipExportStatus({ exp, surface = "panel", className }: { exp: C
if (s.k === "exporting") {
return (
<p role="status" className={cn(base, "m-0")} data-clip-export-state="exporting">
- Exporting {s.clip}
- {s.kind === "raw" ? " (raw window)" : ""}… <span className={cn("font-mono", muted)}>{Math.max(0, Math.round((Date.now() - s.since) / 1000))} s</span>
+ {s.fetching ? "Fetching what it needs through the editor, then exporting " : "Exporting "}
+ {s.clip}
+ {s.kind === "raw" ? " (raw)" : s.kind === "context" ? " (with context)" : ""}… <span className={cn("font-mono", muted)}>{Math.max(0, Math.round((Date.now() - s.since) / 1000))} s</span>
+ {s.line ? <span className={cn("ml-1 font-mono", muted)}>{s.line.slice(0, 120)}</span> : null}
</p>
);
}
diff --git a/umtool/components/projects/NewTakePanel.tsx b/umtool/components/projects/NewTakePanel.tsx
@@ -6,6 +6,7 @@ import { buttonVariants } from "@/components/ui/button";
import { Field, Input, Select, Textarea } from "@/components/ui/field";
import { JobProgress, type JobStepState } from "@/components/ui/job-progress";
import RenderModeBanner, { renderPriorityPref } from "./RenderModeBanner";
+import RenderQueuePanel from "./RenderQueuePanel";
// New take, Make all styles -- and the job either starts (or a card's Rebuild
// starts), watched here until it ends, then the page re-reads the takes.
@@ -162,6 +163,7 @@ export default function NewTakePanel({
return (
<section data-new-take="" className="space-y-2">
<RenderModeBanner />
+ <RenderQueuePanel project={project} />
<details className="rounded border border-[var(--color-line)] bg-[var(--color-panel)]">
<summary data-action="new-take-open" className="cursor-pointer px-3 py-2 text-[12.5px] text-text">
New take
diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -7,6 +7,7 @@ import ClipBenchPage from "./ClipBenchPage";
import ClaimBenchPage from "./ClaimBenchPage";
import SweepProject from "./SweepProject";
import TakesPage from "./TakesPage";
+import TakesComparePage from "./TakesComparePage";
import NarrationPage from "./NarrationPage";
import ReviewPage from "./ReviewPage";
import ClipDeckPage from "./ClipDeckPage";
@@ -61,6 +62,9 @@ export default async function ProjectView({
// `/browse/<project>/takes` -- alternative renders of one part of the
// cut, side by side, each judged like / maybe / no.
if (rest.length === 1 && rest[0] === "takes") return <TakesPage project={project} />;
+ // `/projects/<project>/takes/compare?a=<project>:<take>&b=…` -- two takes of the project
+ // or of its variants side by side, in step, with what differs (UI notes item 19).
+ if (rest.length === 2 && rest[0] === "takes" && rest[1] === "compare") return <TakesComparePage project={project} search={search} />;
// `/projects/<project>/takes/<take>/walk` -- walk a take: its clips, and
// where the walk starts; `…/takes/<take>/clip/<id>` -- the bench on one
// of them, its saves going into the take's patch, never the manifest.
diff --git a/umtool/components/projects/RenderQueuePanel.tsx b/umtool/components/projects/RenderQueuePanel.tsx
@@ -0,0 +1,194 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+// THE RENDER QUEUE on the take panel (UI notes 2026-10-30, #18): what runs in
+// the machine's heavy slot and what waits at it -- e2e suites, next builds,
+// renders -- read from the slot's own files (GET /api/render-queue,
+// common/lib/heavyQueue.mjs), and how long a take of this project renders,
+// from its past renders (lib/report/takeEta.mjs). "Give renders the machine"
+// beside it (RenderModeBanner) is what sends the others to wait at the door.
+
+type Row = {
+ pid: number;
+ what: string;
+ kind: string;
+ estimateMb: number | null;
+ build: boolean;
+ alone: boolean;
+ worktree: string | null;
+ branch: string | null;
+ since: string | null;
+ forSeconds: number | null;
+ stage?: string;
+ stageWords?: string;
+ take?: string;
+};
+type Eta = { etaSeconds: number; rate: number; basis: { id: string; seconds: number; renderSeconds: number; how: string }[]; note: string | null };
+type View = {
+ queue: {
+ running: Row[];
+ waiting: Row[];
+ head: Row | null;
+ suites: (Row & { suite: string })[];
+ render: { held: boolean; what?: string };
+ memory: { availableMb: number; totalMb: number | null; floorMb: number; promisedMb: number } | null;
+ heldBy: string | null;
+ };
+ etas: { seconds: number | null; newest: string | null; fresh: Eta | null; reuse: Eta | null; past: unknown[] } | null;
+ mine: { pid: number; take: string | null; state: "running" | "waiting"; forSeconds: number | null; stage?: string }[];
+};
+
+const dur = (s: number | null | undefined) => {
+ if (s == null || !Number.isFinite(s)) return "—";
+ if (s < 90) return `${Math.round(s)} s`;
+ const m = Math.round(s / 60);
+ return m >= 60 ? `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, "0")} min` : `${m} min`;
+};
+const gb = (mb: number) => `${(mb / 1000).toFixed(1)} GB`;
+const clock = (s: number) => `${Math.floor(s / 60)}:${String(Math.round(s % 60)).padStart(2, "0")}`;
+
+function RowLine({ r, waiting }: { r: Row; waiting?: boolean }) {
+ return (
+ <li
+ data-queue-row={r.kind}
+ data-queue-state={waiting ? "waiting" : "running"}
+ data-queue-pid={r.pid}
+ className="flex flex-wrap items-baseline gap-x-2 border-b border-seam py-1 text-[12px]"
+ >
+ <span className="text-text">{r.what}</span>
+ {r.worktree && (
+ <span className="font-mono text-[11px] text-muted">
+ {r.worktree}
+ {r.branch && r.branch !== r.worktree ? ` (${r.branch})` : ""}
+ </span>
+ )}
+ <span className="font-mono text-[11px] text-meter">
+ {r.estimateMb ? `${gb(r.estimateMb)}` : r.alone ? "alone" : "no estimate"}
+ {r.build ? " · a build" : ""}
+ </span>
+ {waiting && r.stageWords && <span className="text-[11.5px] text-doubt-text">{r.stageWords}</span>}
+ <span className="ml-auto font-mono text-[11px] text-muted">{waiting ? "waiting " : ""}{dur(r.forSeconds)}</span>
+ </li>
+ );
+}
+
+export default function RenderQueuePanel({ project }: { project: string }) {
+ const [view, setView] = useState<View | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let alive = true;
+ const look = () =>
+ fetch(`/api/render-queue?project=${encodeURIComponent(project)}`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
+ .then((j: View) => {
+ if (!alive) return;
+ setView(j);
+ setError(null);
+ })
+ .catch((e: unknown) => alive && setError(e instanceof Error ? e.message : String(e)));
+ void look();
+ const t = setInterval(look, 5000);
+ return () => {
+ alive = false;
+ clearInterval(t);
+ };
+ }, [project]);
+
+ if (!view) {
+ return error ? (
+ <p data-render-queue-error="" className="text-[12px] text-muted">
+ The render queue could not be read: {error}
+ </p>
+ ) : null;
+ }
+ const { queue, etas, mine } = view;
+ const busy = queue.running.length > 0 || queue.waiting.length > 0;
+ return (
+ <section data-render-queue={busy ? "busy" : "idle"} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
+ <div className="flex flex-wrap items-baseline gap-2">
+ <h2 className="micro">Render queue</h2>
+ <span data-render-queue-held-by="" className="text-[12px] text-text-2">
+ {queue.render.held
+ ? `held for a render: ${queue.render.what}`
+ : queue.heldBy
+ ? `held by ${queue.heldBy}`
+ : "the heavy slot is free"}
+ </span>
+ {queue.memory && (
+ <span className="ml-auto font-mono text-[11px] text-muted" title="MemAvailable, the floor a job is admitted above, and what the running jobs declared">
+ {gb(queue.memory.availableMb)} available · floor {gb(queue.memory.floorMb)}
+ {queue.memory.promisedMb ? ` · ${gb(queue.memory.promisedMb)} promised` : ""}
+ </span>
+ )}
+ </div>
+ {queue.running.length > 0 && (
+ <ul data-render-queue-running={queue.running.length} className="mt-1">
+ {queue.running.map((r) => (
+ <RowLine key={`r${r.pid}`} r={r} />
+ ))}
+ </ul>
+ )}
+ {queue.waiting.length > 0 && (
+ <ul data-render-queue-waiting={queue.waiting.length} className="mt-1">
+ {queue.waiting.map((r) => (
+ <RowLine key={`w${r.pid}`} r={r} waiting />
+ ))}
+ </ul>
+ )}
+ {queue.suites.filter((s) => !queue.running.some((r) => r.pid === s.pid) && !queue.waiting.some((r) => r.pid === s.pid)).length > 0 && (
+ <p className="mt-1 text-[11.5px] text-muted">
+ e2e queues held:{" "}
+ {queue.suites
+ .filter((s) => !queue.running.some((r) => r.pid === s.pid) && !queue.waiting.some((r) => r.pid === s.pid))
+ .map((s) => `${s.suite} (${s.worktree ?? "?"}, building or about to ask for the slot)`)
+ .join(", ")}
+ </p>
+ )}
+ {mine.length > 0 && (
+ <p data-render-queue-mine="" className="mt-1 text-[12px] text-text-2">
+ {mine
+ .map((m) => `${m.take ?? "this project's render"}: ${m.state === "running" ? `rendering for ${dur(m.forSeconds)}` : `waiting ${dur(m.forSeconds)} — ${m.stage}`}`)
+ .join(" · ")}
+ </p>
+ )}
+ <div data-take-eta={etas?.fresh || etas?.reuse ? "known" : "unknown"} className="mt-1.5 text-[12px] text-text-2">
+ {etas?.seconds && (etas.fresh || etas.reuse) ? (
+ <>
+ <span>
+ A whole-cut take ({clock(etas.seconds)} of video):{" "}
+ {etas.reuse && (
+ <span data-take-eta-reuse={etas.reuse.etaSeconds}>
+ ~{dur(etas.reuse.etaSeconds)} made from {etas.newest} (reuse)
+ </span>
+ )}
+ {etas.reuse && etas.fresh ? " · " : ""}
+ {etas.fresh && <span data-take-eta-fresh={etas.fresh.etaSeconds}>~{dur(etas.fresh.etaSeconds)} fresh</span>}
+ </span>
+ <details className="mt-0.5">
+ <summary className="cursor-pointer text-[11.5px] text-muted">
+ from {new Set([...(etas.reuse?.basis ?? []), ...(etas.fresh?.basis ?? [])].map((b) => b.id)).size} past render(s) of this project
+ </summary>
+ <ul className="mt-0.5 font-mono text-[11px] text-muted">
+ {[...(etas.reuse?.basis.map((b) => ({ ...b, k: "reuse" })) ?? []), ...(etas.fresh?.basis.map((b) => ({ ...b, k: "fresh" })) ?? [])].map((b) => (
+ <li key={`${b.k}-${b.id}`}>
+ {b.id} ({b.k}): {clock(b.seconds)} of video in {dur(b.renderSeconds)}
+ {b.how === "files" ? " (from its files' times)" : ""}
+ </li>
+ ))}
+ </ul>
+ {[etas.reuse?.note, etas.fresh?.note].filter(Boolean).map((n) => (
+ <p key={n} className="text-[11px] text-muted">
+ {n}
+ </p>
+ ))}
+ </details>
+ </>
+ ) : (
+ <span className="text-muted">No ETA yet: no past render of this project says how long it took.</span>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/umtool/components/projects/SpeakerBadge.tsx b/umtool/components/projects/SpeakerBadge.tsx
@@ -0,0 +1,180 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+
+// THE SPEAKER BADGE ON THE WALK (UI notes 2026-10-30, #15): "Speaker: matches
+// Ember 0.93 / Kirsche 0.83", with the reference sets it was measured against,
+// and "Check speaker", which queues `umtool speaker-check <p> --clip <id>` as
+// a job through the machine's heavy slot (POST /api/report/speaker-check). The
+// voices are the project's speakers.json; "Add to a voice" puts this clip in
+// one. An aid to the ear: the verdict is still the walk's.
+
+type Score = { name: string; score: number; best: number | null; inReference?: boolean };
+type Badge = {
+ speakers: { name: string; clips: string[]; videos: string[]; channels: string[]; inReference: boolean }[];
+ result: null | { scores: Score[]; label?: "matches" | "unsure" | "none"; best?: string; margin?: number | null; why?: string; line: string; madeAt: string | null; speechSeconds?: number };
+ reference: null | { name: string; pieces: number; kept: number; clips: string[]; recordings: { channel: string; video: string }[] }[];
+ running: null | { id: string; state: string };
+ error?: string;
+};
+type JobPoll = { id: string; state: "running" | "done" | "failed"; error: string | null; log: string[] };
+
+export default function SpeakerBadge({ project, clip }: { project: string; clip: string }) {
+ const [badge, setBadge] = useState<Badge | null>(null);
+ const [job, setJob] = useState<JobPoll | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+ const [voice, setVoice] = useState("");
+ const [adding, setAdding] = useState(false);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/speaker-check?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(clip)}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => null)) as Badge | null;
+ if (!r.ok || !j) {
+ setErr(j?.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ setBadge(j);
+ }, [project, clip]);
+
+ useEffect(() => {
+ void load();
+ return () => {
+ if (timer.current) clearTimeout(timer.current);
+ };
+ }, [load]);
+
+ const follow = useCallback(
+ (id: string) => {
+ const tick = async () => {
+ const r = await fetch(`/api/report/speaker-check?job=${encodeURIComponent(id)}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => null)) as JobPoll | null;
+ if (!j) return;
+ setJob(j);
+ if (j.state === "running") timer.current = setTimeout(() => void tick(), 1000);
+ else void load();
+ };
+ void tick();
+ },
+ [load],
+ );
+
+ const check = async () => {
+ setErr(null);
+ const r = await fetch("/api/report/speaker-check", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, clip }),
+ });
+ const j = (await r.json().catch(() => ({}))) as { job?: { id: string }; error?: string };
+ if (!r.ok || !j.job) {
+ setErr(j.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ follow(j.job.id);
+ };
+
+ const addTo = async () => {
+ const name = voice.trim();
+ if (!name) return;
+ setErr(null);
+ const r = await fetch("/api/report/speaker-check", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, clip, addTo: name }),
+ });
+ const j = (await r.json().catch(() => ({}))) as { error?: string };
+ if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`);
+ setVoice("");
+ setAdding(false);
+ void load();
+ };
+
+ if (!badge) return err ? <span data-speaker-badge="error" className="text-[11.5px] text-doubt-text">{err}</span> : null;
+ const res = badge.result;
+ const running = job?.state === "running" || (!!badge.running && !job);
+ const label = res?.label ?? (res ? "unscored" : "unchecked");
+ const tone = label === "matches" ? "text-[var(--color-good)]" : label === "none" ? "text-[var(--color-dirty)]" : "text-text-2";
+ const mine = badge.speakers.find((s) => s.inReference);
+ const refWords = (badge.reference ?? badge.speakers.map((s) => ({ name: s.name, pieces: s.clips.length + s.videos.length, kept: 0, clips: s.clips, recordings: [] })))
+ .map((s) => `${s.name}: ${s.pieces} piece${s.pieces === 1 ? "" : "s"}${s.kept ? ` (${s.kept} kept)` : ""}`)
+ .join(" · ");
+
+ // Compact: one line in the verdict bar (the bench is a one-screen layout at
+ // 1366×768 -- clip-bench.spec), the voice box only when asked for.
+ const refShort = (badge.reference ?? badge.speakers.map((s) => ({ name: s.name, pieces: s.clips.length + s.videos.length })))
+ .map((s) => `${s.name} ${s.pieces}`)
+ .join(" · ");
+ return (
+ <span data-speaker-badge={label} className="inline-flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]">
+ <span data-speaker-line="" className={tone} title={refWords ? `measured against: ${refWords}` : undefined}>
+ Speaker: {res ? res.line : badge.speakers.length ? "not checked" : "no voices named"}
+ </span>
+ {res && (
+ <span
+ data-speaker-reference=""
+ className="text-[11px] text-muted"
+ title={`measured against: ${refWords}${res.madeAt ? ` · ${res.madeAt.slice(0, 16).replace("T", " ")}` : ""}`}
+ >
+ vs {refShort || "—"}
+ </span>
+ )}
+ {mine && <span className="text-[11px] text-muted">in {mine.name}’s voice</span>}
+ <button
+ type="button"
+ data-speaker-check=""
+ disabled={running || !badge.speakers.length}
+ onClick={() => void check()}
+ className={buttonVariants({ variant: "quiet", size: "sm" })}
+ title={
+ badge.speakers.length
+ ? "scores this clip's voice against each named voice (TitaNet-small, local) as a job through the heavy slot"
+ : "name the voices first: + voice, or umtool speaker-check <p> --set 'Name=…'"
+ }
+ >
+ {running ? "Checking…" : "Check speaker"}
+ </button>
+ {adding ? (
+ <span className="inline-flex items-center gap-1">
+ <input
+ data-speaker-voice=""
+ list={`voices-${clip}`}
+ value={voice}
+ autoFocus
+ onChange={(e) => setVoice(e.target.value)}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === "Enter") void addTo();
+ if (e.key === "Escape") setAdding(false);
+ }}
+ placeholder="voice name"
+ className="w-[7.5rem] rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px]"
+ />
+ <datalist id={`voices-${clip}`}>
+ {badge.speakers.map((s) => (
+ <option key={s.name} value={s.name} />
+ ))}
+ </datalist>
+ <button type="button" data-speaker-add="" disabled={!voice.trim()} onClick={() => void addTo()} className={buttonVariants({ variant: "quiet", size: "sm" })} title="this clip is that voice: it joins the voice's reference set (speakers.json)">
+ Add
+ </button>
+ </span>
+ ) : (
+ <button type="button" data-speaker-add-open="" onClick={() => setAdding(true)} className={buttonVariants({ variant: "quiet", size: "sm" })} title="this clip is a known voice: add it to that voice's reference set (speakers.json)">
+ + voice
+ </button>
+ )}
+ {job?.state === "failed" && (
+ <span data-speaker-error="" className="text-[11.5px] text-doubt-text">
+ {job.error ?? job.log.at(-1) ?? "the check failed"}
+ </span>
+ )}
+ {err && (
+ <span data-speaker-error="" className="text-[11.5px] text-doubt-text">
+ {err}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/umtool/components/projects/TakeVariants.tsx b/umtool/components/projects/TakeVariants.tsx
@@ -0,0 +1,231 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import DeletePlan from "@/components/DeletePlan";
+import { buttonVariants } from "@/components/ui/button";
+import { takesCompareHref, takesHref } from "@/lib/hrefs";
+
+// ---------------------------------------------------------------------------
+// TAKE HOUSEKEEPING, the rest of it (UI notes 2026-10-30, item 19): Cancel a
+// take while it renders (lib/report/takeCancel.mjs), Fork as variant
+// (variantFork.mjs: a project beside this one), Compare with… (two takes of
+// the project and its variants side by side: /projects/<p>/takes/compare).
+// All through POST /api/report/takes/housekeeping, as relabel and supersede.
+// ---------------------------------------------------------------------------
+
+export type CompareOption = { ref: string; label: string };
+export type WorkDirs = {
+ rendering: Array<{ id: string; label: string | null; pid: number | null; startedAt: string | null; from: string | null }>;
+ cancelled: Array<{ id: string; label: string | null; at: string; by: string }>;
+};
+
+const sm = buttonVariants({ size: "sm" });
+const smOutline = buttonVariants({ variant: "outline", size: "sm" });
+
+async function housekeeping(body: Record<string, unknown>) {
+ const r = await fetch("/api/report/takes/housekeeping", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ cache: "no-store",
+ });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown> & { error?: string };
+ return { ok: r.ok, j };
+}
+
+export type CancelSaid = { take: string; text: string; ok: boolean };
+
+/**
+ * Cancel: asks the process rendering the take to stop, and waits for it (up to ~25 s).
+ * The answer goes to `onSaid` -- held by a parent that outlives this button, because a
+ * render that stopped is no longer rendering, and the refresh takes the button away.
+ */
+export function CancelRender({ project, take, ready, onSaid }: { project: string; take: string; ready: boolean; onSaid: (s: CancelSaid) => void }) {
+ const router = useRouter();
+ const [busy, setBusy] = useState(false);
+ return (
+ <span className="inline-flex flex-wrap items-center gap-1.5" data-take-cancel={take}>
+ <button
+ type="button"
+ data-action="cancel-render"
+ disabled={!ready || busy}
+ className={`${buttonVariants({ variant: "outline", size: "sm" })} border-[var(--color-bad)] text-[var(--color-bad)]`}
+ title="stop this take's render: the process rendering it stops its render, marks the take cancelled and lets render mode go if the take held it"
+ onClick={async () => {
+ setBusy(true);
+ const { ok, j } = await housekeeping({ project, take, op: "cancel" });
+ setBusy(false);
+ onSaid({ take, ok: ok && j.stopped === true, text: String(j.said ?? j.error ?? (ok ? "asked" : "refused")) });
+ router.refresh();
+ }}
+ >
+ {busy ? "Cancelling…" : "Cancel render"}
+ </button>
+ </span>
+ );
+}
+
+/** What the last Cancel render said. */
+export function CancelSaidLine({ said }: { said: CancelSaid | null }) {
+ if (!said) return null;
+ return (
+ <p role="status" data-take-cancel-said={said.take} className={`m-0 text-[11.5px] ${said.ok ? "text-text-2" : "text-reject-text"}`}>
+ {said.text}
+ </p>
+ );
+}
+
+/** Fork as variant: the take as a project beside this one (default name v-<take>). */
+export function ForkVariant({ project, take, ready }: { project: string; take: string; ready: boolean }) {
+ const [open, setOpen] = useState(false);
+ const [name, setName] = useState(`v-${take}`);
+ const [busy, setBusy] = useState(false);
+ const [done, setDone] = useState<{ id: string; take: { id: string; linked: boolean } | null } | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ if (done) {
+ return (
+ <span data-take-forked={done.id} className="text-[11px] text-text-2">
+ Forked as{" "}
+ <Link href={takesHref(done.id)} className="ink-link font-mono">
+ {done.id}
+ </Link>
+ {done.take?.linked ? ` — with this take in it` : ""} ·{" "}
+ <Link href={takesCompareHref(project, `${project}:${take}`, `${done.id}:${take}`)} className="ink-link" data-take-forked-compare="">
+ compare
+ </Link>
+ </span>
+ );
+ }
+ return (
+ <span className="inline-flex flex-wrap items-center gap-1.5">
+ {!open ? (
+ <button type="button" data-action="fork" disabled={!ready} className={smOutline} title="a variant of the project made from this take: a project beside this one with its manifest, the media linked, the take in it" onClick={() => setOpen(true)}>
+ Fork as variant
+ </button>
+ ) : (
+ <>
+ <input
+ autoFocus
+ aria-label="the variant's name"
+ data-take-fork-name={take}
+ value={name}
+ maxLength={64}
+ onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") setOpen(false);
+ }}
+ className="w-40 rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 font-mono text-[11px] text-[var(--color-text)]"
+ />
+ <button
+ type="button"
+ data-action="fork-go"
+ disabled={busy || !name.trim()}
+ className={sm}
+ onClick={async () => {
+ setBusy(true);
+ setError(null);
+ const { ok, j } = await housekeeping({ project, take, op: "fork", name: name.trim() });
+ setBusy(false);
+ if (!ok) setError(String(j.error ?? "refused"));
+ else setDone({ id: String(j.id), take: (j.take as { id: string; linked: boolean } | null) ?? null });
+ }}
+ >
+ {busy ? "Forking…" : "Fork"}
+ </button>
+ <button type="button" className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={() => setOpen(false)}>
+ Cancel
+ </button>
+ </>
+ )}
+ {error && (
+ <span role="alert" className="text-[11px] text-reject-text">
+ {error}
+ </span>
+ )}
+ </span>
+ );
+}
+
+/** Compare with…: another take of the project or of one of its variants, side by side. */
+export function CompareWith({ project, take, options }: { project: string; take: string; options: CompareOption[] }) {
+ const mine = `${project}:${take}`;
+ const others = options.filter((o) => o.ref !== mine);
+ const [other, setOther] = useState(others[0]?.ref ?? "");
+ if (!others.length) return null;
+ return (
+ <span className="inline-flex flex-wrap items-center gap-1.5 text-[11px]">
+ <select
+ data-take-compare-with={take}
+ value={other}
+ onChange={(e) => setOther(e.target.value)}
+ className="max-w-[14rem] rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[11px]"
+ title="another take of this project or of its variants"
+ >
+ {others.map((o) => (
+ <option key={o.ref} value={o.ref}>
+ {o.label}
+ </option>
+ ))}
+ </select>
+ <Link href={takesCompareHref(project, mine, other)} data-action="compare" className={smOutline}>
+ Compare
+ </Link>
+ </span>
+ );
+}
+
+/**
+ * The take directories that are not takes (yet): a first render in progress,
+ * with Cancel, and first renders cancelled -- folded away, each deletable.
+ */
+export function TakeWorkDirs({ project, dirs, ready }: { project: string; dirs: WorkDirs; ready: boolean }) {
+ const router = useRouter();
+ const [show, setShow] = useState(false);
+ const [said, setSaid] = useState<CancelSaid | null>(null);
+ if (!dirs.rendering.length && !dirs.cancelled.length && !said) return null;
+ return (
+ <section data-take-workdirs="" className="space-y-1.5 text-[12px]">
+ <CancelSaidLine said={said} />
+ {dirs.rendering.map((r) => (
+ <div key={r.id} data-take-rendering={r.id} className="flex flex-wrap items-center gap-2 rounded border border-[var(--color-meter)] bg-[var(--color-panel)] px-3 py-2">
+ <span className="micro">rendering now</span>
+ <span className="font-mono">{r.id}</span>
+ {r.label && <span className="text-text-2">{r.label}</span>}
+ <span className="text-[11px] text-[var(--color-dim)]" suppressHydrationWarning>
+ {r.startedAt ? `since ${r.startedAt.slice(11, 16)}` : ""}
+ {r.pid ? ` · pid ${r.pid}` : ""}
+ {r.from ? ` · from ${r.from}` : ""} · its first render: it becomes a take when it is done
+ </span>
+ <span className="ml-auto">
+ <CancelRender project={project} take={r.id} ready={ready} onSaid={setSaid} />
+ </span>
+ </div>
+ ))}
+ {dirs.cancelled.length > 0 && (
+ <p className="m-0 text-[11px] text-[var(--color-dim)]" data-cancelled-count={dirs.cancelled.length}>
+ {dirs.cancelled.length} cancelled render{dirs.cancelled.length === 1 ? "" : "s"} {show ? "shown" : "folded away"} ·{" "}
+ <button type="button" data-action="show-cancelled" aria-pressed={show} onClick={() => setShow((v) => !v)} className="ink-link">
+ {show ? "fold them away" : "show them"}
+ </button>
+ </p>
+ )}
+ {show &&
+ dirs.cancelled.map((c) => (
+ <div key={c.id} data-take-cancelled={c.id} className="flex flex-wrap items-center gap-2 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 opacity-75">
+ <span className="micro">cancelled</span>
+ <span className="font-mono">{c.id}</span>
+ {c.label && <span className="text-text-2">{c.label}</span>}
+ <span className="text-[11px] text-[var(--color-dim)]" suppressHydrationWarning>
+ {c.at.slice(0, 16).replace("T", " ")}
+ {c.by ? ` · by ${c.by}` : ""} · never finished: no take
+ </span>
+ <span className="ml-auto">
+ <DeletePlan label={`Delete take ${c.id}`} subject={`the cancelled take ${c.id}`} endpoint="/api/report/takes/delete" body={{ project, take: c.id }} onDone={() => router.refresh()} />
+ </span>
+ </div>
+ ))}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/TakesBench.tsx b/umtool/components/projects/TakesBench.tsx
@@ -14,6 +14,7 @@ import { playHref, takeWalkHref } from "@/lib/hrefs";
import { BenchBody, VerdictBar } from "./bench/BenchShell";
import { startTakeJob } from "./NewTakePanel";
import TakeActions from "./TakeActions";
+import { CancelRender, CancelSaidLine, CompareWith, ForkVariant, TakeWorkDirs, type CancelSaid, type CompareOption, type WorkDirs } from "./TakeVariants";
// The takes of one project, a group at a time, every preview on screen at once.
//
@@ -56,6 +57,8 @@ export type Take = {
holds?: string[];
/** The newest whole-cut take of the manifest: the working cut's name (lib/report/workingCut.mjs). */
latest?: boolean;
+ /** Its last render was cancelled (takes/<id>/cancelled.json, lib/report/takeCancel.mjs): the take kept is the one before. */
+ cancelled?: { at: string; by: string } | null;
};
/** A take's work files, as `GET /api/report/takes/prune` measures them (lib/report/takePrune.mjs). */
@@ -130,10 +133,16 @@ export default function TakesBench({
initial,
head,
children,
+ compareOptions = [],
+ workDirs = null,
}: {
project: string;
groups: { group: string; takes: Take[] }[];
initial: Record<string, TakeVerdict>;
+ /** Every take of the project and of its variants (`<project>:<take>`), for Compare with… */
+ compareOptions?: CompareOption[];
+ /** First renders in progress (Cancel) and cancelled (folded away). */
+ workDirs?: WorkDirs | null;
/** Above the groups, in the work column (New take). */
head?: React.ReactNode;
/** Under the groups, in the work column (the takes the listing skipped). */
@@ -284,6 +293,7 @@ export default function TakesBench({
<BenchBody verdict={verdictBar}>
<div className="space-y-6">
{head}
+ {workDirs && <TakeWorkDirs project={project} dirs={workDirs} ready={ready} />}
<WorkSummary project={project} work={work} error={workError} ready={ready} onFreed={() => void loadWork()} />
{groups.map((g) => {
const tally = VERDICTS.map((v) => [v.id, g.takes.filter((t) => verdicts[t.id]?.verdict === v.id).length] as const)
@@ -360,6 +370,7 @@ export default function TakesBench({
onPicked={(v) => setVerdicts(v)}
work={work ? (workOf.get(t.id) ?? null) : undefined}
onFreed={() => void loadWork()}
+ compareOptions={compareOptions}
/>
))}
</div>
@@ -498,7 +509,10 @@ function TakeCard({
onPicked,
work,
onFreed,
+ compareOptions,
}: {
+ /** Every take of the project and its variants, for Compare with… */
+ compareOptions: CompareOption[];
/** The project's other takes: what "superseded by" may name. */
others: { id: string; label: string }[];
onVerdicts: (verdicts: Record<string, TakeVerdict>) => void;
@@ -531,6 +545,8 @@ function TakeCard({
}, []);
const [note, setNote] = useState(verdict?.note ?? "");
const [busy, setBusy] = useState(false);
+ // What Cancel render said: kept here, as the button goes once the render has stopped.
+ const [cancelSaid, setCancelSaid] = useState<CancelSaid | null>(null);
const [error, setError] = useState<string | null>(null);
const saved = verdict?.note ?? "";
// Adopt a server value that moved underneath (another tab, a refresh).
@@ -712,6 +728,11 @@ function TakeCard({
superseded{superseded.by ? ` by ${superseded.by}` : ""}
</span>
)}
+ {t.cancelled && !(t.holds ?? []).some((h) => h.startsWith("it is rendering")) && (
+ <span data-take-cancelled-mark="" title={`its last render was cancelled${t.cancelled.by ? ` by ${t.cancelled.by}` : ""} at ${t.cancelled.at}: this is the take from before it`} className={badgeVariants({ variant: "state", size: "sm" })}>
+ last render cancelled
+ </span>
+ )}
{t.draft && (
<span data-take-is-draft="" className={badgeVariants({ variant: "state", size: "sm" })}>
draft
@@ -844,6 +865,12 @@ function TakeCard({
</p>
)}
<TakeWorkLine project={project} work={work} ready={ready} onFreed={onFreed} />
+ {(t.holds ?? []).some((h) => h.startsWith("it is rendering")) && <CancelRender project={project} take={t.id} ready={ready} onSaid={setCancelSaid} />}
+ <CancelSaidLine said={cancelSaid} />
+ <div className="flex flex-wrap items-center gap-1.5" data-take-variants={t.id}>
+ <ForkVariant project={project} take={t.id} ready={ready} />
+ <CompareWith project={project} take={t.id} options={compareOptions} />
+ </div>
<div className="flex flex-wrap items-center gap-1.5 text-[11px]" data-take-housekeeping={t.id}>
{superseded ? (
<button type="button" data-action="unsupersede" disabled={!ready || busy} onClick={() => void housekeeping({ op: "unsupersede" })} className={buttonVariants({ size: "sm" })}>
diff --git a/umtool/components/projects/TakesComparePage.tsx b/umtool/components/projects/TakesComparePage.tsx
@@ -0,0 +1,168 @@
+import Link from "next/link";
+import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell";
+import { projectRef } from "@/lib/projects";
+import { projectsHref, takesCompareHref, takesHref } from "@/lib/hrefs";
+import { listTakes } from "@/lib/report/takes.mjs";
+import { compareTakes, parseTakeRef, shortValue } from "@/lib/report/takeCompare.mjs";
+import { variantFamily } from "@/lib/report/variantFork.mjs";
+import { REPORTS_ROOT } from "@/lib/paths.mjs";
+import type { ProjectRef } from "@/lib/project-types";
+import TakesComparePlayers from "./TakesComparePlayers";
+
+// `/projects/<project>/takes/compare?a=<project>:<take>&b=<project>:<take>` --
+// two takes side by side (UI notes 2026-10-30, item 19): of the project, or of
+// the project and one of its variants (lib/report/variantFork.mjs). Two
+// players kept in step (TakesComparePlayers), and what differs between the
+// takes (lib/report/takeCompare.mjs): the cut's changes A → B, the look's.
+
+type Search = Record<string, string | undefined>;
+
+export default async function TakesComparePage({ project, search }: { project: ProjectRef; search: Search }) {
+ const family = await variantFamily(project, { root: REPORTS_ROOT }).catch(() => ({ parent: project.id, members: [] as Awaited<ReturnType<typeof variantFamily>>["members"] }));
+ const all = family.members.flatMap((m) => (m.takes as Array<{ id: string; label: string; draft?: boolean }>).map((t) => ({ ref: `${m.id}:${t.id}`, project: m.id, take: t.id, label: t.label, draft: !!t.draft })));
+ const own = all.filter((x) => x.project === project.id);
+ const a = parseTakeRef(search.a, project.id) ?? (own[0] ? { project: own[0].project, take: own[0].take } : null);
+ const b = parseTakeRef(search.b, project.id) ?? (all.find((x) => !a || x.ref !== `${a.project}:${a.take}`) ?? null);
+ let error: string | null = null;
+ let c: Awaited<ReturnType<typeof compareTakes>> | null = null;
+ if (!a || !b) error = "two takes are needed to compare: this project and its variants have fewer";
+ else {
+ try {
+ const pa = a.project === project.id ? project : await projectRef(a.project);
+ const pb = b.project === project.id ? project : await projectRef(b.project);
+ if (!pa || !pb) throw new Error(`no project ${!pa ? a.project : b.project}`);
+ // Each must be a take its project lists (listTakes), as the preview route serves only those.
+ for (const [p, ref] of [[pa, a], [pb, b]] as const) {
+ if (!(await listTakes(p.dir)).takes.some((t: { id: string }) => t.id === ref.take)) throw new Error(`${p.id} has no take ${ref.take}`);
+ }
+ c = await compareTakes({ ref: { project: pa.id, take: a.take }, dir: pa.dir }, { ref: { project: pb.id, take: b.take }, dir: pb.dir });
+ } catch (e) {
+ error = e instanceof Error ? e.message : String(e);
+ }
+ }
+ const pickers = (
+ <form method="get" className="flex flex-wrap items-center gap-2 text-[12px]" data-compare-pick="">
+ {(["a", "b"] as const).map((side) => (
+ <label key={side} className="flex items-center gap-1">
+ <span className="micro">{side.toUpperCase()}</span>
+ <select
+ name={side}
+ defaultValue={side === "a" ? (a ? `${a.project}:${a.take}` : "") : b ? `${b.project}:${b.take}` : ""}
+ className="max-w-[22rem] rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1 py-0.5 text-[12px]"
+ data-compare-select={side}
+ >
+ {all.map((x) => (
+ <option key={x.ref} value={x.ref}>
+ {x.project === project.id ? "" : `${x.project.split("/").pop()} · `}
+ {x.take} — {x.label}
+ {x.draft ? " (draft)" : ""}
+ </option>
+ ))}
+ </select>
+ </label>
+ ))}
+ <button type="submit" className="rounded border border-[var(--color-line)] px-2 py-0.5 text-[12px] hover:bg-panel-2">
+ Compare
+ </button>
+ {a && b && (
+ <Link href={takesCompareHref(project.id, `${b.project}:${b.take}`, `${a.project}:${a.take}`)} className="ink-link text-[11.5px]" data-compare-swap="">
+ swap A and B
+ </Link>
+ )}
+ </form>
+ );
+ return (
+ <BenchFrame
+ kind="takes-compare"
+ top={
+ <BenchTop
+ trail={[{ href: projectsHref(), label: "Projects" }]}
+ back={{ href: takesHref(project.id), label: `${project.id} · takes` }}
+ kind="Compare takes"
+ here="compare"
+ note={c ? `${c.a.ref} · ${c.b.ref}` : undefined}
+ />
+ }
+ >
+ <BenchBody workClassName="space-y-4">
+ {pickers}
+ {error && (
+ <p role="alert" data-compare-error="" className="text-[12px] text-reject-text">
+ {error}
+ </p>
+ )}
+ {c && (
+ <>
+ <TakesComparePlayers
+ a={{ project: c.a.project, take: c.a.take, label: c.a.label, seconds: c.a.seconds, hasPreview: c.a.hasPreview }}
+ b={{ project: c.b.project, take: c.b.take, label: c.b.label, seconds: c.b.seconds, hasPreview: c.b.hasPreview }}
+ />
+ <section data-compare-diff={c.same ? "same" : c.cut.lines.length + c.look.length} className="space-y-3">
+ <h2 className="micro">what differs, A → B</h2>
+ <dl className="grid grid-cols-[auto_1fr_1fr] gap-x-4 gap-y-0.5 text-[12px]" data-compare-facts="">
+ <dt />
+ <dd className="micro m-0">A</dd>
+ <dd className="micro m-0">B</dd>
+ {(
+ [
+ ["project", c.a.project, c.b.project],
+ ["take", c.a.take, c.b.take],
+ ["label", c.a.label, c.b.label],
+ ["length", typeof c.a.seconds === "number" ? `${c.a.seconds.toFixed(1)} s` : "not rendered", typeof c.b.seconds === "number" ? `${c.b.seconds.toFixed(1)} s` : "not rendered"],
+ ["clips", String(c.a.clips), String(c.b.clips)],
+ ["window", c.a.window === "full" ? "full cut" : c.a.window ? `${c.a.window.at}+${c.a.window.dur} s` : "—", c.b.window === "full" ? "full cut" : c.b.window ? `${c.b.window.at}+${c.b.window.dur} s` : "—"],
+ ["style", c.a.style ?? "—", c.b.style ?? "—"],
+ ["built", c.a.builtAt?.slice(0, 16).replace("T", " ") ?? "—", c.b.builtAt?.slice(0, 16).replace("T", " ") ?? "—"],
+ ] as const
+ ).map(([k, x, y]) => (
+ <div key={k} className="contents" data-compare-fact={k} data-differs={x !== y ? "" : undefined}>
+ <dt className="text-[var(--color-dim)]">{k}</dt>
+ <dd className={`m-0 font-mono text-[11.5px] ${x !== y ? "text-[var(--color-text)]" : "text-[var(--color-dim)]"}`}>{x}</dd>
+ <dd className={`m-0 font-mono text-[11.5px] ${x !== y ? "text-[var(--color-text)]" : "text-[var(--color-dim)]"}`}>{y}</dd>
+ </div>
+ ))}
+ </dl>
+ {c.seconds !== null && c.seconds !== 0 && (
+ <p className="m-0 text-[12px] text-text-2" data-compare-seconds={c.seconds}>
+ B is {Math.abs(c.seconds).toFixed(1)} s {c.seconds > 0 ? "longer" : "shorter"} than A.
+ </p>
+ )}
+ {c.same && <p className="m-0 text-[12px] text-[var(--color-dim)]">The same cut and the same look.</p>}
+ {c.cut.lines.length > 0 && (
+ <div>
+ <h3 className="micro mb-1">the cut — {c.cut.lines.length} change{c.cut.lines.length === 1 ? "" : "s"}</h3>
+ <ul className="space-y-0.5 font-mono text-[11.5px]" data-compare-cut="">
+ {c.cut.lines.map((l, i) => (
+ <li key={i}>{l}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+ {c.look.length > 0 && (
+ <div>
+ <h3 className="micro mb-1">
+ the look — {c.look.length}
+ {c.lookMore ? `+${c.lookMore}` : ""} difference{c.look.length === 1 ? "" : "s"}
+ </h3>
+ <ul className="space-y-0.5 font-mono text-[11.5px]" data-compare-look="">
+ {c.look.map((d) => (
+ <li key={d.path} data-compare-look-path={d.path}>
+ {d.path}: <span className="text-[var(--color-dim)]">{shortValue(d.a)}</span> → {shortValue(d.b)}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ <p className="m-0 text-[11px] text-[var(--color-dim)]">
+ <code className="font-mono">
+ umtool takes compare {project.id} {c.a.ref} {c.b.ref}
+ </code>{" "}
+ prints the same.
+ </p>
+ </section>
+ </>
+ )}
+ </BenchBody>
+ </BenchFrame>
+ );
+}
diff --git a/umtool/components/projects/TakesComparePlayers.tsx b/umtool/components/projects/TakesComparePlayers.tsx
@@ -0,0 +1,175 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+
+// ---------------------------------------------------------------------------
+// TWO TAKES IN STEP (the compare page, UI notes item 19): A leads, B follows.
+// One transport for both -- play, pause, the seek bar, ±5 s -- because two
+// players each with its own controls drift apart the moment one is touched.
+// While they play, B is pulled back to A whenever it strays past 0.15 s (a
+// seek into a file that is only partly loaded starts late). ONE AUDIO SOURCE,
+// as on the Takes page: A or B, the other muted.
+// ---------------------------------------------------------------------------
+
+type Side = { project: string; take: string; label: string; seconds: number | null; hasPreview: boolean };
+
+const src = (s: Side) => `/api/report/takes/preview?${new URLSearchParams({ project: s.project, take: s.take })}`;
+const clock = (t: number) => {
+ const s = Math.max(0, t);
+ const m = Math.floor(s / 60);
+ return `${m}:${(s - m * 60).toFixed(1).padStart(4, "0")}`;
+};
+/** How far B may stray from A while playing before it is pulled back (s). */
+const DRIFT = 0.15;
+
+export default function TakesComparePlayers({ a, b }: { a: Side; b: Side }) {
+ const va = useRef<HTMLVideoElement | null>(null);
+ const vb = useRef<HTMLVideoElement | null>(null);
+ const [ready, setReady] = useState(false);
+ const [playing, setPlaying] = useState(false);
+ const [t, setT] = useState(0);
+ const [drift, setDrift] = useState(0);
+ const [sound, setSound] = useState<"a" | "b">("a");
+ const length = Math.max(a.seconds ?? 0, b.seconds ?? 0);
+ const [dur, setDur] = useState(length);
+ useEffect(() => setReady(true), []);
+
+ useEffect(() => {
+ if (va.current) va.current.muted = sound !== "a";
+ if (vb.current) vb.current.muted = sound !== "b";
+ }, [sound]);
+
+ const both = () => [va.current, vb.current].filter((v): v is HTMLVideoElement => !!v);
+ const seek = useCallback((to: number) => {
+ const at = Math.max(0, to);
+ for (const v of both()) v.currentTime = Math.min(at, Number.isFinite(v.duration) ? v.duration : at);
+ setT(at);
+ }, []);
+ const play = useCallback(async () => {
+ const lead = va.current ?? vb.current;
+ if (!lead) return;
+ const at = lead.currentTime;
+ for (const v of both()) if (Math.abs(v.currentTime - at) > 0.01) v.currentTime = Math.min(at, Number.isFinite(v.duration) ? v.duration : at);
+ await Promise.allSettled(both().map((v) => v.play()));
+ setPlaying(true);
+ }, []);
+ const pause = useCallback(() => {
+ for (const v of both()) v.pause();
+ setPlaying(false);
+ const lead = va.current ?? vb.current;
+ if (lead && vb.current && va.current) vb.current.currentTime = Math.min(lead.currentTime, Number.isFinite(vb.current.duration) ? vb.current.duration : lead.currentTime);
+ }, []);
+
+ // The clock and the leash, four times a second.
+ useEffect(() => {
+ const id = window.setInterval(() => {
+ const x = va.current;
+ const y = vb.current;
+ const lead = x ?? y;
+ if (!lead) return;
+ setT(lead.currentTime);
+ if (x && y) {
+ const d = Math.abs(y.currentTime - x.currentTime);
+ // B past its own end is not drift: it simply has less.
+ const past = Number.isFinite(y.duration) && x.currentTime >= y.duration - 0.05;
+ setDrift(past ? 0 : d);
+ if (!x.paused && !past && d > DRIFT) y.currentTime = x.currentTime;
+ }
+ if (lead.ended || (x?.paused && y?.paused && playing)) setPlaying(false);
+ }, 250);
+ return () => window.clearInterval(id);
+ }, [playing]);
+
+ // The keys: space plays / pauses, ← → five seconds.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ const el = e.target as HTMLElement | null;
+ if (el?.closest?.("input, textarea, select, [contenteditable='true']")) return;
+ if (e.key === " ") {
+ e.preventDefault();
+ void (playing ? pause() : play());
+ } else if (e.key === "ArrowLeft") seek(t - 5);
+ else if (e.key === "ArrowRight") seek(t + 5);
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [playing, play, pause, seek, t]);
+
+ const player = (s: Side, side: "a" | "b") => (
+ <figure className="m-0 flex min-w-0 flex-col gap-1" data-compare-player={side} data-compare-take={`${s.project}:${s.take}`}>
+ <figcaption className="flex flex-wrap items-baseline gap-2 text-[12px]">
+ <span className="micro">{side.toUpperCase()}</span>
+ <span className="font-mono text-[11.5px]">{s.project.split("/").pop()}</span>
+ <span className="font-mono text-[11.5px]">{s.take}</span>
+ <span className="truncate text-text-2">{s.label}</span>
+ </figcaption>
+ {s.hasPreview ? (
+ <video
+ ref={side === "a" ? va : vb}
+ src={src(s)}
+ preload="auto"
+ playsInline
+ muted={sound !== side}
+ onLoadedMetadata={(e) => {
+ const d = e.currentTarget.duration;
+ if (Number.isFinite(d)) setDur((cur) => Math.max(cur, d));
+ }}
+ className="aspect-video w-full bg-black"
+ />
+ ) : (
+ <div className="flex aspect-video w-full items-center justify-center bg-black text-[12px] text-[var(--color-dim)]">a draft: nothing rendered to play</div>
+ )}
+ </figure>
+ );
+
+ return (
+ <section data-compare-players="" data-compare-time={t.toFixed(2)} data-compare-drift={drift.toFixed(2)} data-compare-state={playing ? "playing" : "paused"} className="space-y-2">
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ {player(a, "a")}
+ {player(b, "b")}
+ </div>
+ <div className="flex flex-wrap items-center gap-2 text-[12px]">
+ <button type="button" data-compare-play="" disabled={!ready} className={buttonVariants({ variant: "go", size: "sm" })} onClick={() => void (playing ? pause() : play())}>
+ {playing ? "Pause both" : "Play both"}
+ </button>
+ <button type="button" data-compare-back="" disabled={!ready} className={buttonVariants({ variant: "outline", size: "sm" })} onClick={() => seek(t - 5)}>
+ −5 s
+ </button>
+ <button type="button" data-compare-fwd="" disabled={!ready} className={buttonVariants({ variant: "outline", size: "sm" })} onClick={() => seek(t + 5)}>
+ +5 s
+ </button>
+ <input
+ type="range"
+ aria-label="where both are"
+ data-compare-seek=""
+ min={0}
+ max={Math.max(0.1, dur)}
+ step={0.1}
+ value={Math.min(t, Math.max(0.1, dur))}
+ onChange={(e) => seek(Number(e.target.value))}
+ className="min-w-[10rem] flex-1"
+ />
+ <span className="num font-mono text-[11.5px]">
+ {clock(t)} / {clock(dur)}
+ </span>
+ <span className="flex items-center gap-1" role="group" aria-label="whose sound">
+ <span className="micro">sound</span>
+ {(["a", "b"] as const).map((s) => (
+ <button
+ key={s}
+ type="button"
+ data-compare-sound={s}
+ aria-pressed={sound === s}
+ className={buttonVariants({ variant: sound === s ? "pressed" : "outline", size: "sm" })}
+ onClick={() => setSound(s)}
+ >
+ {s.toUpperCase()}
+ </button>
+ ))}
+ </span>
+ <span className="text-[11px] text-[var(--color-dim)]">space plays · ← → 5 s · B follows A</span>
+ </div>
+ </section>
+ );
+}
diff --git a/umtool/components/projects/TakesPage.tsx b/umtool/components/projects/TakesPage.tsx
@@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises";
import path from "node:path";
import Link from "next/link";
import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell";
-import { projectsHref } from "@/lib/hrefs";
+import { projectsHref, takesHref } from "@/lib/hrefs";
import { listTakes, readVerdicts } from "@/lib/report/takes.mjs";
import { pieceHrefOfProject } from "@/lib/pieces/article";
import type { ProjectRef } from "@/lib/project-types";
@@ -14,6 +14,10 @@ import TakesBench, { type Take, type TakeVerdict } from "./TakesBench";
import { LatestLine } from "./review/WhatPlays";
import { readWorkingCut } from "@/lib/report/workingCut.mjs";
import { resolveTakeManifest } from "@/lib/report/takeManifest.mjs";
+import { readCancelled, takeWorkDirs } from "@/lib/report/takeCancel.mjs";
+import { variantFamily } from "@/lib/report/variantFork.mjs";
+import { REPORTS_ROOT } from "@/lib/paths.mjs";
+import { TakeWorkDirs, type CompareOption } from "./TakeVariants";
// `/browse/<project>/takes` -- alternative renders of one part of the cut,
// watched side by side and judged like / maybe / no.
@@ -43,7 +47,27 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
const holds = new Map(await Promise.all((listing.takes as Take[]).map(async (t) => [t.id, await renderHolds(project.dir, t.id)] as const)));
// The working cut's name: the latest whole-cut take and the edits since it (lib/report/workingCut.mjs).
const working = await readWorkingCut(project.dir, { manifestText, resolveNow: async (id) => (await resolveTakeManifest(project.dir, id)).manifest }).catch(() => null);
- const takes = (listing.takes as Take[]).map((t) => ({ ...t, stale: t.baseHash ? t.baseHash !== current : null, holds: holds.get(t.id) ?? [], latest: t.id === working?.latest?.id }));
+ // Cancel, fork, compare (UI notes item 19): first renders in progress or cancelled, each take's
+ // last-render-cancelled mark, and every take of the project and its variants (variantFork.mjs).
+ const [workDirs, cancelledMarks, family] = await Promise.all([
+ takeWorkDirs(project.dir),
+ Promise.all((listing.takes as Take[]).map(async (t) => [t.id, await readCancelled(project.dir, t.id)] as const)).then((xs) => new Map(xs)),
+ variantFamily(project, { root: REPORTS_ROOT }).catch(() => ({ parent: project.id, members: [] })),
+ ]);
+ const compareOptions: CompareOption[] = family.members.flatMap((m) =>
+ (m.takes as Array<{ id: string; label: string; draft?: boolean }>).map((t) => ({
+ ref: `${m.id}:${t.id}`,
+ label: `${m.id === project.id ? "" : `${m.id.split("/").pop()} · `}${t.id} — ${t.label}${t.draft ? " (draft)" : ""}`.slice(0, 90),
+ })),
+ );
+ const variants = family.members.filter((m) => m.id !== family.parent);
+ const parentOf = family.parent !== project.id ? family.parent : null;
+ const takes = (listing.takes as Take[]).map((t) => {
+ const c = cancelledMarks.get(t.id);
+ // A cancel after the take was last built (a rebuild stopped): the take kept is the one from before.
+ const cancelled = c && (!t.builtAt || c.at > t.builtAt) ? { at: String(c.at), by: String(c.by ?? "") } : null;
+ return { ...t, stale: t.baseHash ? t.baseHash !== current : null, holds: holds.get(t.id) ?? [], latest: t.id === working?.latest?.id, cancelled };
+ });
const byId = new Map(takes.map((t) => [t.id, t]));
const panel =
project.kind === "report-video" ? (
@@ -90,6 +114,7 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
{takes.length === 0 ? (
<BenchBody workClassName="space-y-4">
{panel}
+ <TakeWorkDirs project={project.id} dirs={workDirs} ready />
<p data-takes-empty="" className="text-[12px] text-[var(--color-dim)]">
No takes yet.{" "}
<Link href={back} className="ink-link">
@@ -103,11 +128,43 @@ export default async function TakesPage({ project }: { project: ProjectRef }) {
project={project.id}
groups={listing.groups.map((g) => ({ group: g.group, takes: g.takes.map((t: { id: string }) => byId.get(t.id) as Take) }))}
initial={verdicts as Record<string, TakeVerdict>}
+ compareOptions={compareOptions}
+ workDirs={workDirs}
head={
<>
<p className="m-0 text-[12.5px]" data-takes-working="">
<LatestLine project={project.id} working={working} />
</p>
+ {(parentOf || variants.length > 0) && (
+ <p className="m-0 text-[12px] text-text-2" data-takes-family={family.members.length}>
+ {parentOf ? (
+ <>
+ A variant of{" "}
+ <Link href={takesHref(parentOf)} className="ink-link font-mono">
+ {parentOf}
+ </Link>
+ {family.members.find((m) => m.id === project.id)?.fromTake ? `, forked from its take ${family.members.find((m) => m.id === project.id)?.fromTake}` : ""}.{" "}
+ </>
+ ) : null}
+ {variants.filter((v) => v.id !== project.id).length > 0 && (
+ <>
+ Variants:{" "}
+ {variants
+ .filter((v) => v.id !== project.id)
+ .map((v, i) => (
+ <span key={v.id}>
+ {i > 0 ? ", " : ""}
+ <Link href={takesHref(v.id)} className="ink-link font-mono" data-takes-variant={v.id}>
+ {v.id.split("/").pop()}
+ </Link>
+ {v.fromTake ? <span className="text-[var(--color-dim)]"> (from {v.fromTake})</span> : null}
+ </span>
+ ))}
+ . Their takes are in each card’s <span className="italic">Compare</span>.
+ </>
+ )}
+ </p>
+ )}
{panel}
</>
}
diff --git a/umtool/components/projects/bench/GapsZoom.tsx b/umtool/components/projects/bench/GapsZoom.tsx
@@ -5,6 +5,7 @@ import type { Peaks } from "@/components/Waveform";
import { buttonVariants } from "@/components/ui/button";
import { alpha, usePalette } from "@/components/ui/use-palette";
import { cn } from "@/lib/utils";
+import { pauseSpans } from "umtool-report-to-video/pauses";
import {
DETAIL_SPAN, ZOOM_STEP, centreOn, clampVis, isFit, panBy, quietPoints, rulerFor, tickLabel, wheelFactor, zoomAt, zoomTo,
} from "@/lib/report/benchZoom.mjs";
@@ -22,8 +23,11 @@ import {
// strip under it, which shows the whole cached window, what is
// shown in it, the selection and the gaps; a two-finger pinch on it.
// closer a ruler of round ticks, and at DETAIL_SPAN seconds or less the
-// measured silences (the cut-points route's, the build's own) and
-// the pauses between words, so a gap's edge goes between two words.
+// measured silences (the cut-points route's, the build's own), the
+// pauses (pauses.mjs pauseSpans: those silences and the gaps
+// between timed words, merged) as bands, and a box per WORD with
+// its text (a caption word's box runs to the next word's start),
+// so a gap's edge -- or a tightened edge -- goes between two words.
// gaps each a hatched band over the waveform, `cut` on it; a click on
// one removes it. A span for a new one is dragged with Alt held
// (or after `g` / Select a gap); Cut gap (or `g`) writes it.
@@ -193,7 +197,8 @@ export function GapLayer({
selection: Span | null;
picking: boolean;
silences: Span[] | null;
- words: { start: number; end: number }[] | null;
+ /** The recording's words (the clip-editor route's): timed (`end`), or a caption word's start only. */
+ words: { start: number; end?: number; w?: string }[] | null;
busy: boolean;
onRemove: (g: Span) => void;
onSelect: (s: Span, done: boolean) => void;
@@ -203,7 +208,14 @@ export function GapLayer({
const width = (a: number, b: number) => `calc(${pct(b)} - ${pct(a)})`;
const inView = (s: Span) => s.to > vis.from && s.from < vis.to;
const close = vis.to - vis.from <= DETAIL_SPAN;
- const quiet = close ? quietPoints({ words, silences }, vis.from, vis.to) : [];
+ const timed = (words ?? []).filter((w): w is { start: number; end: number; w?: string } => typeof w.end === "number");
+ const quiet = close ? quietPoints({ words: timed, silences }, vis.from, vis.to) : [];
+ const pauses = close ? pauseSpans({ words: timed, silences }, { from: vis.from, to: vis.to }) : [];
+ // A box per word in view: its own end, else (a caption's word) the next word's start, at most a second on.
+ const sorted = close ? [...(words ?? [])].sort((a, b) => a.start - b.start) : [];
+ const boxes = sorted
+ .map((w, i) => ({ text: w.w ?? "", from: w.start, to: typeof w.end === "number" ? w.end : Math.min(w.start + 1, sorted[i + 1]?.start ?? w.start + 1) }))
+ .filter((b) => b.to > b.from && inView(b));
const drag = useRef<{ id: number; at: number } | null>(null);
const tAt = (el: HTMLElement, clientX: number) => {
const r = el.getBoundingClientRect();
@@ -221,6 +233,28 @@ export function GapLayer({
style={{ left: pct(s.from), width: width(s.from, s.to) }}
/>
))}
+ {pauses.filter(inView).map((p) => (
+ <div
+ key={`pause-${p.from}`}
+ data-wave-pause={`${p.from.toFixed(2)}-${p.to.toFixed(2)}`}
+ aria-hidden
+ className="pointer-events-none absolute top-0 h-full bg-[color-mix(in_srgb,var(--color-meter)_10%,transparent)]"
+ style={{ left: pct(p.from), width: width(p.from, p.to) }}
+ />
+ ))}
+ {boxes.map((b) => (
+ <div
+ key={`word-${b.from}`}
+ data-wave-word={b.text}
+ data-wave-word-at={`${b.from.toFixed(2)}-${b.to.toFixed(2)}`}
+ title={`“${b.text}” ${b.from.toFixed(2)}–${b.to.toFixed(2)}`}
+ aria-hidden
+ className="pointer-events-none absolute top-0 h-3.5 overflow-hidden whitespace-nowrap rounded-sm border border-[color-mix(in_srgb,var(--color-text)_30%,transparent)] bg-[color-mix(in_srgb,var(--color-panel-2)_75%,transparent)] px-0.5 font-mono text-[9px] leading-3 text-[var(--color-text)]"
+ style={{ left: pct(b.from), width: width(b.from, b.to) }}
+ >
+ {b.text}
+ </div>
+ ))}
{quiet.map((t) => (
<div key={`q-${t}`} data-wave-quiet={t} aria-hidden className="pointer-events-none absolute top-0 h-full border-l border-dotted border-[color-mix(in_srgb,var(--color-meter)_55%,transparent)]" style={{ left: pct(t) }} />
))}
diff --git a/umtool/components/projects/bench/TightenTools.tsx b/umtool/components/projects/bench/TightenTools.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { buttonVariants } from "@/components/ui/button";
+import { HOW_SAID, nearestPause, snapSaid, tightWindow } from "@/lib/report/tightWindow.mjs";
+
+// ---------------------------------------------------------------------------
+// TIGHTEN TO THE SENTENCE, SNAP AN EDGE TO A PAUSE (UI notes 2026-10-30, item
+// 4), on the bench's waveform tools. lib/report/tightWindow.mjs decides where
+// the edges go -- the sentence from the cues (sentenceEdges.mjs), the pause
+// from the measured silences and the words (report-to-video/pauses.mjs) --
+// and the edit is WRITTEN AT ONCE through the bench's one window writer
+// (`save`: PUT /api/report/window, the token, the cite that follows the edge),
+// like Extend and the gaps, with an Undo that writes back what was there.
+// ---------------------------------------------------------------------------
+
+export type BenchWord = { w?: string; start: number; end?: number };
+type Span = { from: number; to: number };
+type Cue = { start: number; end: number; text: string };
+
+type ClipEdges = {
+ id: string;
+ start: number;
+ end: number;
+ cutStart: number | null;
+ cutEnd: number | null;
+ muteFrom: number | null;
+ cite: number | null;
+ citeUrl: string | null;
+};
+
+/** The words of [from, to] on this clip's recording (the clip-editor route's, the bench's zoom asks the same). */
+export async function benchWords(project: string, clip: string, video: string, from: number, to: number): Promise<BenchWord[] | null> {
+ const q = new URLSearchParams({ project, clip, video, from: String(Math.max(0, Math.floor(from))), to: String(Math.ceil(to)) });
+ try {
+ const r = await fetch(`/api/report/clip-editor?${q}`, { cache: "no-store" });
+ if (!r.ok) return null;
+ const j = (await r.json()) as { words?: BenchWord[] | null };
+ return j.words ?? null;
+ } catch {
+ return null;
+ }
+}
+
+const r2 = (n: number) => Number(n.toFixed(2));
+const toWords = (ws: BenchWord[] | null) => (ws ?? []).map((w) => ({ start: w.start, ...(typeof w.end === "number" ? { end: w.end } : {}), text: w.w ?? "" }));
+
+/**
+ * Tighten / snap / undo, over the bench's state. `save` is the bench's queued
+ * writer (it re-syncs the clip, the selection and the token, and says when
+ * the cite followed); `lastSaved` its last answer.
+ */
+export function useEdgeTools({
+ project,
+ clip,
+ video,
+ sel,
+ playhead,
+ cues,
+ silences,
+ lo,
+ hi,
+ save,
+ lastSaved,
+ play,
+ setNote,
+}: {
+ project: string;
+ clip: ClipEdges;
+ video: string;
+ sel: Span;
+ playhead: number | null;
+ cues: Cue[];
+ silences: Span[] | null;
+ lo: number;
+ hi: number;
+ save: (patch: Record<string, unknown>) => Promise<boolean>;
+ lastSaved: React.MutableRefObject<Record<string, unknown> | null>;
+ play: (from: number, to: number) => unknown;
+ setNote: (s: string | null) => void;
+}) {
+ const [undo, setUndo] = useState<{ patch: Record<string, unknown>; what: string } | null>(null);
+ const [working, setWorking] = useState<string | null>(null);
+ // Another clip: nothing to undo here.
+ useEffect(() => setUndo(null), [clip.id]);
+
+ /** Write new edges through the window writer, the cut and the mute mark cleared when they no longer fit -- as Save window does. */
+ const writeEdges = useCallback(
+ async (next: Span, what: string, moved: "start" | "end" | "both") => {
+ const start = r2(next.from);
+ const end = r2(next.to);
+ const patch: Record<string, unknown> = { start, end };
+ const cleared: string[] = [];
+ if (clip.cutStart != null && clip.cutEnd != null && (clip.cutStart < start - 0.02 || clip.cutEnd > end + 0.02)) {
+ patch.cutStart = "";
+ patch.cutEnd = "";
+ cleared.push("the cut");
+ }
+ if (clip.muteFrom != null && (clip.muteFrom < start - 0.02 || clip.muteFrom > end + 0.02)) {
+ patch.muteFrom = "";
+ cleared.push("the mute mark");
+ }
+ const before = clip;
+ const ok = await save(patch);
+ if (!ok) return false;
+ const followed = (lastSaved.current?.citeFollowed ?? null) as { cite?: unknown; citeUrl?: unknown } | null;
+ const back: Record<string, unknown> = {
+ start: before.start,
+ end: before.end,
+ ...(patch.cutStart !== undefined ? { cutStart: before.cutStart ?? "", cutEnd: before.cutEnd ?? "" } : {}),
+ ...(patch.muteFrom !== undefined ? { muteFrom: before.muteFrom ?? "" } : {}),
+ // The cite and the QR went with the edge: they come back with it.
+ ...(followed?.cite ? { cite: before.cite ?? "" } : {}),
+ ...(followed?.citeUrl ? { citeUrl: before.citeUrl ?? "" } : {}),
+ };
+ setUndo({ patch: back, what });
+ setNote(
+ `${what}${cleared.length ? ` — ${cleared.join(" and ")} no longer fitted and ${cleared.length > 1 ? "were" : "was"} cleared` : ""}` +
+ `${followed?.cite ? " — the cite followed the edge" : followed?.citeUrl ? " — the QR's t= followed the edge" : ""} · Undo puts it back`,
+ );
+ // Hear what moved.
+ if (moved === "end") play(Math.max(start, end - 4), end);
+ else play(start, Math.min(end, start + 4));
+ return true;
+ },
+ [clip, save, lastSaved, play, setNote],
+ );
+
+ const tighten = useCallback(async () => {
+ setWorking("tighten");
+ try {
+ // tightWindow decides whether the playhead is a place (not parked on an edge).
+ const at = playhead;
+ const words = await benchWords(project, clip.id, video, sel.from - 12, sel.to + 12);
+ const r = tightWindow({
+ clip: { start: sel.from, end: sel.to, cutStart: clip.cutStart, cutEnd: clip.cutEnd },
+ cues,
+ words: toWords(words),
+ silences,
+ at,
+ lo,
+ hi,
+ });
+ if (!r.ok) {
+ setNote(`not tightened: ${r.why}`);
+ return;
+ }
+ const span = `${r.start.toFixed(2)}–${r.end.toFixed(2)} (${(r.end - r.start).toFixed(2)} s, was ${(sel.to - sel.from).toFixed(2)} s)`;
+ if (!r.changed) {
+ setNote(`already tight: ${HOW_SAID[r.how]} is ${span}`);
+ return;
+ }
+ await writeEdges({ from: r.start, to: r.end }, `tightened to ${HOW_SAID[r.how]}: ${span}${r.said.length ? ` — ${r.said.join("; ")}` : ""}`, "both");
+ } finally {
+ setWorking(null);
+ }
+ }, [playhead, sel, project, clip, video, cues, silences, lo, hi, writeEdges, setNote]);
+
+ const snap = useCallback(
+ async (edge: "start" | "end") => {
+ setWorking(edge);
+ try {
+ const t = edge === "start" ? sel.from : sel.to;
+ const words = await benchWords(project, clip.id, video, t - 3, t + 3);
+ const other = edge === "start" ? sel.to : sel.from;
+ const s = nearestPause(t, {
+ words: toWords(words),
+ silences,
+ lo: edge === "start" ? lo : other + 0.5,
+ hi: edge === "start" ? other - 0.5 : hi,
+ });
+ const said = snapSaid(edge, s) ?? "";
+ if (!s.moved) {
+ setNote(`not moved: ${said}${!silences?.length && !words?.length ? " — no silences measured and no words for this recording" : ""}`);
+ return;
+ }
+ await writeEdges(edge === "start" ? { from: s.at, to: sel.to } : { from: sel.from, to: s.at }, said, edge);
+ } finally {
+ setWorking(null);
+ }
+ },
+ [sel, project, clip.id, video, silences, lo, hi, writeEdges, setNote],
+ );
+
+ const undoEdges = useCallback(async () => {
+ const u = undo;
+ if (!u) return;
+ const ok = await save(u.patch);
+ if (!ok) return;
+ setUndo(null);
+ setNote(`undone — ${u.what.split(":")[0]} is reversed`);
+ }, [undo, save, setNote]);
+
+ return { tighten, snap, undoEdges, undo, working };
+}
+
+const btn = buttonVariants({ variant: "outline", size: "sm" });
+
+/** The buttons, in the waveform's tools row. */
+export function TightenButtons({ tools, busy }: { tools: ReturnType<typeof useEdgeTools>; busy: boolean }) {
+ const off = busy || !!tools.working;
+ return (
+ <span data-edge-tools="" className="flex flex-wrap items-center gap-1.5">
+ <button
+ type="button"
+ data-tighten=""
+ className={btn}
+ disabled={off}
+ title="both edges to the sentence at the playhead (else the cut's, else the whole sentences in the window), each into its pause — saved at once, Undo puts it back"
+ onClick={() => void tools.tighten()}
+ >
+ {tools.working === "tighten" ? "Tightening…" : "Tighten to this sentence"}
+ </button>
+ <span className="micro">snap edge to nearest pause</span>
+ <button type="button" data-snap-edge="start" className={btn} disabled={off} title="the start into the middle of the nearest pause (a silence, or between two words) — at most a second" onClick={() => void tools.snap("start")}>
+ ← start
+ </button>
+ <button type="button" data-snap-edge="end" className={btn} disabled={off} title="the end into the middle of the nearest pause — at most a second" onClick={() => void tools.snap("end")}>
+ end →
+ </button>
+ {tools.undo && (
+ <button type="button" data-edge-undo="" className={btn} disabled={off} title={`undo: ${tools.undo.what}`} onClick={() => void tools.undoEdges()}>
+ Undo
+ </button>
+ )}
+ </span>
+ );
+}
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -12,6 +12,7 @@ import { clipBenchHref, clipDeckHref, clipEditorHref, mixHref as toolsMixHref, p
import { readTrailerBeats } from "@/lib/report/trailerBeats.mjs";
import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs";
import FetchUnfetchedButton from "../FetchUnfetchedButton";
+import TightWindowsPanel from "./TightWindowsPanel";
import { clipRecord, storedUrlOf } from "@/lib/clips/stored";
import { Fragment } from "react";
import { deckOn } from "umtool-report-to-video/deck";
@@ -421,6 +422,8 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
/>
)}
{fetchBody && <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} />}
+ {/* Tight windows: each clip to its sentence, for review (UI notes item 4) -- a button until pressed. */}
+ {clips.length > 0 && <TightWindowsPanel project={project.id} />}
</div>
{/* --- the timeline --------------------------------------------- */}
diff --git a/umtool/components/projects/report/DecisionSettle.tsx b/umtool/components/projects/report/DecisionSettle.tsx
@@ -42,7 +42,13 @@ export default function DecisionSettle({
headers: { "content-type": "application/json" },
body: JSON.stringify({ project, file: settle.file }),
})
- : await fetch("/api/report/links", {
+ : settle.kind === "publish-site"
+ ? await fetch("/api/report/publish-site", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, siteId: settle.siteId }),
+ })
+ : await fetch("/api/report/links", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ project, ...(settle.fix ? { fix: true } : {}) }),
@@ -53,6 +59,7 @@ export default function DecisionSettle({
fixed?: { clip: string }[];
notes?: string[];
left?: { label: string | null; after: string }[];
+ jobId?: string | null;
};
if (!r.ok) {
setErr(j.error ?? `HTTP ${r.status}`);
@@ -68,6 +75,10 @@ export default function DecisionSettle({
`${moved} marker${moved === 1 ? "" : "s"} moved` +
(left.length ? ` · left by hand: ${left.map((l) => `${l.label ? `"${l.label}"` : "a marker"} after ${l.after}`).join(", ")}` : ""),
);
+ } else if (settle.kind === "publish-site") {
+ // The editor's publish queue runs it; nothing here changes until the deploy lands and a check reads it.
+ setSaid(`queued on the editor's publish queue${j.jobId ? ` (job ${j.jobId})` : ""} — Check links once it is deployed`);
+ return;
} else setSaid("saved");
router.refresh();
} catch (e) {
@@ -81,7 +92,7 @@ export default function DecisionSettle({
<span className="inline-flex items-center gap-2" data-settle={settle.kind}>
<button
type="button"
- data-settle-button={settle.kind === "patch" ? settle.clip : settle.kind === "patch-markers" ? settle.file : "links"}
+ data-settle-button={settle.kind === "patch" ? settle.clip : settle.kind === "patch-markers" ? settle.file : settle.kind === "publish-site" ? `publish-${settle.siteId}` : "links"}
disabled={busy}
onClick={() => void run()}
className={buttonVariants({ variant: settle.kind === "patch" ? "go" : "outline", size: "sm" })}
@@ -90,10 +101,12 @@ export default function DecisionSettle({
? `writes ${Object.keys(settle.patch).join(", ")} on ${settle.clip} through the window writer`
: settle.kind === "patch-markers"
? `each marker of ${settle.file} after a clip that is gone takes the cut's marker of the same label`
- : "resolves every clip QR against the site it links (corpus.json → the shard's record), one request at a time per host"
+ : settle.kind === "publish-site"
+ ? `asks the editor to build and deploy ${settle.siteId} (its publish queue, through the heavy slot)`
+ : "resolves every clip QR against the site it links (corpus.json → the shard's record), one request at a time per host"
}
>
- {busy ? (settle.kind === "check-links" ? "Checking…" : "Saving…") : settle.label}
+ {busy ? (settle.kind === "check-links" ? "Checking…" : settle.kind === "publish-site" ? "Asking the editor…" : "Saving…") : settle.label}
</button>
{said && !err && (
<span data-settle-said="" className="text-[11.5px] text-text-2">
diff --git a/umtool/components/projects/report/LinkPolicyPanel.tsx b/umtool/components/projects/report/LinkPolicyPanel.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { buttonVariants } from "@/components/ui/button";
+
+// THE PROJECT'S LINK POLICY (UI notes 2026-10-30, #10): "cite via site X;
+// these channels direct" -- `provenance.linkPolicy`, through the one writer
+// (PUT /api/report/link-policy; `umtool link-policy <p>` from a terminal).
+// New clips are written by it; the clips already in the cut that break it are
+// the check's clip-link-policy rows, each with its one-press fix.
+
+type View = {
+ policy: { via: string | null; direct: string[] } | null;
+ siteOrigin: string | null;
+ channels: { slug: string; clips: number }[];
+ sites: { origin: string; siteId: string; title: string | null }[];
+ token: string | null;
+};
+
+const DEFAULT = "";
+
+export default function LinkPolicyPanel({ project }: { project: string }) {
+ const router = useRouter();
+ const [view, setView] = useState<View | null>(null);
+ const [via, setVia] = useState(DEFAULT);
+ const [direct, setDirect] = useState<string[]>([]);
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<string | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ const r = await fetch(`/api/report/link-policy?project=${encodeURIComponent(project)}`, { cache: "no-store" });
+ const j = (await r.json().catch(() => null)) as View | null;
+ if (!r.ok || !j) return;
+ setView(j);
+ setVia(j.policy?.via ?? DEFAULT);
+ setDirect(j.policy?.direct ?? []);
+ }, [project]);
+
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ if (!view || !view.channels.length) return null;
+ const options = [...view.sites];
+ if (view.policy?.via && !options.some((s) => s.origin === view.policy?.via)) {
+ options.push({ origin: view.policy.via, siteId: new URL(view.policy.via).host, title: null });
+ }
+ const dirty = via !== (view.policy?.via ?? DEFAULT) || direct.join(",") !== (view.policy?.direct ?? []).join(",");
+
+ const save = async () => {
+ setBusy(true);
+ setErr(null);
+ setSaid(null);
+ try {
+ const policy = via || direct.length ? { ...(via ? { via } : {}), ...(direct.length ? { direct } : {}) } : null;
+ const r = await fetch("/api/report/link-policy", {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, token: view.token, policy }),
+ });
+ const j = (await r.json().catch(() => ({}))) as { error?: string; changed?: boolean };
+ if (!r.ok) {
+ setErr(j.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ setSaid(j.changed ? "saved — the check names every clip that breaks it" : "unchanged");
+ await load();
+ router.refresh();
+ } catch (e) {
+ setErr(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const defaultHost = (() => {
+ try {
+ return view.siteOrigin ? new URL(view.siteOrigin).host : null;
+ } catch {
+ return view.siteOrigin;
+ }
+ })();
+
+ return (
+ <section data-link-policy={view.policy ? "set" : "none"} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
+ <h2 className="micro mb-1.5">Link policy</h2>
+ <label className="flex flex-wrap items-center gap-2 text-[12.5px] text-text-2">
+ Cite via
+ <select
+ data-link-policy-via=""
+ value={via}
+ onChange={(e) => setVia(e.target.value)}
+ className="rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12.5px]"
+ >
+ <option value={DEFAULT}>{defaultHost ? `the cut's site origin (${defaultHost})` : "the cut's site origin"}</option>
+ {options.map((s) => (
+ <option key={s.origin} value={s.origin}>
+ {s.siteId} — {new URL(s.origin).host}
+ </option>
+ ))}
+ </select>
+ </label>
+ <p className="mt-1.5 text-[12px] text-muted">These channels link their platform’s own page directly:</p>
+ <ul className="mt-1 flex flex-wrap gap-x-4 gap-y-1">
+ {view.channels.map((c) => (
+ <li key={c.slug}>
+ <label className="flex items-center gap-1.5 text-[12.5px]">
+ <input
+ type="checkbox"
+ data-link-policy-direct={c.slug}
+ checked={direct.includes(c.slug)}
+ onChange={(e) => setDirect((d) => (e.target.checked ? [...d, c.slug].sort() : d.filter((x) => x !== c.slug)))}
+ />
+ <span className="font-mono text-[12px]">{c.slug}</span>
+ <span className="text-[11.5px] text-muted">
+ {c.clips} clip{c.clips === 1 ? "" : "s"}
+ </span>
+ </label>
+ </li>
+ ))}
+ </ul>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ data-link-policy-save=""
+ disabled={busy || !dirty}
+ onClick={() => void save()}
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ title="writes provenance.linkPolicy; new clips take its links, and the check names the clips that break it"
+ >
+ {busy ? "Saving…" : "Save link policy"}
+ </button>
+ <span className="font-mono text-[11px] text-muted">umtool link-policy {project} --via <site> --direct a,b</span>
+ {said && !err && (
+ <span data-link-policy-said="" className="text-[11.5px] text-text-2">
+ {said}
+ </span>
+ )}
+ {err && (
+ <span data-link-policy-error="" className="text-[11.5px] text-doubt-text">
+ {err}
+ </span>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/umtool/components/projects/report/OverviewTab.tsx b/umtool/components/projects/report/OverviewTab.tsx
@@ -16,6 +16,8 @@ import type { PieceFrame } from "@/lib/pieces/frame";
import { TONE, hms, type ReportTabProps } from "./shared";
import DecisionSettle from "./DecisionSettle";
import SourceBacklog from "./SourceBacklog";
+import ProjectSites from "./ProjectSites";
+import LinkPolicyPanel from "./LinkPolicyPanel";
import { manifestToken } from "@/lib/report/manifest.mjs";
// The Overview tab (canvas "Piece · Overview"): the Next card, then the
@@ -120,6 +122,8 @@ export default async function OverviewTab({ project, detail, frame }: ReportTabP
{/* How much of each cited channel the archive holds and has transcribed (UI notes item 16). */}
{clips.length > 0 && <SourceBacklog project={project.id} />}
+ <ProjectSites project={project} detail={detail} />
+ <LinkPolicyPanel project={project.id} />
{frame.board && (
<section data-piece-board={frame.board.id}>
diff --git a/umtool/components/projects/report/ProjectSites.tsx b/umtool/components/projects/report/ProjectSites.tsx
@@ -0,0 +1,84 @@
+import { stat } from "node:fs/promises";
+import { readLinkCheck } from "@/lib/report/linkCheck.mjs";
+import { dayOf, projectSites, sitesByOrigin } from "@/lib/report/siteDeploys.mjs";
+import { SITES_DIR } from "@/lib/paths.mjs";
+import type { ProjectRef } from "@/lib/project-types";
+import DecisionSettle from "./DecisionSettle";
+import type { ClipDetail } from "./shared";
+
+// THE SITES THIS CUT'S LINKS DEPEND ON (UI notes 2026-10-30, #9), on the
+// piece's Overview: each site a clip QR opens, named from its site.json, with
+// its deploy's date -- the corpus.json `generatedAt` the last link check read
+// (out/links.json; this never fetches) -- and the cited videos newer than that
+// deploy. "Publish <site>" asks the editor to build and deploy it; "Check
+// links" reads every site again. The same answer is the check's
+// `site-deploy-behind` row (lib/report/siteDeploys.mjs).
+
+const STATE: Record<string, string> = {
+ ok: "",
+ unreachable: "couldn't reach it at the last check",
+ "no-corpus": "it publishes no corpus.json",
+ unchecked: "not checked yet",
+};
+
+export default async function ProjectSites({ project, detail }: { project: ProjectRef; detail: ClipDetail }) {
+ const m = detail.manifest as Record<string, unknown>;
+ const doc = await readLinkCheck(project.dir);
+ const records = new Map<string, { uploadDate: string | null; landedAt: string | null }>();
+ for (const e of detail.entries) {
+ if (e.kind !== "clip") continue;
+ const cueFile = (e as { cueFile?: string | null }).cueFile;
+ const st = cueFile ? await stat(cueFile).catch(() => null) : null;
+ records.set(e.id, {
+ uploadDate: (e as { uploadDate?: string | null }).uploadDate ?? null,
+ landedAt: st ? new Date(st.mtimeMs).toISOString() : null,
+ });
+ }
+ const sites = projectSites(m, doc, { sites: sitesByOrigin(SITES_DIR), recordOf: (id: string) => records.get(id) ?? null });
+ if (!sites.length) return null;
+ return (
+ <section data-project-sites={sites.length}>
+ <h2 className="micro mb-1.5">Sites the links depend on</h2>
+ <ul className="space-y-1.5">
+ {sites.map((s) => (
+ <li
+ key={s.origin}
+ data-link-site={s.host}
+ data-link-site-id={s.siteId ?? undefined}
+ data-link-site-deployed={dayOf(s.deployedAt) ?? undefined}
+ data-link-site-newer={s.newer.length}
+ className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-1.5 text-[12.5px]"
+ >
+ <div className="flex flex-wrap items-baseline gap-2">
+ <a href={s.origin} target="_blank" rel="noreferrer" className="ink-link font-mono text-[12px]">
+ {s.host}
+ </a>
+ {s.siteId && <span className="text-text-2">{s.siteId}</span>}
+ <span className="ml-auto font-mono text-[11.5px] text-meter">
+ {s.links} link{s.links === 1 ? "" : "s"} · {s.clips.length} clip{s.clips.length === 1 ? "" : "s"}
+ </span>
+ </div>
+ <p className="text-[12px] text-muted" data-link-site-deploy="">
+ {s.deployedAt ? `deployed ${dayOf(s.deployedAt)} (its corpus.json)` : "deploy date unknown"}
+ {STATE[s.state] ? ` · ${STATE[s.state]}` : ""}
+ {doc?.checkedAt ? ` · checked ${doc.checkedAt.slice(0, 16).replace("T", " ")}` : ""}
+ </p>
+ {s.newer.length > 0 && (
+ <p className="text-[12px] text-doubt-text" data-link-site-warning="">
+ {s.newer.length} cited video{s.newer.length === 1 ? " is" : "s are"} newer than this deploy:{" "}
+ {s.newer.slice(0, 6).map((n) => `${n.clip} (${n.why})`).join(", ")}
+ {s.newer.length > 6 ? ` and ${s.newer.length - 6} more` : ""}
+ </p>
+ )}
+ <div className="mt-1 flex flex-wrap items-center gap-2">
+ {s.siteId && s.newer.length > 0 && (
+ <DecisionSettle project={project.id} settle={{ kind: "publish-site", siteId: s.siteId, label: `Publish ${s.siteId}` }} />
+ )}
+ <DecisionSettle project={project.id} settle={{ kind: "check-links", label: doc ? "Check links again" : "Check links" }} />
+ </div>
+ </li>
+ ))}
+ </ul>
+ </section>
+ );
+}
diff --git a/umtool/components/projects/report/TightWindowsPanel.tsx b/umtool/components/projects/report/TightWindowsPanel.tsx
@@ -0,0 +1,256 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useRef, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { buttonVariants } from "@/components/ui/button";
+import { clipBenchHref } from "@/lib/hrefs";
+
+// ---------------------------------------------------------------------------
+// PROPOSE TIGHT WINDOWS (UI notes 2026-10-30, item 4): every clip of the cut
+// tightened to its sentence and each edge into its pause
+// (lib/report/tightPropose.mjs, GET /api/report/tighten), as a review list --
+// before and after, the seconds either way, what moved and why. NOTHING
+// APPLIES WITHOUT A PRESS: each row's Apply is one window save (PUT
+// /api/report/window, the token, the cite that follows the edge), and an
+// applied row offers Undo, which writes back what was there.
+// ---------------------------------------------------------------------------
+
+type Edge = { start: number; end: number; seconds: number };
+type Row = {
+ id: string;
+ quote: string | null;
+ before: Edge;
+ after: Edge | null;
+ changed: boolean;
+ how: string | null;
+ said: string[];
+ why: string | null;
+ fetched: boolean;
+ locked: boolean;
+ words: string | null;
+ clear: { cut: boolean; mute: boolean };
+ prior: { cutStart: number | null; cutEnd: number | null; muteFrom: number | null; cite: number | null; citeUrl: string | null };
+};
+type Got = { token: string | null; rows: Row[]; counts: { clips: number; proposed: number; same: number; none: number } };
+type Applied = { k: "applying" } | { k: "applied"; undo: Record<string, unknown>; note: string } | { k: "undone" } | { k: "failed"; error: string };
+
+const hms = (t: number) => {
+ const s = Math.max(0, t);
+ const m = Math.floor(s / 60);
+ return `${m}:${(s - m * 60).toFixed(2).padStart(5, "0")}`;
+};
+const signed = (d: number) => `${d > 0 ? "+" : d < 0 ? "−" : "±"}${Math.abs(d).toFixed(2)} s`;
+
+export default function TightWindowsPanel({ project }: { project: string }) {
+ const router = useRouter();
+ const [got, setGot] = useState<Got | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [all, setAll] = useState(false);
+ const [done, setDone] = useState<Record<string, Applied>>({});
+ const token = useRef<string | null>(null);
+ // One write at a time: each reads the token the last one was handed back.
+ const chain = useRef<Promise<unknown>>(Promise.resolve());
+
+ const propose = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const r = await fetch(`/api/report/tighten?${new URLSearchParams({ project })}`, { cache: "no-store" });
+ const j = (await r.json()) as Got & { error?: string };
+ if (!r.ok) {
+ setError(j.error ?? `HTTP ${r.status}`);
+ return;
+ }
+ token.current = j.token;
+ setGot(j);
+ setDone({});
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setLoading(false);
+ }
+ }, [project]);
+
+ const put = useCallback(
+ async (clip: string, patch: Record<string, unknown>) => {
+ const r = await fetch("/api/report/window", {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, clip, token: token.current, ...patch }),
+ });
+ const j = (await r.json().catch(() => ({}))) as Record<string, unknown>;
+ if (r.ok) token.current = String(j.token ?? "");
+ return { ok: r.ok, j };
+ },
+ [project],
+ );
+
+ const apply = useCallback(
+ (row: Row) => {
+ if (!row.after) return;
+ setDone((d) => ({ ...d, [row.id]: { k: "applying" } }));
+ const after = row.after;
+ const patch: Record<string, unknown> = {
+ start: after.start,
+ end: after.end,
+ ...(row.clear.cut ? { cutStart: "", cutEnd: "" } : {}),
+ ...(row.clear.mute ? { muteFrom: "" } : {}),
+ };
+ chain.current = chain.current.then(async () => {
+ const { ok, j } = await put(row.id, patch);
+ if (!ok) {
+ setDone((d) => ({
+ ...d,
+ [row.id]: { k: "failed", error: j.stale ? "the manifest changed since these were proposed — Propose again" : String(j.error ?? "refused") },
+ }));
+ return;
+ }
+ const before = row.prior;
+ const followed = (j.citeFollowed ?? null) as { cite?: { from: number; to: number }; citeUrl?: unknown } | null;
+ const undo: Record<string, unknown> = {
+ start: row.before.start,
+ end: row.before.end,
+ ...(row.clear.cut ? { cutStart: before.cutStart ?? "", cutEnd: before.cutEnd ?? "" } : {}),
+ ...(row.clear.mute ? { muteFrom: before.muteFrom ?? "" } : {}),
+ ...(followed?.cite ? { cite: before.cite ?? "" } : {}),
+ ...(followed?.citeUrl ? { citeUrl: before.citeUrl ?? "" } : {}),
+ };
+ const note = followed?.cite ? `the cite followed: ${hms(followed.cite.from)} → ${hms(followed.cite.to)}${followed.citeUrl ? ", and the QR" : ""}` : "";
+ setDone((d) => ({ ...d, [row.id]: { k: "applied", undo, note } }));
+ router.refresh();
+ });
+ },
+ [put, router],
+ );
+
+ const undo = useCallback(
+ (row: Row) => {
+ const s = done[row.id];
+ if (s?.k !== "applied") return;
+ setDone((d) => ({ ...d, [row.id]: { k: "applying" } }));
+ chain.current = chain.current.then(async () => {
+ const { ok, j } = await put(row.id, s.undo);
+ setDone((d) => ({ ...d, [row.id]: ok ? { k: "undone" } : { k: "failed", error: j.stale ? "the manifest changed since — Propose again" : String(j.error ?? "refused") } }));
+ if (ok) router.refresh();
+ });
+ },
+ [done, put, router],
+ );
+
+ const rows = got ? got.rows.filter((r) => all || r.changed) : [];
+ // Until it is pressed, one button among the Cut tab's tools (it adds nothing to the page's
+ // height); the review list then opens on a line of its own under them.
+ const button = (
+ <button
+ type="button"
+ data-action="propose-tight"
+ className={buttonVariants({ variant: "outline", size: "sm" })}
+ disabled={loading}
+ title="each clip to its sentence (the cut's, else the whole ones in its window), each edge into its pause — a list to review; nothing changes until you Apply a row"
+ onClick={() => void propose()}
+ >
+ {loading ? "Proposing…" : got ? "Propose again" : "Propose tight windows"}
+ </button>
+ );
+ if (!got && !error) return <span data-tight-windows="">{button}</span>;
+ return (
+ <section data-tight-windows={got ? got.counts.proposed : ""} className="basis-full rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
+ <div className="flex flex-wrap items-center gap-2">
+ <h2 className="micro">tight windows</h2>
+ {button}
+ {got && (
+ <span data-tight-counts="" className="text-[11.5px] text-[var(--color-dim)]">
+ {got.counts.proposed} of {got.counts.clips} clips would change · {got.counts.same} already tight
+ {got.counts.none ? ` · ${got.counts.none} with nothing to go by` : ""}
+ {" · "}
+ <button type="button" data-action="tight-show-all" aria-pressed={all} className="ink-link" onClick={() => setAll((v) => !v)}>
+ {all ? "only the changes" : "show every clip"}
+ </button>
+ </span>
+ )}
+ </div>
+ {error && (
+ <p role="alert" className="mt-1 text-[12px] text-reject-text">
+ {error}
+ </p>
+ )}
+ {got && rows.length === 0 && <p className="mt-1 text-[12px] text-[var(--color-dim)]">every clip is already tight</p>}
+ {rows.length > 0 && (
+ <ul className="mt-2 space-y-1.5" aria-label="proposed tight windows">
+ {rows.map((r) => {
+ const s = done[r.id];
+ const d = r.after ? r.after.seconds - r.before.seconds : 0;
+ return (
+ <li key={r.id} data-tight-row={r.id} data-tight-state={s?.k ?? (r.changed ? "proposed" : r.after ? "same" : "none")} className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-[12px] leading-snug">
+ <Link href={clipBenchHref(project, r.id)} className="ink-link font-mono text-[11px]">
+ {r.id}
+ </Link>
+ <span className="num font-mono text-[11px] text-[var(--color-dim)]" data-tight-before={`${r.before.start}-${r.before.end}`}>
+ {hms(r.before.start)}–{hms(r.before.end)} ({r.before.seconds.toFixed(2)} s)
+ </span>
+ {r.after ? (
+ <>
+ <span aria-hidden>→</span>
+ <span className="num font-mono text-[11px]" data-tight-after={`${r.after.start}-${r.after.end}`}>
+ {hms(r.after.start)}–{hms(r.after.end)} ({r.after.seconds.toFixed(2)} s)
+ </span>
+ {r.changed && (
+ <span data-tight-delta={d.toFixed(2)} className={badgeVariants({ variant: d <= 0 ? "meter" : "state", size: "sm" })}>
+ {signed(d)}
+ </span>
+ )}
+ </>
+ ) : (
+ <span className="text-[var(--color-dim)]">{r.why}</span>
+ )}
+ {r.locked && <span className={badgeVariants({ variant: "state", size: "sm" })} title="locked against the widener (resolve-windows); Apply keeps the lock">locked</span>}
+ {!r.fetched && <span className={badgeVariants({ variant: "state", size: "sm" })} title="no cached window holds it: proposed from the cues and the words, no silences">not fetched</span>}
+ {r.clear.cut && <span className={badgeVariants({ variant: "state", size: "sm" })} title="the cut would no longer fit: Apply clears it">clears the cut</span>}
+ {r.changed && r.after && (
+ <span className="ml-auto flex items-center gap-1.5">
+ {s?.k === "applied" ? (
+ <>
+ <span data-tight-applied="" className="text-[11px] text-[var(--color-dim)]">
+ applied{s.note ? ` — ${s.note}` : ""}
+ </span>
+ <button type="button" data-action="tight-undo" className={buttonVariants({ variant: "outline", size: "sm" })} onClick={() => undo(r)}>
+ Undo
+ </button>
+ </>
+ ) : s?.k === "undone" ? (
+ <span className="text-[11px] text-[var(--color-dim)]">undone</span>
+ ) : (
+ <button type="button" data-action="tight-apply" className={buttonVariants({ size: "sm" })} disabled={s?.k === "applying"} onClick={() => apply(r)}>
+ {s?.k === "applying" ? "Applying…" : "Apply"}
+ </button>
+ )}
+ {s?.k === "failed" && (
+ <span role="alert" className="text-[11px] text-reject-text">
+ {s.error}
+ </span>
+ )}
+ </span>
+ )}
+ {(r.how || r.said.length > 0) && (
+ <span className="basis-full pl-6 text-[11px] text-[var(--color-dim)]">
+ {r.how}
+ {r.said.length ? ` — ${r.said.join("; ")}` : ""}
+ {r.words ? ` · words: ${r.words}` : ""}
+ </span>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ {got && (
+ <p className="mt-2 text-[11px] text-[var(--color-dim)]">
+ <code className="font-mono">umtool tighten {project}</code> prints the same list; <code className="font-mono">--apply <clip>[,…]</code> applies rows.
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -1058,6 +1058,7 @@ export default function PlayCut({
exp={clipExport}
clip={item?.clip ? item.id : null}
why={!item?.clip ? "a card is not a clip: nothing to export" : !entry?.media ? "its window is not fetched — fetch it first" : null}
+ around={item?.clip && typeof entry?.start === "number" && typeof entry?.end === "number" ? { start: entry.start, end: entry.end } : null}
/>
<ClipExportStatus exp={clipExport} />
</div>
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -26,7 +26,9 @@ Inbox cannot disagree about what is wrong with one.
| `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)) |
-| `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>`; **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)) |
+| `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>`; **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)) |
| `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)) |
| `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 |
@@ -45,6 +47,7 @@ Inbox cannot disagree about what is wrong with one.
| `snapshot <project> [--label L]` | copy the manifest into `revisions/` |
| `diff <project> <snapshot>` | added / removed / moved / window / retyped, by entry id |
| `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) |
@@ -56,7 +59,8 @@ Inbox cannot disagree about what is wrong with one.
| `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") |
| `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-delete)) |
+| `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 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)) |
| `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` · `candidates [--add]` | **the trailer's beats** (`promo/trailer-beats.json`, the Trailer page's file, what `trailer --beats` reads): 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 ([knobs.md](knobs.md#the-trailers-beats)) |
| `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)) |
@@ -66,6 +70,7 @@ 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)) |
| `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) |
| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) |
| `timeline <project> insert (--to-section N \| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` | a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) |
diff --git a/umtool/docs/clip-bench.md b/umtool/docs/clip-bench.md
@@ -250,6 +250,15 @@ mtime is in the URL: a request whose `v` matches is immutable for an hour, and o
whose `v` does not is served `no-store` rather than handing back the cut from
before the edit.
+## Export ▾ — the clip as a file
+
+The reader's footer has **Export clip** (the clip as the cut plays it), **raw** (the fetched window) and **Export ▾**:
+**As cut (no chrome)**, **With context** (N s either side of what the cut plays, as recorded) and **Raw / full
+exchange** (a from–to span of source seconds, starting at the clip's extent ± 30 s). Each is a umtool job in the heavy
+slot, named from the clip id and its date into the project's `exports/`; what context or a full exchange needs that is
+not on disk is fetched through the editor first, in the same job, and the line under the buttons says so while it
+does. Then Download (a phone's way) and Open folder ([knobs.md](knobs.md#export-one-clip)).
+
## Walking the cut
`p` and `n` (and the links in the header line) move to the previous and next
@@ -475,6 +484,20 @@ uploads of the same event are two clocks). The bench shows them three ways:
*"already in the cut as c03"*, so reading ahead answers "is this missing?"
rather than only "what is out there?".
+## Tighten to the sentence, snap an edge to a pause
+
+Under the waveform, beside the gaps: **Tighten to this sentence** moves both edges to the sentence at the playhead (a
+playhead still parked on the start, where the bench puts it on arrival, is not a place: then every sentence the cut
+touches, else the whole sentences inside the window, else the one it is inside), each edge then into its pause — the
+start back into the quiet before its first word, the end forward into the quiet after its last — and never past the
+cached window. **Snap edge to nearest pause** (**start** / **end**) moves one edge to the middle of the closest pause,
+at most a second away. Both are WRITTEN AT ONCE through the one window writer, like Extend and the gaps — the cite and
+the QR follow the edge, a cut or mute mark the window no longer holds is cleared and said — the moved edge is heard, and
+**Undo** writes back what was there (the edges, and the cut, the mute mark, the cite and the QR when they moved). The
+words and pauses the snap reads are drawn in the zoom: a box per word, the pauses as bands
+([knobs.md](knobs.md#tighten-to-the-sentence-snap-to-a-pause)). The whole cut at once is the Cut tab's **Propose tight
+windows**: a review list, before → after per clip, each row applied by its own **Apply**.
+
## The cue rail
Every cue in view, positioned by time. Inside the selection in full contrast,
diff --git a/umtool/docs/inbox.md b/umtool/docs/inbox.md
@@ -70,6 +70,8 @@ on (`decisionTab`, `songTabOfSection`).
| `link-dead` | blocking | the recorded link check (`umtool links`, out/links.json) found clip QRs that don't open on their site — one row per site, the clips and the first reason | Fix the links |
| `links-unverified` | info | the link check could not reach a site (offline, a timeout, no corpus.json) | Check links again |
| `links-unchecked` | info | archive links never checked, or changed since the check | Check links |
+| `site-deploy-behind` | open | a site the QRs open whose deploy (its recorded corpus.json `generatedAt`) is older than cited videos whose links the check did not find open — one row per site ([knobs.md](knobs.md#the-sites-the-links-depend-on)) | Publish <site> |
+| `clip-link-policy` | open | a clip whose QR breaks the project's link policy (`provenance.linkPolicy`): a direct channel's clip opening an archive, or another clip not opening the policy's site ([knobs.md](knobs.md#the-link-policy)) | Link it by the policy |
| `no-punctuation` | info | a source's ASR has no terminators — one row per project | Check the windows |
| `clip-cue-gap` | open | the cue file ends before a clip does (`cues end 880 s · c03 needs 897 s`), one row per source | Fix the window |
| `claim-unadjudicated` | blocking | a `ledger[]` entry missing any of the six adjudication fields — one row per entry | Adjudicate claim |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -60,6 +60,30 @@ it wrote. The CLI prints *cite followed the edge*, the route answers `citeFollow
before this existed is the check's `clip-cite-off` row (open): *the clock and the QR point 78 s before
the clip*, with **Move to m:ss** (`umtool window <p> <clip> --cite N`).
+## Tighten to the sentence, snap to a pause
+
+What punchy tightening took by hand (silencedetect, en-orig word times read from a VTT) is two buttons on the bench and
+a review list on the Cut tab. Nothing new decides where a sentence or a pause is: the sentence is the phone walk's
+(`lib/report/sentenceEdges.mjs`, read off the cues), the pause is L1's (`report-to-video/pauses.mjs`: the build's
+measured silences, the cut-points route's, and the gaps between the recording's **timed** words — the corpus's
+`words.json`, a whisper `transcript.json`, else the en-orig captions' word starts, `report-to-video/clip-words.mjs`),
+composed in `lib/report/tightWindow.mjs`. Every write is the window writer's (`PUT /api/report/window`, the token, the
+cite and the QR that [follow the edge](#the-cite-follows-the-edge)); a cut or a mute mark the new window no longer holds
+is cleared in the same write, and said.
+
+| | In umtool | From a terminal | Route |
+|---|---|---|---|
+| both edges to the sentence: the one at the playhead (a playhead parked on an edge does not count), else every sentence the clip's cut (its quote) touches, else the whole sentences inside the window, else the one it is inside — then the start back into the pause before its first word and the end forward into the one after its last (0.1 s of quiet, ≤ 1 s away), inside the cached window | clip bench, under the waveform: **Tighten to this sentence**; **Undo** writes back the edges (and the cut, the mute mark, the cite, the QR) it moved | — | `PUT /api/report/window {project, clip, token, start, end}` |
+| one edge to the middle of its nearest pause (≤ 1 s) | **Snap edge to nearest pause**: **start** / **end**; **Undo** | — | same |
+| the words and the pauses, drawn | the bench's zoom, at 20 s or less shown: a box per word with its text (a caption word's box runs to the next word's start), the pauses as bands, the measured silences under them | — | `GET /api/report/clip-editor?project&clip&video&from&to` (`words`, `wordsFrom`, `timed`) |
+| every clip of the cut, proposed: before → after and the seconds either way, what moved and why; **nothing applies without a press** | the Cut tab's **Propose tight windows**: each row's **Apply**, then its **Undo**; **show every clip** lists the ones already tight | `umtool tighten <p> [--json] [--all] [--no-measure]` · `--apply <clip>[,<clip>…]` | `GET /api/report/tighten?project=<p>[&clip=…][&measure=0]`, each Apply a `PUT /api/report/window` |
+
+The batch has no playhead: the cut's sentences, else the whole ones in the window. A clip with nothing on disk is
+proposed from its cues and words (no silences) and says *not fetched*; one whose recording has no cues says so and is
+left. **A lock is not a refusal**: `lock`/`lockStart`/`lockEnd` pin an edge against `resolve-windows --write`, not
+against a person, so a locked clip is proposed like any other, its row says *locked*, and Apply keeps the lock. The batch
+is the project's cut; a take's clips are tightened on the take's bench (the take's patch, as every save there).
+
## Take patches follow a removal
A take patch beside the manifest (`*.patch.json`, the file `umtool take --patch` reads) that carries
@@ -88,6 +112,37 @@ site: *12 of 124 QR links don't open on anilyzer.pages.dev (deployed 2026-10-09)
the site serves as `v<id>`, and only a link still exactly what the check saw — through the window writer,
then checks again. A platform link (YouTube's own page) is not an archive link and is not checked.
+### The sites the links depend on
+
+The project page's Overview names every site a clip QR opens (**Sites the links depend on**): the site
+whose `site.json` `siteUrl` is that origin, how many links and clips it carries, and its deploy's date
+— the `corpus.json` `generatedAt` the last link check read (`out/links.json`; the page never fetches;
+**Check links** reads them again). A cited video **newer than that deploy** — uploaded after it, or
+transcribed here after it — whose link the check did not find open is named under it, and is the
+check's `site-deploy-behind` row (open, one per site): *anilyzer's deploy is from 2026-10-09; 3 cited
+videos are newer: …*. Its **Publish anilyzer** asks the editor to build and deploy that site (`POST
+/api/report/publish-site {project, siteId}` → the editor's ops `build-deploy`, its publish queue, each
+stage through the heavy slot); from a terminal, `pnpm ops build-deploy --json '{"siteId":"anilyzer"}'`.
+A link the check opened is on the site, whatever its dates say.
+
+## The link policy
+
+"Cite via site X; these channels direct." `provenance.linkPolicy` — `{via?, direct?}`: `via` the archive
+every clip's QR opens (an origin; absent: `provenance.siteOrigin`), `direct` the channel slugs whose
+clips link the platform's own page at the cite (YouTube `t=<s>s`, Twitch `t=<h>h<m>m<s>s`, Rumble
+`start=<s>`, from the record's `webpage_url`). Set on the project page's Overview (**Link policy**:
+**Cite via**, a box per channel the cut cites, **Save link policy**), `umtool link-policy <p> --via
+<site id | https://…> --direct a,b` (`''` clears one, `--clear` the policy), or `PUT
+/api/report/link-policy {project, token, policy}`. Saving rewrites no clip. **New clips are written
+by it**: every inserter (`addClip` — the strip's selection, the clip finder, a live share — and
+`insertEntry` — `umtool timeline insert`, the Cut tab) gives a new clip the policy's link when its own
+would break it (a neighbour's copied citeUrl included). The clips already in the cut that break it are
+the check's `clip-link-policy` rows (open, one per clip), each with its one press — **Link via
+site.test** / **Link its YouTube page**, the citeUrl through the window writer — and its terminal twin
+(`umtool window <p> <clip> --cite-url '…'`); `umtool link-policy <p> --fix` does them all. A direct
+clip whose record names no `webpage_url` is a row without a fix. A clip with its own media (`src`) is
+not judged.
+
## Gaps inside a clip
A clip may leave seconds out of its middle: you suggest one long clip and cut a gap or two out of it, rather than
@@ -139,8 +194,11 @@ second under it stays there; **−** / **+** / **Fit** / **Zoom to selection** (
selection); keys `z` in, `Z` out, `f` fit, `F` to the selection. Zoomed, the wheel pans (either axis), and an
**overview** strip under the waveform shows the whole cached window with what is shown, the selection and the gaps:
drag it to pan, click elsewhere to centre, pinch it with two fingers. A ruler of round ticks sits over a zoomed
-waveform; at 20 s across or closer it also draws the measured silences (the cut-points route's, the build's own) and
-the pauses between words (when the project's words file is this recording's), so a gap's edge goes between two words.
+waveform; at 20 s across or closer it also draws the measured silences (the cut-points route's, the build's own), the
+pauses (those silences and the gaps between timed words, merged) as bands, and a box per word with its text — the
+project's words file when it is this recording's, else the corpus's (`words.json`, a whisper transcript, the en-orig
+captions' word starts: `report-to-video/clip-words.mjs`) — so a gap's edge, or a tightened one
+([below](#tighten-to-the-sentence-snap-to-a-pause)), goes between two words.
At fit — the default, on every clip — the waveform is what it always was. The same zoom is on Play the cut's reel strip,
over cut seconds ([below](#the-reel-strip-zoom-and-reorder)).
@@ -590,16 +648,19 @@ left to transcribe.
## Export one clip
-A clean mp4 of ONE clip, to post or hand on: the clip's footage as the cut plays it, with none of the deck — no rail,
-subtitles, QR, cards or stamps — written to the project's **`exports/`** (beside the hand-made ones) as
-`<clip>-<YYYY-MM-DD>-<slug>.mp4` (`<clip>-raw-…` for raw): the clip's date (its `date`, else the on-screen date, else
-the upload date; today with none) and the first words of its quote (else its title, else the video id). The same name
-again is written over.
+A clean mp4 of ONE clip, to post or hand on, with none of the deck — no rail, subtitles, QR, cards or stamps — written
+to the project's **`exports/`** (beside the hand-made ones) as `<clip>[-<kind>]-<YYYY-MM-DD>-<slug>.mp4`: the clip's
+date (its `date`, else the on-screen date, else the upload date; today with none) and the first words of its quote
+(else its title, else the video id). The kind is in the name — `-ctx<N>` with context, `-raw` for the fetched window,
+`-raw-<from>-<to>` for a span (the full exchange) — so the kinds never overwrite each other; the same export again is
+written over. Three kinds (UI notes 2026-10-30, item 12), the bench's and Play's **Export ▾**:
| | In umtool | From a terminal | Route |
|---|---|---|---|
-| the clip as the cut plays it | the clip bench's reader, **Export clip** (on a phone too); Play the cut, **Export clip** under the transport (the clip at the playhead) or a note's **Export <clip>** | `umtool export <p> <clip> [--take <t>] [--json]` | `POST /api/report/clip-export {project, clip, take?, kind?: "cut"}` |
-| the whole fetched window, as recorded | **raw** beside it | `umtool export <p> <clip> --raw` | `… {kind: "raw"}` |
+| **as cut (no chrome)**: the clip as the cut plays it | **Export clip**, or Export ▾ → **As cut (no chrome)** — the clip bench's reader (on a phone too); Play the cut under the transport (the clip at the playhead) or a note's **Export <clip>** | `umtool export <p> <clip> [--take <t>] [--json]` | `POST /api/report/clip-export {project, clip, take?, kind?: "cut"}` |
+| **with N s of context**: what the cut plays and N s either side (1–120, default 5), as recorded | Export ▾ → **With context**, the seconds beside it | `umtool export <p> <clip> --context N [--fetch]` | `… {kind: "context", context: N, fetch?: true}` |
+| **raw / full exchange**: a stretch of the recording as recorded — the clip and the fetch pad (**raw**), or a span of source seconds | **raw** beside Export clip; Export ▾ → **Raw / full exchange**, from–to (starting at the clip's extent ± 30 s) | `umtool export <p> <clip> --raw [--from S --to S] [--fetch]` | `… {kind: "raw", span?: {from, to}, fetch?: true}` |
+| the export's job | the status line under the buttons (*Fetching what it needs through the editor, then exporting…*, the job's last line), then the file | — | `GET /api/report/clip-export?job=<id>` → `{job, done?, error?}` |
| the file | **Download** (an attachment; the phone's way) | the path it prints | `GET /api/report/exports?project=<p>&name=<file>` (`GET …?project=<p>` lists them) |
| `exports/` in this machine's file manager, the file selected | **Open folder** | `--open` | `POST /api/report/exports {project, name?}` |
@@ -609,19 +670,30 @@ again is written over.
its **`gaps`** out as jump cuts on the frame grid with the build's 25 ms join fades, its sound **silenced** where the
cut silences it (`muteFrom`, a locked edge: `mute.mjs` soundOnSegment), its `audio` knobs (offset, gain, fades) and
the cut's loudness gain. Not applied: a blur (the export is unblurred, and says so), a montage's phrase cut.
-- **Raw**: the clip and the build's fetch pad either side (`render.fetchPad`, 3 s), clamped to the cached file — no
- gaps, no mute, no knobs.
+- **With context, and raw**: as recorded — no gaps, no mute, no knobs — from the tightest cached window of the
+ recording that **holds** the span (a wider fetch than the build's own source, often); where none does, clamped to
+ what is there and said (*the cached window ends 8.00 s before what was asked*).
+- **A umtool job, in the heavy slot.** Every export from the app is ONE job on the app's runner (`lib/jobs.ts`: one at
+ a time — a second job is a 409 naming the first — with a log and Stop): `umtool export … --progress ndjson`, which
+ takes the machine's heavy slot itself (`report-to-video/heavy-gate.mjs`) declaring a small estimate (600 MB), so it
+ runs beside others while memory allows and waits at the door in render mode. A terminal's `umtool export` takes the
+ same slot.
+- **Fetched if needed, through the editor.** A context or raw export whose span no cached window holds is refused —
+ *not on disk (−2 s / +14 s around the clip)* — unless asked with `fetch` (Export ▾ always asks, `--fetch` from a
+ terminal): then the same job first asks the editor for the window (`fetch-via-editor.mjs --fetch-only` with those
+ pads, the bench's own path: `POST /api/media/fetch-window`, paced, cookie-aware, provenanced; `UMTOOL_LOCAL_FETCH=1`
+ the pipeline's own), and cuts from what lands. A pad is at most 120 s either side of the clip's extent. **As cut**
+ fetches nothing: a clip whose window is not on disk is refused — "fetch it first" (the Cut tab's Fetch, `umtool
+ fetch <p>`); the buttons say so before you press them. On the bench the export is of the SAVED clip: save an edge
+ you moved first.
- **The encode**: cut on the input and re-encoded, so every cut is frame-exact — libx264 crf 18, yuv420p, AAC 192k,
- `+faststart`, no metadata or chapters. A few seconds for a short clip (≈10 s for 30 s of 720p); it does not take
- the heavy slot or the job runner, so it never waits behind a build. A second ask for the same file waits for the
- first.
-- **Nothing is fetched.** A clip whose window is not on disk is refused — "fetch it first" (the Cut tab's Fetch,
- `umtool fetch <p>`); the buttons say so before you press them. On the bench the export is of the SAVED clip: save an
- edge you moved first.
+ `+faststart`, no metadata or chapters. A few seconds for a short clip (≈10 s for 30 s of 720p).
- **Open folder** asks the desktop: `org.freedesktop.FileManager1.ShowItems` over the session bus (the file
selected), else `xdg-open <exports/>` on Linux; `open -R` on macOS. Refused, with the reason, inside a container,
on another OS, and from any device but the machine umtool runs on (by the request's Host, Origin and
X-Forwarded-For) — use **Download** there.
+- **No "send to phone".** Nothing in the repo sends a file to a phone (no share path, no pairing); **Download** from the
+ phone's browser is the way, and the option was left out rather than invented.
## The trailer's beats
@@ -647,20 +719,53 @@ length here ([report-video.md](report-video.md#trailer-from-the-master)).
| the limit, the crossfade, the intro | **limit** (a platform, or seconds), **crossfade**, **open on the brand intro** | `limit <s\|m:ss\|x\|instagram\|shorts\|tiktok\|default>` · `xfade <s>` · `intro on\|off` | `{op: "settings", limit?, xfade?, intro?}` |
| the walk's ★ clips | **★ from the walk**: each **Add** | `umtool trailer-beats <p> candidates [--add]` | `GET` (`candidates`) |
-## Takes: relabel, supersede, delete
+## Takes: relabel, supersede, cancel, delete, fork as variant, compare
| | In umtool | From a terminal | Route |
|---|---|---|---|
| list | the Takes page | `umtool takes ls <p> [--json]` (picked, superseded, RENDERING) | `GET /api/report/takes` |
| relabel (take.json's `label`; an undo point in the take's `revisions/`) | a take's ✎ | `umtool takes relabel <p> <take> <label…>` | `POST /api/report/takes/housekeeping {project, take, op: "relabel", label}` |
| superseded (verdicts.json `superseded: {by, at}`; folded away in the list, nothing deleted; a pick clears it) | **Mark superseded** (by a take), **Not superseded**; **show them** in the group | `umtool takes supersede <p> <take> [--by <take>]` · `--clear` | `{op: "supersede", by?}` · `{op: "unsupersede"}` |
-| delete `takes/<take>/` | **Delete take** (the plan first) | `umtool takes delete <p> <take> [--dry-run] [--force]` | `POST /api/report/takes/delete {project, take, dryRun?, force?}` |
+| **cancel a take while it renders** — its render stopped, the take marked cancelled (`takes/<take>/cancelled.json`), render mode let go if it held it | **Cancel render** on the take's card (a rebuild) or on its *rendering now* row (a first render, which has no card yet) | `umtool takes cancel <p> <take> [--json]` | `{op: "cancel"}` → `{stopped, how, cancelled, renderMode, said}` |
+| delete `takes/<take>/` | **Delete take** (the plan first) — a cancelled first render too, under **show them** | `umtool takes delete <p> <take> [--dry-run] [--force]` | `POST /api/report/takes/delete {project, take, dryRun?, force?}` |
+| **fork as variant** — the take as a project beside this one (see below) | **Fork as variant** on the card (the name, default `v-<take>`), then a link to it and **compare** | `umtool takes fork <p> <take> [--name N] [--json]` | `{op: "fork", name?}` → `{id, take, links, copied, variant}` |
+| **compare two takes side by side** — of the project or of it and its variants | **Compare with…** on the card → `/projects/<p>/takes/compare?a=<project>:<take>&b=<project>:<take>`: two players in step (one transport: **Play both**, ±5 s, the seek bar; B pulled back to A past 0.15 s; **sound A / B**), then what differs | `umtool takes compare <p> <a> <b> [--json]` (`<take>` or `<project>:<take>`) | — (the page reads `lib/report/takeCompare.mjs`) |
**What a running render names is respected**: a take whose build lock (`takes/<id>/.building.json`) is live is
rendering — its take.json is written last, from the label it started with — and a take a live build names as its
-`from` is that build's base. Relabel and delete are refused for both (`force` does not pass it); a supersede mark is
+`from` is that build's base. Relabel, delete and fork are refused for both (`force` does not pass it); a supersede mark is
not (no render writes verdicts.json).
+**Cancel is a request the take maker answers** (`lib/report/takeCancel.mjs`). The route writes `takes/<id>/.cancel.json`
+beside a live lock on this machine (refused, in words, for a take not rendering or rendering on another host); the take
+maker — the app's take job or a `umtool take` in a terminal, whichever holds the lock — polls for it, stops its render
+(the render runs in a process group of its own, `takeRender.mjs`: TERM to the whole group — queue-lock, build-video,
+every ffmpeg — then KILL after 8 s; a signal to the take process itself is passed on the same way), removes the
+half-made manifest, writes `cancelled.json` (`{at, by, label, rebuild}`) and exits; its build lock goes, and render mode
+with it when the take held it (`--priority`). The page waits for that (15 s), then — for the app's own job that did not
+answer — stops the job; render mode is released after a holder that went without letting go. A first render cancelled
+is a work dir with no take.json: the list folds it away (**N cancelled renders folded away · show them**), each with
+**Delete take**. A rebuild cancelled keeps its last take whole, its card marked **last render cancelled**. Made again,
+the take's mark is cleared.
+
+**A variant is a project beside its parent** (a narrative variant of the cut — not the encode ladder's variants of
+[Make variants](#make-variants-and-the-sync-report)) — as the hand copies were (`emberparadox/v-a-cold-open` …), because a
+project is a leaf of the walk and cannot sit inside one — so the walk, the cut, takes and Deliver all work on it
+unchanged. `lib/report/variantFork.mjs` writes: `video.manifest.json` (the take's — the one it was rendered from; a
+draft's resolved from its patch — its `slug` the variant's name), `variant.json` (`{variantOf, fromTake, takeLabel,
+forkedAt, baseHash}`), a README, `out/clips-raw` and `out/narration` as links to the parent's (the fetched media
+reused, never copied, as a take's out/ links them), a link to each of the parent's top-level files or folders the
+manifest names by a relative path (`shots/`, `posts-media/` …), `module-config.json` copied (a variant's modules are
+its own), and the take itself under `takes/<take>/` (its preview a hard link, its take.json a reference take of the
+variant's manifest, `forkedFrom` naming where it came from). Refused while the take renders, for a name that is not one
+path segment, or one already beside it. The parent's Takes page names its variants, a variant's its parent; **Compare
+with…** lists every take of the family.
+
+**What the compare lists** (`lib/report/takeCompare.mjs`): the facts side by side (project, take, label, length, clips,
+window, style, built — the ones that differ in full contrast); the cut's changes A → B (`manifest-diff.mjs`: entries
+added, removed, moved, their windows and other fields), one line each; and every leaf of the manifests outside the
+timeline that differs (`render.crf: 30 → 34`, `slug`, a title), at most 200.
+
## Make variants, and the sync report
| | In umtool | From a terminal | Route |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -945,7 +945,8 @@ them and records the verdicts.
```
takes/<id>/take.json id (== dir, [a-z0-9-]), group, order, label,
kind reference|similar|different, preview;
- optional summary, changes[], seconds, builtAt
+ optional summary, changes[], seconds, builtAt,
+ renderSeconds (the render's own time: the next take's ETA)
takes/<id>/preview.mp4 whatever `preview` names, inside the take dir
takes/<id>/out/<slug>.mp4 the take maker's render again, a hard link of preview.mp4
(what `umtool variants --take` and Deliver encode)
@@ -1167,6 +1168,19 @@ take: done, failed, or stopped (Ctrl-C, the job's Stop). A window ends at its `u
it at once, and the editor's heartbeat releases its lanes. Close Firefox and other heavy
apps while it renders.
+**The render queue and a take's ETA.** Under the banner, **Render queue** says what the heavy
+slot is doing, read from its own files (`common/lib/heavyQueue.mjs`; `GET /api/render-queue`):
+each job running in it (an e2e suite by its queue's name, a `next build`, a render by its take
+and project) with its worktree, its declared memory and for how long; each job **waiting** at
+it and for what — the render (render mode), the line, the slot, memory, the build slot — from
+the waiting tickets queue-lock keeps (`heavy-queue.lock.waiting/<pid>.json`); "held by …";
+MemAvailable against the floor. Beside it, **the ETA of a whole-cut take** of this project,
+made from the newest take and fresh: the median seconds of render per second of video over the
+project's past renders of that kind (`lib/report/takeEta.mjs`) — the `renderSeconds` a take
+records (from the build's first event, so a wait at the slot is not counted), else the take's
+own files (its `video.manifest.json`, written as the render starts, to `builtAt`), less any
+wait its `<take>.log` reports. With no render of a kind it says it used the others.
+
### A take's work files, and pruning them
A take's build leaves behind what makes the NEXT build fast: its clip segments, the chrome
@@ -1537,6 +1551,32 @@ fallback?, inReference?, why?}}}` — keyed by the source moment, as the
rulings are, so a re-seed keeps it. A clip with no window on disk, or no
speech in it, has `score: null` and says why.
+### The speaker check on the walk: which of several voices
+
+The voice match scores every clip against one voice, the host's. A panel show needs more: which of
+**several named voices** a clip is. `umtool speaker-check <project> [--clip <id> …]` scores each clip
+the same way (TitaNet-small through sherpa-onnx, local; the phrase ± 1 s, voiced frames only) against
+each voice in `<project>/speakers.json` —
+
+```json
+{ "speakers": [ { "name": "Ember", "clips": ["e01", "e07"] },
+ { "name": "Kirsche", "videos": ["kirsche/abc123"], "channels": ["kirsche"] } ] }
+```
+
+— a voice's **clips** of this cut, **videos** of that voice alone (the first 60 s of speech, in
+pieces), or **channels** whose solo recordings it is (the voice match's heuristic). A clip in a voice's
+set is scored against the rest of it. The answer is `<project>/speaker-check.json` (a check of one clip
+keeps the others' rows; new reference sets start it over): per clip, every voice's score best first,
+and `matches` (the best ≥ 0.42 and 0.05 ahead of the next), `none` (every one under 0.30: a voice the
+sets do not hold) or `unsure`.
+
+On the clip bench's walk the verdict bar says **Speaker: matches Ember 0.93 / Kirsche 0.83**, with the
+reference sets it was measured against; **Check speaker** queues the check of that clip as a job
+through the machine's heavy slot (`queue-lock --heavy --estimate 800`: beside other jobs by memory,
+after a render in render mode), and **Add to a voice** puts the clip in a voice's set (made when new).
+From a terminal: `umtool speaker-check <p> --set 'Ember=e01,e07' --set 'Kirsche=kirsche/abc123,channel:kirsche'`,
+`--remove <name>`, `--list`. An aid to the ear: it rules on nothing.
+
## Highlights: the clip finder
A long recording cut down to its best moments — a stream, a podcast, a host
diff --git a/umtool/e2e/clip-export.spec.ts b/umtool/e2e/clip-export.spec.ts
@@ -21,6 +21,9 @@ const HERE = path.dirname(fileURLToPath(import.meta.url));
const FIXTURE = path.join(HERE, "..", ".e2e-song");
const PLAY = "reports/play-cut-fixture";
const WALK = "reports/phone-walk-fixture";
+const EXPORT = "reports/export-fixture";
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const SHOTS = process.env.U3_SHOTS ?? null;
const exportsOf = (project: string) => path.join(FIXTURE, ...project.split("/"), "exports");
const OPEN_LOG = path.join(FIXTURE, "open-folder.jsonl");
@@ -29,7 +32,7 @@ test.beforeEach(() => {
});
test.afterAll(() => {
- for (const p of [PLAY, WALK]) rmSync(exportsOf(p), { recursive: true, force: true });
+ for (const p of [PLAY, WALK, EXPORT]) rmSync(exportsOf(p), { recursive: true, force: true });
});
const ready = async (page: Page) => {
@@ -107,3 +110,49 @@ test("the bench on a phone: Export clip in the reader, then Download", async ({
expect(await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth)).toBeLessThanOrEqual(0);
await page.screenshot({ path: test.info().outputPath("bench-export-390.png") });
});
+
+test("Export ▾ on the bench: with N s of context, and the full exchange fetched through the editor first", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.clipBenchHref(EXPORT, "x01"));
+ await expect(page.locator('[data-bench="x01"]')).toHaveCount(1);
+ const menu = page.locator('[data-clip-export-menu="x01"]');
+ await menu.scrollIntoViewIfNeeded();
+ await expect(menu).toBeEnabled();
+ await menu.click();
+ const options = page.locator("[data-clip-export-options]");
+ await expect(options).toBeVisible();
+ await expect(options.locator('[data-clip-export-kind="cut"]')).toHaveText("As cut (no chrome)");
+ // The full exchange starts from the clip's extent ± 30 s (the recording starts at 0).
+ await expect(options.locator("[data-clip-export-from]")).toHaveValue("0");
+ await expect(options.locator("[data-clip-export-to]")).toHaveValue("36");
+ await page.screenshot({ path: test.info().outputPath("bench-export-menu.png") });
+ if (SHOTS) await page.screenshot({ path: path.join(SHOTS, "u3-3-export-menu.png") });
+
+ // With 2 s of context: the cached 0–9 window holds it, nothing is fetched.
+ await options.locator("[data-clip-export-context]").fill("2");
+ await options.locator('[data-clip-export-kind="context"]').click();
+ const state = page.locator("[data-clip-export-state]");
+ await expect(state).toHaveAttribute("data-clip-export-state", "ready", { timeout: 60_000 });
+ await expect(state).toHaveAttribute("data-clip-export-name", "x01-ctx2-2026-07-22-the-full-exchange.mp4");
+ await expect(state).toContainText("the cut with 2 s either side, as recorded");
+ expect(existsSync(path.join(exportsOf(EXPORT), "x01-ctx2-2026-07-22-the-full-exchange.mp4"))).toBe(true);
+
+ // A context the cache does not hold, asked without `fetch`: refused, with what it needs.
+ const no = await page.request.post("/api/report/clip-export", { data: { project: EXPORT, clip: "x01", kind: "context", context: 20 } });
+ expect(no.status()).toBe(409);
+ expect(((await no.json()) as { error: string }).error).toContain("not on disk");
+
+ // The full exchange, 0–20 s: past the cached 9 s, so the job asks the editor first (fetch-window), then cuts it.
+ await menu.click();
+ await options.locator("[data-clip-export-from]").fill("0");
+ await options.locator("[data-clip-export-to]").fill("20");
+ await options.locator('[data-clip-export-kind="raw"]').click();
+ await expect(state).toHaveAttribute("data-clip-export-name", "x01-raw-0-20-2026-07-22-the-full-exchange.mp4", { timeout: 90_000 });
+ await expect(state).toContainText("the span asked for, as recorded");
+ const asked = JSON.parse(readFileSync(STUB_LOG, "utf8")) as { videoId?: string; clipId?: string; from?: number; to?: number }[];
+ const fetchAsk = asked.filter((r) => r.videoId === "exportvid").at(-1);
+ expect(fetchAsk?.clipId).toBe("x01");
+ expect(fetchAsk?.from).toBe(0);
+ expect(fetchAsk?.to).toBe(20);
+ expect(existsSync(path.join(exportsOf(EXPORT), "x01-raw-0-20-2026-07-22-the-full-exchange.mp4"))).toBe(true);
+});
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -976,6 +976,17 @@ function generationRoute(req, res, url, auth) {
req.resume();
return json(res, 200, { ok: true, key: "autoQueue", value: lanes });
}
+ // "Publish <site>" (umtool's /api/report/publish-site, UI notes #9): the
+ // editor's build-deploy alias. Recorded; a site named "refused" is refused
+ // the way the editor refuses a private one.
+ if (req.method === "POST" && url.pathname === "/api/ops/build-deploy") {
+ return readBody(req, (body) => {
+ requests.push({ route: "build-deploy", ...(body ?? {}), authorization: auth });
+ record();
+ if (body?.siteId === "refused") return json(res, 400, { ok: false, error: "refused is private: it never deploys" });
+ return json(res, 200, { ok: true, jobId: `deploy-${nextJob}`, jobs: [{ siteId: body?.siteId, jobId: `deploy-${nextJob++}` }], skipped: [] });
+ });
+ }
if (req.method === "POST" && url.pathname === "/api/ops/lane") {
return readBody(req, (body) => {
requests.push({ route: "lane", ...(body ?? {}), authorization: auth });
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -36,6 +36,7 @@ import { makeClipEditorFixture } from "./clip-editor-fixture.mjs";
import { makeBenchShellFixture } from "./bench-shell-fixture.mjs";
import { makeTakeWalkFixture } from "./take-walk-fixture.mjs";
import { makeCutIntegrityFixture } from "./cut-integrity-fixture.mjs";
+import { makeUiOpsFixture } from "./ui-ops-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
import { makeDigestContextFixture } from "./digest-context-fixture.mjs";
@@ -799,6 +800,14 @@ const CUES = {
// widen every vid1 cache -- and the phone walk asserts where its cache ENDS
// (a sentence past it is offered as a fetch). Source isolation, as vid3/vid4.
CUES.walk1 = CUES.vid1.map((r) => [...r]);
+// The tighten spec's source (tighten.spec.ts): vid1's words under a name of its own, with a
+// words.json sidecar of TIMED words written below -- what the bench's word boxes draw and what the
+// pause snap reads (report-to-video clip-words.mjs) -- laid on the tone window's silences
+// (2.9-3.1, 5.9-6.1).
+CUES.tightvid = CUES.vid1.map((r) => [...r]);
+// The clip-export spec's Export ▾ source (clip-export.spec.ts): a recording nothing else fetches, so
+// its full-exchange fetch (through the editor stub) moves no other spec's cache.
+CUES.exportvid = CUES.vid1.map((r) => [...r]);
for (const [vid, rows] of Object.entries(CUES)) {
const dir = path.join(CHANNELS, "testchan", "data", vid);
mkdirSync(dir, { recursive: true });
@@ -1490,6 +1499,17 @@ if (argv.includes("--version")) {
process.stdout.write("qrencode version 0.0.0-fixture\\n");
process.exit(0);
}
+// A RENDER IN PROGRESS, on demand (take-variants.spec.ts cancels one): while
+// <bin>/qrencode.stall-ms exists the stub records its pid beside it and sleeps
+// that long first -- a build that is plainly rendering, for as long as asked.
+{
+ const { existsSync, readFileSync, writeFileSync } = await import("node:fs");
+ const stall = ${JSON.stringify(path.join(BIN, "qrencode.stall-ms"))};
+ if (existsSync(stall)) {
+ writeFileSync(${JSON.stringify(path.join(BIN, "qrencode.stall.pid"))}, String(process.pid));
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(readFileSync(stall, "utf8")) || 0);
+ }
+}
const i = argv.indexOf("-o");
if (i < 0) process.exit(2);
const out = argv[i + 1];
@@ -1856,6 +1876,8 @@ makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out"
makeTakeWalkFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Cut integrity (UI notes 2026-10-30): the cite following the edge, repeatOf, ★ and walk notes, take patch markers, the QR link check (cut-integrity.spec.ts).
makeCutIntegrityFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
+// ui-ops.spec's own project and channels (UI notes #9 #10 #15 #18).
+makeUiOpsFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), ff });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 36 lane D: the assistant's labels, Suggest, Ask and Apply in the clip editor (clips-suggest.spec.ts).
@@ -1893,6 +1915,43 @@ makeIntakeFixture({ reports, channels: CHANNELS, deckManifest, cachedWindow: pat
mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "gapvid_0.00-9.00.mp4"));
}
+// Tighten to the sentence, snap an edge to its pause, and the batch's proposals (tighten.spec.ts),
+// which WRITES (the spec puts the manifest back before each test): its own project on tightvid
+// (vid1's cues; sentences 0-3, 3-9, 9-12), the tone window cached as tightvid_0.00-9.00.mp4, and
+// the recording's timed words in the corpus (data/tightvid/words.json).
+// t01 tightvid 1.2-7.4 both edges mid-sentence: tightens to the sentence 3-9 (bounded by the cache's 9)
+// t02 tightvid 3.0-9.0 already the sentence: already tight
+// t03 tightvid 0.5-8.6 a cut 3.5-5.0 inside it (the quote): the cut's sentence, 3-9
+{
+ const g = manifest("tight-fixture", "The Tight Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "t01", video: "tightvid", start: 1.2, end: 7.4, cite: 1, section: 0, quote: "and this one runs on and because" },
+ { type: "clip", id: "t02", video: "tightvid", start: 3.0, end: 9.0, cite: 3, section: 0, quote: "and this one runs on and because of that it finishes here" },
+ { type: "clip", id: "t03", video: "tightvid", start: 0.5, end: 8.6, cutStart: 3.5, cutEnd: 5.0, cite: 0, section: 0, quote: "runs on and because" },
+ ]);
+ g.render.fetchPad = 0;
+ const dir = writeProject("tight-fixture", g);
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "tightvid_0.00-9.00.mp4"));
+ const words = [
+ ["This", 0.2, 0.5], ["is", 0.55, 0.7], ["a", 0.75, 0.8], ["complete", 0.9, 1.6], ["sentence.", 1.7, 2.8],
+ ["And", 3.2, 3.5], ["this", 3.55, 3.8], ["one", 3.85, 4.1], ["runs", 4.15, 4.5], ["on", 4.55, 4.7], ["and", 4.75, 5], ["because", 5.1, 5.85],
+ ["of", 6.2, 6.4], ["that", 6.45, 6.8], ["it", 6.85, 7], ["finishes", 7.1, 7.9], ["here.", 8, 8.8],
+ ["Another", 9.2, 9.8], ["whole", 9.9, 10.3], ["sentence", 10.4, 11], ["entirely.", 11.1, 11.8],
+ ].map(([w, start, end]) => ({ w, start, end }));
+ writeFileSync(path.join(CHANNELS, "testchan", "data", "tightvid", "words.json"), JSON.stringify({ words }, null, 1));
+}
+// Export ▾ (clip-export.spec.ts, UI notes item 12): with context and the full exchange, which WRITES
+// exports/ and -- through the editor stub's fetch-window -- a wider window of exportvid in the corpus.
+// x01 exportvid 2.0-6.0, the tone window cached as exportvid_0.00-9.00.mp4
+{
+ const g = manifest("export-fixture", "The Export Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "x01", video: "exportvid", start: 2.0, end: 6.0, cite: 2, section: 0, date: "2026-07-22", quote: "the full exchange" },
+ ]);
+ g.render.fetchPad = 0;
+ const dir = writeProject("export-fixture", g);
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "exportvid_0.00-9.00.mp4"));
+}
// A clip fetched PER KEPT PIECE (pieced.spec.ts, fetch-per-piece): no window holds its extent, the
// pieces do. READ-ONLY (the spec writes nothing), so one project serves it.
// pc01 pcvid 1-98, gap 8-91 (83 s out): both pieces on disk -- raw windows 0-9 and 90-99
@@ -2161,6 +2220,36 @@ take("intro-a", { group: "opening", order: 5, label: "Cold open", kind: "similar
take("bad-kind", { group: "finale", order: 4, label: "Bad", kind: "maybe" });
mkdirSync(path.join(TAKES, "takes", "current", "out"), { recursive: true });
+// variants-fixture: take housekeeping, the rest (take-variants.spec.ts, UI notes item 19) -- Cancel a
+// take while it renders (a real render, held in the qrencode stub's stall), Fork as variant (a
+// project made beside it: v-draft-2, removed by the spec), two takes compared. WRITES takes/.
+// m01 vid1 3-6, its window cached; two takes rendered by hand:
+// draft-1 the manifest as it is (a 330 Hz preview)
+// draft-2 m01 tightened to 3.5-6, render.crf 34 (a 440 Hz preview)
+{
+ const base = manifest("variants-fixture", "The Variants Fixture", { siteOrigin: "https://archive.example" }, [
+ { type: "clip", id: "m01", video: "vid1", start: 3, end: 6, cite: 3, section: 0, lock: true, quote: "and because" },
+ ]);
+ const dir = writeProject("variants-fixture", base);
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4"));
+ const tight = { ...base, render: { ...base.render, crf: 34 }, timeline: [{ ...base.timeline[0], start: 3.5 }] };
+ const vtake = (id, doc, m, hz) => {
+ const tdir = path.join(dir, "takes", id);
+ mkdirSync(tdir, { recursive: true });
+ writeFileSync(path.join(tdir, "take.json"), JSON.stringify({ id, preview: "preview.mp4", group: "drafts", kind: "different", seconds: 2, window: "full", ...doc }, null, 2));
+ writeFileSync(path.join(tdir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+ ff([
+ "-f", "lavfi", "-i", "testsrc=size=320x180:rate=15:duration=2",
+ "-f", "lavfi", "-i", `sine=frequency=${hz}:duration=2`,
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", "-movflags", "+faststart",
+ path.join(tdir, "preview.mp4"),
+ ]);
+ };
+ vtake("draft-1", { order: 1, label: "draft 1", kind: "reference", builtAt: "2026-10-30T10:00:00Z" }, base, 330);
+ vtake("draft-2", { order: 2, label: "draft 2: tighter", builtAt: "2026-10-31T10:00:00Z", changes: ["m01 3.5-6 (was 3-6)", "render.crf: 34 (was 30)"] }, tight, 440);
+}
+
// takes-make-fixture: a project the take MAKER makes takes of (takes.spec.ts:
// New take -> the take appears -> Use this take). One clip, its window cached
// in out/clips-raw (the take links it, never fetches), no takes/ yet. Its own
diff --git a/umtool/e2e/fixtures/ui-ops-fixture.mjs b/umtool/e2e/fixtures/ui-ops-fixture.mjs
@@ -0,0 +1,109 @@
+// What ui-ops.spec.ts acts on (UI notes 2026-10-30, #9 #10 #15 #18): its own
+// project and its own two channels, written by that spec alone.
+//
+// channels/uiopschan/ u1 (uploaded 2025-01-01, transcribed here long ago)
+// u2 (uploaded 2026-10-20: newer than the site's deploy)
+// channels/uiopsdirect/ d1, a YouTube upload (webpageUrl) -- the channel the
+// link policy links direct
+// reports/ui-ops-fixture/
+// video.manifest.json o01 u1, o02 u2, o03 d1; every QR on the spec's own
+// site (a local server; SITE_PLACEHOLDER is replaced
+// with its origin before a page opens)
+// takes/draft-0..2 three past renders of the whole cut (take.json
+// seconds + renderSeconds), and draft-2 made `from`
+// draft-1: the ETA's records
+// draft-0.log an older render's log line ("take draft-0: done (…)"),
+// the ETA's other source
+// out/clips-raw/ u1 0.00-9.00, so the speaker check has a window
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, utimesSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const UI_OPS = "ui-ops-fixture";
+export const UI_OPS_SITE_PLACEHOLDER = "http://127.0.0.1:9";
+export const UI_OPS_SPEAKER = "ui-ops-speaker-fixture";
+
+const write = (dir, name, doc) => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), typeof doc === "string" ? doc : JSON.stringify(doc, null, 2) + "\n");
+};
+
+const LONG_AGO = new Date("2025-01-02T00:00:00Z");
+
+function source(channels, slug, id, { uploadDate, webpageUrl, old = true }) {
+ const dir = path.join(channels, slug, "data", id);
+ const cues = Array.from({ length: 30 }, (_, i) => ({ start: i * 2, end: i * 2 + 2, text: `Line ${i} of ${id}.` }));
+ write(dir, "transcript.cues.json", { title: `UI ops source ${id}`, uploadDate, channel: "UI Ops", webpageUrl, duration: 60, cues });
+ if (old) utimesSync(path.join(dir, "transcript.cues.json"), LONG_AGO, LONG_AGO);
+}
+
+/** The fixture's manifest, its QRs on `site`. Exported so the spec writes the same thing with its server's origin. */
+export function uiOpsManifest(manifest, site) {
+ const link = (chan, id, t) => `${site}/?v=${encodeURIComponent(`${chan}/${id}`)}&t=${t}`;
+ const clip = (id, channel, video, start, end) => ({
+ type: "clip", id, channel, video, start, end, cite: start, citeUrl: link(channel, video, start), lock: true, section: 0, quote: `Line of ${video}.`,
+ });
+ const doc = manifest(UI_OPS, "The UI Ops Fixture", { siteOrigin: "https://archive.example", channelSlug: "uiopschan" }, [
+ clip("o01", "uiopschan", "u1", 2, 6),
+ clip("o02", "uiopschan", "u2", 4, 8),
+ clip("o03", "uiopsdirect", "d1", 10, 14),
+ ]);
+ doc.render.fetchPad = 0;
+ return doc;
+}
+
+/**
+ * @param {{ reports: string, channels: string, manifest: Function, cachedWindow: string, ff: (args: string[]) => void }} o
+ */
+export function makeUiOpsFixture({ reports, channels, manifest, cachedWindow, ff }) {
+ source(channels, "uiopschan", "u1", { uploadDate: "20250101", webpageUrl: "https://example.invalid/watch?v=u1" });
+ source(channels, "uiopschan", "u2", { uploadDate: "20261020", webpageUrl: "https://example.invalid/watch?v=u2" });
+ source(channels, "uiopsdirect", "d1", { uploadDate: "20250301", webpageUrl: "https://www.youtube.com/watch?v=d1" });
+ write(path.join(channels, "uiopsdirect"), "config.json", { name: "UI Ops Direct", url: "https://www.youtube.com/@uiopsdirect", platform: "youtube" });
+ const dir = path.join(reports, UI_OPS);
+ write(dir, "video.manifest.json", uiOpsManifest(manifest, UI_OPS_SITE_PLACEHOLDER));
+ // Three past renders of the whole cut (30 s of video each): draft-0 known only
+ // by its files (its manifest 11 min before builtAt) and its log's 1 min wait
+ // at the slot -- 600 s; draft-1 recorded 600 s; draft-2, made from draft-1, 240 s.
+ const take = (id, order, extra) => ({ id, group: "takes", order, label: id.replace("-", " "), kind: "reference", preview: "preview.mp4", seconds: 30, window: "full", ...extra });
+ write(path.join(dir, "takes", "draft-0"), "take.json", take("draft-0", 0, { builtAt: "2026-10-29T10:11:00.000Z" }));
+ write(path.join(dir, "takes", "draft-0"), "video.manifest.json", "{}\n");
+ const at0 = new Date("2026-10-29T10:00:00.000Z");
+ utimesSync(path.join(dir, "takes", "draft-0", "video.manifest.json"), at0, at0);
+ write(dir, "draft-0.log", "heavy: waiting for memory — 2917 MB available, the floor is 6000 MB\nheavy: 8879 MB available after 1m00s — admitted\ntake draft-0: done (30 s)\n");
+ write(path.join(dir, "takes", "draft-1"), "take.json", take("draft-1", 1, { builtAt: "2026-10-30T10:10:00.000Z", renderSeconds: 600 }));
+ write(path.join(dir, "takes", "draft-2"), "take.json", take("draft-2", 2, { builtAt: "2026-10-31T10:04:00.000Z", renderSeconds: 240, from: "draft-1" }));
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "u1_0.00-9.00.mp4"));
+ makeSpeakerProject({ reports, channels, manifest, ff });
+ return dir;
+}
+
+// THE SPEAKER CHECK'S PROJECT (#15): four clips, each window already in the
+// corpus under its own channel -- three of one "voice" (a 150 Hz tone and its
+// octave), one of another (1.1 kHz) -- and speakers.json naming Host (k01, k02)
+// and Guest (k03). k04 is the clip the walk checks. The app's job runs the test
+// kit's fake embedder (VOICE_MATCH_* in playwright.config.ts).
+function makeSpeakerProject({ reports, channels, manifest, ff }) {
+ const chan = "uiopsvoice";
+ const voices = { host: "0.3*sin(2*PI*150*t)+0.15*sin(2*PI*300*t)", guest: "0.3*sin(2*PI*1100*t)+0.1*sin(2*PI*2300*t)" };
+ const timeline = [];
+ for (const [id, who] of [["k01", "host"], ["k02", "host"], ["k03", "guest"], ["k04", "host"]]) {
+ const vid = `voice-${id}`;
+ const vdir = path.join(channels, chan, "data", vid);
+ mkdirSync(path.join(vdir, "clips"), { recursive: true });
+ write(vdir, "transcript.cues.json", { title: `Voice ${vid}`, uploadDate: "20250101", channel: "UI Ops Voices", webpageUrl: `https://example.invalid/watch?v=${vid}`, duration: 20, cues: [{ start: 2, end: 4.5, text: "slow news day." }] });
+ ff([
+ "-f", "lavfi", "-i", "color=c=gray:size=160x90:rate=15:duration=6",
+ "-f", "lavfi", "-i", `aevalsrc=${voices[who]}:s=48000:d=6`,
+ "-map", "0:v", "-map", "1:a", "-t", "6",
+ "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-ar", "48000", "-ac", "2",
+ path.join(vdir, "clips", "0.00-6.00.mp4"),
+ ]);
+ timeline.push({ type: "clip", id, channel: chan, video: vid, start: 0.5, end: 5.5, cutStart: 2, cutEnd: 4.5, cite: 2, section: 0, lock: true, quote: "slow news day." });
+ }
+ const dir = path.join(reports, UI_OPS_SPEAKER);
+ write(dir, "video.manifest.json", manifest(UI_OPS_SPEAKER, "The Speaker Check Fixture", { siteOrigin: "https://archive.example", channelSlug: chan }, timeline));
+ write(dir, "speakers.json", { speakers: [{ name: "Host", clips: ["k01", "k02"] }, { name: "Guest", clips: ["k03"] }] });
+}
diff --git a/umtool/e2e/take-variants.spec.ts b/umtool/e2e/take-variants.spec.ts
@@ -0,0 +1,163 @@
+import { test, expect, type Page } from "@playwright/test";
+import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// Take housekeeping, the rest (UI notes 2026-10-30, item 19):
+//
+// - Cancel a take while it renders: a REAL render (the take maker's job,
+// `umtool take … --priority`), held in the qrencode stub's stall; Cancel
+// render on the Takes page asks the take maker, which stops its render's
+// process group, writes takes/<id>/cancelled.json, never a take.json, and
+// lets render mode go (lib/report/takeCancel.mjs)
+// - Fork as variant: the take as a project beside this one -- its manifest,
+// variant.json, the media linked, the take in it (variantFork.mjs)
+// - two takes side by side, of the project and of its variant: two players
+// in step, the differences listed (takeCompare.mjs, TakesComparePlayers)
+//
+// Fixture: variants-fixture (make-fixture.mjs), which this spec WRITES: m01
+// vid1 3-6; takes draft-1 (the manifest) and draft-2 (m01 3.5-6, crf 34).
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const SONG = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/variants-fixture";
+const DIR = path.join(SONG, "reports", "variants-fixture");
+const VARIANT_DIR = path.join(SONG, "reports", "v-draft-2");
+const STALL = path.join(SONG, "bin", "qrencode.stall-ms");
+const STALL_PID = path.join(SONG, "bin", "qrencode.stall.pid");
+const STATE = path.join(SONG, "render-priority.json");
+const SHOTS = process.env.U3_SHOTS ?? null;
+
+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 alive = (pid: number) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+};
+
+test.afterAll(() => {
+ rmSync(STALL, { force: true });
+ rmSync(VARIANT_DIR, { recursive: true, force: true });
+});
+
+test("two takes side by side: two players in step, and what differs A → B", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.takesCompareHref(PROJECT, `${PROJECT}:draft-1`, `${PROJECT}:draft-2`));
+ const players = page.locator("[data-compare-players]");
+ await expect(players.locator("[data-compare-player='a']")).toHaveAttribute("data-compare-take", `${PROJECT}:draft-1`);
+ await expect(players.locator("[data-compare-player='b']")).toHaveAttribute("data-compare-take", `${PROJECT}:draft-2`);
+ await expect(page.locator("[data-compare-cut]")).toContainText("~ m01 window: 3–6 -> 3.5–6");
+ await expect(page.locator("[data-compare-look-path='render.crf']")).toContainText("render.crf: 30 → 34");
+ await expect(page.locator("[data-compare-fact='label']")).toHaveAttribute("data-differs", "");
+ // Both play from one transport, and stay together.
+ await page.locator("[data-compare-play]").click();
+ await expect(players).toHaveAttribute("data-compare-state", "playing");
+ await expect.poll(async () => Number(await players.getAttribute("data-compare-time")), { timeout: 10_000 }).toBeGreaterThan(0.6);
+ const times = await page.locator("[data-compare-players] video").evaluateAll((vs) => (vs as HTMLVideoElement[]).map((v) => v.currentTime));
+ expect(times.length).toBe(2);
+ expect(Math.abs(times[0] - times[1])).toBeLessThan(0.3);
+ // One sound: A's, until B's is asked for.
+ const muted = () => page.locator("[data-compare-players] video").evaluateAll((vs) => (vs as HTMLVideoElement[]).map((v) => v.muted));
+ expect(await muted()).toEqual([false, true]);
+ await page.locator("[data-compare-sound='b']").click();
+ expect(await muted()).toEqual([true, false]);
+ await page.locator("[data-compare-play]").click();
+ await expect(players).toHaveAttribute("data-compare-state", "paused");
+});
+
+test("Fork as variant: a project beside this one, with the take in it; compared across the two", async ({ page }) => {
+ rmSync(VARIANT_DIR, { recursive: true, force: true });
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.takesHref(PROJECT));
+ const card = page.locator("[data-take='draft-2']");
+ await card.locator("[data-action='fork']").click();
+ await expect(card.locator("[data-take-fork-name='draft-2']")).toHaveValue("v-draft-2");
+ await card.locator("[data-action='fork-go']").click();
+ await expect(card.locator("[data-take-forked='reports/v-draft-2']")).toBeVisible();
+ const variant = JSON.parse(readFileSync(path.join(VARIANT_DIR, "variant.json"), "utf8")) as { variantOf: string; fromTake: string };
+ expect(variant).toMatchObject({ variantOf: PROJECT, fromTake: "draft-2" });
+ const m = JSON.parse(readFileSync(path.join(VARIANT_DIR, "video.manifest.json"), "utf8")) as { slug: string; timeline: { start: number }[] };
+ expect(m.slug).toBe("v-draft-2");
+ expect(m.timeline[0].start).toBe(3.5);
+ expect(existsSync(path.join(VARIANT_DIR, "takes", "draft-2", "preview.mp4"))).toBe(true);
+
+ // The project's Takes page names its variant; the variant's names its parent.
+ await page.reload();
+ await expect(page.locator("[data-takes-variant='reports/v-draft-2']")).toBeVisible();
+ await page.goto(urls.takesHref("reports/v-draft-2"));
+ await expect(page.locator("[data-takes-family]")).toContainText(`A variant of ${PROJECT}, forked from its take draft-2`);
+
+ // Compare with…: the parent's draft-1 against the variant's draft-2.
+ await page.goto(urls.takesHref(PROJECT));
+ const one = page.locator("[data-take='draft-1']");
+ await one.locator("[data-take-compare-with='draft-1']").selectOption("reports/v-draft-2:draft-2");
+ await one.locator("[data-action='compare']").click();
+ await expect(page.locator("[data-compare-player='b']")).toHaveAttribute("data-compare-take", "reports/v-draft-2:draft-2");
+ await expect(page.locator("[data-compare-look-path='slug']")).toContainText("variants-fixture → v-draft-2");
+ await page.locator("[data-compare-play]").click();
+ await expect.poll(async () => Number(await page.locator("[data-compare-players]").getAttribute("data-compare-time")), { timeout: 10_000 }).toBeGreaterThan(0.5);
+ await page.locator("[data-compare-play]").click();
+ await shot(page, "u3-5-compare-side-by-side.png");
+});
+
+test("Cancel a take while it renders: its render stops, it is marked cancelled, render mode lets go", async ({ page, request }) => {
+ test.setTimeout(240_000);
+ rmSync(STATE, { force: true });
+ rmSync(STALL_PID, { force: true });
+ writeFileSync(STALL, "120000");
+ let id = "";
+ try {
+ // A real take, through the app's take job, with Give renders the machine.
+ const r = await request.post("/api/report/takes/make", { data: { project: PROJECT, take: { label: "Slow render", window: "full" }, priority: true } });
+ expect(r.status(), await r.text()).toBe(200);
+ const made = (await r.json()) as { takes: string[]; job: { id: string } };
+ id = made.takes[0];
+ // It is rendering: its build lock, render mode held for it, the stub stalled inside the build.
+ await expect.poll(() => existsSync(STALL_PID), { timeout: 120_000 }).toBe(true);
+ const stubPid = Number(readFileSync(STALL_PID, "utf8"));
+ expect(alive(stubPid)).toBe(true);
+ expect(existsSync(path.join(DIR, "takes", id, ".building.json"))).toBe(true);
+ expect((JSON.parse(readFileSync(STATE, "utf8")) as { holder?: { take?: string } }).holder?.take).toBe(id);
+
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.takesHref(PROJECT));
+ const row = page.locator(`[data-take-rendering='${id}']`);
+ await expect(row).toContainText("Slow render");
+ await shot(page, "u3-4-cancel-rendering-take.png");
+ await row.locator("[data-action='cancel-render']").click();
+ // The answer stays on the page after the refresh takes the row away (it is not rendering any more).
+ await expect(page.locator(`[data-take-cancel-said='${id}']`)).toContainText("its render stopped (the take maker)", { timeout: 60_000 });
+
+ // Stopped cleanly: the render's process gone, no take.json, the mark, the lock gone, render mode off.
+ await expect.poll(() => alive(stubPid), { timeout: 15_000 }).toBe(false);
+ expect(existsSync(path.join(DIR, "takes", id, "take.json"))).toBe(false);
+ expect(JSON.parse(readFileSync(path.join(DIR, "takes", id, "cancelled.json"), "utf8"))).toMatchObject({ by: "the Takes page", label: "Slow render", rebuild: false });
+ expect(existsSync(path.join(DIR, "takes", id, ".building.json"))).toBe(false);
+ await expect.poll(() => existsSync(STATE), { timeout: 15_000 }).toBe(false);
+ await expect
+ .poll(async () => ((await (await request.get(`/api/report/takes/make?job=${made.job.id}`)).json()) as { state: string }).state, { timeout: 30_000 })
+ .toBe("failed");
+
+ // The list: no longer rendering; folded away as cancelled, deletable.
+ await expect(page.locator(`[data-take-rendering='${id}']`)).toHaveCount(0);
+ await shot(page, "u3-4b-cancelled.png");
+ await page.reload();
+ await expect(page.locator(`[data-take-rendering='${id}']`)).toHaveCount(0);
+ await expect(page.locator("[data-cancelled-count]")).toContainText("1 cancelled render folded away");
+ await page.locator("[data-action='show-cancelled']").click();
+ await expect(page.locator(`[data-take-cancelled='${id}']`)).toContainText("never finished: no take");
+ } finally {
+ rmSync(STALL, { force: true });
+ if (id) rmSync(path.join(DIR, "takes", id), { recursive: true, force: true });
+ rmSync(STATE, { force: true });
+ }
+});
diff --git a/umtool/e2e/tighten.spec.ts b/umtool/e2e/tighten.spec.ts
@@ -0,0 +1,126 @@
+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";
+
+// ---------------------------------------------------------------------------
+// Tighten to the sentence, snap an edge to its pause, and Propose tight
+// windows (UI notes 2026-10-30, item 4; lib/report/tightWindow.mjs,
+// tightPropose.mjs, components/projects/bench/TightenTools.tsx,
+// report/TightWindowsPanel.tsx):
+//
+// - the bench's zoom draws a box per WORD (the corpus's words.json for the
+// recording) and the pauses (the silences and the gaps between words)
+// - Tighten to this sentence writes both edges through the window writer,
+// Undo puts them back; Snap edge (start / end) moves one edge to the
+// middle of its nearest pause
+// - the Cut tab's Propose tight windows lists before/after per clip and
+// writes NOTHING until a row's Apply; an applied row's Undo restores it
+//
+// Fixture: tight-fixture (make-fixture.mjs), which this spec WRITES and puts
+// back before each test: t01 tightvid 1.2-7.4, t02 3.0-9.0 (already the
+// sentence), t03 0.5-8.6 with a cut 3.5-5.0; vid1's cues (sentences 0-3, 3-9,
+// 9-12), the tone window cached as 0-9, timed words in the corpus.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const PROJECT = "reports/tight-fixture";
+const MANIFEST = path.join(HERE, "..", ".e2e-song", "reports", "tight-fixture", "video.manifest.json");
+const SHOTS = process.env.U3_SHOTS ?? null;
+type Clip = { id: string; start: number; end: number; cutStart?: number; cutEnd?: number; cite?: number };
+const clipOf = (id: string) => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Clip[] }).timeline.find((e) => e.id === id)!;
+
+let PRISTINE = "";
+test.beforeAll(() => {
+ PRISTINE = readFileSync(MANIFEST, "utf8");
+});
+test.beforeEach(() => {
+ test.setTimeout(120_000);
+ writeFileSync(MANIFEST, PRISTINE);
+});
+
+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 openBench = async (page: Page, clip = "t01") => {
+ await page.setViewportSize({ width: 1440, height: 1000 });
+ await page.goto(urls.clipBenchHref(PROJECT, clip));
+ await page.locator("[data-wave-box]").scrollIntoViewIfNeeded();
+ await expect(page.locator("[data-wave-box]")).toBeInViewport();
+};
+
+test("the zoom draws the recording's words as boxes and its pauses", async ({ page }) => {
+ await openBench(page);
+ // A 9 s window is close enough at fit: the words and the pauses are drawn.
+ const word = page.locator("[data-wave-word='because']");
+ await expect(word).toHaveCount(1, { timeout: 20_000 });
+ await expect(word).toHaveAttribute("data-wave-word-at", "5.10-5.85");
+ expect(await page.locator("[data-wave-word]").count()).toBeGreaterThanOrEqual(10);
+ // The pause between "sentence." and "And" (the words' gap, 2.80-3.20, merged with the measured silence).
+ await expect(page.locator("[data-wave-pause]").first()).toBeAttached();
+ const pauses = await page.locator("[data-wave-pause]").evaluateAll((els) => els.map((e) => e.getAttribute("data-wave-pause")));
+ expect(pauses.some((p) => { const [a, b] = String(p).split("-").map(Number); return a <= 2.81 && b >= 3.19; })).toBe(true);
+ await page.locator("[data-zoom-in]").click();
+ await page.locator("[data-wave-box]").scrollIntoViewIfNeeded();
+ await expect(word).toBeVisible();
+ await shot(page, "u3-1-word-boxes-and-pauses.png");
+});
+
+test("Tighten to this sentence writes both edges through the window writer; Undo puts them back", async ({ page }) => {
+ await openBench(page);
+ await page.locator("[data-tighten]").click();
+ // No playhead: the window 1.2-7.4 holds no whole sentence, so the one it is inside (3-9), the end at the cache's 9.
+ await expect.poll(() => [clipOf("t01").start, clipOf("t01").end]).toEqual([3, 9]);
+ await expect(page.locator("body")).toContainText("tightened to the sentence the window is inside");
+ await page.locator("[data-edge-undo]").click();
+ await expect.poll(() => [clipOf("t01").start, clipOf("t01").end]).toEqual([1.2, 7.4]);
+ await expect(page.locator("body")).toContainText("undone");
+});
+
+test("Snap edge: the start, then the end, each to the middle of its nearest pause", async ({ page }) => {
+ await openBench(page);
+ await page.locator("[data-snap-edge='start']").click();
+ // 1.2 sits between "a" (…0.8) / "complete" (0.9…) and "complete" (…1.6) / "sentence." (1.7…): the nearer pause is 0.8-0.9.
+ await expect.poll(() => clipOf("t01").start).toBe(0.85);
+ await expect(page.locator("[data-edge-undo]")).toBeVisible();
+ await page.locator("[data-snap-edge='end']").click();
+ // 7.4: "it" (…7.0) / "finishes" (7.1…) is nearer than "finishes" (…7.9) / "here." (8.0…).
+ await expect.poll(() => clipOf("t01").end).toBe(7.05);
+ expect(clipOf("t01").start).toBe(0.85);
+});
+
+test("Propose tight windows: a review list, nothing written until Apply; Apply and Undo per row", async ({ page }) => {
+ await page.setViewportSize({ width: 1440, height: 1100 });
+ await page.goto(urls.section(PROJECT, "cut"));
+ const panel = page.locator("[data-tight-windows]");
+ await panel.scrollIntoViewIfNeeded();
+ await panel.locator("[data-action='propose-tight']").click();
+ const t01 = panel.locator("[data-tight-row='t01']");
+ await expect(t01).toBeVisible({ timeout: 60_000 });
+ await expect(t01.locator("[data-tight-before]")).toHaveAttribute("data-tight-before", "1.2-7.4");
+ await expect(t01.locator("[data-tight-after]")).toHaveAttribute("data-tight-after", "3-9");
+ await expect(t01.locator("[data-tight-delta]")).toHaveAttribute("data-tight-delta", "-0.20");
+ // t03's cut (its quote, 3.5-5.0) anchors it: the sentence 3-9.
+ await expect(panel.locator("[data-tight-row='t03'] [data-tight-after]")).toHaveAttribute("data-tight-after", "3-9");
+ // t02 is already the sentence: not listed until every clip is shown.
+ await expect(panel.locator("[data-tight-row='t02']")).toHaveCount(0);
+ await expect(panel.locator("[data-tight-counts]")).toContainText("2 of 3 clips would change · 1 already tight");
+ // Proposing wrote nothing.
+ expect(readFileSync(MANIFEST, "utf8")).toBe(PRISTINE);
+ await shot(page, "u3-2-propose-tight-review.png");
+
+ await t01.locator("[data-action='tight-apply']").click();
+ await expect(t01).toHaveAttribute("data-tight-state", "applied");
+ await expect.poll(() => [clipOf("t01").start, clipOf("t01").end]).toEqual([3, 9]);
+ // Only that row: t03 is as it was.
+ expect([clipOf("t03").start, clipOf("t03").end]).toEqual([0.5, 8.6]);
+ await t01.locator("[data-action='tight-undo']").click();
+ await expect(t01).toHaveAttribute("data-tight-state", "undone");
+ await expect.poll(() => [clipOf("t01").start, clipOf("t01").end]).toEqual([1.2, 7.4]);
+
+ await panel.locator("[data-action='tight-show-all']").click();
+ await expect(panel.locator("[data-tight-row='t02']")).toHaveAttribute("data-tight-state", "same");
+});
diff --git a/umtool/e2e/ui-ops.spec.ts b/umtool/e2e/ui-ops.spec.ts
@@ -0,0 +1,218 @@
+import { test, expect, type Page } from "@playwright/test";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+import { WARM_TIMEOUT, warm } from "./warm";
+import { UI_OPS, UI_OPS_SITE_PLACEHOLDER, UI_OPS_SPEAKER } from "./fixtures/ui-ops-fixture.mjs";
+
+// ---------------------------------------------------------------------------
+// OPERATIONS UI (UI notes 2026-10-30), each through the app:
+//
+// #9 the sites the cut's links depend on, each with its deploy's date, and
+// the warning when cited videos are newer than it; Publish <site> asks
+// the editor (its stub records build-deploy)
+// #10 the link policy: "these channels direct" saved through its writer,
+// the check's clip-link-policy row and its one-press fix, and a new
+// clip written by the policy
+// #18 the render queue panel, read from the slot's own files (the
+// fixture's: HEAVY_LOCK_FILE), and a take's ETA from past renders
+// #15 the walk's speaker badge and Check speaker (the fake embedder)
+//
+// Fixture: fixtures/ui-ops-fixture.mjs, written for this file alone. Serial:
+// each test leaves what the next reads.
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial" });
+
+const PROJECT = `reports/${UI_OPS}`;
+const SPEAKERS = `reports/${UI_OPS_SPEAKER}`;
+const FIXTURE = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song");
+const DIR = path.join(FIXTURE, "reports", UI_OPS);
+const MANIFEST = path.join(DIR, "video.manifest.json");
+const SITE_DIR = path.join(FIXTURE, "sites", "ui-ops-site");
+const HEAVY = path.join(FIXTURE, "heavy");
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+type Entry = { id: string; type: string; citeUrl?: string; channel?: string; video?: string };
+const entries = () => (JSON.parse(readFileSync(MANIFEST, "utf8")) as { timeline: Entry[] }).timeline;
+const entry = (id: string) => entries().find((e) => e.id === id);
+// Screenshots for the morning review, when asked for (UI_OPS_SHOTS=<dir>).
+const SHOTS = process.env.UI_OPS_SHOTS ?? "";
+const shot = async (page: Page, name: string, el?: ReturnType<Page["locator"]>) => {
+ if (!SHOTS) return;
+ mkdirSync(SHOTS, { recursive: true });
+ if (el) await el.screenshot({ path: path.join(SHOTS, `${name}.png`) });
+ else await page.screenshot({ path: path.join(SHOTS, `${name}.png`), fullPage: false });
+};
+
+// The site the QRs link: built 9 Oct, with uiopschan's u1 only -- no u2
+// (uploaded the 20th), no uiopsdirect.
+let server: Server;
+let origin = "";
+const startSite = () =>
+ new Promise<void>((resolve) => {
+ server = createServer((req, res) => {
+ const p = new URL(req.url ?? "/", "http://x").pathname;
+ const json = (doc: unknown) => {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify(doc));
+ };
+ if (p === "/corpus.json") {
+ return json({
+ spec: 5,
+ generatedAt: "2026-10-09T10:00:00.000Z",
+ site: { title: "UI ops archive" },
+ channels: [{ slug: "uiopschan", manifests: { transcripts: `${origin}/transcripts/uiopschan/manifest.json` } }],
+ });
+ }
+ if (p === "/transcripts/uiopschan/manifest.json") return json({ pageCount: 1, slugToPage: { u1: 0 } });
+ if (p === "/transcripts/uiopschan/page-0000.json") return json([{ id: "u1" }]);
+ res.writeHead(404);
+ res.end();
+ });
+ server.listen(0, "127.0.0.1", () => {
+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ resolve();
+ });
+ });
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ await startSite();
+ writeFileSync(MANIFEST, readFileSync(MANIFEST, "utf8").split(UI_OPS_SITE_PLACEHOLDER).join(origin));
+ // The site the QRs open, as transcripts/sites/<id>/site.json names it.
+ mkdirSync(SITE_DIR, { recursive: true });
+ writeFileSync(path.join(SITE_DIR, "site.json"), JSON.stringify({ siteId: "ui-ops-site", siteTitle: "UI Ops Site", siteUrl: origin, channels: [{ slug: "uiopschan", order: 0 }] }));
+ await warm(playwright, [urls.projectHref(PROJECT), urls.takesHref(PROJECT), urls.clipBenchHref(SPEAKERS, "k04")]);
+});
+test.afterAll(() => {
+ server?.close();
+ rmSync(SITE_DIR, { recursive: true, force: true });
+ rmSync(HEAVY, { recursive: true, force: true });
+});
+
+const row = (page: Page, kind: string, target: string) => page.locator(`[data-decision="${kind}"][data-target="${target}"]`);
+
+test("#9 the sites the links depend on: the deploy's date, the cited videos newer than it, and Publish <site>", async ({ page }) => {
+ const host = new URL(origin).host;
+ await page.goto(urls.projectHref(PROJECT));
+ const site = page.locator(`[data-link-site="${host}"]`);
+ await expect(site).toHaveAttribute("data-link-site-id", "ui-ops-site");
+ await expect(site.locator("[data-link-site-deploy]")).toContainText("deploy date unknown · not checked yet");
+ // Check links reads every site's corpus.json; its date is the deploy's.
+ await site.locator('[data-settle-button="links"]').click();
+ await expect(site).toHaveAttribute("data-link-site-deployed", "2026-10-09", { timeout: 30_000 });
+ await expect(site.locator("[data-link-site-deploy]")).toContainText("deployed 2026-10-09 (its corpus.json)");
+ await expect(site).toHaveAttribute("data-link-site-newer", "1");
+ await expect(site.locator("[data-link-site-warning]")).toHaveText("1 cited video is newer than this deploy: o02 (uploaded 2026-10-20)");
+ const behind = row(page, "site-deploy-behind", host);
+ await expect(behind).toContainText("ui-ops-site's deploy is from 2026-10-09; 1 cited video is newer: o02 (uploaded 2026-10-20)");
+ await expect(behind.locator("[data-fix]")).toHaveAttribute("data-fix", `pnpm ops build-deploy --json '{"siteId":"ui-ops-site"}'`);
+ await shot(page, "9-site-deploy-warning");
+ await shot(page, "9-site-deploy-warning-panel", site);
+ // Publish asks the editor's build-deploy (the stub records it).
+ await site.locator('[data-settle-button="publish-ui-ops-site"]').click();
+ await expect(site.locator('[data-settle="publish-site"] [data-settle-said]')).toContainText(/queued on the editor's publish queue \(job deploy-\d+\)/);
+ const asked = (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; siteId?: string; authorization?: string }[]).filter((r) => r.route === "build-deploy");
+ expect(asked.at(-1)).toMatchObject({ siteId: "ui-ops-site", authorization: "Bearer umtool-e2e-token" });
+});
+
+test("#10 the link policy: cite via ui-ops-site, uiopsdirect direct; the check's row and its fix; a new clip is written by it", async ({ page }) => {
+ await page.goto(urls.projectHref(PROJECT));
+ const panel = page.locator("[data-link-policy]");
+ await expect(panel).toHaveAttribute("data-link-policy", "none");
+ // "Cite via ui-ops-site; uiopsdirect direct."
+ await panel.locator("[data-link-policy-via]").selectOption(origin);
+ await panel.locator('[data-link-policy-direct="uiopsdirect"]').check();
+ await panel.locator("[data-link-policy-save]").click();
+ await expect(panel.locator("[data-link-policy-said]")).toContainText("saved");
+ await expect(panel).toHaveAttribute("data-link-policy", "set");
+ expect((JSON.parse(readFileSync(MANIFEST, "utf8")) as { provenance: { linkPolicy?: unknown } }).provenance.linkPolicy).toEqual({ via: origin, direct: ["uiopsdirect"] });
+ // Only o03 breaks it: o01 and o02 already open ui-ops-site.
+ await expect(page.locator('[data-decision="clip-link-policy"]')).toHaveCount(1);
+ const policyRow = row(page, "clip-link-policy", "o03");
+ await expect(policyRow).toContainText(`uiopsdirect links direct by the project's link policy, but its QR opens ${new URL(origin).host}`);
+ await expect(policyRow.locator('[data-settle-button="o03"]')).toHaveText("Link its YouTube page");
+ await expect(policyRow.locator("[data-fix]")).toHaveAttribute("data-fix", `umtool window ${PROJECT} o03 --cite-url 'https://www.youtube.com/watch?v=d1&t=10s'`);
+ await shot(page, "10-link-policy-row");
+ await shot(page, "10-link-policy-panel", panel);
+ await policyRow.locator('[data-settle-button="o03"]').click();
+ await expect(row(page, "clip-link-policy", "o03")).toHaveCount(0);
+ expect(entry("o03")?.citeUrl).toBe("https://www.youtube.com/watch?v=d1&t=10s");
+ await shot(page, "10-link-policy-fixed");
+ // A new clip of the direct channel: the inserter writes its YouTube page.
+ const r = await page.request.post("/api/report/timeline", {
+ data: { project: PROJECT, op: "insert", afterId: "o03", entry: { type: "clip", channel: "uiopsdirect", video: "d1", start: 20, end: 24, citeUrl: `${origin}/?v=uiopsdirect%2Fd1&t=20` } },
+ });
+ expect(r.ok()).toBe(true);
+ const added = entries().find((e) => e.type === "clip" && e.video === "d1" && e.id !== "o03");
+ expect(added?.citeUrl).toBe("https://www.youtube.com/watch?v=d1&t=20s");
+});
+
+test("#18 the render queue: what runs and waits at the heavy slot, from its files, and a take's ETA from past renders", async ({ page }) => {
+ // The slot's own files, as queue-lock writes them (the fixture's slot): an
+ // e2e suite running, a render of this project waiting for memory. Both name
+ // live pids (this worker and its parent), so they count.
+ const lock = path.join(HEAVY, "heavy-queue.lock");
+ const put = (file: string, doc: unknown) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, JSON.stringify(doc));
+ };
+ const now = Date.now();
+ put(`${lock}.jobs/${process.pid}.json`, { pid: process.pid, estimateMb: 1500, build: false, exclusive: false, worktree: "/w/lane-a", branch: "lane/a", cmd: "playwright test", startedAt: new Date(now - 12 * 60_000).toISOString() });
+ put(path.join(HEAVY, "e2e-editor-queue.lock.holder.json"), { name: "e2e-editor", pid: process.pid, worktree: "/w/lane-a", branch: "lane/a", cmd: "playwright test", startedAt: new Date(now - 13 * 60_000).toISOString() });
+ put(`${lock}.waiting/${process.ppid}.json`, {
+ pid: process.ppid, estimateMb: 6020, build: false, exclusive: false, worktree: "/w/main", branch: "main",
+ cmd: `node /repo/umtool/report-to-video/build-video.mjs ${DIR}/.take-draft-3.render.json --out ${DIR}/takes/draft-3/out --progress ndjson`,
+ since: new Date(now - 3 * 60_000).toISOString(), stage: "memory", stageSince: new Date(now - 2 * 60_000).toISOString(),
+ });
+ await page.goto(urls.takesHref(PROJECT));
+ const q = page.locator("[data-render-queue]");
+ await expect(q).toHaveAttribute("data-render-queue", "busy", { timeout: 15_000 });
+ await expect(q.locator("[data-render-queue-held-by]")).toHaveText("held by e2e suite e2e-editor");
+ const running = q.locator('[data-queue-state="running"]');
+ await expect(running).toHaveCount(1);
+ await expect(running).toContainText("e2e suite e2e-editor");
+ await expect(running).toContainText("lane-a (lane/a)");
+ await expect(running).toContainText("12 min");
+ const waiting = q.locator('[data-queue-state="waiting"]');
+ await expect(waiting).toContainText("render of draft-3");
+ await expect(waiting).toContainText("at the head of the line, for memory");
+ await expect(q.locator("[data-render-queue-mine]")).toContainText("draft-3: waiting 3 min — at the head of the line, for memory");
+ // The ETA: draft-2 (from draft-1) 240 s for 30 s; draft-0 and draft-1 600 s fresh.
+ const eta = q.locator("[data-take-eta]");
+ await expect(eta).toHaveAttribute("data-take-eta", "known");
+ await expect(eta.locator("[data-take-eta-reuse]")).toHaveText("~4 min made from draft-2 (reuse)");
+ await expect(eta.locator("[data-take-eta-fresh]")).toHaveText("~10 min fresh");
+ await eta.locator("summary").click();
+ await expect(eta).toContainText("draft-0 (fresh): 0:30 of video in 10 min (from its files' times)");
+ await shot(page, "18-render-queue-eta", q);
+ await shot(page, "18-render-queue-page");
+ // The job lets go: its ticket is gone and the panel says so.
+ rmSync(HEAVY, { recursive: true, force: true });
+ await expect(q).toHaveAttribute("data-render-queue", "idle", { timeout: 15_000 });
+ await expect(q.locator("[data-render-queue-held-by]")).toHaveText("the heavy slot is free");
+});
+
+test("#15 the walk's speaker badge: Check speaker scores the clip against the named voices", async ({ page }) => {
+ await page.goto(urls.clipBenchHref(SPEAKERS, "k04"));
+ const badge = page.locator("[data-speaker-badge]");
+ await expect(badge).toHaveAttribute("data-speaker-badge", "unchecked");
+ await expect(badge.locator("[data-speaker-line]")).toHaveText("Speaker: not checked");
+ await badge.locator("[data-speaker-check]").click();
+ await expect(badge).toHaveAttribute("data-speaker-badge", "matches", { timeout: 60_000 });
+ await expect(badge.locator("[data-speaker-line]")).toHaveText(/^Speaker: matches Host \d\.\d\d \/ Guest 0\.\d\d$/);
+ await expect(badge.locator("[data-speaker-reference]")).toHaveText("vs Host 2 · Guest 1");
+ await expect(badge.locator("[data-speaker-reference]")).toHaveAttribute("title", /^measured against: Host: 2 pieces \(2 kept\) · Guest: 1 piece \(1 kept\) · \d{4}-\d\d-\d\d \d\d:\d\d$/);
+ await shot(page, "15-speaker-badge", page.locator("[data-verdict-bar]").first());
+ await shot(page, "15-speaker-badge-page");
+ // This clip is Host's: it joins Host's reference set.
+ await badge.locator("[data-speaker-add-open]").click();
+ await badge.locator("[data-speaker-voice]").fill("Host");
+ await badge.locator("[data-speaker-add]").click();
+ await expect(badge).toContainText("in Host’s voice");
+ const speakers = JSON.parse(readFileSync(path.join(FIXTURE, "reports", UI_OPS_SPEAKER, "speakers.json"), "utf8")) as { speakers: { name: string; clips?: string[] }[] };
+ expect(speakers.speakers.find((s) => s.name === "Host")?.clips).toEqual(["k01", "k02", "k04"]);
+});
diff --git a/umtool/lib/decisions.ts b/umtool/lib/decisions.ts
@@ -89,7 +89,8 @@ export type Decision = {
settle?:
| { kind: "patch"; clip: string; patch: Record<string, unknown>; label: string }
| { kind: "check-links"; label: string; fix?: boolean }
- | { kind: "patch-markers"; file: string; label: string };
+ | { kind: "patch-markers"; file: string; label: string }
+ | { kind: "publish-site"; siteId: string; label: string };
/** The clips a project-wide row is about (a site's dead links). */
clips?: string[];
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -301,6 +301,11 @@ export function takesHref(project: string, q: NoteOpt = {}): string {
return withQuery(`/projects/${encodePath(project)}/takes`, {}, q.note);
}
+/** Two takes side by side -- of the project or of its variants (`<project>:<take>` each). */
+export function takesCompareHref(project: string, a: string, b: string, q: NoteOpt = {}): string {
+ return withQuery(`/projects/${encodePath(project)}/takes/compare`, { a, b }, q.note);
+}
+
/**
* Walk a take: the take's clips, the walk's start (an overview of every clip,
* and where the walk begins). `all`: the walk visits every fetched clip, judged
diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs
@@ -136,6 +136,8 @@ const ACTION_LABEL = {
"link-dead": "Fix the links",
"links-unverified": "Check links again",
"links-unchecked": "Check links",
+ "site-deploy-behind": (d) => (d.settle?.kind === "publish-site" ? d.settle.label : "Publish the site"),
+ "clip-link-policy": "Link it by the policy",
"no-punctuation": "Check the windows",
"manifest-invalid": "Fix the manifest",
"stale-build": "Rebuild the video",
diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs
@@ -39,6 +39,8 @@ export const WHAT = {
"link-dead": "QR links that don't open",
"links-unverified": "links not verified",
"links-unchecked": "links not checked",
+ "site-deploy-behind": "a cited site's deploy is behind the cut",
+ "clip-link-policy": "QR links that break the link policy",
"no-punctuation": "windows without punctuation",
"manifest-invalid": "manifest invalid",
"stale-build": "video out of date",
diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs
@@ -18,7 +18,7 @@ import { rawCacheOf } from "../report/raw-cache.mjs";
import { rejectionOf } from "../report/rejectReasons.mjs";
import { resolveVideoDirSync } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
import { deliverablesState, finishCommand, outDirState, leftoversOf } from "../report/storage.mjs";
-import { CHANNELS_DIR, inside, resolveInRoots } from "../paths.mjs";
+import { CHANNELS_DIR, SITES_DIR, inside, resolveInRoots } from "../paths.mjs";
import { channelName, cleanTitle } from "umtool-report-to-video/attribution";
import { archiveMomentUrl } from "umtool-report-to-video/site-links";
import { deckOn, resolveDeck, teaserTitle } from "umtool-report-to-video/deck";
@@ -46,6 +46,8 @@ import { fileSig, pathCache } from "../pathCache.mjs";
import { citeOffsets } from "../report/citeFollow.mjs";
import { PATCH_FILE_RE, stalePatchMarkers } from "../report/patchMarkers.mjs";
import { linkVerdicts, linksFile, readLinkCheck } from "../report/linkCheck.mjs";
+import { deployBehindWhy, projectSites, sitesByOrigin } from "../report/siteDeploys.mjs";
+import { policyBreaks, policyFixLabel } from "../report/linkPolicy.mjs";
// widen() and the cache's window naming are IMPORTED, never reimplemented. The
// bench's "extend to sentence end" has to be the same function the CLI runs, or
@@ -1071,6 +1073,14 @@ export const REPORT_DECISION_KINDS = [
"links-unverified",
// Links never checked, or changed since the check. `info`, with Check links.
"links-unchecked",
+ // A site the QRs open whose deploy (its recorded corpus.json generatedAt)
+ // is older than videos the cut cites there, and the check did not find
+ // those open (siteDeploys.mjs). `open`, with Publish <site>.
+ "site-deploy-behind",
+ // A clip whose QR breaks the project's link policy (provenance.linkPolicy,
+ // linkPolicy.mjs): a direct channel's clip opening an archive, or another
+ // clip not opening the policy's site. `open`, with the policy's link.
+ "clip-link-policy",
];
/**
@@ -1225,6 +1235,8 @@ export async function reportDecisions(ctx, summary) {
}
const unpunctuated = [];
+ /** @type {Map<string, { uploadDate: string | null, landedAt: string | null, webpageUrl: string | null }>} */
+ const recordByClip = new Map();
for (const [key, list] of byVideo) {
const file = cuePathFor(m, list[0], channelsDir);
const doc = file ? await readCues(file) : null;
@@ -1248,6 +1260,12 @@ export async function reportDecisions(ctx, summary) {
}
if (doc.punctuationRate < 0.1) unpunctuated.push(key);
+ // What the site-deploy row reads (siteDeploys.mjs): the recording's upload
+ // date and when its transcript landed here.
+ {
+ const st = await stat0(file);
+ for (const e of list) recordByClip.set(e.id, { uploadDate: doc.uploadDate ?? null, landedAt: st ? new Date(st.mtimeMs).toISOString() : null, webpageUrl: doc.webpageUrl ?? null });
+ }
for (const e of list) {
// The standing rule, mechanised. One 14-clip cut shipped with 8 clips
@@ -1618,6 +1636,37 @@ export async function reportDecisions(ctx, summary) {
}
}
+ // --- the project's link policy (linkPolicy.mjs) --------------------------
+ // "Cite via site X; these channels direct": one row per clip whose QR
+ // breaks it, the fix the window writer's citeUrl.
+ for (const b of policyBreaks(m, { webpageOf: (e) => recordByClip.get(e.id)?.webpageUrl ?? null })) {
+ add("clip-link-policy", b.clip, b.why, "open", {
+ href: clipHref(b.clip),
+ ...(b.fix
+ ? {
+ fix: `umtool window ${id} ${b.clip} --cite-url '${b.fix}'`,
+ settle: { kind: "patch", clip: b.clip, patch: { citeUrl: b.fix }, label: policyFixLabel(b) },
+ }
+ : {}),
+ });
+ }
+
+ // --- is each site's deploy recent enough? (siteDeploys.mjs) --------------
+ // From the same recorded check: the deploy's date is its corpus.json's
+ // generatedAt. A cited video newer than it, whose link the check did not
+ // find open, is not on the site yet.
+ {
+ const doc = await readLinkCheck(dir);
+ for (const site of projectSites(m, doc, { sites: sitesByOrigin(SITES_DIR), recordOf: (cid) => recordByClip.get(cid) ?? null })) {
+ if (!site.newer.length) continue;
+ add("site-deploy-behind", site.host, deployBehindWhy(site), "open", {
+ fix: site.siteId ? `pnpm ops build-deploy --json '{"siteId":"${site.siteId}"}'` : `umtool links ${id}`,
+ ...(site.siteId ? { settle: { kind: "publish-site", siteId: site.siteId, label: `Publish ${site.siteId}` } } : {}),
+ clips: site.newer.map((n) => n.clip),
+ });
+ }
+ }
+
// --- the build -----------------------------------------------------------
if (s.build.stale) {
add(
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -25,7 +25,7 @@
import { readFile, stat } from "node:fs/promises";
import path from "node:path";
import { clipMomentKey } from "umtool-report-to-video/montage-rulings";
-import { channelFor, clipsOf, cuesInWindow, readManifest } from "../projects/report.mjs";
+import { channelFor, channelsDirFor, clipsOf, cuesInWindow, hasShadowChannels, readManifest } from "../projects/report.mjs";
import {
StaleToken,
StructureRefused,
@@ -263,7 +263,22 @@ const overlapping = (list, from, to) =>
export async function clipNeighbourhood(project, { clip, from, to, video = null }) {
if (!fin(from) || !fin(to) || to <= from) throw new Error("from and to must be seconds, from < to");
const { doc } = await readReactions(project.dir);
- const words = video && doc?.source?.video !== video ? null : await readWords(project.dir, doc);
+ let words = video && doc?.source?.video !== video ? null : await readWords(project.dir, doc);
+ // The bench, zoomed in, on a recording the project has no words file for:
+ // the corpus's words for it (report-to-video clip-words.mjs -- a words
+ // sidecar, a whisper transcript, else the en-orig captions' word starts),
+ // the same ones the trailer's pause snap reads. Never a cue spread by its
+ // characters: a box drawn there would be a made-up place.
+ let wordsFrom = words?.length ? "project" : null;
+ let timed = words?.length ? true : null;
+ if (video && !words?.length && clip) {
+ const corpus = await corpusWords(project.dir, clip, video, from, to).catch(() => null);
+ if (corpus?.words?.length) {
+ words = corpus.words.map((w) => ({ w: w.text, start: w.start, ...(fin(w.end) ? { end: w.end } : {}) }));
+ wordsFrom = corpus.from;
+ timed = corpus.timed;
+ }
+ }
const turns = overlapping(doc?.turns, from, to).map((t) => ({ start: t.start, end: t.end, speaker: t.speaker }));
const laughs = overlapping(doc?.laughs, from, to).map((l) => ({ start: l.start, end: l.end, score: fin(l.score) ? l.score : null, speaker: fin(l.speaker) ? l.speaker : null }));
let cues = null;
@@ -278,12 +293,33 @@ export async function clipNeighbourhood(project, { clip, from, to, video = null
to,
turns,
laughs,
- words: words?.length ? words.filter((w) => w.end >= from && w.start <= to).map((w) => ({ w: String(w.w ?? w.word ?? w.text ?? ""), start: w.start, end: w.end })) : null,
+ words: words?.length
+ ? words
+ .filter((w) => (fin(w.end) ? w.end : w.start) >= from && w.start <= to)
+ .map((w) => ({ w: String(w.w ?? w.word ?? w.text ?? ""), start: w.start, ...(fin(w.end) ? { end: w.end } : {}) }))
+ : null,
+ // Where the words came from (the project's words file, words.json /
+ // transcript.json / captions in the corpus), and whether they carry their
+ // ends (captions' words have only their starts).
+ ...(video ? { wordsFrom, timed } : {}),
cues,
duration,
};
}
+/**
+ * A recording's words from the corpus (clip-words.mjs), for the bench's zoom:
+ * the clip named, on THAT recording.
+ */
+async function corpusWords(dir, clipId, video, from, to) {
+ const manifest = await readManifest(dir);
+ const entry = clipsOf(manifest).find((e) => e.id === clipId);
+ if (!entry || entry.video !== video) return null;
+ const { clipWords } = await import("umtool-report-to-video/clip-words");
+ const channelsDir = channelsDirFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) });
+ return clipWords(entry, manifest.provenance, from, to, { channelsDir });
+}
+
/** The words of a span around one clip (for a quote), from words or cues. */
async function quoteFor(project, clipId, from, to) {
const n = await clipNeighbourhood(project, { clip: clipId, from: Math.max(0, from - 1), to: to + 1 }).catch(() => null);
diff --git a/umtool/lib/report/clipExport.mjs b/umtool/lib/report/clipExport.mjs
@@ -4,7 +4,8 @@
// `exports/`, where the operator keeps the hand-made ones
// (`exports/tr3-2026-08-12-deal-with-it-autogynephiliac.mp4`).
//
-// TWO KINDS.
+// THREE KINDS (UI notes 2026-10-30, item 12: "as cut (no chrome)", "with N s
+// context", "raw / full exchange (fetch if needed)").
//
// cut the clip as the cut plays it: the render's edges (cutPoints.mjs --
// the build's own source, snap and room; the muted room at an edge is
@@ -15,14 +16,26 @@
// its `audio` knobs (offset, gain, fades) and the cut's loudness gain.
// When the edges cannot be measured, the manifest's play window
// (noted). A blur, a montage's phrase cut and the deck are not applied.
-// raw the whole fetched window -- the clip and the build's fetch pad
-// either side, clamped to the file -- as recorded: no gaps, no mute,
-// no knobs.
+// context what the cut plays (its play window: the lead-in, the cut) with
+// N seconds either side (`context`, 1-120, default 5), as recorded: no
+// gaps, no mute, no knobs -- "what was said around it".
+// raw a stretch of the recording as recorded: `span` {from, to} in
+// source seconds (the full exchange), else the clip and the build's
+// fetch pad either side. No gaps, no mute, no knobs.
+//
+// Each cuts from a cached window that HOLDS what it asks for (the build's own
+// source for a cut; for context and raw the tightest window of the recording
+// holding the span), clamped to the file and said when none does.
+// `exportNeeds` says what a context or raw export needs that is not on disk,
+// as the pads the editor's fetch-window takes (POST /api/report/clip-export
+// with `fetch: true` runs that fetch first, in the same job).
//
// Re-encoded, never stream-copied, so every cut is on the asked-for frame:
-// libx264 crf 18, AAC 192k, +faststart. Light work (one short clip), so it
-// does not take the heavy slot. Nothing is fetched: a clip with no window on
-// disk is refused with "fetch it first".
+// libx264 crf 18, AAC 192k, +faststart. Run as a umtool job (the route) or
+// from a terminal (`umtool export`), and either way through the machine's
+// heavy slot (the CLI takes it: report-to-video/heavy-gate.mjs, a small
+// declared estimate, so it runs beside others when memory allows). Nothing is
+// fetched here: a cut with no window on disk is refused with "fetch it first".
//
// The pure half (names, the plan's ffmpeg arguments) is tested in
// clipExport.test.mjs; `exportClip` runs it.
@@ -36,8 +49,12 @@ import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow } from "umt
/** The folder under a project that exports go into. */
export const EXPORTS_DIR = "exports";
-/** The two kinds of export. */
-export const EXPORT_KINDS = Object.freeze(["cut", "raw"]);
+/** The kinds of export. */
+export const EXPORT_KINDS = Object.freeze(["cut", "context", "raw"]);
+/** Seconds of context either side (the `context` kind): the default, and the bounds (the editor's fetch pad cap). */
+export const EXPORT_CONTEXT = Object.freeze({ default: 5, min: 1, max: 120 });
+/** What an export declares to the heavy slot (MB): one short re-encode. */
+export const EXPORT_ESTIMATE_MB = 600;
/** What a name under exports/ may be: one plain file name, an mp4. */
export const EXPORT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,180}\.mp4$/;
@@ -94,26 +111,79 @@ export function exportDate(entry) {
}
/**
- * The export's file name: `<clipId>[-raw]-<YYYY-MM-DD>-<slug>.mp4`, the
- * shape of the hand-made ones (`ss1-raw-2026-07-22-side-scrollers-full-exchange.mp4`).
+ * The export's file name: `<clipId>[-ctx<N> | -raw[-<from>-<to>]]-<YYYY-MM-DD>-<slug>.mp4`,
+ * the shape of the hand-made ones (`ss1-raw-2026-07-22-side-scrollers-full-exchange.mp4`).
* The slug is the quote's first words, else the title's, else the video id;
- * the date the clip's, else `today` (YYYY-MM-DD).
+ * the date the clip's, else `today` (YYYY-MM-DD). A raw export of a span of
+ * its own (the full exchange) carries the span's whole seconds, so two
+ * exchanges of one clip are two files.
*
* @param {Record<string, any>} entry
- * @param {{ kind?: "cut" | "raw", today?: string }} [opts]
+ * @param {{ kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null, today?: string }} [opts]
*/
-export function exportName(entry, { kind = "cut", today = new Date().toISOString().slice(0, 10) } = {}) {
+export function exportName(entry, { kind = "cut", context = EXPORT_CONTEXT.default, span = null, today = new Date().toISOString().slice(0, 10) } = {}) {
const id = exportSlug(String(entry?.id ?? "clip"), { words: 8, max: 40 }) || "clip";
const date = exportDate(entry) ?? today;
const slug = exportSlug(entry?.quote) || exportSlug(entry?.onscreen?.title) || exportSlug(entry?.title) || exportSlug(entry?.video);
- return `${[id, kind === "raw" ? "raw" : null, date, slug || null].filter(Boolean).join("-")}.mp4`;
+ const tag =
+ kind === "raw"
+ ? span && fin(span.from) && fin(span.to)
+ ? `raw-${Math.floor(span.from)}-${Math.ceil(span.to)}`
+ : "raw"
+ : kind === "context"
+ ? `ctx${Math.round(context)}`
+ : null;
+ return `${[id, tag, date, slug || null].filter(Boolean).join("-")}.mp4`;
+}
+
+/** `context` as seconds inside EXPORT_CONTEXT's bounds, or an error naming them. */
+export function contextSeconds(v) {
+ if (v === undefined || v === null || v === "") return EXPORT_CONTEXT.default;
+ const n = Number(v);
+ if (!Number.isFinite(n) || n < EXPORT_CONTEXT.min || n > EXPORT_CONTEXT.max) {
+ throw new ExportRefused(`context is ${EXPORT_CONTEXT.min}–${EXPORT_CONTEXT.max} seconds either side (got ${String(v)})`, 400);
+ }
+ return Math.round(n * 10) / 10;
+}
+
+/** A raw export's span `{from, to}` (source seconds), checked; null when none is asked for. */
+export function spanOf(v) {
+ if (v === undefined || v === null) return null;
+ const from = Number(v?.from);
+ const to = Number(v?.to);
+ if (!Number.isFinite(from) || !Number.isFinite(to) || from < 0 || to - from < 0.5) {
+ throw new ExportRefused("a raw span is {from, to}: source seconds, from ≥ 0, at least half a second", 400);
+ }
+ if (to - from > 1800) throw new ExportRefused("a raw span is at most 30 minutes", 400);
+ return { from: Math.round(from * 100) / 100, to: Math.round(to * 100) / 100 };
+}
+
+/**
+ * The SOURCE seconds an export asks for, before the file clamps it: a cut's
+ * is its play window (the render may snap it a second either way), a context
+ * export's that ± N, a raw one's its span or the clip ± the fetch pad.
+ *
+ * @param {Record<string, any>} entry
+ * @param {Record<string, any>} render
+ * @param {{ kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null }} opts
+ */
+export function exportSpan(entry, render, { kind = "cut", context = EXPORT_CONTEXT.default, span = null } = {}) {
+ if (kind === "raw") {
+ if (span) return { from: span.from, to: span.to };
+ const pad = fin(render?.fetchPad) ? render.fetchPad : 3;
+ return { from: Math.max(0, entry.start - pad), to: entry.end + pad };
+ }
+ const pw = playEdges(entry, render ?? {});
+ if (kind === "context") return { from: Math.max(0, pw.from - context), to: pw.to + context };
+ return { from: pw.from, to: pw.to };
}
/**
* What one export cuts, in SOURCE seconds -- the arithmetic, no I/O.
*
* @typedef {{
- * kind: "cut" | "raw",
+ * kind: "cut" | "context" | "raw",
+ * context?: number, span?: { from: number, to: number },
* file: string, fetchStart: number, duration?: number | null, hasVideo?: boolean,
* from: number, to: number,
* gaps: Array<{ from: number, to: number }>,
@@ -133,10 +203,11 @@ export function exportName(entry, { kind = "cut", today = new Date().toISOString
* (cutPoints.mjs; null or an errored row falls back to the manifest's edges).
*
* @param {{ entry: Record<string, any>, render?: Record<string, any>, source: { path: string, fetchStart: number },
- * media?: { duration?: number | null, hasVideo?: boolean }, row?: Record<string, any> | null, kind?: "cut" | "raw" }} o
+ * media?: { duration?: number | null, hasVideo?: boolean }, row?: Record<string, any> | null, kind?: "cut" | "context" | "raw",
+ * context?: number, span?: { from: number, to: number } | null }} o
* @returns {ExportPlan}
*/
-export function planExport({ entry, render = {}, source, media = {}, row = null, kind = "cut" }) {
+export function planExport({ entry, render = {}, source, media = {}, row = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null }) {
const fps = fin(render.fps) && render.fps > 0 ? render.fps : 30;
const fileFrom = source.fetchStart;
const fileTo = fin(media.duration) ? source.fetchStart + /** @type {number} */ (media.duration) : Infinity;
@@ -145,11 +216,23 @@ export function planExport({ entry, render = {}, source, media = {}, row = null,
kind, file: source.path, fetchStart: source.fetchStart, duration: media.duration ?? null,
hasVideo: media.hasVideo !== false, fps, notes,
};
- if (kind === "raw") {
- const pad = fin(render.fetchPad) ? render.fetchPad : 3;
- const from = Math.max(fileFrom, Math.max(0, entry.start - pad));
- const to = Math.min(fileTo, entry.end + pad);
- return { ...base, from, to, gaps: [], mute: null, soundFrom: null, audio: null, gainDb: null, edges: "window" };
+ if (kind === "raw" || kind === "context") {
+ // As recorded: the span asked for (raw: the full exchange, else the clip
+ // and the fetch pad; context: what the cut plays ± N -- the render's
+ // edges when measured), clamped to the file and said.
+ let want = exportSpan(entry, render, { kind, context, span });
+ if (kind === "context" && row && !row.missing && !row.error && fin(row.cutStart) && fin(row.cutEnd)) {
+ want = { from: Math.max(0, row.cutStart - context), to: row.cutEnd + context };
+ }
+ let from = Math.max(fileFrom, want.from);
+ let to = Math.min(fileTo, want.to);
+ if (want.from < fileFrom - 0.05) notes.push(`the cached window starts ${(fileFrom - want.from).toFixed(2)} s after what was asked: from its first frame`);
+ if (want.to > fileTo + 0.05) notes.push(`the cached window ends ${(want.to - fileTo).toFixed(2)} s before what was asked: to its last frame`);
+ if (to < from) to = from;
+ return {
+ ...base, from, to, gaps: [], mute: null, soundFrom: null, audio: null, gainDb: null, edges: "window",
+ ...(kind === "context" ? { context } : {}), ...(kind === "raw" && span ? { span } : {}),
+ };
}
let from;
let to;
@@ -249,7 +332,15 @@ export function planSummary(plan) {
if (plan.mute != null) parts.push(`muted from ${n3(plan.mute)} s`);
if (plan.soundFrom != null) parts.push(`sound from ${n3(plan.soundFrom)} s`);
parts.push(`${n3(planSeconds(plan))} s`);
- parts.push(plan.kind === "raw" ? "the whole window" : plan.edges === "render" ? "the render's edges" : "the manifest's edges");
+ parts.push(
+ plan.kind === "raw"
+ ? plan.span ? "the span asked for, as recorded" : "the whole window"
+ : plan.kind === "context"
+ ? `the cut with ${plan.context ?? EXPORT_CONTEXT.default} s either side, as recorded`
+ : plan.edges === "render"
+ ? "the render's edges"
+ : "the manifest's edges",
+ );
return parts.join(" · ");
}
@@ -285,29 +376,72 @@ export class ExportRefused extends Error {
const inflight = new Map();
/**
+ * What a context or raw export of this clip asks for, and whether a cached
+ * window holds it: `{ entry, want, held, padBefore, padAfter }`, the pads as
+ * the editor's fetch-window takes them (from the clip's extent, whole
+ * seconds, at most EXPORT_CONTEXT.max). A cut asks for what its own source
+ * holds (`held` is whether there is one).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} clipId
+ * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null }} [opts]
+ */
+export async function exportNeeds(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null } = {}) {
+ const { clipSourceOf } = await import("./cutPoints.mjs");
+ const got = await clipSourceOf(project, clipId, { take });
+ if (!got.entry) throw new ExportRefused(`no clip ${clipId} in ${take ? `take ${take} of ` : ""}${project.id}`, 404);
+ const e = got.entry;
+ if (kind === "cut") return { entry: e, want: null, held: !!got.source, padBefore: 0, padAfter: 0 };
+ const want = exportSpan(e, got.render, { kind, context, span });
+ const held = !!(await heldWindow(project, e, want));
+ const pad = (v) => Math.min(EXPORT_CONTEXT.max, Math.max(0, Math.ceil(v)));
+ return { entry: e, want, held, padBefore: pad(e.start - want.from), padAfter: pad(want.to - e.end) };
+}
+
+/** The tightest cached window of the clip's recording holding [want.from, want.to] (projectCache: out/clips-raw and the corpus's windows). */
+async function heldWindow(project, entry, want) {
+ const { projectCache } = await import("./serve.mjs");
+ const cache = await projectCache(project);
+ return cache.containing(entry.video, want.from + 0.02, want.to - 0.02) ?? null;
+}
+
+/**
* Export one clip of a project's cut (or of a take) into `<project>/exports/`.
*
* @param {{ id: string, dir: string }} project
* @param {string} clipId
- * @param {{ take?: string | null, kind?: "cut" | "raw", ffmpeg?: string, today?: string }} [opts]
- * @returns {Promise<{ project: string, clip: string, take: string | null, kind: "cut" | "raw", name: string, rel: string,
+ * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null,
+ * ffmpeg?: string, today?: string }} [opts]
+ * @returns {Promise<{ project: string, clip: string, take: string | null, kind: "cut" | "context" | "raw", name: string, rel: string,
* abs: string, size: number, mtimeMs: number, seconds: number, summary: string, notes: string[], plan: ExportPlan }>}
*/
-export async function exportClip(project, clipId, { take = null, kind = "cut", ffmpeg, today } = {}) {
+export async function exportClip(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, ffmpeg, today } = {}) {
if (!EXPORT_KINDS.includes(kind)) throw new ExportRefused(`an export is one of ${EXPORT_KINDS.join(", ")}`, 400);
+ const ctx = kind === "context" ? contextSeconds(context) : EXPORT_CONTEXT.default;
+ const sp = kind === "raw" ? spanOf(span) : null;
const { clipSourceOf, cutPointsFor } = await import("./cutPoints.mjs");
- const { FFMPEG_BIN, probeMedia } = await import("umtool-report-to-video/build-video");
+ const { FFMPEG_BIN, alignedClipSource, probeMedia } = await import("umtool-report-to-video/build-video");
const got = await clipSourceOf(project, clipId, { take });
if (!got.entry) throw new ExportRefused(`no clip ${clipId} in ${take ? `take ${take} of ` : ""}${project.id}`, 404);
- if (!got.source) {
+ // A context or raw export is cut from the window that holds what it asks for -- a wider fetch
+ // than the build's own source, often (the full exchange) -- when there is one.
+ /** @type {{ path: string, fetchStart: number, pieced?: { entry: Record<string, any> } } | null} */
+ let source = got.source;
+ if (kind !== "cut") {
+ const want = exportSpan(got.entry, got.render, { kind, context: ctx, span: sp });
+ const win = await heldWindow(project, got.entry, want);
+ if (win) source = await alignedClipSource({ path: win.path, fetchStart: win.from }).then((x) => ({ path: x.path, fetchStart: x.fetchStart }), () => ({ path: win.path, fetchStart: win.from }));
+ }
+ if (!source) {
throw new ExportRefused(
- `${clipId}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)`,
+ `${clipId}: its window is not on disk — fetch it first (the Cut tab's Fetch, or \`umtool fetch ${project.id}\`)` +
+ (kind === "cut" ? "" : `; \`umtool export ${project.id} ${clipId} … --fetch\` asks the editor for what this export needs`),
409,
);
}
- const media = await probeMedia(got.source.path).catch(() => ({ hasVideo: true, duration: null }));
+ const media = await probeMedia(source.path).catch(() => ({ hasVideo: true, duration: null }));
let row = null;
- if (kind === "cut") {
+ if (kind === "cut" || kind === "context") {
try {
row = (await cutPointsFor(project, { take, clips: [clipId] })).clips?.[0] ?? null;
} catch (e) {
@@ -316,13 +450,13 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", f
}
// A clip cut from its pieces (cutPoints.mjs piecedDiskSourceOf) is a file on its own clock:
// the plan is made on that clock -- the clip and the cut's numbers as the build sees them.
- const pieced = got.source.pieced ?? null;
+ const pieced = source.pieced ?? null;
const planRow = pieced && row && !row.error && !row.missing && row.pieced
? { ...row, cutStart: row.pieced.cutStart, cutEnd: row.pieced.cutEnd, gaps: row.pieced.gaps }
: row;
- const plan = planExport({ entry: pieced ? pieced.entry : got.entry, render: got.render, source: got.source, media, row: planRow, kind });
+ const plan = planExport({ entry: pieced ? pieced.entry : got.entry, render: got.render, source, media, row: planRow, kind, context: ctx, span: sp });
if (!(planSeconds(plan) > 0.05)) throw new ExportRefused(`${clipId}: nothing to export (${planSummary(plan)})`, 422);
- const name = exportName(got.entry, { kind, ...(today ? { today } : {}) });
+ const name = exportName(got.entry, { kind, context: ctx, span: sp, ...(today ? { today } : {}) });
const dir = path.join(/* turbopackIgnore: true */ project.dir, EXPORTS_DIR);
const abs = path.join(/* turbopackIgnore: true */ dir, name);
const run = inflight.get(abs) ?? (async () => {
@@ -350,6 +484,37 @@ export async function exportClip(project, clipId, { take = null, kind = "cut", f
}
/**
+ * The job that makes an export (the route's): the editor's fetch first when
+ * `fetch` names the pads a context or raw export still needs (driver.mjs
+ * editorFetchSteps, the bench's own; fetchSteps under UMTOOL_LOCAL_FETCH=1),
+ * then `umtool export … --progress ndjson`, which takes the heavy slot itself
+ * and ends with one `export` event.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} clipId
+ * @param {{ take?: string | null, kind?: "cut" | "context" | "raw", context?: number, span?: { from: number, to: number } | null,
+ * fetch?: { padBefore: number, padAfter: number } | null, manifestPath?: string | null }} o
+ */
+export async function exportSteps(project, clipId, { take = null, kind = "cut", context = EXPORT_CONTEXT.default, span = null, fetch = null, manifestPath = null } = {}) {
+ const { UMTOOL_DIR, editorFetchSteps, fetchSteps, localFetch } = await import("./driver.mjs");
+ const steps = [];
+ if (fetch) {
+ const pads = { padBefore: fetch.padBefore, padAfter: fetch.padAfter };
+ steps.push(...(localFetch() ? fetchSteps(project, clipId, pads, { manifestPath }) : editorFetchSteps(project, clipId, pads, { manifestPath })));
+ }
+ const kindArgs = kind === "context" ? ["--context", String(context)] : kind === "raw" ? ["--raw", ...(span ? ["--from", String(span.from), "--to", String(span.to)] : [])] : [];
+ steps.push({
+ cwd: UMTOOL_DIR,
+ env: {},
+ label: `export ${clipId}${kind === "context" ? ` with ${context} s either side` : kind === "raw" ? (span ? ` ${span.from}–${span.to} s, as recorded` : " raw") : ""}`,
+ argv: [process.execPath, path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "export", project.id, clipId, ...kindArgs, ...(take ? ["--take", take] : []), "--progress", "ndjson"],
+ ndjson: true,
+ timeoutMs: 15 * 60_000,
+ });
+ return steps;
+}
+
+/**
* The exports a project holds, newest first: `{name, size, mtimeMs}`.
*
* @param {string} projectDir
diff --git a/umtool/lib/report/clipExport.test.mjs b/umtool/lib/report/clipExport.test.mjs
@@ -19,7 +19,8 @@ process.env.CHANNELS_DIR = CORPUS;
process.env.UMTOOL_CACHE_DIR = CACHE;
const {
- exportArgs, exportClip, exportDate, exportFileOf, exportName, exportSlug, listExports, planExport, planSeconds, planSummary,
+ EXPORT_CONTEXT, contextSeconds, exportArgs, exportClip, exportDate, exportFileOf, exportName, exportNeeds, exportSlug, exportSpan, exportSteps,
+ listExports, planExport, planSeconds, planSummary, spanOf,
} = await import("./clipExport.mjs");
const { cannotOpen, hostName, isLoopbackHost, localRequest, openFolder, openersFor } = await import("./openFolder.mjs");
@@ -203,8 +204,23 @@ test("export a clip: the kept seconds land in exports/ under the clip's name; ra
const rawExp = await exportClip(project, "c1", { kind: "raw" });
assert.equal(rawExp.name, "c1-raw-2026-08-12-deal-with-it.mp4");
near(probeDuration(rawExp.abs), 9, "1 s pad either side of 2–9 s, no gap", 0.12);
+ // With context: what the cut plays (2–9) and 1 s either side, as recorded -- no gap taken out.
+ const ctx = await exportClip(project, "c1", { kind: "context", context: 1 });
+ assert.equal(ctx.name, "c1-ctx1-2026-08-12-deal-with-it.mp4");
+ near(probeDuration(ctx.abs), 9, "1 s either side of 2–9 s, as recorded", 0.15);
+ // The full exchange: a span of its own, its seconds in the name; one past the file is clamped and said.
+ const full = await exportClip(project, "c1", { kind: "raw", span: { from: 0.5, to: 11.5 } });
+ assert.equal(full.name, "c1-raw-0-12-2026-08-12-deal-with-it.mp4");
+ near(probeDuration(full.abs), 11, "0.5–11.5 s", 0.15);
+ const past = await exportClip(project, "c1", { kind: "raw", span: { from: 6, to: 20 } });
+ assert.match(past.notes.join(" "), /ends 8\.00 s before what was asked/);
+ // What a context export needs that is not on disk: 30 s either side is past the 0–12 window.
+ const need = await exportNeeds(project, "c1", { kind: "context", context: 30 });
+ assert.equal(need.held, false);
+ // The pads are from the clip's extent (2–9), as the editor's fetch-window takes them; the recording starts at 0.
+ assert.deepEqual([need.padBefore, need.padAfter], [2, 30]);
const listed = await listExports(root);
- assert.deepEqual(listed.map((x) => x.name).sort(), [cut.name, rawExp.name].sort());
+ assert.deepEqual(listed.map((x) => x.name).sort(), [cut.name, rawExp.name, ctx.name, full.name, past.name].sort());
assert.deepEqual(readdirSync(path.join(root, "exports")).filter((n) => n.startsWith(".")), [], "no part file left");
await assert.rejects(exportClip(project, "nope"), /no clip nope/);
});
@@ -219,6 +235,35 @@ test("export a clip whose window is not on disk: refused, fetch it first", async
await assert.rejects(exportClip({ id: "exp2", dir: root }, "c9"), (e) => e.status === 409 && /fetch it first/.test(e.message));
});
+test("context and a raw span: their bounds, the span they ask for, and the job that makes them", async () => {
+ assert.equal(contextSeconds(undefined), EXPORT_CONTEXT.default);
+ assert.equal(contextSeconds("12"), 12);
+ for (const bad of [0, 121, "x", -1]) assert.throws(() => contextSeconds(bad), (e) => e.status === 400);
+ assert.equal(spanOf(undefined), null);
+ assert.deepEqual(spanOf({ from: 1.234, to: 9 }), { from: 1.23, to: 9 });
+ for (const bad of [{ from: 5, to: 5.2 }, { from: -1, to: 4 }, { from: 0, to: 4000 }, {}]) assert.throws(() => spanOf(bad), (e) => e.status === 400);
+ const e = { id: "c1", start: 103, end: 137, cutStart: 110, cutEnd: 130 };
+ assert.deepEqual(exportSpan(e, { leadIn: 0.4 }, { kind: "cut" }), { from: 109.6, to: 130 });
+ assert.deepEqual(exportSpan(e, { leadIn: 0.4 }, { kind: "context", context: 10 }), { from: 99.6, to: 140 });
+ assert.deepEqual(exportSpan(e, { fetchPad: 3 }, { kind: "raw" }), { from: 100, to: 140 });
+ assert.deepEqual(exportSpan(e, {}, { kind: "raw", span: { from: 50, to: 200 } }), { from: 50, to: 200 });
+ // Names: the kind in the name, so the three never overwrite each other.
+ const named = { id: "ss1", date: "2026-07-22", quote: "side scrollers full exchange" };
+ assert.equal(exportName(named, { kind: "context", context: 10 }), "ss1-ctx10-2026-07-22-side-scrollers-full-exchange.mp4");
+ assert.equal(exportName(named, { kind: "raw", span: { from: 1832.4, to: 1910.2 } }), "ss1-raw-1832-1911-2026-07-22-side-scrollers-full-exchange.mp4");
+ // The job: the editor's fetch first when asked (its pads), then `umtool export … --progress ndjson`.
+ const steps = await exportSteps({ id: "reports/x", dir: "/r/x" }, "c1", { kind: "context", context: 10, fetch: { padBefore: 14, padAfter: 9 } });
+ assert.equal(steps.length, 2);
+ assert.ok(steps[0].argv.some((a) => String(a).endsWith("fetch-via-editor.mjs")), "the editor's fetch-window path");
+ assert.deepEqual(steps[0].argv.slice(-6), ["--pad-before", "14", "--pad-after", "9", "--progress", "ndjson"]);
+ assert.deepEqual(steps[1].argv.slice(2), ["export", "reports/x", "c1", "--context", "10", "--progress", "ndjson"]);
+ assert.equal(steps[1].ndjson, true);
+ const raw = await exportSteps({ id: "reports/x", dir: "/r/x" }, "c1", { kind: "raw", span: { from: 5, to: 50 }, take: "t1" });
+ assert.equal(raw.length, 1, "nothing to fetch: the export alone");
+ assert.deepEqual(raw[0].argv.slice(2), ["export", "reports/x", "c1", "--raw", "--from", "5", "--to", "50", "--take", "t1", "--progress", "ndjson"]);
+ assert.match(planSummary({ kind: "context", context: 10, from: 0, to: 30, gaps: [], mute: null, soundFrom: null, edges: "window" }), /the cut with 10 s either side, as recorded/);
+});
+
// ---- open folder ----------------------------------------------------------------
test("who may ask to open a folder: this machine, by the headers a browser sends", () => {
diff --git a/umtool/lib/report/linkPolicy.mjs b/umtool/lib/report/linkPolicy.mjs
@@ -0,0 +1,211 @@
+// A project's LINK POLICY (UI notes 2026-10-30, #10): "cite via site X; these
+// channels direct". On the Ember cut Ember's and Side Scrollers' clips linked
+// anilyzer while Harmful Opinions' linked YouTube, and the citeUrls were
+// rewritten by hand twice. The policy lives in the manifest, beside the other
+// link setting it qualifies (`provenance.siteOrigin`):
+//
+// provenance.linkPolicy = { via?: "<origin>", direct?: ["<channel slug>", …] }
+//
+// via the archive every clip's QR opens (default: provenance.siteOrigin)
+// direct the channels whose clips link the platform's own page at the cite
+// (YouTube `t=<s>s`, Twitch `t=<h>h<m>m<s>s`, Rumble `start=<s>` --
+// common/lib/clips/assist.mjs watchUrlAt over the record's webpage_url)
+//
+// Enforced in two places, both through the existing writers:
+//
+// - THE INSERTERS (manifest.mjs addClip: the strip's selection, the clip
+// finder, a live share; `umtool timeline insert`): the citeUrl a new clip
+// is written with is the policy's (`policyCiteUrl`), never a neighbour's
+// link that breaks it.
+// - THE CHECK (lib/projects/report.mjs): `clip-link-policy`, one row per clip
+// whose QR breaks the policy, its settle the window writer's citeUrl patch
+// ("Link via site.test" / "Link its YouTube page").
+//
+// A clip with its own media (`src`) is not judged. Plain ESM: the CLI runs it
+// under bare node.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { watchUrlAt } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
+import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { archiveMomentUrl } from "umtool-report-to-video/site-links";
+import { archiveLinkOf } from "./linkCheck.mjs";
+import { originOf } from "./siteDeploys.mjs";
+
+export const LINK_POLICY_KEY = "linkPolicy";
+const SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/i;
+
+/**
+ * A policy as written, checked and normalised: `{ via, direct }` (via an
+ * origin or null, direct sorted and unique), or null for "no policy". Throws
+ * on a policy the check could not apply.
+ * @param {unknown} raw
+ * @returns {{ via: string | null, direct: string[] } | null}
+ */
+export function normalizeLinkPolicy(raw) {
+ if (raw == null) return null;
+ if (typeof raw !== "object" || Array.isArray(raw)) throw new Error("provenance.linkPolicy is { via?, direct? }");
+ const r = /** @type {Record<string, unknown>} */ (raw);
+ for (const k of Object.keys(r)) if (k !== "via" && k !== "direct") throw new Error(`provenance.linkPolicy has no key "${k}" (via, direct)`);
+ let via = null;
+ if (r.via != null && String(r.via).trim() !== "") {
+ via = originOf(String(r.via).trim());
+ if (!via) throw new Error(`linkPolicy.via is a site's http(s) address, not ${JSON.stringify(r.via)}`);
+ }
+ const list = r.direct == null ? [] : Array.isArray(r.direct) ? r.direct : String(r.direct).split(",");
+ const direct = [...new Set(list.map((s) => String(s).trim()).filter(Boolean))].sort();
+ for (const s of direct) if (!SLUG_RE.test(s)) throw new Error(`linkPolicy.direct names channel slugs, not ${JSON.stringify(s)}`);
+ return via || direct.length ? { via, direct } : null;
+}
+
+/** The manifest's policy, or null (none, or one that does not read). */
+export function linkPolicyOf(m) {
+ try {
+ return normalizeLinkPolicy(m?.provenance?.[LINK_POLICY_KEY]);
+ } catch {
+ return null;
+ }
+}
+
+const chanOf = (m, e) => e?.channel ?? m?.provenance?.channelSlug ?? null;
+const citeOf = (e) => Math.floor(Number(e?.cite ?? e?.cutStart ?? e?.start ?? 0) || 0);
+
+/**
+ * Where a clip's QR points now -- build-video's rule (lib/projects/report.mjs
+ * citeUrlFor): its own citeUrl, else its moment on the provenance's origin.
+ */
+export function currentLinkOf(m, e) {
+ if (typeof e?.citeUrl === "string" && e.citeUrl) return e.citeUrl;
+ return archiveMomentUrl({ ...e, channel: chanOf(m, e) }, m?.provenance, e?.start ?? 0, { origin: m?.provenance?.siteOrigin ?? "" });
+}
+
+/**
+ * What the policy wants of one clip: `{ want: "direct" | "via", url }`, the
+ * url null when it cannot be built (a direct clip whose record names no
+ * webpage_url, a via policy with no origin). Null when the policy has nothing
+ * to say about the clip.
+ * @param {Record<string, any>} m
+ * @param {Record<string, any>} e
+ * @param {{ webpageUrl?: string | null, policy?: ReturnType<typeof linkPolicyOf> }} [o]
+ */
+export function policyLinkFor(m, e, { webpageUrl = null, policy = linkPolicyOf(m) } = {}) {
+ if (!policy || e?.type !== "clip" || e.src != null) return null;
+ const chan = chanOf(m, e);
+ const cite = citeOf(e);
+ if (chan && policy.direct.includes(chan)) return { want: /** @type {const} */ ("direct"), url: watchUrlAt(webpageUrl, cite) };
+ const via = policy.via ?? originOf(m?.provenance?.siteOrigin);
+ if (!via) return null;
+ return { want: /** @type {const} */ ("via"), url: archiveMomentUrl({ ...e, channel: chan }, m?.provenance, cite, { origin: via }), via };
+}
+
+/**
+ * Whether the clip's QR keeps the policy: a direct channel's is not an
+ * archive link; any other's is an archive link on `via`. `null` when the
+ * policy says nothing about the clip.
+ */
+export function keepsPolicy(m, e, o = {}) {
+ const want = policyLinkFor(m, e, o);
+ if (!want) return null;
+ const a = archiveLinkOf(currentLinkOf(m, e));
+ if (want.want === "direct") return !a;
+ return !!a && a.origin === /** @type {any} */ (want).via;
+}
+
+/**
+ * Every clip whose QR breaks the policy, with the citeUrl that keeps it (null
+ * when it cannot be built). Pure over `webpageOf` (the record's webpage_url).
+ * @param {Record<string, any>} m
+ * @param {{ webpageOf?: (e: Record<string, any>) => string | null }} [o]
+ */
+export function policyBreaks(m, { webpageOf = () => null } = {}) {
+ const policy = linkPolicyOf(m);
+ if (!policy) return [];
+ const out = [];
+ for (const e of m?.timeline ?? []) {
+ if (e?.type !== "clip" || e.src != null) continue;
+ const webpageUrl = webpageOf(e);
+ const want = policyLinkFor(m, e, { webpageUrl, policy });
+ if (!want || keepsPolicy(m, e, { webpageUrl, policy }) !== false) continue;
+ const current = currentLinkOf(m, e);
+ let host = "";
+ try {
+ host = new URL(current).host;
+ } catch {
+ host = current;
+ }
+ out.push({
+ clip: e.id,
+ channel: chanOf(m, e),
+ current,
+ want: want.want,
+ fix: want.url,
+ why:
+ want.want === "direct"
+ ? `${chanOf(m, e)} links direct by the project's link policy, but its QR opens ${host}${want.url ? "" : " — and its record names no platform page to link (no webpage_url)"}`
+ : `the project's link policy cites via ${new URL(/** @type {any} */ (want).via).host}, but its QR opens ${host}`,
+ });
+ }
+ return out;
+}
+
+/** The settle button's words for a fix. */
+export function policyFixLabel(b) {
+ if (b.want === "direct") {
+ let host = "the platform";
+ try {
+ host = new URL(String(b.fix)).hostname.replace(/^(?:www|m)\./, "");
+ } catch {
+ /* keep the generic word */
+ }
+ const name = /youtu/.test(host) ? "YouTube" : /twitch/.test(host) ? "Twitch" : /rumble/.test(host) ? "Rumble" : host;
+ return `Link its ${name} page`;
+ }
+ try {
+ return `Link via ${new URL(String(b.fix)).host}`;
+ } catch {
+ return "Link via the site";
+ }
+}
+
+/**
+ * The record's webpage_url, read once per recording: the cue file's
+ * `webpageUrl`, else metadata.info.json's `webpage_url`. Null when neither
+ * says (or there is no channels dir).
+ * @param {string | null} channelsDir
+ */
+export function webpageReader(channelsDir) {
+ const memo = new Map();
+ return async (slug, video) => {
+ if (!channelsDir || !slug || !video) return null;
+ const key = `${slug}/${video}`;
+ if (!memo.has(key)) {
+ memo.set(key, (async () => {
+ const dir = await resolveVideoDir(channelsDir, slug, video).catch(() => path.join(channelsDir, slug, "data", video));
+ const read = (name) => readFile(path.join(/* turbopackIgnore: true */ dir, name), "utf8").then(JSON.parse, () => null);
+ const cues = await read("transcript.cues.json");
+ if (typeof cues?.webpageUrl === "string" && cues.webpageUrl) return cues.webpageUrl;
+ const meta = await read("metadata.info.json");
+ return typeof meta?.webpage_url === "string" && meta.webpage_url ? meta.webpage_url : null;
+ })());
+ }
+ return memo.get(key);
+ };
+}
+
+/**
+ * The citeUrl an inserter writes a NEW clip with under the policy: the
+ * policy's link when the clip's link would break it (a neighbour's copied
+ * citeUrl, or the default origin when `via` is another site), `undefined`
+ * when the clip keeps it as it is (so nothing is written), `null` when the
+ * link the policy wants cannot be built (the clip's citeUrl is dropped so the
+ * check names it, rather than a copied link that breaks the policy).
+ * @param {Record<string, any>} m
+ * @param {Record<string, any>} entry
+ * @param {string | null} webpageUrl
+ */
+export function policyCiteUrl(m, entry, webpageUrl) {
+ const policy = linkPolicyOf(m);
+ const want = policyLinkFor(m, entry, { webpageUrl, policy });
+ if (!want) return undefined;
+ if (keepsPolicy(m, entry, { webpageUrl, policy }) === true) return undefined;
+ return want.url;
+}
diff --git a/umtool/lib/report/linksCli.mjs b/umtool/lib/report/linksCli.mjs
@@ -159,3 +159,111 @@ export async function patchMarkersCommand(args, { root = REPORTS_ROOT, out = (s)
return e instanceof CliError ? 2 : 1;
}
}
+
+export const LINK_POLICY_USAGE = [
+ "usage: umtool link-policy <project> [--via <site id | https://…>] [--direct <slug,slug…>] [--clear] [--fix] [--json]",
+ "",
+ "The project's link policy, provenance.linkPolicy: \"cite via site X; these channels direct\". --via names the",
+ "archive every clip's QR opens (a site id from transcripts/sites, or its address; '' goes back to",
+ "provenance.siteOrigin); --direct the channels whose clips link the platform's own page at the cite ('' none);",
+ "--clear removes the policy. New clips are written by it (the inserters); the clips already in the cut that",
+ "break it are `umtool check`'s clip-link-policy rows. --fix rewrites each of them that has a fix through the",
+ "window writer. With no flag, prints the policy and what breaks it. Exit 1 when a clip still breaks it.",
+].join("\n");
+
+/**
+ * `umtool link-policy …`
+ * @param {string[]} args the words after `link-policy`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, sitesDir?: string }} [opts]
+ * @returns {Promise<number>}
+ */
+export async function linkPolicyCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), sitesDir } = {}) {
+ try {
+ const { linkPolicyOf, normalizeLinkPolicy, policyBreaks, webpageReader } = await import("./linkPolicy.mjs");
+ const { sitesByOrigin } = await import("./siteDeploys.mjs");
+ const { updateLinkPolicy } = await import("./manifest.mjs");
+ const { channelsDirFor, hasShadowChannels } = await import("../projects/report.mjs");
+ const { SITES_DIR } = await import("../paths.mjs");
+ const words = [];
+ /** @type {Map<string, string | true>} */
+ const flags = new Map();
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a === "--via" || a === "--direct") {
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value ('' clears it)`);
+ flags.set(a, args[++i]);
+ } else if (["--clear", "--fix", "--json", "--help"].includes(a)) flags.set(a, true);
+ else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`);
+ else words.push(a);
+ }
+ if (!words[0] || flags.has("--help")) {
+ (flags.has("--help") ? out : err)(LINK_POLICY_USAGE);
+ return flags.has("--help") ? 0 : 2;
+ }
+ const r = await resolveProject(words[0], root);
+ if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${words[0]}"`);
+ const project = r.project;
+ if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`);
+ let m = await readManifest(project.dir);
+ if (!m) throw new CliError(`${project.id} has no video.manifest.json`);
+ const notes = [];
+ if (flags.has("--clear") || flags.has("--via") || flags.has("--direct")) {
+ if (flags.has("--clear") && (flags.has("--via") || flags.has("--direct"))) throw new CliError("--clear takes no --via or --direct");
+ let next = null;
+ if (!flags.has("--clear")) {
+ const was = linkPolicyOf(m) ?? { via: null, direct: [] };
+ let via = was.via;
+ if (flags.has("--via")) {
+ const v = String(flags.get("--via")).trim();
+ if (!v) via = null;
+ else if (/^https?:\/\//i.test(v)) via = v;
+ else {
+ const hit = [...sitesByOrigin(sitesDir ?? SITES_DIR)].find(([, s]) => s.siteId === v);
+ if (!hit) throw new CliError(`--via ${v}: no site of that id has a siteUrl (transcripts/sites/<id>/site.json); pass its address`);
+ via = hit[0];
+ }
+ }
+ const direct = flags.has("--direct") ? String(flags.get("--direct")) : was.direct;
+ next = normalizeLinkPolicy({ via, direct });
+ }
+ const res = await withEditNotes(project, () => updateLinkPolicy(project.dir, next));
+ notes.push(res.result.changed ? "link policy saved" : "link policy unchanged");
+ m = await readManifest(project.dir);
+ }
+ const shadowExists = await hasShadowChannels(project.dir);
+ const read = webpageReader(channelsDirFor(project.dir, m, { shadowExists }));
+ const web = new Map();
+ for (const e of m.timeline ?? []) {
+ if (e?.type === "clip") web.set(e.id, await read(e.channel ?? m.provenance?.channelSlug, e.video));
+ }
+ let breaks = policyBreaks(m, { webpageOf: (e) => web.get(e.id) ?? null });
+ const fixed = [];
+ if (flags.has("--fix")) {
+ for (const b of breaks) {
+ if (!b.fix) continue;
+ await withEditNotes(project, () => updateClip(project.dir, b.clip, { citeUrl: b.fix }));
+ fixed.push({ clip: b.clip, from: b.current, to: b.fix });
+ }
+ if (fixed.length) {
+ m = await readManifest(project.dir);
+ breaks = policyBreaks(m, { webpageOf: (e) => web.get(e.id) ?? null });
+ }
+ }
+ const policy = linkPolicyOf(m);
+ if (flags.has("--json")) {
+ out(JSON.stringify({ ok: breaks.length === 0, project: project.id, policy, breaks, ...(flags.has("--fix") ? { fixed } : {}) }, null, 2));
+ return breaks.length ? 1 : 0;
+ }
+ for (const n of notes) out(n);
+ for (const f of fixed) out(`fixed ${f.clip}: ${f.from} -> ${f.to}`);
+ if (!policy) out(`${project.id}: no link policy (every QR opens provenance.siteOrigin, or the clip's own citeUrl)`);
+ else out(`${project.id}: cite via ${policy.via ?? `provenance.siteOrigin (${m.provenance?.siteOrigin ?? "unset"})`}; direct: ${policy.direct.length ? policy.direct.join(", ") : "none"}`);
+ for (const b of breaks) out(`BREAKS ${b.clip} ${b.why}${b.fix ? `\n fix: ${b.fix}` : ""}`);
+ if (policy && !breaks.length) out("every clip's QR keeps it");
+ return breaks.length ? 1 : 0;
+ } catch (e) {
+ err(`umtool link-policy: ${e instanceof Error ? e.message : String(e)}`);
+ return e instanceof CliError ? 2 : 1;
+ }
+}
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -58,6 +58,9 @@ import {
} from "./knobs.mjs";
import { validateNarration } from "umtool-report-to-video/narration";
import { parseMuteFrom } from "./playback.mjs";
+import { LINK_POLICY_KEY, linkPolicyOf, normalizeLinkPolicy, policyCiteUrl, webpageReader } from "./linkPolicy.mjs";
+import { SHADOW_CHANNELS as POLICY_SHADOW, channelsDirFor as policyChannelsDirFor } from "umtool-report-to-video/sources";
+import { CHANNELS_DIR as POLICY_CHANNELS_DIR } from "../paths.mjs";
import { FACT_REASONS, applyVerdictPatch, rejectPatch, rejectReasonOf } from "./rejectReasons.mjs";
import { DELIVERABLES_MODES } from "./storage.mjs";
import { createSnapshot, listSnapshots } from "./snapshots.mjs";
@@ -1076,7 +1079,7 @@ export async function mergeClips(dir, clipId, { token = null, quote, now = null
* @param {{ token?: string | null, now?: string | null }} [opts]
*/
export async function addClip(dir, spec, { token = null, now = null } = {}) {
- return prepAfter(dir, (r) => [r.id], structural(dir, "add", token, (m) => {
+ return prepAfter(dir, (r) => [r.id], structural(dir, "add", token, (m, webpageUrl) => {
if (!isObj(spec)) throw new Error("a clip to add is { video, cutStart, cutEnd }");
if (typeof spec.video !== "string" || !/^[\w.-]+$/.test(spec.video)) throw new Error("a clip needs its video id");
const num = (k, v) => {
@@ -1097,6 +1100,8 @@ export async function addClip(dir, spec, { token = null, now = null } = {}) {
if (quote) entry.quote = quote.slice(0, 2000);
const title = typeof spec.title === "string" ? spec.title.trim() : "";
if (title) entry.title = title.slice(0, 300);
+ // The project's link policy (linkPolicy.mjs): the QR a new clip gets is the policy's.
+ applyPolicyLink(m, entry, webpageUrl);
const stamp = now ?? new Date().toISOString();
entry.assist = {
by: "operator",
@@ -1115,7 +1120,7 @@ export async function addClip(dir, spec, { token = null, now = null } = {}) {
}
m.timeline.splice(at, 0, entry);
return { id: entry.id, at, entry };
- }));
+ }, { prepare: (m) => policyWebpage(dir, m, spec) }));
}
@@ -2092,13 +2097,16 @@ export function reanchorAfterRemove(m, removed, i) {
* One structural write: token, read, `mutate` (which throws to refuse), the
* build's checks, the auto snapshot of the file as it still is, then the write.
*/
-async function structural(dir, op, token, mutate, { snapshotEvery = undefined } = {}) {
+async function structural(dir, op, token, mutate, { snapshotEvery = undefined, prepare = null } = {}) {
return withManifestLock(async () => {
const current = await manifestToken(dir);
if (token !== null && current !== token) throw new StaleToken(token, current);
const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
const timelineBefore = Array.isArray(manifest.timeline) ? [...manifest.timeline] : [];
- const result = applyStructural(manifest, mutate);
+ // What a write must read before it mutates (an inserter's link policy:
+ // the record's webpage_url), inside the lock, after the token is checked.
+ const prepared = prepare ? await prepare(manifest) : undefined;
+ const result = applyStructural(manifest, (m) => mutate(m, prepared));
const snapshot = await autoSnapshot(dir, op, snapshotEvery === undefined ? {} : { every: snapshotEvery });
const nextToken = await writeManifestAtomic(dir, manifest);
// The project's take patches follow a removal as the manifest's markers
@@ -2291,12 +2299,70 @@ function clipEntry(timeline, e) {
* @param {{ token?: string | null, at?: number | null }} [opts] `at` is afterId's index
*/
export async function insertEntry(dir, afterId, spec, { token = null, at = null } = {}) {
- return prepAfter(dir, clipIdOf, structural(dir, "insert", token, (m) => {
+ return prepAfter(dir, clipIdOf, structural(dir, "insert", token, (m, webpageUrl) => {
const i = afterId ? entryIndex(m.timeline, afterId, at) + 1 : 0;
const entry = entryFromSpec(m.timeline, spec);
+ // A clip's QR is the project's link policy's (linkPolicy.mjs), not a copied link that breaks it.
+ if (entry.type === "clip") applyPolicyLink(m, entry, webpageUrl);
m.timeline.splice(i, 0, entry);
return { id: entry.id, at: i, entry };
- }));
+ }, { prepare: (m) => policyWebpage(dir, m, typeof spec === "string" ? parseClipSpec(spec) : spec) }));
+}
+
+// ---- the link policy (UI notes 2026-10-30, #10; linkPolicy.mjs) -----------
+
+/**
+ * The record's webpage_url when the project's link policy links `spec`'s
+ * channel direct, else null: read inside the write's lock (structural's
+ * `prepare`), so the inserters write the platform link in the same write.
+ * @param {string} dir
+ * @param {Record<string, any>} m the manifest as the write read it
+ * @param {{ channel?: string, video?: string } | null | undefined} spec
+ */
+async function policyWebpage(dir, m, spec) {
+ const policy = linkPolicyOf(m);
+ if (!policy?.direct.length || !spec || typeof spec !== "object") return null;
+ const chan = typeof spec.channel === "string" && spec.channel ? spec.channel : m.provenance?.channelSlug;
+ if (!chan || !policy.direct.includes(chan) || typeof spec.video !== "string") return null;
+ const shadowExists = await stat(path.join(dir, POLICY_SHADOW)).then((st) => st.isDirectory(), () => false);
+ const channelsDir = policyChannelsDirFor(dir, m, { shadowExists, fallback: POLICY_CHANNELS_DIR });
+ return webpageReader(channelsDir)(chan, spec.video);
+}
+
+/** Write the policy's citeUrl on a new clip: its link when the clip's breaks it; a copied one it cannot replace is dropped. */
+function applyPolicyLink(m, entry, webpageUrl) {
+ const cu = policyCiteUrl(m, entry, webpageUrl);
+ if (typeof cu === "string" && cu) entry.citeUrl = cu;
+ else if (cu === null) delete entry.citeUrl;
+}
+
+/**
+ * Set (or with null, clear) the project's link policy,
+ * `provenance.linkPolicy = { via?, direct? }` (linkPolicy.mjs
+ * normalizeLinkPolicy: `via` an origin, `direct` channel slugs). A no-op
+ * writes nothing. The clips already in the cut are not rewritten here: what
+ * breaks the policy is the check's `clip-link-policy` rows, each with its fix.
+ *
+ * @param {string} dir
+ * @param {unknown} policy
+ * @param {{ token?: string | null }} [opts]
+ * @returns {Promise<{ linkPolicy: { via: string | null, direct: string[] } | null, token: string | null, changed: boolean }>}
+ */
+export async function updateLinkPolicy(dir, policy, { token = null } = {}) {
+ const next = normalizeLinkPolicy(policy);
+ return withManifestLock(async () => {
+ const current = await manifestToken(dir);
+ if (token !== null && current !== token) throw new StaleToken(token, current);
+ const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
+ const was = manifest.provenance?.[LINK_POLICY_KEY] ?? null;
+ const written = next ? { ...(next.via ? { via: next.via } : {}), ...(next.direct.length ? { direct: next.direct } : {}) } : null;
+ if (JSON.stringify(was) === JSON.stringify(written)) return { linkPolicy: next, token: current, changed: false };
+ if (!isObj(manifest.provenance)) manifest.provenance = {};
+ if (written) manifest.provenance[LINK_POLICY_KEY] = written;
+ else delete manifest.provenance[LINK_POLICY_KEY];
+ const nextToken = await writeManifestAtomic(dir, manifest);
+ return { linkPolicy: next, token: nextToken, changed: true };
+ });
}
/**
diff --git a/umtool/lib/report/siteDeploys.mjs b/umtool/lib/report/siteDeploys.mjs
@@ -0,0 +1,155 @@
+// Which sites does this cut's QR links depend on, and is each one's deploy
+// recent enough to hold what the cut cites? (UI notes 2026-10-30, #9)
+//
+// On the Ember cut anilyzer's publish policy was "build" only: nothing said
+// the video being made cited a site that had not been deployed since 9 Oct.
+// The link check (linkCheck.mjs, #8) already reads each site's corpus.json and
+// records its `generatedAt` -- the day the deployed bundle's data was built --
+// in out/links.json. This module reads that record (it never fetches):
+//
+// - the SITES: every origin a clip QR the cut draws opens (linksOf), each
+// named by the site whose site.json `siteUrl` it is (SITES_DIR, read only)
+// and dated by the recorded corpus.json;
+// - the cited videos NEWER than that deploy: a clip on that site whose
+// recording was uploaded after it, or whose transcript landed here after
+// it, and whose link the check did not find open (a link the check opened
+// is on the site, whatever its dates say).
+//
+// The check row `site-deploy-behind` (lib/projects/report.mjs) is one per site
+// with such clips, its settle "Publish <site>" asking the editor to build and
+// deploy that site (POST /api/report/publish-site -> the editor's ops
+// build-deploy). Plain ESM: the CLI runs it under bare node.
+import { readdirSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { archiveLinkOf, linksOf } from "./linkCheck.mjs";
+
+/** `https://x.pages.dev/` -> `https://x.pages.dev`; null for anything not http(s). */
+export function originOf(url) {
+ try {
+ const u = new URL(String(url));
+ return u.protocol === "http:" || u.protocol === "https:" ? u.origin : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Every site with a `siteUrl`, by its origin: `{ siteId, title }`. Read once
+ * per call (a handful of small files); a site.json that does not parse is
+ * skipped.
+ * @param {string} sitesDir
+ * @returns {Map<string, { siteId: string, title: string | null }>}
+ */
+export function sitesByOrigin(sitesDir) {
+ const out = new Map();
+ let ids = [];
+ try {
+ ids = readdirSync(/* turbopackIgnore: true */ sitesDir);
+ } catch {
+ return out;
+ }
+ for (const id of ids.sort()) {
+ let doc;
+ try {
+ doc = JSON.parse(readFileSync(/* turbopackIgnore: true */ path.join(sitesDir, id, "site.json"), "utf8"));
+ } catch {
+ continue;
+ }
+ const origin = originOf(doc?.siteUrl);
+ if (!origin || out.has(origin)) continue;
+ out.set(origin, { siteId: id, title: typeof doc?.siteTitle === "string" ? doc.siteTitle : typeof doc?.title === "string" ? doc.title : null });
+ }
+ return out;
+}
+
+/** `20261020` / `2026-10-20` / an ISO time -> `2026-10-20`, else null. */
+export function dayOf(v) {
+ const s = String(v ?? "").trim();
+ if (/^\d{8}$/.test(s)) return `${s.slice(0, 4)}-${s.slice(4, 6)}-${s.slice(6, 8)}`;
+ const m = /^(\d{4}-\d{2}-\d{2})/.exec(s);
+ return m ? m[1] : null;
+}
+
+/**
+ * The sites the cut's links depend on, with each one's deploy and the cited
+ * videos newer than it. Pure over its inputs.
+ *
+ * @param {Record<string, any>} m the manifest
+ * @param {{ origins?: Record<string, any>, links?: Array<{ clip: string, url: string, state: string }>, checkedAt?: string } | null} linkDoc out/links.json
+ * @param {{ sites?: Map<string, { siteId: string, title: string | null }>, recordOf?: (clipId: string) => { uploadDate?: string | null, landedAt?: string | null } | null }} [opts]
+ * `recordOf`: what is known of the clip's recording here -- its upload date
+ * and when its transcript landed (the cue file's mtime, ISO).
+ * @returns {Array<{
+ * origin: string, host: string, siteId: string | null, title: string | null,
+ * deployedAt: string | null, state: "ok" | "unreachable" | "no-corpus" | "unchecked",
+ * clips: string[], links: number,
+ * newer: Array<{ clip: string, why: string, day: string }>,
+ * }>}
+ */
+export function projectSites(m, linkDoc, { sites = new Map(), recordOf = () => null } = {}) {
+ /** @type {Map<string, { clips: Set<string>, links: Array<{ clip: string, url: string }> }>} */
+ const by = new Map();
+ for (const l of linksOf(m)) {
+ const a = archiveLinkOf(l.url);
+ if (!a) continue;
+ if (!by.has(a.origin)) by.set(a.origin, { clips: new Set(), links: [] });
+ const g = /** @type {{ clips: Set<string>, links: Array<{ clip: string, url: string }> }} */ (by.get(a.origin));
+ g.clips.add(l.clip);
+ g.links.push(l);
+ }
+ const checked = new Map((linkDoc?.links ?? []).map((l) => [`${l.clip}\u0000${l.url}`, l.state]));
+ const out = [];
+ for (const [origin, g] of by) {
+ const o = linkDoc?.origins?.[origin] ?? null;
+ const deployedAt = typeof o?.generatedAt === "string" ? o.generatedAt : null;
+ const deployDay = dayOf(deployedAt);
+ const site = sites.get(origin) ?? null;
+ const newer = [];
+ if (deployDay) {
+ const seen = new Set();
+ for (const l of g.links) {
+ if (seen.has(l.clip)) continue;
+ // The check opened it: the record is on the site.
+ if (checked.get(`${l.clip}\u0000${l.url}`) === "ok") continue;
+ const r = recordOf(l.clip) ?? {};
+ const up = dayOf(r.uploadDate);
+ const landed = dayOf(r.landedAt);
+ if (up && up > deployDay) {
+ seen.add(l.clip);
+ newer.push({ clip: l.clip, why: `uploaded ${up}`, day: up });
+ } else if (landed && landed > deployDay) {
+ seen.add(l.clip);
+ newer.push({ clip: l.clip, why: `transcribed here ${landed}`, day: landed });
+ }
+ }
+ }
+ let host = origin;
+ try {
+ host = new URL(origin).host;
+ } catch {
+ /* the origin as written */
+ }
+ out.push({
+ origin,
+ host,
+ siteId: site?.siteId ?? null,
+ title: site?.title ?? (typeof o?.title === "string" ? o.title : null),
+ deployedAt,
+ state: o ? o.state : "unchecked",
+ clips: [...g.clips],
+ links: g.links.length,
+ newer,
+ });
+ }
+ return out.sort((a, b) => b.links - a.links || a.host.localeCompare(b.host));
+}
+
+/** The check row's sentence for one site with newer videos. */
+export function deployBehindWhy(s) {
+ const list = s.newer.slice(0, 6).map((n) => `${n.clip} (${n.why})`).join(", ");
+ const more = s.newer.length > 6 ? ` and ${s.newer.length - 6} more` : "";
+ return (
+ `${s.siteId ?? s.host}'s deploy is from ${dayOf(s.deployedAt)}; ${s.newer.length} cited video${s.newer.length === 1 ? " is" : "s are"} newer: ${list}${more}` +
+ ` — publish the site before the video ships, or link elsewhere`
+ );
+}
diff --git a/umtool/lib/report/speakerCheck.mjs b/umtool/lib/report/speakerCheck.mjs
@@ -0,0 +1,321 @@
+// `umtool speaker-check <project>` (UI notes 2026-10-30, #15): which of the
+// project's named voices a clip is -- "Speaker: matches Ember 0.93 / Kirsche
+// 0.83" on the walk -- with the reference sets it was measured against.
+//
+// The scorer is common's (lib/montage/speakerCheck.mjs, over the voice match's
+// pieces: TitaNet-small through sherpa-onnx, local). This module is umtool's
+// half, the voice match's (voiceMatch.mjs) again: which seconds of which file
+// each clip is (planClips), and the reference sets, `<project>/speakers.json`:
+//
+// { "speakers": [ { "name": "Ember", "clips": ["e01", "e07"] },
+// { "name": "Kirsche", "videos": ["kirsche/abc123"], "channels": ["kirsche"] } ] }
+//
+// clips clips of this cut known to be that voice (a confirmed clip; the
+// walk's "Add to <name>'s voice")
+// videos recordings of that voice alone (`<channel>/<id>`): the first
+// REFERENCE_SECONDS of speech, in pieces, as the voice match reads them
+// channels channels whose solo recordings are that voice (the voice
+// match's heuristic picks them)
+//
+// The app's "Check speaker" runs this command as a job (speakerCheckSteps)
+// through the machine's heavy slot -- light, but a render the operator is
+// waiting for comes first (render mode). Nothing here calls a model but the
+// local speaker-embedding one; nothing touches the network.
+import { existsSync } from "node:fs";
+import { readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { DEFAULT_THRESHOLDS, PHRASE_PAD_S, REFERENCE_VIDEOS, resolveEngine } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+import { readSpeakerCheck, runSpeakerCheck, writeSpeakerCheck } from "yt-dlp-transcript-common/lib/montage/speakerCheck.mjs";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { kindMakesTakes } from "../projects/kinds.mjs";
+import { channelsDirFor, hasShadowChannels, readManifest } from "../projects/report.mjs";
+import { REPO_ROOT } from "../paths.mjs";
+import { UMTOOL_DIR } from "./driver.mjs";
+import { planClips, referenceRecordings } from "./voiceMatch.mjs";
+
+export const SPEAKERS_FILE = "speakers.json";
+const NAME_RE = /^[^\s/=,][^/=,]{0,47}$/;
+const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+const VIDEO_RE = /^[a-z0-9][a-z0-9._-]*\/[A-Za-z0-9_.-]+$/i;
+
+class CliError extends Error {}
+
+/**
+ * The reference sets, checked: `[{ name, clips, videos, channels }]` ([] with
+ * no file). Throws on a file that does not read as one.
+ * @param {unknown} raw
+ */
+export function normalizeSpeakers(raw) {
+ const list = raw && typeof raw === "object" && Array.isArray(/** @type {any} */ (raw).speakers) ? /** @type {any} */ (raw).speakers : null;
+ if (!list) throw new Error(`${SPEAKERS_FILE} is { "speakers": [ { "name", "clips"?, "videos"?, "channels"? } ] }`);
+ const seen = new Set();
+ return list.map((s, i) => {
+ const name = String(s?.name ?? "").trim();
+ if (!NAME_RE.test(name)) throw new Error(`speaker ${i + 1}: a name of 1–48 characters, no / = or comma (got ${JSON.stringify(s?.name)})`);
+ if (seen.has(name.toLowerCase())) throw new Error(`two speakers are named "${name}"`);
+ seen.add(name.toLowerCase());
+ const strs = (k, re) => {
+ const v = s?.[k] ?? [];
+ if (!Array.isArray(v)) throw new Error(`${name}: ${k} is a list`);
+ const out = [...new Set(v.map((x) => String(x).trim()).filter(Boolean))];
+ for (const x of out) if (!re.test(x)) throw new Error(`${name}: ${k} has ${JSON.stringify(x)}`);
+ return out;
+ };
+ return { name, clips: strs("clips", ID_RE), videos: strs("videos", VIDEO_RE), channels: strs("channels", /^[a-z0-9][a-z0-9._-]*$/i) };
+ });
+}
+
+/** The project's reference sets ([] when there is no speakers.json). */
+export async function readSpeakers(dir) {
+ let text;
+ try {
+ text = await readFile(path.join(dir, SPEAKERS_FILE), "utf8");
+ } catch {
+ return [];
+ }
+ return normalizeSpeakers(JSON.parse(text));
+}
+
+/** Write the reference sets whole (tmp + rename). */
+export async function writeSpeakers(dir, speakers) {
+ const list = normalizeSpeakers({ speakers });
+ const file = path.join(dir, SPEAKERS_FILE);
+ const tmp = `${file}.${process.pid}.tmp`;
+ const doc = { speakers: list.map((s) => ({ name: s.name, ...(s.clips.length ? { clips: s.clips } : {}), ...(s.videos.length ? { videos: s.videos } : {}), ...(s.channels.length ? { channels: s.channels } : {}) })) };
+ await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`);
+ await rename(tmp, file);
+ return list;
+}
+
+/**
+ * `Name=clip:e01,video:chan/id,channel:slug` (a bare word is a clip id, a
+ * `chan/id` a video) -> a speaker.
+ * @param {string} spec
+ */
+export function parseSpeakerSpec(spec) {
+ const i = String(spec).indexOf("=");
+ if (i <= 0) throw new CliError(`--set takes Name=<clip id | channel/id | channel:slug>,… (got ${JSON.stringify(spec)})`);
+ const name = spec.slice(0, i).trim();
+ const s = { name, clips: [], videos: [], channels: [] };
+ for (const raw of spec.slice(i + 1).split(",").map((x) => x.trim()).filter(Boolean)) {
+ const [k, v] = raw.includes(":") ? [raw.slice(0, raw.indexOf(":")), raw.slice(raw.indexOf(":") + 1)] : [raw.includes("/") ? "video" : "clip", raw];
+ if (k === "clip") s.clips.push(v);
+ else if (k === "video") s.videos.push(v);
+ else if (k === "channel") s.channels.push(v);
+ else throw new CliError(`--set ${name}: "${raw}" is clip:<id>, video:<channel>/<id> or channel:<slug>`);
+ }
+ return s;
+}
+
+/** Add one clip of the cut to a voice (made when it is new); a clip is in one voice at a time. */
+export async function addClipToSpeaker(dir, name, clipId) {
+ const list = await readSpeakers(dir);
+ const n = String(name ?? "").trim();
+ let s = list.find((x) => x.name.toLowerCase() === n.toLowerCase());
+ for (const x of list) x.clips = x.clips.filter((c) => c !== clipId);
+ if (!s) {
+ s = { name: n, clips: [], videos: [], channels: [] };
+ list.push(s);
+ }
+ s.clips.push(String(clipId));
+ return writeSpeakers(dir, list);
+}
+
+/**
+ * The scorer's inputs for the project: the planned clips, the keys to check,
+ * the voices with their pieces.
+ */
+export async function planSpeakerCheck(dir, manifest, { clipIds = [], channelsDir, speakers }) {
+ const clips = await planClips(dir, manifest, { channelsDir, pad: PHRASE_PAD_S });
+ const keyOf = new Map(clips.filter((c) => c.id).map((c) => [c.id, c.key]));
+ for (const id of clipIds) if (!keyOf.has(id)) throw new CliError(`no clip ${id} in the cut (or it has its own media)`);
+ const check = clipIds.length ? clipIds.map((id) => /** @type {string} */ (keyOf.get(id))) : clips.filter((c) => c.id).map((c) => c.key);
+ const voices = [];
+ const skipped = [];
+ for (const s of speakers) {
+ const clipKeys = s.clips.map((id) => keyOf.get(id)).filter(Boolean);
+ for (const id of s.clips) if (!keyOf.has(id)) skipped.push({ speaker: s.name, why: `clip ${id} is not in the cut` });
+ let items = [];
+ let recordings = [];
+ if (s.videos.length || s.channels.length) {
+ const r = await referenceRecordings({ channelsDir, channels: s.channels, videos: s.videos, n: REFERENCE_VIDEOS });
+ items = r.items.map((it) => ({ key: it.key, file: it.file, start: it.start, dur: it.dur }));
+ recordings = [...new Map(r.items.map((it) => [`${it.slug}/${it.video}`, { channel: it.slug, video: it.video, date: it.date ?? null, title: it.title ?? null }])).values()];
+ for (const x of r.skipped) skipped.push({ speaker: s.name, why: `${x.channel}/${x.video}: ${x.why}` });
+ }
+ voices.push({ name: s.name, clipKeys: /** @type {string[]} */ (clipKeys), items, recordings });
+ }
+ return { clips, check, voices, skipped };
+}
+
+export const SPEAKER_CHECK_USAGE = [
+ "usage: umtool speaker-check <project> [--clip <id> …] [--json] [--progress ndjson]",
+ " umtool speaker-check <project> --list | --set 'Name=<clip id>,<channel>/<id>,channel:<slug>,…' | --remove Name",
+ "",
+ "Which of the project's named voices each clip is: TitaNet-small (sherpa-onnx, local) on the clip's phrase",
+ `± ${PHRASE_PAD_S} s, voiced frames only, against each voice's robust centroid -> ${"<project>"}/speaker-check.json (merged:`,
+ "a check of one clip keeps the others'). The voices are <project>/speakers.json: per name, clips of the cut,",
+ "recordings of that voice alone (<channel>/<id>), or channels whose solo recordings it is. A clip that is in a",
+ "voice's set is scored against the rest of it. An aid to the ear: it rules on nothing.",
+ "The engine: VOICE_MATCH_PYTHON / VOICE_MATCH_MODEL, else settings.diarization.python / .embModel, else .diarize/.",
+].join("\n");
+
+const SETTINGS_FILE = () => process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json");
+
+/**
+ * `umtool speaker-check …`
+ * @param {string[]} args
+ * @param {{ reportsRoot?: string, log?: (s: string) => void, err?: (s: string) => void, engine?: Record<string, unknown> }} [opts]
+ */
+export async function speakerCheckCommand(args, { reportsRoot = REPORTS_ROOT, log = console.log, err = console.error, engine: engineOpts = {} } = {}) {
+ try {
+ const words = [];
+ /** @type {Record<string, string[]>} */
+ const flags = {};
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (["--clip", "--set", "--remove", "--progress"].includes(a)) {
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value`);
+ (flags[a] ??= []).push(args[++i]);
+ } else if (["--json", "--list", "--help"].includes(a)) (flags[a] ??= []).push("");
+ else if (a.startsWith("--")) throw new CliError(`unknown flag ${a}`);
+ else words.push(a);
+ }
+ if (flags["--help"] || !words.length) {
+ log(SPEAKER_CHECK_USAGE);
+ return flags["--help"] ? 0 : 2;
+ }
+ const r = await resolveProject(words[0], reportsRoot);
+ if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${words[0]}"`);
+ const project = r.project;
+ if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`);
+ const ndjson = flags["--progress"]?.at(-1) === "ndjson";
+ const say = (line) => (ndjson ? err(line) : log(line));
+ const emit = (ev) => {
+ if (ndjson) log(JSON.stringify({ ev: "speaker-check", ...ev }));
+ };
+
+ // The reference sets: edited, or listed.
+ if (flags["--set"] || flags["--remove"]) {
+ let list = await readSpeakers(project.dir);
+ for (const spec of flags["--set"] ?? []) {
+ const s = parseSpeakerSpec(spec);
+ list = [...list.filter((x) => x.name.toLowerCase() !== s.name.toLowerCase()), s];
+ }
+ for (const name of flags["--remove"] ?? []) list = list.filter((x) => x.name.toLowerCase() !== name.trim().toLowerCase());
+ await writeSpeakers(project.dir, list);
+ say(`${SPEAKERS_FILE}: ${list.length} voice(s)`);
+ }
+ const speakers = await readSpeakers(project.dir);
+ if (flags["--list"] || flags["--set"] || flags["--remove"]) {
+ if (flags["--json"]) log(JSON.stringify({ project: project.id, speakers }, null, 2));
+ else for (const s of speakers) log(`${s.name}: ${[...s.clips.map((c) => `clip ${c}`), ...s.videos, ...s.channels.map((c) => `channel ${c}`)].join(", ") || "(nothing yet)"}`);
+ return 0;
+ }
+ if (!speakers.length) {
+ throw new CliError(`no voices to compare with: name them in ${SPEAKERS_FILE} (umtool speaker-check ${project.id} --set 'Name=<clip id>,<channel>/<id>,…'), or the walk's "Add to a voice"`);
+ }
+
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+ if (!channelsDir) throw new CliError("no channels directory (CHANNELS_DIR) to read the windows from");
+ emit({ phase: "plan" });
+ const plan = await planSpeakerCheck(project.dir, manifest, { clipIds: flags["--clip"] ?? [], channelsDir, speakers });
+ for (const s of plan.skipped) say(`${s.speaker}: ${s.why}`);
+ say(`${plan.check.length} clip(s) to check against ${plan.voices.map((v) => `${v.name} (${v.clipKeys.length + v.items.length} piece(s))`).join(", ")}`);
+
+ let settings = null;
+ try {
+ settings = JSON.parse(await readFile(SETTINGS_FILE(), "utf8"));
+ } catch {
+ settings = null;
+ }
+ const engine = resolveEngine({ repoRoot: REPO_ROOT, settings, ...engineOpts });
+ const t0 = Date.now();
+ const doc = await runSpeakerCheck({
+ clips: plan.clips.map((c) => (c.file ? { key: c.key, id: c.id, file: c.file, start: c.start, dur: c.dur, fallback: c.fallback ?? null } : { key: c.key, id: c.id, file: null, start: 0, dur: 0, missing: c.missing })),
+ check: plan.check,
+ speakers: plan.voices,
+ engine,
+ // Beside the project, never /tmp (a RAM tmpfs here); removed at the end.
+ scratch: path.join(/* turbopackIgnore: true */ project.dir, ".speaker-check-work"),
+ thresholds: DEFAULT_THRESHOLDS,
+ onProgress: (e) => emit({ phase: e.event, ...(e.n ? { n: e.n, of: e.of } : {}), ...(e.items ? { items: e.items } : {}) }),
+ });
+ const { file, doc: merged } = await writeSpeakerCheck(project.dir, doc);
+ emit({ phase: "done", file, seconds: Math.round((Date.now() - t0) / 100) / 10 });
+ if (flags["--json"]) log(JSON.stringify(merged, null, 1));
+ else if (!ndjson) {
+ for (const key of plan.check) {
+ const row = /** @type {any} */ (doc.clips[key]);
+ if (!row) continue;
+ log(`${String(row.id ?? "-").padEnd(5)} ${speakerLine(row)}`);
+ }
+ log(`→ ${file}`);
+ } else say(`→ ${file}`);
+ return 0;
+ } catch (e) {
+ err(e instanceof CliError ? `umtool speaker-check: ${e.message}` : `umtool speaker-check: ${e instanceof Error ? e.stack ?? e.message : String(e)}`);
+ return e instanceof CliError ? 2 : 1;
+ }
+}
+
+/** "matches Ember 0.93 / Kirsche 0.83", "unsure: Ember 0.51 / Kirsche 0.49", or why it was not scored. */
+export function speakerLine(row) {
+ if (!row || !Array.isArray(row.scores) || !row.scores.length) return row?.why ? `not scored — ${row.why}` : "not scored";
+ const list = row.scores.map((s) => `${s.name} ${Number(s.score).toFixed(2)}`).join(" / ");
+ if (row.label === "matches") return `matches ${list}`;
+ if (row.label === "none") return `matches none of them: ${list}`;
+ return `unsure: ${list}`;
+}
+
+/** The CLI path the app's job runs. */
+const umtoolCli = () => path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs");
+
+/** The checkout's heavy-slot CLI (takeRender.mjs's rule), when this umtool sits in the checkout. */
+function queueLockScript() {
+ const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs");
+ return existsSync(/* turbopackIgnore: true */ file) ? file : null;
+}
+
+/** What a check declares to the heavy slot: TitaNet-small and ffmpeg on a few seconds a clip. */
+export const SPEAKER_CHECK_ESTIMATE_MB = 800;
+
+/**
+ * The walk's "Check speaker": ONE job step on lib/jobs.ts running this
+ * command through the machine's heavy slot (queue-lock --heavy, with its
+ * estimate: admitted beside other jobs by memory, and waiting at the door
+ * while render mode gives a render the machine), nice'd.
+ * @param {{ id: string }} project
+ * @param {{ clip?: string | null, queueLock?: string | null }} [req]
+ */
+export function speakerCheckSteps(project, { clip = null, queueLock = queueLockScript() } = {}) {
+ const cmd = ["nice", "-n", "10", process.execPath, umtoolCli(), "speaker-check", project.id, ...(clip ? ["--clip", clip] : []), "--progress", "ndjson"];
+ return {
+ kind: `speaker-check ${project.id}`,
+ steps: [{
+ label: clip ? `check ${clip}'s speaker` : "check each clip's speaker",
+ argv: queueLock ? [process.execPath, queueLock, "--heavy", "--estimate", String(SPEAKER_CHECK_ESTIMATE_MB), "--", ...cmd] : cmd,
+ cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."),
+ env: {},
+ ndjson: /** @type {const} */ (true),
+ timeoutMs: 20 * 60 * 1000,
+ }],
+ };
+}
+
+/** The walk's badge for one clip: its row in speaker-check.json, and the voices it was measured against. */
+export async function speakerBadge(dir, manifest, clipId) {
+ const [doc, speakers] = await Promise.all([readSpeakerCheck(dir), readSpeakers(dir).catch(() => [])]);
+ let row = null;
+ if (doc) {
+ row = Object.values(doc.clips).find((r) => /** @type {any} */ (r)?.id === clipId) ?? null;
+ }
+ return {
+ speakers: speakers.map((s) => ({ name: s.name, clips: s.clips, videos: s.videos, channels: s.channels, inReference: s.clips.includes(clipId) })),
+ result: row ? { ...row, line: speakerLine(row), madeAt: doc?.madeAt ?? null } : null,
+ reference: doc ? doc.speakers : null,
+ };
+}
diff --git a/umtool/lib/report/takeCancel.mjs b/umtool/lib/report/takeCancel.mjs
@@ -0,0 +1,245 @@
+// CANCEL A TAKE WHILE IT RENDERS (UI notes 2026-10-30, item 19: "a cancel
+// button while it renders").
+//
+// The render belongs to whichever process holds the take's build lock
+// (`takes/<id>/.building.json`, takePrune.mjs): the app's take job (a `umtool
+// take` the job runner spawned), or a `umtool take` an agent started in a
+// terminal. Nothing outside that process can stop its render CLEANLY -- a
+// signal from here would leave its scratch behind, or reach a process group it
+// does not own -- so a cancel is a REQUEST the take maker answers:
+//
+// requestCancel writes `takes/<id>/.cancel.json` {at, by, pid} beside a
+// LIVE build lock on this machine (a take that is not
+// rendering, or renders on another host, is refused in words)
+// watchCancel the take maker polls for it while it holds the lock; seen,
+// it stops its render (takeRender.mjs: the render's whole
+// process group, TERM then KILL), removes the half-made
+// render manifest, and
+// markCancelled writes `takes/<id>/cancelled.json` {at, by, label, rebuild}
+// -- what the list shows: a first render cancelled is a work
+// dir with this and no take.json (folded away, deletable), a
+// rebuild cancelled keeps its last take whole and says so
+//
+// The take maker then rejects with TakeCancelled; its build lock goes in its
+// own `finally`, and so does render mode when this take held it
+// (renderMode.mjs withRenderHold's `finally`). `releaseTakeHold` is the
+// belt-and-braces for a process that went without letting go.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { readdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { BUILD_LOCK, lockIsLive, readBuildLock } from "./takePrune.mjs";
+import { isTakeId, takesDirOf, TAKE_FILE } from "./takes.mjs";
+
+export const CANCEL_FILE = ".cancel.json";
+export const CANCELLED_FILE = "cancelled.json";
+/** How often the take maker looks for a cancel request (ms). */
+export const CANCEL_POLL_MS = 400;
+
+export class TakeCancelled extends Error {
+ /** @param {string} take @param {string} [by] */
+ constructor(take, by = "") {
+ super(`take ${take} was cancelled${by ? ` (${by})` : ""} — its render stopped; nothing was written over a finished take`);
+ this.take = take;
+ this.cancelled = true;
+ }
+}
+
+const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null);
+async function writeJson(file, doc) {
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
+ await rename(tmp, file);
+}
+
+/**
+ * Ask the render of take `takeId` to stop. Refused unless its build lock is
+ * live and on this machine.
+ *
+ * @param {string} projectDir
+ * @param {string} takeId
+ * @param {{ by?: string, now?: () => Date, host?: string, alive?: (pid: number) => boolean }} [opts]
+ * @returns {Promise<{ lock: Record<string, any>, file: string }>}
+ */
+export async function requestCancel(projectDir, takeId, { by = "the Takes page", now = () => new Date(), host = os.hostname(), alive } = {}) {
+ if (!isTakeId(takeId)) throw new Error("not a take id");
+ const dir = path.join(takesDirOf(projectDir), takeId);
+ const lock = await readBuildLock(path.join(dir, BUILD_LOCK));
+ if (!lock || !lockIsLive(lock, { host, ...(alive ? { alive } : {}) })) throw new Error(`take ${takeId} is not rendering — nothing to cancel`);
+ if (lock.host && lock.host !== host) throw new Error(`take ${takeId} is rendering on ${lock.host}: cancel it there`);
+ const file = path.join(dir, CANCEL_FILE);
+ await writeJson(file, { at: now().toISOString(), by, pid: lock.pid ?? null });
+ return { lock, file };
+}
+
+/**
+ * Poll for a cancel request in `takeDir`; call `onCancel(request)` once when one
+ * appears. A request older than the watch (left by a crashed run) is cleared
+ * first. Returns stop().
+ *
+ * @param {string} takeDir
+ * @param {(req: Record<string, any>) => void} onCancel
+ * @param {{ intervalMs?: number }} [opts]
+ */
+export function watchCancel(takeDir, onCancel, { intervalMs = CANCEL_POLL_MS } = {}) {
+ const file = path.join(takeDir, CANCEL_FILE);
+ let done = false;
+ let busy = false;
+ const ready = unlink(file).catch(() => {});
+ const timer = setInterval(() => {
+ if (done || busy) return;
+ busy = true;
+ void ready
+ .then(() => readJson(file))
+ .then((req) => {
+ if (req && !done) {
+ done = true;
+ clearInterval(timer);
+ onCancel(req);
+ }
+ })
+ .finally(() => {
+ busy = false;
+ });
+ }, intervalMs);
+ timer.unref?.();
+ return () => {
+ done = true;
+ clearInterval(timer);
+ };
+}
+
+/**
+ * Record that take `takeId`'s render was cancelled (and clear the request).
+ *
+ * @param {string} projectDir
+ * @param {string} takeId
+ * @param {{ by?: string, label?: string | null, rebuild?: boolean, at?: string, now?: () => Date }} info
+ */
+export async function markCancelled(projectDir, takeId, { by = "", label = null, rebuild = false, at, now = () => new Date() } = {}) {
+ const dir = path.join(takesDirOf(projectDir), takeId);
+ const doc = { at: at ?? now().toISOString(), by, label, rebuild };
+ await writeJson(path.join(dir, CANCELLED_FILE), doc);
+ await unlink(path.join(dir, CANCEL_FILE)).catch(() => {});
+ return doc;
+}
+
+/** A take's cancelled.json, or null. */
+export async function readCancelled(projectDir, takeId) {
+ if (!isTakeId(takeId)) return null;
+ const doc = await readJson(path.join(takesDirOf(projectDir), takeId, CANCELLED_FILE));
+ return doc && typeof doc === "object" && typeof doc.at === "string" ? doc : null;
+}
+
+/**
+ * The take directories that are not (or not yet) takes: a first render in
+ * progress (a live build lock, no take.json) and a first render cancelled
+ * (cancelled.json, no take.json). What the Takes page lists beside the takes:
+ * the first with Cancel, the second folded away with Delete.
+ *
+ * @param {string} projectDir
+ * @param {{ host?: string, alive?: (pid: number) => boolean }} [opts]
+ * @returns {Promise<{ rendering: Array<{ id: string, label: string | null, pid: number | null, startedAt: string | null, from: string | null }>, cancelled: Array<{ id: string, label: string | null, at: string, by: string }> }>}
+ */
+export async function takeWorkDirs(projectDir, opts = {}) {
+ const root = takesDirOf(projectDir);
+ const names = await readdir(root).catch(() => []);
+ const rendering = [];
+ const cancelled = [];
+ for (const id of names.sort()) {
+ if (!isTakeId(id)) continue;
+ const dir = path.join(root, id);
+ const hasTake = await readFile(path.join(dir, TAKE_FILE), "utf8").then(() => true, () => false);
+ if (hasTake) continue;
+ const lock = await readBuildLock(path.join(dir, BUILD_LOCK));
+ if (lock && lockIsLive(lock, opts.host || opts.alive ? { ...(opts.host ? { host: opts.host } : {}), ...(opts.alive ? { alive: opts.alive } : {}) } : undefined)) {
+ rendering.push({ id, label: typeof lock.label === "string" ? lock.label : null, pid: Number(lock.pid) || null, startedAt: lock.startedAt ?? null, from: lock.from ?? null });
+ continue;
+ }
+ const c = await readCancelled(projectDir, id);
+ if (c) cancelled.push({ id, label: c.label ?? null, at: c.at, by: c.by ?? "" });
+ }
+ return { rendering, cancelled };
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/**
+ * Release render mode when take `takeId` of `projectId` holds it and its
+ * holder is gone (the take maker's own `finally` normally does this; a process
+ * killed outright cannot). Returns the lanes released, or null when the take
+ * held nothing.
+ *
+ * @param {string} projectId
+ * @param {string} takeId
+ * @param {{ file?: string, lanes?: any, isAlive?: (pid: number) => boolean }} [opts]
+ */
+export async function releaseTakeHold(projectId, takeId, opts = {}) {
+ const { editorLanes, renderModeFile } = await import("./renderMode.mjs");
+ const { editorConfig } = await import("./fetchWindows.mjs");
+ const { readRenderPriorityState, renderModeOff } = await import("yt-dlp-transcript-common/lib/renderPriority.mjs");
+ const file = opts.file ?? renderModeFile();
+ const st = readRenderPriorityState(file);
+ const h = st?.holder;
+ if (!st || st.ended || !h || h.take !== takeId || (h.project && h.project !== projectId)) return null;
+ const alive = opts.isAlive ?? ((pid) => {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+ });
+ if (Number(h.pid) > 0 && alive(Number(h.pid))) return null;
+ const off = await renderModeOff({ file, token: st.token, lanes: opts.lanes !== undefined ? opts.lanes : editorLanes(editorConfig(process.env)) });
+ return { released: off.released ?? [], failed: off.failed ?? [] };
+}
+
+/**
+ * Cancel take `takeId`'s render and wait for it to stop: the request
+ * (requestCancel), the take maker answering it within `waitMs`, then -- when
+ * it has not, and `fallback` can stop the process that holds the lock (the
+ * app's job runner, for a take it spawned) -- that. Render mode is let go if
+ * this take held it and did not let go itself.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} takeId
+ * @param {{ by?: string, waitMs?: number, pollMs?: number, fallback?: (lock: Record<string, any>) => boolean, isAlive?: (pid: number) => boolean, renderModeFile?: string, lanes?: any }} [opts]
+ * @returns {Promise<{ stopped: boolean, how: "the take maker" | "the job runner" | null, cancelled: Record<string, any> | null, renderMode: { released: string[], failed: unknown[] } | null, said: string }>}
+ */
+export async function cancelTake(project, takeId, { by = "the Takes page", waitMs = 15_000, pollMs = 250, fallback, isAlive, renderModeFile: rmFile, lanes } = {}) {
+ const { lock } = await requestCancel(project.dir, takeId, { by, ...(isAlive ? { alive: isAlive } : {}) });
+ const lockFile = path.join(takesDirOf(project.dir), takeId, BUILD_LOCK);
+ const gone = async () => {
+ const l = await readBuildLock(lockFile);
+ return !l || Number(l.pid) !== Number(lock.pid) || !lockIsLive(l, isAlive ? { alive: isAlive } : undefined);
+ };
+ let how = null;
+ const until = Date.now() + waitMs;
+ while (Date.now() < until) {
+ if (await gone()) {
+ how = "the take maker";
+ break;
+ }
+ await sleep(pollMs);
+ }
+ if (!how && fallback && fallback(lock)) {
+ const late = Date.now() + 10_000;
+ while (Date.now() < late) {
+ if (await gone()) {
+ how = "the job runner";
+ break;
+ }
+ await sleep(pollMs);
+ }
+ }
+ const renderMode = await releaseTakeHold(project.id, takeId, { ...(rmFile ? { file: rmFile } : {}), ...(lanes !== undefined ? { lanes } : {}), ...(isAlive ? { isAlive } : {}) }).catch(() => null);
+ // A take stopped by the job runner never wrote its own mark: this one does.
+ let cancelled = await readCancelled(project.dir, takeId);
+ if (how === "the job runner" && !cancelled) cancelled = await markCancelled(project.dir, takeId, { by, label: lock.label ?? null }).catch(() => null);
+ const said = how
+ ? `take ${takeId}: its render stopped (${how})${renderMode?.released?.length ? ` — render mode off, lanes released: ${renderMode.released.join(", ")}` : renderMode ? " — render mode off" : ""}`
+ : `take ${takeId}: asked to stop (pid ${lock.pid}); it has not yet — it stops at its next check, or cancel it where it runs`;
+ return { stopped: !!how, how, cancelled, renderMode, said };
+}
diff --git a/umtool/lib/report/takeCli.mjs b/umtool/lib/report/takeCli.mjs
@@ -92,6 +92,14 @@ export const TAKES_USAGE = [
" umtool takes supersede <project> <take> [--by <take>] | --clear folded away in the takes list (verdicts.json)",
" umtool takes delete <project> <take> [--dry-run] [--force] takes/<take>/ whole (refused while it renders or a",
" render is made from it; --force only past the take the project's manifest is)",
+ " umtool takes cancel <project> <take> [--json] stop the take's render (it renders now: its build lock is live",
+ " here): asked of the process rendering it, which stops its render, marks the take cancelled",
+ " (takes/<take>/cancelled.json) and lets render mode go if the take held it",
+ " umtool takes fork <project> <take> [--name N] [--json] the take as a VARIANT: a project beside this one",
+ " (default name v-<take>) with the take's manifest, variant.json naming where it came from, the",
+ " parent's fetched media linked, and the take itself (its preview hard-linked)",
+ " umtool takes compare <project> <a> <b> [--json] two takes side by side: <take> of this project or",
+ " <project>:<take> (a variant's): the facts, the cut's changes A → B, the look's differences",
].join("\n");
class CliError extends Error {}
@@ -100,7 +108,7 @@ class CliError extends Error {}
function parse(args) {
const valued = new Set([
"--id", "--label", "--group", "--kind", "--summary", "--style", "--patch", "--patch-json", "--set", "--effect",
- "--at", "--dur", "--recipe", "--only", "--progress", "--from", "--by",
+ "--at", "--dur", "--recipe", "--only", "--progress", "--from", "--by", "--name",
]);
/** @type {Record<string, string[]>} */
const flags = {};
@@ -395,6 +403,56 @@ export async function takesCommand(args, { reportsRoot = REPORTS_ROOT, log = con
else log(p.has("--clear") ? `${take}: not superseded` : `${take}: superseded${r.entry?.superseded?.by ? ` by ${r.entry.superseded.by}` : ""} (folded away in the takes list; nothing deleted)`);
return 0;
}
+ if (sub === "cancel") {
+ const project = await pickProject(rest[0], reportsRoot);
+ const take = rest[1];
+ if (!take) throw new CliError("umtool takes cancel <project> <take>");
+ const { cancelTake } = await import("./takeCancel.mjs");
+ const r = await cancelTake(project, take, { by: "umtool takes cancel" });
+ if (p.has("--json")) log(JSON.stringify({ ok: r.stopped, ...r }, null, 2));
+ else log(r.said);
+ return r.stopped ? 0 : 1;
+ }
+ if (sub === "fork") {
+ const project = await pickProject(rest[0], reportsRoot);
+ const take = rest[1];
+ if (!take) throw new CliError("umtool takes fork <project> <take> [--name N]");
+ const { ForkRefused, forkTakeAsVariant } = await import("./variantFork.mjs");
+ try {
+ const r = await forkTakeAsVariant(project, take, { name: p.one("--name") ?? null });
+ if (p.has("--json")) log(JSON.stringify({ ok: true, ...r }, null, 2));
+ else {
+ log(`${r.id}: a variant of ${project.id}, forked from its take ${take}`);
+ if (r.links.length) log(` linked from ${project.id}: ${r.links.join(", ")}`);
+ if (r.copied.length) log(` copied: ${r.copied.join(", ")}`);
+ log(r.take ? (r.take.linked ? ` its take ${take} is there too (the preview hard-linked)` : ` its take ${take}: the preview could not be hard-linked (another filesystem) — render it there`) : ` no rendered take to bring: render one there`);
+ log(` walk it: /projects/${r.id}/takes · compare: umtool takes compare ${project.id} ${take} ${r.id}:${take}`);
+ }
+ return 0;
+ } catch (e) {
+ if (e instanceof ForkRefused) {
+ err(e.message);
+ return 1;
+ }
+ throw e;
+ }
+ }
+ if (sub === "compare") {
+ const project = await pickProject(rest[0], reportsRoot);
+ if (!rest[1] || !rest[2]) throw new CliError("umtool takes compare <project> <a> <b> (<take> or <project>:<take>)");
+ const { compareLines, compareTakes, parseTakeRef } = await import("./takeCompare.mjs");
+ const refs = [rest[1], rest[2]].map((x) => parseTakeRef(x, project.id));
+ if (refs.some((x) => !x)) throw new CliError("a take is <take> or <project>:<take>");
+ const sides = [];
+ for (const ref of /** @type {Array<{ project: string, take: string }>} */ (refs)) {
+ const pr = ref.project === project.id ? project : await pickProject(ref.project, reportsRoot);
+ sides.push({ ref: { project: pr.id, take: ref.take }, dir: pr.dir });
+ }
+ const c = await compareTakes(sides[0], sides[1]);
+ if (p.has("--json")) log(JSON.stringify(c, null, 2));
+ else for (const l of compareLines(c)) log(l);
+ return 0;
+ }
if (sub === "delete") {
const project = await pickProject(rest[0], reportsRoot);
const take = rest[1];
diff --git a/umtool/lib/report/takeCompare.mjs b/umtool/lib/report/takeCompare.mjs
@@ -0,0 +1,149 @@
+// TWO TAKES SIDE BY SIDE -- of one project, or of a project and its variants
+// (UI notes 2026-10-30, item 19; variantFork.mjs): what each is, and what
+// differs between them.
+//
+// a take ref `<take>` (of the project asked about) or `<project>:<take>`
+// -- a take id has no colon, and neither has a project id
+// the facts label, project, length, built, window, style, quick
+// the cut lib/report/manifest-diff.mjs over the two manifests (entries
+// added, removed, moved, their windows and fields), one line each
+// the look every leaf of the manifests outside the timeline (render.*,
+// title, subtitle …) that differs, a before and an after
+//
+// The manifests are the ones each take was rendered from (takes/<id>/
+// video.manifest.json), a draft's resolved from its patch (takeManifest.mjs).
+// Reads only.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { diffManifests, formatChange } from "./manifest-diff.mjs";
+import { MANIFEST } from "./takeMaker.mjs";
+import { isTakeId, listTakes, takesDirOf } from "./takes.mjs";
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+/** How many look differences are listed at most. */
+export const LOOK_LIMIT = 200;
+
+/**
+ * `<take>` or `<project>:<take>` as `{ project, take }` (project defaulting to `defaultProject`); null when malformed.
+ * @param {unknown} s
+ * @param {string} defaultProject
+ */
+export function parseTakeRef(s, defaultProject) {
+ const v = String(s ?? "").trim();
+ if (!v) return null;
+ const i = v.lastIndexOf(":");
+ const project = i >= 0 ? v.slice(0, i) : defaultProject;
+ const take = i >= 0 ? v.slice(i + 1) : v;
+ if (!project || !isTakeId(take)) return null;
+ return { project, take };
+}
+
+/** A ref back to its string: `<project>:<take>`. */
+export const takeRefOf = (r) => `${r.project}:${r.take}`;
+
+/**
+ * Every leaf of `obj` as `[dotted path, value]`; arrays are leaves (their JSON).
+ * @param {unknown} obj
+ * @param {string} [prefix]
+ * @returns {Array<[string, unknown]>}
+ */
+export function leaves(obj, prefix = "") {
+ if (!isObj(obj)) return prefix ? [[prefix, obj]] : [];
+ const keys = Object.keys(obj);
+ if (!keys.length) return prefix ? [[prefix, {}]] : [];
+ return keys.flatMap((k) => leaves(/** @type {any} */ (obj)[k], prefix ? `${prefix}.${k}` : k));
+}
+
+/** A value for a difference line: short. */
+export function shortValue(v) {
+ if (v === undefined) return "—";
+ const s = typeof v === "string" ? v : JSON.stringify(v);
+ return s.length > 80 ? `${s.slice(0, 79)}…` : s;
+}
+
+/**
+ * What differs between two manifests outside the timeline: `[{ path, a, b }]`, sorted by path.
+ * @param {Record<string, any>} a
+ * @param {Record<string, any>} b
+ */
+export function lookDiff(a, b) {
+ const skip = (p) => p === "timeline" || p.startsWith("timeline.") || p === "generatedOn" || p === "timelineNodes" || p.startsWith("timelineNodes.");
+ const la = new Map(leaves(a).filter(([p]) => !skip(p)));
+ const lb = new Map(leaves(b).filter(([p]) => !skip(p)));
+ const out = [];
+ for (const p of [...new Set([...la.keys(), ...lb.keys()])].sort()) {
+ const x = la.get(p);
+ const y = lb.get(p);
+ if (JSON.stringify(x) !== JSON.stringify(y)) out.push({ path: p, a: x, b: y });
+ }
+ return out;
+}
+
+/** A take's manifest: the one it was rendered from, else resolved from its patch. */
+async function manifestOf(dir, take) {
+ try {
+ const m = JSON.parse(await readFile(path.join(takesDirOf(dir), take, MANIFEST), "utf8"));
+ if (isObj(m)) return m;
+ } catch {
+ /* a draft, or a take made by hand */
+ }
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ return (await resolveTakeManifest(dir, take)).manifest;
+}
+
+/**
+ * Two takes, compared.
+ *
+ * @param {{ ref: { project: string, take: string }, dir: string }} a
+ * @param {{ ref: { project: string, take: string }, dir: string }} b
+ */
+export async function compareTakes(a, b) {
+ const side = async (s) => {
+ const t = (await listTakes(s.dir)).takes.find((x) => x.id === s.ref.take);
+ if (!t) throw new Error(`${s.ref.project} has no take ${s.ref.take}`);
+ const manifest = await manifestOf(s.dir, s.ref.take);
+ return {
+ ref: takeRefOf(s.ref),
+ project: s.ref.project,
+ take: t.id,
+ label: t.label,
+ seconds: t.seconds,
+ builtAt: t.builtAt,
+ window: t.window,
+ style: t.style,
+ quick: t.quick === true,
+ draft: t.draft === true,
+ hasPreview: !t.draft,
+ clips: (manifest.timeline ?? []).filter((e) => isObj(e) && e.type === "clip").length,
+ entries: (manifest.timeline ?? []).length,
+ manifest,
+ };
+ };
+ const [x, y] = await Promise.all([side(a), side(b)]);
+ const cut = diffManifests(x.manifest, y.manifest);
+ const look = lookDiff(x.manifest, y.manifest);
+ const strip = ({ manifest: _m, ...rest }) => rest;
+ return {
+ a: strip(x),
+ b: strip(y),
+ cut: { changes: cut.changes, lines: cut.changes.map(formatChange), counts: cut.counts },
+ look: look.slice(0, LOOK_LIMIT),
+ lookMore: Math.max(0, look.length - LOOK_LIMIT),
+ seconds: typeof x.seconds === "number" && typeof y.seconds === "number" ? Number((y.seconds - x.seconds).toFixed(2)) : null,
+ same: cut.same && look.length === 0,
+ };
+}
+
+/** The comparison as lines (`umtool takes compare`). */
+export function compareLines(c) {
+ const lines = [];
+ const fact = (s) => `${s.ref} "${s.label}" ${typeof s.seconds === "number" ? `${s.seconds.toFixed(1)} s` : "not rendered"} ${s.clips} clips${s.style ? ` style ${s.style}` : ""}${s.window && s.window !== "full" ? ` window ${s.window.at}+${s.window.dur}` : ""}`;
+ lines.push(`A ${fact(c.a)}`, `B ${fact(c.b)}`);
+ if (c.seconds !== null) lines.push(`length: ${c.seconds > 0 ? "+" : ""}${c.seconds} s (B against A)`);
+ if (c.same) lines.push("the same cut and the same look");
+ if (c.cut.lines.length) lines.push(`the cut — ${c.cut.lines.length} change(s), A → B:`, ...c.cut.lines.map((l) => ` ${l}`));
+ if (c.look.length) lines.push(`the look — ${c.look.length}${c.lookMore ? `+${c.lookMore}` : ""} difference(s):`, ...c.look.map((d) => ` ${d.path}: ${shortValue(d.a)} → ${shortValue(d.b)}`));
+ return lines;
+}
diff --git a/umtool/lib/report/takeEta.mjs b/umtool/lib/report/takeEta.mjs
@@ -0,0 +1,160 @@
+// HOW LONG WILL THIS TAKE RENDER? (UI notes 2026-10-30, #18) -- from the
+// project's own past renders, never a constant. On the Ember cut every ETA was
+// worked out by hand.
+//
+// A past render is a take (takes/<id>/take.json) whose render time is known:
+//
+// - `renderSeconds`, which the take maker records (takeMaker.mjs: from the
+// build's first event to its end, so a wait at the heavy slot's door is
+// not counted);
+// - else the take's own files: from its video.manifest.json (written just
+// before the render starts and renamed into place unchanged) to its
+// take.json `builtAt`, less any wait at the slot its log says it had (a
+// `<take>.log` beside the project or in the take, the heavy gate's
+// `admitted after …` / `the render let go after …` lines).
+//
+// The ETA is the median seconds of render per second of video, over the past
+// renders of the same kind -- made `from` another take (its segments, frames
+// and chunks reused) or fresh, the whole cut or a window -- times the take's
+// length; with none of its kind it says it used the others. Plain ESM: the CLI
+// and the route read it under bare node.
+import { readdir, readFile, stat } from "node:fs/promises";
+import path from "node:path";
+
+const TAKE_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+
+/** `35s`, `2m10s`, `1h02m` (queue-lock's humanDuration) -> seconds, else null. */
+export function parseDuration(s) {
+ const m = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(String(s ?? "").trim());
+ if (!m || (!m[1] && !m[2] && !m[3])) return null;
+ return Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0);
+}
+
+/** The seconds a render's log says it waited at the heavy slot (its door, its line, memory). */
+export function slotWaitOf(text) {
+ let s = 0;
+ for (const m of String(text ?? "").matchAll(/(?:heavy: .* after |queue-lock: the render let go after )(\d+h)?(\d+m)?(\d+s)?(?: — admitted| — going on)/g)) {
+ s += parseDuration(`${m[1] ?? ""}${m[2] ?? ""}${m[3] ?? ""}`) ?? 0;
+ }
+ return s;
+}
+
+/**
+ * Every past render of the project with its render time and length.
+ * @param {string} projectDir
+ * @returns {Promise<Array<{ id: string, seconds: number, renderSeconds: number, how: "recorded" | "files", window: "full" | "window", from: string | null, quick: boolean, builtAt: string | null }>>}
+ */
+export async function pastRenders(projectDir) {
+ const takesDir = path.join(projectDir, "takes");
+ const names = await readdir(takesDir).catch(() => []);
+ const out = [];
+ for (const id of names) {
+ if (!TAKE_ID.test(id)) continue;
+ const dir = path.join(takesDir, id);
+ let t;
+ try {
+ t = JSON.parse(await readFile(path.join(dir, "take.json"), "utf8"));
+ } catch {
+ continue;
+ }
+ if (t?.draft === true || !num(t?.seconds) || t.seconds <= 0) continue;
+ let renderSeconds = num(t.renderSeconds) && t.renderSeconds > 0 ? t.renderSeconds : null;
+ let how = /** @type {"recorded" | "files"} */ ("recorded");
+ if (renderSeconds === null && typeof t.builtAt === "string") {
+ const st = await stat(path.join(dir, "video.manifest.json")).catch(() => null);
+ const end = Date.parse(t.builtAt);
+ if (st && Number.isFinite(end)) {
+ let wait = 0;
+ for (const log of [path.join(projectDir, `${id}.log`), path.join(dir, `${id}.log`), path.join(dir, "take.log")]) {
+ const text = await readFile(log, "utf8").catch(() => null);
+ if (text) {
+ wait = slotWaitOf(text);
+ break;
+ }
+ }
+ const s = (end - st.mtimeMs) / 1000 - wait;
+ // A manifest older than a day before its build is a take rebuilt in
+ // place long after: its files say nothing about the render.
+ if (s > 0 && s < 86_400) {
+ renderSeconds = Math.round(s * 10) / 10;
+ how = "files";
+ }
+ }
+ }
+ if (renderSeconds === null) continue;
+ out.push({
+ id,
+ seconds: t.seconds,
+ renderSeconds,
+ how,
+ window: t.window && t.window !== "full" ? "window" : "full",
+ from: typeof t.from === "string" && t.from ? t.from : null,
+ quick: t.quick === true,
+ builtAt: typeof t.builtAt === "string" ? t.builtAt : null,
+ });
+ }
+ return out.sort((a, b) => String(a.builtAt).localeCompare(String(b.builtAt)));
+}
+
+const median = (xs) => {
+ const s = [...xs].sort((a, b) => a - b);
+ const n = s.length;
+ return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
+};
+
+/**
+ * The ETA of a take of `seconds` of video. Pure over `past`.
+ * @param {Awaited<ReturnType<typeof pastRenders>>} past
+ * @param {{ seconds: number, from?: boolean, window?: "full" | "window", quick?: boolean, last?: number }} want
+ * `from`: made from another take (reuse); `last`: at most this many of the newest renders count (default 6)
+ * @returns {null | { etaSeconds: number, rate: number, basis: Array<{ id: string, seconds: number, renderSeconds: number, how: string }>, kind: string, note: string | null }}
+ */
+export function takeEta(past, { seconds, from = false, window = "full", quick = false, last = 6 }) {
+ if (!num(seconds) || seconds <= 0 || !past.length) return null;
+ const kindOf = (p) => `${p.from ? "reuse" : "fresh"}/${p.window}${p.quick ? "/quick" : ""}`;
+ const want = `${from ? "reuse" : "fresh"}/${window}${quick ? "/quick" : ""}`;
+ let pool = past.filter((p) => kindOf(p) === want);
+ let note = null;
+ if (!pool.length) {
+ pool = past.filter((p) => p.window === window);
+ if (!pool.length) pool = past;
+ note = `no past ${from ? "take made from another" : "fresh take"}${window === "window" ? " of a window" : " of the whole cut"} — from the project's other renders`;
+ }
+ pool = pool.slice(-last);
+ const rate = median(pool.map((p) => p.renderSeconds / p.seconds));
+ return {
+ etaSeconds: Math.round(rate * seconds),
+ rate: Math.round(rate * 100) / 100,
+ basis: pool.map((p) => ({ id: p.id, seconds: p.seconds, renderSeconds: p.renderSeconds, how: p.how })),
+ kind: want,
+ note,
+ };
+}
+
+/** `1 h 05 min` / `23 min` / `40 s`. */
+export function etaText(s) {
+ if (!num(s)) return "—";
+ if (s < 90) return `${Math.round(s)} s`;
+ const m = Math.round(s / 60);
+ return m >= 60 ? `${Math.floor(m / 60)} h ${String(m % 60).padStart(2, "0")} min` : `${m} min`;
+}
+
+/**
+ * The project's ETAs for the take panel: a whole-cut take fresh and made from
+ * the newest take, at the length of the newest whole-cut take.
+ * @param {string} projectDir
+ */
+export async function projectEtas(projectDir) {
+ const past = await pastRenders(projectDir);
+ const fulls = past.filter((p) => p.window === "full");
+ const newest = fulls.at(-1) ?? null;
+ const seconds = newest?.seconds ?? null;
+ return {
+ past,
+ seconds,
+ newest: newest?.id ?? null,
+ fresh: seconds ? takeEta(past, { seconds, from: false }) : null,
+ reuse: seconds ? takeEta(past, { seconds, from: true }) : null,
+ };
+}
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -409,7 +409,9 @@ export function normalizeWindow(w) {
* manifestPath: string, outDir: string, slug: string, full: boolean, xfade: boolean,
* keepFrames?: boolean, estimateMb?: number | null,
* emit: (ev: Record<string, unknown>) => void, log: (line: string) => void,
+ * signal?: AbortSignal,
* }} RenderJob
+ * `signal`: a cancel (takeCancel.mjs) -- the render stops its process group and rejects.
* @typedef {(job: RenderJob) => Promise<{ file: string }>} RenderFn
*/
@@ -478,7 +480,7 @@ export async function linkSharedOut(projectDir, takeOut) {
* @param {{ force?: boolean, render?: RenderFn, probe?: (file: string) => Promise<number | null>,
* styles?: Record<string, { label: string, summary: string, patch: Record<string, unknown> }>,
* emit?: (ev: Record<string, unknown>) => void, log?: (line: string) => void,
- * ensureOut?: (dir: string) => Promise<unknown>, now?: () => Date,
+ * ensureOut?: (dir: string) => Promise<unknown>, now?: () => Date, clock?: () => number,
* from?: string | null, keepFrames?: boolean }} [opts]
* `from`: another take whose built segments, chrome renders and crossfade
* batches are hard-linked in before the render (takeFrom.mjs), so the build
@@ -496,16 +498,44 @@ export async function linkSharedOut(projectDir, takeOut) {
*/
export async function makeTake(projectDir, rawSpec, opts = {}) {
const prune = await import("./takePrune.mjs");
+ const cancel = await import("./takeCancel.mjs");
let lockFile = null;
+ // CANCEL (takeCancel.mjs): while the take holds its build lock it answers a
+ // cancel request -- its render stopped, the take marked cancelled.
+ const abort = new AbortController();
+ /** @type {Record<string, any> | null} */
+ let asked = null;
+ let stopWatch = null;
+ let rebuild = false;
+ const label = typeof rawSpec?.label === "string" ? rawSpec.label : null;
const onTakeDir = async (takeDir, id) => {
- lockFile = await prune.writeBuildLock(takeDir, { take: id, from: opts.from ?? null }).catch(() => null);
+ lockFile = await prune.writeBuildLock(takeDir, { take: id, from: opts.from ?? null, ...(label ? { label } : {}) }).catch(() => null);
+ rebuild = await stat(path.join(takeDir, TAKE_FILE)).then(() => true, () => false);
+ stopWatch = cancel.watchCancel(takeDir, (req) => {
+ asked = req;
+ (opts.log ?? (() => {}))(`${id}: cancel asked${req?.by ? ` by ${req.by}` : ""} — stopping the render`);
+ abort.abort();
+ });
};
let r;
try {
- r = await makeTakeLocked(projectDir, rawSpec, { ...opts, onTakeDir });
+ r = await makeTakeLocked(projectDir, rawSpec, { ...opts, onTakeDir, signal: abort.signal });
+ } catch (e) {
+ if (abort.signal.aborted && typeof rawSpec?.id === "string") {
+ const by = String(asked?.by ?? "");
+ await cancel.markCancelled(projectDir, rawSpec.id, { by, label, rebuild }).catch(() => {});
+ throw new cancel.TakeCancelled(rawSpec.id, by);
+ }
+ throw e;
} finally {
+ stopWatch?.();
if (lockFile) await prune.removeBuildLock(lockFile);
}
+ // Made: a cancel asked too late to stop it is moot, and an earlier cancelled run's mark is history.
+ if (!r.skipped) {
+ const dir = path.join(takesDirOf(projectDir), r.id);
+ await Promise.all([unlink(path.join(dir, cancel.CANCEL_FILE)).catch(() => {}), unlink(path.join(dir, cancel.CANCELLED_FILE)).catch(() => {})]);
+ }
if (!r.skipped && opts.pruneAfter !== false) {
const log = opts.log ?? (() => {});
await prune.pruneAfterBuild(projectDir, { built: r.id, log: (line) => log(`${r.id}: ${line}`) });
@@ -640,7 +670,20 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
const xfade = patches.some((p) => getPath(p, "render.transition") !== undefined) && transition > 0;
emit({ ev: "take", id: spec.id, phase: "render", window: spec.window, entries: covered?.ids ?? null, basis: covered?.basis ?? null });
let file;
+ // How long the render itself took (UI notes #18: a take's ETA is read from
+ // the project's past renders, lib/report/takeEta.mjs): from the build's
+ // first event -- after the heavy slot admitted it, so a wait at the slot's
+ // door is not counted -- to its end. Recorded as take.json `renderSeconds`.
+ const clock = opts.clock ?? Date.now;
+ const renderStart = clock();
+ let firstEventAt = null;
+ const timedEmit = (ev) => {
+ if (firstEventAt === null && ev?.ev !== "take") firstEventAt = clock();
+ emit(ev);
+ };
try {
+ // A cancel asked while the take was being set up: no render at all.
+ if (opts.signal?.aborted) throw new Error(`${spec.id}: cancelled before its render started`);
const render = opts.render ?? (await import("./takeRender.mjs")).renderTake;
({ file } = await render({
manifestPath: renderPath,
@@ -649,12 +692,18 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
full: spec.window === "full",
xfade,
keepFrames: opts.keepFrames === true,
- emit,
+ emit: timedEmit,
log,
+ ...(opts.signal ? { signal: opts.signal } : {}),
}));
+ } catch (e) {
+ // Stopped by a cancel: the half-made manifest goes too (a finished take's own is untouched).
+ if (opts.signal?.aborted) await rm(nextManifest, { force: true });
+ throw e;
} finally {
await rm(renderPath, { force: true });
}
+ const renderSeconds = Math.round((clock() - (firstEventAt ?? renderStart)) / 100) / 10;
await moveFile(file, preview);
await keepBuildName(preview, file, (line) => log(`${spec.id}: ${line}`));
@@ -686,6 +735,8 @@ async function makeTakeLocked(projectDir, rawSpec, opts) {
baseHash: hashText(baseText),
// The take it was built from: the pruner keeps a kept take's base (takePrune.mjs).
...(opts.from ? { from: opts.from } : {}),
+ // The render's own time, for the next take's ETA (takeEta.mjs).
+ renderSeconds,
};
const tmp = `${takeFile}.tmp-${process.pid}`;
await writeFile(tmp, JSON.stringify(doc, null, 2) + "\n", "utf8");
diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs
@@ -590,3 +590,22 @@ test("makeTake refuses a cut that still holds a clip ruled incorrect, by name an
await rm(root, { recursive: true, force: true });
}
});
+
+test("makeTake records renderSeconds: from the build's first event (after any wait at the heavy slot) to its end (UI notes #18)", async () => {
+ const { root, dir } = await project();
+ let t = 0;
+ const r = stubRender();
+ const render = async (job) => {
+ t = 30_000; // 30 s waiting at the slot's door: not counted
+ job.emit({ ev: "phase", phase: "clips" });
+ t = 30_000 + 95_400;
+ return r.render(job);
+ };
+ try {
+ await makeTake(dir, { id: "timed", label: "Timed", group: "g", window: "full" }, opts(r, { render, clock: () => t }));
+ const doc = JSON.parse(await readFile(path.join(dir, "takes", "timed", "take.json"), "utf8"));
+ assert.equal(doc.renderSeconds, 95.4);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/takeRender.mjs b/umtool/lib/report/takeRender.mjs
@@ -36,6 +36,9 @@ import { PIPELINE_DIR, UMTOOL_DIR } from "./driver.mjs";
const execFileP = promisify(execFile);
+/** How long a stopped render's group gets after TERM before KILL (ms). */
+const RENDER_KILL_GRACE_MS = 8000;
+
/** The checkout's heavy-slot CLI, when this umtool sits in the checkout. */
export function queueLockScript() {
const file = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "..", "scripts", "queue-lock.mjs");
@@ -103,12 +106,48 @@ export async function takeEstimateMb({ manifestPath, xfade }, env = process.env)
export async function renderTake(job) {
const argv = renderArgv({ ...job, estimateMb: job.estimateMb !== undefined ? job.estimateMb : await takeEstimateMb(job) });
job.log(`$ ${argv.join(" ")}`);
+ if (job.signal?.aborted) throw new Error("the render was cancelled before it started");
return new Promise((resolve, reject) => {
const child = spawn(argv[0], argv.slice(1), {
// In the checkout, so queue-lock finds the checkout's lock.
cwd: path.join(/* turbopackIgnore: true */ UMTOOL_DIR, ".."),
stdio: ["ignore", "pipe", "pipe"],
+ // ITS OWN PROCESS GROUP, so a cancel (takeCancel.mjs) stops the whole
+ // render -- queue-lock, build-video and every ffmpeg under it -- and
+ // nothing else: this process's group may be a terminal's or a script's.
+ detached: true,
});
+ // Stopping it: TERM to the group, KILL a grace later. A signal to THIS
+ // process (the job runner's Stop, Ctrl-C) is passed on to the group too --
+ // the render no longer shares this process's group, and must not outlive it.
+ /** @type {string | null} */
+ let stopped = null;
+ const killGroup = (sig) => {
+ try {
+ if (child.pid) process.kill(-child.pid, sig);
+ } catch {
+ /* already gone */
+ }
+ };
+ const stop = (why) => {
+ if (stopped) return;
+ stopped = why;
+ killGroup("SIGTERM");
+ setTimeout(() => killGroup("SIGKILL"), RENDER_KILL_GRACE_MS).unref();
+ };
+ const onAbort = () => stop("cancelled");
+ job.signal?.addEventListener("abort", onAbort, { once: true });
+ /** @type {Array<[NodeJS.Signals, () => void]>} */
+ const forward = [];
+ for (const sig of /** @type {NodeJS.Signals[]} */ (["SIGINT", "SIGTERM", "SIGHUP"])) {
+ const h = () => stop(sig);
+ forward.push([sig, h]);
+ process.on(sig, h);
+ }
+ const settle = () => {
+ job.signal?.removeEventListener("abort", onAbort);
+ for (const [sig, h] of forward) process.off(sig, h);
+ };
const failed = [];
let buf = "";
child.stdout.on("data", (b) => {
@@ -133,8 +172,16 @@ export async function renderTake(job) {
child.stderr.on("data", (b) => {
for (const line of b.toString().split("\n")) if (line.trim()) job.log(line);
});
- child.on("error", reject);
+ child.on("error", (e) => {
+ settle();
+ reject(e);
+ });
child.on("close", (code) => {
+ settle();
+ if (stopped) {
+ reject(new Error(stopped === "cancelled" ? "the render was cancelled" : `the render was stopped (${stopped})`));
+ return;
+ }
if (code === 0 && !failed.length) {
resolve({ file: variantPaths(job.outDir, job.slug, DEFAULT_VARIANT).final });
return;
diff --git a/umtool/lib/report/takeVariants.test.mjs b/umtool/lib/report/takeVariants.test.mjs
@@ -0,0 +1,200 @@
+// Take housekeeping, the rest (UI notes item 19): Cancel a take while it
+// renders (takeCancel.mjs, the take maker answering it), Fork as variant
+// (variantFork.mjs) and two takes compared (takeCompare.mjs).
+//
+// Run with: node --test lib/report/takeVariants.test.mjs
+import assert from "node:assert/strict";
+import { lstat, mkdir, mkdtemp, readFile, readlink, stat, writeFile } from "node:fs/promises";
+import os, { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { CANCEL_FILE, CANCELLED_FILE, TakeCancelled, cancelTake, markCancelled, readCancelled, releaseTakeHold, requestCancel, takeWorkDirs, watchCancel } from "./takeCancel.mjs";
+import { compareLines, compareTakes, leaves, lookDiff, parseTakeRef } from "./takeCompare.mjs";
+import { makeTake } from "./takeMaker.mjs";
+import { listTakes } from "./takes.mjs";
+import { ForkRefused, VARIANT_FILE, forkTakeAsVariant, readVariant, referencedAssets, variantFamily } from "./variantFork.mjs";
+
+const clip = (id, start, end, extra = {}) => ({ type: "clip", id, video: `v-${id}`, start, end, cite: start, section: 0, ...extra });
+const MANIFEST = {
+ schemaVersion: 1,
+ slug: "fixture",
+ title: "Fixture",
+ render: { width: 640, height: 360, fps: 15, transition: 0, crf: 30, chrome: { fx: { zoom: {} } } },
+ timeline: [clip("s01", 0, 10, { fx: { zoom: { shot: "shots/a.png", focus: [0, 0, 1, 1] } } }), clip("s02", 20, 25), clip("s03", 40, 50)],
+};
+
+async function project() {
+ const root = await mkdtemp(path.join(tmpdir(), "takevariants-"));
+ const reports = path.join(root, "reports");
+ const dir = path.join(reports, "case", "proj");
+ await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true });
+ await mkdir(path.join(dir, "shots"), { recursive: true });
+ await writeFile(path.join(dir, "shots", "a.png"), "png");
+ await writeFile(path.join(dir, "module-config.json"), "{}\n");
+ await writeFile(path.join(dir, "out", "clips-raw", "v-s01_0.00-13.00.mp4"), "media");
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2) + "\n");
+ return { root, reports, dir, ref: { id: "case/proj", dir } };
+}
+
+/** A renderer that writes the file, or -- `hold` -- waits until its signal aborts and rejects. */
+function render({ hold = false } = {}) {
+ return async (job) => {
+ if (hold) {
+ await new Promise((resolve, reject) => {
+ if (job.signal?.aborted) return reject(new Error("the render was cancelled"));
+ job.signal?.addEventListener("abort", () => reject(new Error("the render was cancelled")), { once: true });
+ setTimeout(resolve, 20_000).unref();
+ });
+ }
+ const doc = JSON.parse(await readFile(job.manifestPath, "utf8"));
+ const file = path.join(job.outDir, `${job.slug}.mp4`);
+ await writeFile(file, `render of ${doc.timeline.map((e) => e.id).join(",")}`);
+ return { file };
+ };
+}
+const opts = (extra = {}) => ({ styles: {}, probe: async () => 30, now: () => new Date("2026-11-02T10:00:00Z"), pruneAfter: false, ...extra });
+
+test("a take answers a cancel: its render stopped, no take.json, marked cancelled, its lock gone; the list shows it", async () => {
+ const p = await project();
+ const run = makeTake(p.dir, { id: "draft-2", label: "draft 2: the cold open", window: "full", patch: { title: "B" } }, opts({ render: render({ hold: true }) }));
+ const ended = run.then(() => null, (e) => e);
+ // While it renders: its directory is a work dir with a live lock (this process), listed as rendering.
+ const lock = path.join(p.dir, "takes", "draft-2", ".building.json");
+ for (let i = 0; i < 100 && !(await stat(lock).then(() => true, () => false)); i += 1) await new Promise((r) => setTimeout(r, 20));
+ const dirs = await takeWorkDirs(p.dir);
+ assert.deepEqual(dirs.rendering.map((r) => [r.id, r.label]), [["draft-2", "draft 2: the cold open"]]);
+ const r = await cancelTake(p.ref, "draft-2", { by: "a test", pollMs: 50, waitMs: 8000, lanes: null, renderModeFile: path.join(p.root, "rm.json") });
+ const e = await ended;
+ assert.ok(e instanceof TakeCancelled && /cancelled/.test(e.message), String(e));
+ assert.equal(r.stopped, true);
+ assert.equal(r.how, "the take maker");
+ assert.match(r.said, /its render stopped/);
+ const mark = await readCancelled(p.dir, "draft-2");
+ assert.equal(mark?.by, "a test");
+ assert.equal(mark?.label, "draft 2: the cold open");
+ assert.equal(mark?.rebuild, false);
+ assert.equal(await stat(path.join(p.dir, "takes", "draft-2", "take.json")).then(() => true, () => false), false, "never a take");
+ assert.equal(await stat(lock).then(() => true, () => false), false, "the lock is gone");
+ assert.equal(await stat(path.join(p.dir, "takes", "draft-2", CANCEL_FILE)).then(() => true, () => false), false, "the request is cleared");
+ assert.equal(await stat(path.join(p.dir, "takes", "draft-2", ".next.video.manifest.json")).then(() => true, () => false), false, "no half-made manifest");
+ const after = await takeWorkDirs(p.dir);
+ assert.deepEqual(after.rendering, []);
+ assert.deepEqual(after.cancelled.map((c) => c.id), ["draft-2"]);
+ // Made again, the take is a take and its mark is history.
+ await makeTake(p.dir, { id: "draft-2", label: "draft 2", window: "full", patch: { title: "B" } }, opts({ render: render(), force: true }));
+ assert.equal(await readCancelled(p.dir, "draft-2"), null);
+ assert.deepEqual((await takeWorkDirs(p.dir)).cancelled, []);
+});
+
+test("a cancel is refused for a take that is not rendering, or renders on another machine", async () => {
+ const p = await project();
+ await makeTake(p.dir, { id: "t1", label: "one", window: "full" }, opts({ render: render() }));
+ await assert.rejects(requestCancel(p.dir, "t1"), /is not rendering/);
+ await writeFile(path.join(p.dir, "takes", "t1", ".building.json"), JSON.stringify({ pid: 1, host: "elsewhere", startedAt: "x" }));
+ await assert.rejects(requestCancel(p.dir, "t1"), /rendering on elsewhere/);
+});
+
+test("watchCancel calls back once a request appears, and clears one a crashed run left", async () => {
+ const p = await project();
+ const dir = path.join(p.dir, "takes", "w");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, CANCEL_FILE), JSON.stringify({ at: "old" }));
+ let got = null;
+ const stop = watchCancel(dir, (req) => (got = req), { intervalMs: 20 });
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(got, null, "the stale request was cleared, not answered");
+ await writeFile(path.join(dir, CANCEL_FILE), JSON.stringify({ at: "now", by: "x" }));
+ for (let i = 0; i < 50 && !got; i += 1) await new Promise((r) => setTimeout(r, 20));
+ stop();
+ assert.equal(got?.by, "x");
+ const m = await markCancelled(p.dir, "w", { by: "x", label: "L", rebuild: true, at: "2026-11-02T00:00:00.000Z" });
+ assert.deepEqual(m, { at: "2026-11-02T00:00:00.000Z", by: "x", label: "L", rebuild: true });
+ assert.equal(await stat(path.join(dir, CANCELLED_FILE)).then(() => true, () => false), true);
+});
+
+test("render mode is let go when the cancelled take held it and is gone; another's hold is left", async () => {
+ const p = await project();
+ const file = path.join(p.root, "render-priority.json");
+ const state = (holder) => JSON.stringify({ token: "tok", since: "2026-11-02T10:00:00Z", until: "2099-01-01T00:00:00Z", holder, lanesHeld: [] });
+ await writeFile(file, state({ pid: 999999, project: "case/proj", take: "draft-2", cmd: "umtool take" }));
+ assert.equal(await releaseTakeHold("case/proj", "other", { file, lanes: null, isAlive: () => false }), null);
+ assert.equal(await releaseTakeHold("case/proj", "draft-2", { file, lanes: null, isAlive: () => true }), null, "still alive: its own finally lets go");
+ const r = await releaseTakeHold("case/proj", "draft-2", { file, lanes: null, isAlive: () => false });
+ assert.deepEqual(r, { released: [], failed: [] });
+});
+
+test("fork as variant: a project beside this one -- the take's manifest, variant.json, the media and assets linked, the take in it", async () => {
+ const p = await project();
+ await makeTake(p.dir, { id: "cold-open", label: "A cold open", window: "full", patch: { title: "Cold open" } }, opts({ render: render() }));
+ const r = await forkTakeAsVariant(p.ref, "cold-open", { name: "v-a-cold-open", now: () => new Date("2026-11-02T11:00:00Z") });
+ assert.equal(r.id, "case/v-a-cold-open");
+ const vdir = path.join(p.reports, "case", "v-a-cold-open");
+ const m = JSON.parse(await readFile(path.join(vdir, "video.manifest.json"), "utf8"));
+ assert.equal(m.title, "Cold open");
+ assert.equal(m.slug, "v-a-cold-open");
+ const v = await readVariant(vdir);
+ assert.equal(v?.variantOf, "case/proj");
+ assert.equal(v?.fromTake, "cold-open");
+ assert.equal(v?.takeLabel, "A cold open");
+ assert.match(await readFile(path.join(vdir, "README.md"), "utf8"), /A variant of `case\/proj`, forked 2026-11-02 from its take `cold-open`/);
+ assert.equal(await readlink(path.join(vdir, "out", "clips-raw")), path.join(p.dir, "out", "clips-raw"));
+ assert.equal(await readlink(path.join(vdir, "shots")), path.join(p.dir, "shots"), "the manifest's shots/ still resolve");
+ assert.equal((await lstat(path.join(vdir, "module-config.json"))).isFile(), true, "copied, not linked");
+ assert.deepEqual(r.links.sort(), ["out/clips-raw", "shots"]);
+ // The take came with it, its preview the same inode.
+ const [a, b] = await Promise.all([stat(path.join(p.dir, "takes", "cold-open", "preview.mp4")), stat(path.join(vdir, "takes", "cold-open", "preview.mp4"))]);
+ assert.equal(a.ino, b.ino);
+ const listed = await listTakes(vdir);
+ assert.deepEqual(listed.takes.map((t) => [t.id, t.kind]), [["cold-open", "reference"]]);
+ assert.deepEqual(listed.skipped, []);
+ // Refusals: the name taken, a bad name, a take that is not there.
+ await assert.rejects(forkTakeAsVariant(p.ref, "cold-open", { name: "v-a-cold-open" }), (e) => e instanceof ForkRefused && /exists/.test(e.message));
+ await assert.rejects(forkTakeAsVariant(p.ref, "cold-open", { name: "a/b" }), (e) => e instanceof ForkRefused && e.status === 400);
+ await assert.rejects(forkTakeAsVariant(p.ref, "nope"), (e) => e instanceof ForkRefused && e.status === 404);
+ // The family, from either side.
+ const fam = await variantFamily(p.ref, { root: p.reports });
+ assert.equal(fam.parent, "case/proj");
+ assert.deepEqual(fam.members.map((x) => x.id), ["case/proj", "case/v-a-cold-open"]);
+ const fam2 = await variantFamily({ id: "case/v-a-cold-open", dir: vdir }, { root: p.reports });
+ assert.deepEqual(fam2.members.map((x) => [x.id, x.fromTake]), [["case/proj", null], ["case/v-a-cold-open", "cold-open"]]);
+});
+
+test("a take rendering now is not forked", async () => {
+ const p = await project();
+ await makeTake(p.dir, { id: "t1", label: "one", window: "full" }, opts({ render: render() }));
+ await writeFile(path.join(p.dir, "takes", "t1", ".building.json"), JSON.stringify({ pid: process.pid, host: os.hostname(), startedAt: "x" }));
+ await assert.rejects(forkTakeAsVariant(p.ref, "t1"), /not forked: it is rendering now/);
+});
+
+test("two takes compared: refs, the cut's changes A → B, the look's differences", async () => {
+ const p = await project();
+ await makeTake(p.dir, { id: "a1", label: "plain", window: "full" }, opts({ render: render() }));
+ await makeTake(
+ p.dir,
+ { id: "b1", label: "tight", window: "full", patch: { render: { crf: 34 }, timeline: [clip("s02", 20, 24), clip("s01", 0, 10), clip("s09", 5, 9)] } },
+ opts({ render: render() }),
+ );
+ assert.deepEqual(parseTakeRef("b1", "case/proj"), { project: "case/proj", take: "b1" });
+ assert.deepEqual(parseTakeRef("case/v-x:a1", "case/proj"), { project: "case/v-x", take: "a1" });
+ assert.equal(parseTakeRef("Not A Take", "p"), null);
+ const c = await compareTakes({ ref: { project: "case/proj", take: "a1" }, dir: p.dir }, { ref: { project: "case/proj", take: "b1" }, dir: p.dir });
+ assert.equal(c.a.label, "plain");
+ assert.equal(c.b.clips, 3);
+ const lines = c.cut.lines.join("\n");
+ assert.match(lines, /- s03 {2}removed/);
+ assert.match(lines, /\+ s09 {2}added/);
+ assert.match(lines, /~ s02 {2}window: 20–25 -> 20–24/);
+ assert.deepEqual(c.look.map((d) => [d.path, d.a, d.b]), [["render.crf", 30, 34]]);
+ assert.equal(c.same, false);
+ assert.match(compareLines(c).join("\n"), /the look — 1 difference\(s\):\n {2}render\.crf: 30 → 34/);
+ assert.deepEqual(lookDiff({ a: { b: 1 }, timeline: [1] }, { a: { b: 1 }, timeline: [2] }), []);
+ assert.deepEqual(leaves({ x: { y: [1, 2], z: null } }), [["x.y", [1, 2]], ["x.z", null]]);
+});
+
+test("referencedAssets: the project's entries a manifest names by a relative path, its own state left out", () => {
+ const entries = new Set(["shots", "posts-media", "out", "takes", "module-config.json", "README.md"]);
+ const m = { a: "shots/x.png", b: ["posts-media/p.jpg", "out/clips-raw/a.mp4"], c: { d: "https://x/shots/y", e: "/abs/shots/z", f: "../shots/q" }, g: "takes/t/preview.mp4" };
+ assert.deepEqual(referencedAssets(m, entries), ["posts-media", "shots"]);
+ assert.equal(VARIANT_FILE, "variant.json");
+});
diff --git a/umtool/lib/report/tightCli.mjs b/umtool/lib/report/tightCli.mjs
@@ -0,0 +1,92 @@
+// `umtool tighten <project> [--json] [--no-measure] [--all] [--apply <clip>[,<clip>…]]`:
+// the Cut tab's "Propose tight windows" (lib/report/tightPropose.mjs) from a
+// terminal -- every clip of the cut tightened to its sentence and each edge
+// into its pause, before and after. Prints only; `--apply` writes the named
+// rows through the window writer (the token, the cite that follows the edge,
+// an edit note on a generated manifest), re-proposed first.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { kindMakesTakes } from "../projects/kinds.mjs";
+import { applyTightWindows, proposeTightWindows } from "./tightPropose.mjs";
+
+export const TIGHTEN_USAGE = [
+ "usage: umtool tighten <project> [--json] [--all] [--no-measure]",
+ " umtool tighten <project> --apply <clip>[,<clip>…]",
+ "",
+ "Each clip of the cut to its sentence -- the sentences its cut (its quote) touches, else the whole",
+ "sentences inside its window -- and each edge into its pause (the build's measured silences and the",
+ "gaps between the recording's timed words, at most 1 s away, inside the cached window). Prints the",
+ "clips that would change, before -> after with the seconds (--all: every clip). --no-measure skips",
+ "the silences (the words alone). --apply writes those rows through the window writer; a locked edge",
+ "is proposed like any other (a lock is against resolve-windows) and the lock is kept.",
+].join("\n");
+
+class CliError extends Error {}
+
+const hms = (t) => {
+ const m = Math.floor(t / 60);
+ return `${m}:${(t - m * 60).toFixed(2).padStart(5, "0")}`;
+};
+
+/** One row as a line. */
+export function tightLine(r) {
+ const b = `${hms(r.before.start)}–${hms(r.before.end)} (${r.before.seconds.toFixed(2)} s)`;
+ if (!r.after) return `${r.id.padEnd(8)} ${b} — ${r.why}`;
+ const a = `${hms(r.after.start)}–${hms(r.after.end)} (${r.after.seconds.toFixed(2)} s)`;
+ const d = r.after.seconds - r.before.seconds;
+ const marks = [r.locked ? "locked" : null, r.fetched ? null : "not fetched", r.clear.cut ? "clears the cut" : null].filter(Boolean);
+ return `${r.id.padEnd(8)} ${b} → ${a} ${r.changed ? `${d > 0 ? "+" : "−"}${Math.abs(d).toFixed(2)} s` : "already tight"}${marks.length ? ` [${marks.join(", ")}]` : ""}` +
+ (r.changed ? `\n ${r.how}${r.said.length ? ` — ${r.said.join("; ")}` : ""}` : "");
+}
+
+/**
+ * @param {string[]} args the words after `tighten`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts]
+ * @returns {Promise<number>}
+ */
+export async function tightenCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ try {
+ const flags = new Set();
+ const words = [];
+ let apply = null;
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (a === "--apply") {
+ apply = String(args[i + 1] ?? "").split(",").map((s) => s.trim()).filter(Boolean);
+ i += 1;
+ if (!apply.length) throw new CliError("--apply names clips: --apply c01,c02");
+ } else if (a.startsWith("--")) {
+ if (!["--json", "--all", "--no-measure", "--help"].includes(a)) throw new CliError(`unknown flag ${a}`);
+ flags.add(a);
+ } else words.push(a);
+ }
+ if (!words[0] || flags.has("--help")) {
+ (flags.has("--help") ? out : err)(TIGHTEN_USAGE);
+ return flags.has("--help") ? 0 : 2;
+ }
+ const r = await resolveProject(words[0], root);
+ if (r.ambiguous) throw new CliError(`"${words[0]}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${words[0]}"`);
+ const project = r.project;
+ if (!kindMakesTakes(project.kind)) throw new CliError(`${project.id} is a ${project.kind}, not a report video`);
+ if (apply) {
+ const done = await applyTightWindows(project, apply);
+ if (flags.has("--json")) out(JSON.stringify({ applied: done }, null, 2));
+ else for (const d of done) out(`${d.ok ? "applied" : "NOT applied"} ${d.id}: ${d.said}`);
+ return done.every((d) => d.ok) ? 0 : 1;
+ }
+ const got = await proposeTightWindows(project, { measure: !flags.has("--no-measure") });
+ if (flags.has("--json")) {
+ out(JSON.stringify(got, null, 2));
+ return 0;
+ }
+ out(`${got.counts.proposed} of ${got.counts.clips} clips would change · ${got.counts.same} already tight${got.counts.none ? ` · ${got.counts.none} with nothing to go by` : ""}`);
+ for (const row of got.rows) if (flags.has("--all") || row.changed) out(tightLine(row));
+ if (got.counts.proposed) out(`\napply: umtool tighten ${project.id} --apply ${got.rows.filter((x) => x.changed).map((x) => x.id).join(",")}`);
+ return 0;
+ } catch (e) {
+ err(e instanceof Error ? e.message : String(e));
+ return e instanceof CliError ? 2 : 1;
+ }
+}
diff --git a/umtool/lib/report/tightCli.test.mjs b/umtool/lib/report/tightCli.test.mjs
@@ -0,0 +1,41 @@
+// The pure halves of the batch: the window patch an Apply writes
+// (tightPropose.mjs applyPatchOf) and a row as `umtool tighten` prints it.
+//
+// Run with: node --test lib/report/tightCli.test.mjs
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { tightLine } from "./tightCli.mjs";
+import { applyPatchOf } from "./tightPropose.mjs";
+
+const row = (o = {}) => ({
+ id: "t01",
+ quote: "and because of that",
+ section: 0,
+ before: { start: 1.2, end: 7.4, seconds: 6.2 },
+ after: { start: 3.0, end: 9.0, seconds: 6 },
+ changed: true,
+ how: "the sentences the cut (its quote) touches",
+ said: ["start 3.00 → 3.01, into the pause before “And”"],
+ why: null,
+ fetched: true,
+ locked: false,
+ words: "words.json",
+ clear: { cut: false, mute: false },
+ prior: { cutStart: null, cutEnd: null, muteFrom: null, cite: null, citeUrl: null },
+ ...o,
+});
+
+test("applyPatchOf: the edges, and the cut / mute mark cleared only when they no longer fit", () => {
+ assert.deepEqual(applyPatchOf(row()), { start: 3, end: 9 });
+ assert.deepEqual(applyPatchOf(row({ clear: { cut: true, mute: true } })), { start: 3, end: 9, cutStart: "", cutEnd: "", muteFrom: "" });
+ assert.equal(applyPatchOf(row({ after: null })), null);
+});
+
+test("tightLine: before → after with the seconds, the marks, and why", () => {
+ const l = tightLine(row({ locked: true, fetched: false }));
+ assert.match(l, /^t01 +0:01\.20–0:07\.40 \(6\.20 s\) → 0:03\.00–0:09\.00 \(6\.00 s\) {2}−0\.20 s {2}\[locked, not fetched\]/);
+ assert.match(l, /into the pause before/);
+ assert.match(tightLine(row({ after: null, changed: false, why: "no cues" })), /— no cues$/);
+ assert.match(tightLine(row({ changed: false, after: { start: 1.2, end: 7.4, seconds: 6.2 } })), /already tight/);
+});
diff --git a/umtool/lib/report/tightPropose.mjs b/umtool/lib/report/tightPropose.mjs
@@ -0,0 +1,211 @@
+// PROPOSE TIGHT WINDOWS for a cut (UI notes 2026-10-30, item 4: "a batch
+// 'propose tight windows' that shows before/after durations for review").
+//
+// For every clip of the project's cut, lib/report/tightWindow.mjs over what
+// this machine already has -- nothing is fetched, nothing is written:
+//
+// cues the recording's cue file (projects/report.mjs cuesInWindow),
+// 60 s either side, for where a sentence starts and ends
+// words the project's words file when it is THAT recording's, else the
+// corpus's (report-to-video clip-words.mjs: a words sidecar, a
+// whisper transcript, the en-orig captions' starts)
+// silences the build's own, measured on the build's own file and cached
+// (lib/report/cutPoints.mjs -- the bench's ghosts and Play read the
+// same); a clip with nothing on disk goes by its words alone
+// the bound the cached window holding the clip, when there is one: a
+// proposal never reaches past what the bench could play
+//
+// with no playhead: the cut's sentences when the clip has a cut (its quote),
+// else the whole sentences inside the window. Each row is before and after,
+// what moved and why; the review list (the Cut tab) applies a row only when
+// its Apply is pressed -- PUT /api/report/window, the token, the cite that
+// follows the edge -- and `umtool tighten <p> --apply <clip>` does the same
+// through the same writer.
+//
+// A LOCK IS NOT A REFUSAL HERE. `lock`/`lockStart`/`lockEnd` pin an edge
+// against `resolve-windows --write` (the widener), not against a person: five
+// of six real cuts are fully locked. A locked clip is proposed like any other
+// and its row says it is locked; Apply leaves the locks as they are.
+
+import { clipWords } from "umtool-report-to-video/clip-words";
+import { hasLocalMedia } from "umtool-report-to-video/local-media";
+import { channelsDirFor, clipsOf, cuesInWindow, hasShadowChannels, readManifest } from "../projects/report.mjs";
+import { readWords } from "./clipEditor.mjs";
+import { readReactions } from "./clipEditorBridge.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { manifestToken, updateClip } from "./manifest.mjs";
+import { projectCache, windowsFor } from "./serve.mjs";
+import { HOW_SAID, tightWindow } from "./tightWindow.mjs";
+
+/** How far either side of a clip its cues are read (seconds). */
+const CUE_REACH = 60;
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r2 = (v) => Math.round(v * 100) / 100;
+
+/**
+ * @typedef {{
+ * id: string, quote: string | null, section: unknown,
+ * before: { start: number, end: number, seconds: number },
+ * after: { start: number, end: number, seconds: number } | null,
+ * changed: boolean, how: string | null, said: string[], why: string | null,
+ * fetched: boolean, locked: boolean, words: string | null,
+ * clear: { cut: boolean, mute: boolean },
+ * prior: { cutStart: number | null, cutEnd: number | null, muteFrom: number | null, cite: number | null, citeUrl: string | null },
+ * }} TightRow
+ */
+
+/**
+ * The proposals for a project's cut (or the named clips).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ clips?: string[] | null, measure?: boolean }} [opts]
+ * `measure: false` skips the silences (the words alone), for a cut whose sources are not on disk
+ * @returns {Promise<{ token: string | null, rows: TightRow[], counts: { clips: number, proposed: number, same: number, none: number } }>}
+ */
+export async function proposeTightWindows(project, { clips = null, measure = true } = {}) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new Error("no manifest");
+ const want = clips ? new Set(clips) : null;
+ const entries = clipsOf(manifest).filter((e) => fin(e.start) && fin(e.end) && typeof e.video === "string" && !hasLocalMedia(e) && (!want || want.has(e.id)));
+ const token = await manifestToken(project.dir);
+ const channelsDir = channelsDirFor(project.dir, manifest, { shadowExists: await hasShadowChannels(project.dir) });
+ const { doc: reactions } = await readReactions(project.dir);
+ const projectWords = await readWords(project.dir, reactions).catch(() => null);
+ const cache = await projectCache(project, manifest);
+
+ // The build's silences per clip (cached on disk; the first read measures).
+ /** @type {Map<string, Array<{ from: number, to: number }>>} */
+ const silences = new Map();
+ if (measure && entries.length) {
+ try {
+ const { cutPointsFor } = await import("./cutPoints.mjs");
+ const got = await cutPointsFor(project, { clips: entries.map((e) => e.id) });
+ for (const row of got.clips ?? []) {
+ if (!row || row.missing || row.error || !Array.isArray(row.silences) || !fin(row.fetchStart)) continue;
+ silences.set(row.id, row.silences.map((x) => ({ from: row.fetchStart + x.s, to: row.fetchStart + x.e })));
+ }
+ } catch {
+ /* the words alone */
+ }
+ }
+
+ /** @type {TightRow[]} */
+ const rows = [];
+ for (const e of entries) {
+ const before = { start: e.start, end: e.end, seconds: r2(e.end - e.start) };
+ const base = {
+ id: e.id,
+ quote: typeof e.quote === "string" ? e.quote : null,
+ section: e.section ?? null,
+ before,
+ locked: !!(e.lock || e.lockStart || e.lockEnd),
+ // What an Undo of an applied row writes back besides the edges (the writer answers only the edges' `before`).
+ prior: {
+ cutStart: fin(e.cutStart) ? e.cutStart : null,
+ cutEnd: fin(e.cutEnd) ? e.cutEnd : null,
+ muteFrom: fin(e.muteFrom) ? e.muteFrom : null,
+ cite: fin(e.cite) ? e.cite : null,
+ citeUrl: typeof e.citeUrl === "string" ? e.citeUrl : null,
+ },
+ };
+ const wins = /** @type {Array<{ from: number, to: number }>} */ (await windowsFor(project, e, cache).catch(() => []));
+ const holds = wins.find((w) => w.from <= e.start + 0.02 && w.to >= e.end - 0.02) ?? null;
+ const c = await cuesInWindow(project.dir, e.id, e.start - CUE_REACH, e.end + CUE_REACH, { manifest }).catch(() => null);
+ let words = null;
+ let wordsFrom = null;
+ if (projectWords?.length && reactions?.source?.video === e.video) {
+ words = projectWords.filter((w) => w.end >= e.start - CUE_REACH && w.start <= e.end + CUE_REACH).map((w) => ({ start: w.start, end: w.end, text: String(w.w ?? w.word ?? w.text ?? "") }));
+ wordsFrom = "project";
+ } else {
+ const cw = await clipWords(e, manifest.provenance, e.start - CUE_REACH, e.end + CUE_REACH, { channelsDir }).catch(() => null);
+ if (cw?.words?.length) {
+ words = cw.words;
+ wordsFrom = cw.from;
+ }
+ }
+ const r = tightWindow({
+ clip: { start: e.start, end: e.end, cutStart: fin(e.cutStart) ? e.cutStart : null, cutEnd: fin(e.cutEnd) ? e.cutEnd : null },
+ cues: c?.cues ?? [],
+ words,
+ silences: silences.get(e.id) ?? null,
+ at: null,
+ ...(holds ? { lo: holds.from, hi: holds.to } : { lo: 0 }),
+ });
+ if (!r.ok) {
+ rows.push({ ...base, after: null, changed: false, how: null, said: [], why: r.why, fetched: !!holds, words: wordsFrom, clear: { cut: false, mute: false } });
+ continue;
+ }
+ const cutOut = fin(e.cutStart) && fin(e.cutEnd) && (e.cutStart < r.start - 0.02 || e.cutEnd > r.end + 0.02);
+ const muteOut = fin(e.muteFrom) && (e.muteFrom < r.start - 0.02 || e.muteFrom > r.end + 0.02);
+ rows.push({
+ ...base,
+ after: { start: r.start, end: r.end, seconds: r2(r.end - r.start) },
+ changed: r.changed,
+ how: HOW_SAID[r.how],
+ said: r.said,
+ why: null,
+ fetched: !!holds,
+ words: wordsFrom,
+ clear: { cut: !!cutOut, mute: !!muteOut },
+ });
+ }
+ const proposed = rows.filter((x) => x.changed).length;
+ const none = rows.filter((x) => !x.after).length;
+ return { token, rows, counts: { clips: rows.length, proposed, same: rows.length - proposed - none, none } };
+}
+
+/**
+ * The window patch that applies one row: its edges, and the cut / the mute
+ * mark cleared when they no longer fit (as the bench's Save window does).
+ *
+ * @param {TightRow} row
+ */
+export function applyPatchOf(row) {
+ if (!row.after) return null;
+ return {
+ start: row.after.start,
+ end: row.after.end,
+ ...(row.clear.cut ? { cutStart: "", cutEnd: "" } : {}),
+ ...(row.clear.mute ? { muteFrom: "" } : {}),
+ };
+}
+
+/**
+ * Apply proposals by clip id through the window writer (the terminal's
+ * `umtool tighten <p> --apply <ids>`), one write each, re-proposed first so a
+ * row is never applied from a stale reading.
+ *
+ * @param {{ id: string, dir: string, kind: string }} project
+ * @param {string[]} ids
+ * @returns {Promise<Array<{ id: string, ok: boolean, said: string }>>}
+ */
+export async function applyTightWindows(project, ids) {
+ const { rows } = await proposeTightWindows(project, { clips: ids });
+ const out = [];
+ for (const id of ids) {
+ const row = rows.find((x) => x.id === id);
+ if (!row) {
+ out.push({ id, ok: false, said: "not a clip of the cut with a window" });
+ continue;
+ }
+ const patch = applyPatchOf(row);
+ if (!patch || !row.changed) {
+ out.push({ id, ok: false, said: row.why ?? "already tight" });
+ continue;
+ }
+ try {
+ const token = await manifestToken(project.dir);
+ const { result: res } = await withEditNotes(project, () => updateClip(project.dir, id, patch, { token }));
+ const f = res.citeFollowed;
+ out.push({
+ id,
+ ok: true,
+ said: `${row.before.start}–${row.before.end} → ${row.after?.start}–${row.after?.end} (${row.before.seconds} s → ${row.after?.seconds} s)` +
+ `${f?.cite ? `; cite ${f.cite.from} → ${f.cite.to}` : ""}${f?.citeUrl ? "; the QR's t= with it" : ""}`,
+ });
+ } catch (e) {
+ out.push({ id, ok: false, said: e instanceof Error ? e.message : String(e) });
+ }
+ }
+ return out;
+}
diff --git a/umtool/lib/report/tightWindow.mjs b/umtool/lib/report/tightWindow.mjs
@@ -0,0 +1,198 @@
+// TIGHTEN A CLIP TO ITS SENTENCE, and an edge into the nearest pause (UI notes
+// 2026-10-30, item 4: "punchy tightening meant silencedetect by hand and
+// en-orig word times read from VTT").
+//
+// Two existing rules, composed -- nothing here detects a pause or a sentence
+// of its own:
+//
+// the sentence lib/report/sentenceEdges.mjs (the phone walk's strip, the
+// pre-cut's rule): a start edge lands on a sentence START,
+// an end edge on a sentence END, read off the cues;
+// the pause report-to-video/pauses.mjs (L1's helper, the trailer's
+// snap): the measured silences and the gaps between timed
+// words, and `snapEdge` -- a start back into the pause
+// before its first word, an end forward into the one after
+// its last, "nearest" to the middle of the closest one.
+//
+// WHICH SENTENCE ("the sentence around the playhead or the current window"):
+//
+// at the playhead, when it is inside the clip (more than AT_MARGIN from
+// either edge: a playhead parked on the start, where the bench puts it
+// on arrival, is not a place somebody chose): the one sentence it is in
+// cut else the clip's cut (the quote's span): every sentence it touches,
+// whole -- the quote finished, nothing more
+// window else the whole sentences inside the window: a partial sentence at
+// either edge is dropped
+// middle a window inside one sentence: that sentence
+//
+// then each edge into its pause (a hard cut's SNAP_HARD_ROOM of quiet, at most
+// SNAP_MAX_SHIFT away, never past `lo`/`hi`: the cached window on the bench).
+// What moved and why comes back to be said; nothing here writes. The bench
+// writes through the window writer (PUT /api/report/window, the token, the cite
+// that follows the edge), and so does each Apply of the batch's proposals
+// (tightPropose.mjs).
+//
+// PURE: no fs, no DOM -- the bench imports it.
+
+import { sentenceBoundaries } from "./sentenceEdges.mjs";
+import { pauseSpans, snapEdge } from "umtool-report-to-video/pauses";
+
+/** Two seconds closer than this are the same boundary (sentenceEdges' SAME). */
+const SAME = 0.05;
+/** A playhead this close to an edge is parked there, not placed (seconds). */
+export const AT_MARGIN = 0.25;
+/** How far past the sentence the pauses are read (seconds): a snap moves at most SNAP_MAX_SHIFT. */
+const PAUSE_REACH = 2;
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r2 = (v) => Math.round(v * 100) / 100;
+
+/**
+ * The sentence(s) around the span [a, b]: the last sentence start at or
+ * before `a` and the first sentence end at or after `b`. null when the cues
+ * hold no such boundary on either side.
+ *
+ * @param {Array<{ start: number, end: number, text: string }>} cues
+ * @param {number} a
+ * @param {number} b
+ * @returns {{ start: number, end: number } | null}
+ */
+export function sentenceAround(cues, a, b) {
+ const { starts, ends } = sentenceBoundaries(cues);
+ let start = null;
+ for (const s of starts) if (s <= a + SAME) start = s;
+ const end = ends.find((e) => e >= b - SAME && e > (start ?? -Infinity) + SAME) ?? null;
+ return start !== null && end !== null ? { start, end } : null;
+}
+
+/**
+ * The whole sentences inside [from, to]: the first sentence start at or after
+ * `from`, the last sentence end at or before `to`. null when no whole sentence
+ * fits.
+ *
+ * @param {Array<{ start: number, end: number, text: string }>} cues
+ * @param {number} from
+ * @param {number} to
+ */
+export function sentencesInside(cues, from, to) {
+ const { starts, ends } = sentenceBoundaries(cues);
+ const start = starts.find((s) => s >= from - SAME) ?? null;
+ let end = null;
+ for (const e of ends) if (e <= to + SAME) end = e;
+ return start !== null && end !== null && end > start + SAME ? { start, end } : null;
+}
+
+/**
+ * The pauses around [from, to] (pauses.mjs pauseSpans): the measured silences
+ * and the gaps between timed words.
+ *
+ * @param {{ words?: Array<{ start: number, end?: number }> | null, silences?: Array<{ from: number, to: number }> | null }} o
+ * @param {number} from
+ * @param {number} to
+ */
+export function pausesNear({ words = null, silences = null }, from, to) {
+ return pauseSpans({ words, silences }, { from: from - PAUSE_REACH, to: to + PAUSE_REACH });
+}
+
+/** One snap in words: "start 12.40 → 12.95, into the pause before “So”". */
+export function snapSaid(edge, snap) {
+ if (!snap) return null;
+ if (!snap.moved) {
+ const why = snap.reason === "fits" ? "already in a pause" : snap.reason === "far" ? "the nearest pause is more than a second away" : snap.reason === "bound" ? "the pause is past the cached window" : "no pause near it";
+ return `${edge} stays at ${snap.at.toFixed(2)} (${why})`;
+ }
+ const word = snap.word ? ` ${snap.side === "start" ? "before" : snap.side === "end" ? "after" : "by"} “${snap.word}”` : "";
+ return `${edge} ${snap.from.toFixed(2)} → ${snap.at.toFixed(2)}, into the pause${word}${snap.bounded ? " (as far as the cached window)" : ""}`;
+}
+
+/**
+ * An edge into the pause nearest it (pauses.mjs snapEdge "nearest"): what the
+ * bench's "Snap edge to nearest pause" does.
+ *
+ * @param {number} t
+ * @param {{ words?: Array<{ start: number, end?: number, text?: string }> | null, silences?: Array<{ from: number, to: number }> | null, lo?: number, hi?: number }} o
+ */
+export function nearestPause(t, { words = null, silences = null, lo = -Infinity, hi = Infinity }) {
+ const pauses = pausesNear({ words, silences }, t, t);
+ return snapEdge(t, "nearest", { pauses, words, lo, hi });
+}
+
+/**
+ * Tighten a clip to its sentence (see the header).
+ *
+ * @param {{
+ * clip: { start: number, end: number, cutStart?: number | null, cutEnd?: number | null },
+ * cues: Array<{ start: number, end: number, text: string }>,
+ * words?: Array<{ start: number, end?: number, text?: string }> | null,
+ * silences?: Array<{ from: number, to: number }> | null,
+ * at?: number | null,
+ * lo?: number, hi?: number,
+ * snap?: boolean,
+ * }} o
+ * @returns {{ ok: true, start: number, end: number, how: "at" | "cut" | "window" | "middle",
+ * sentence: { start: number, end: number }, snaps: { start: any, end: any } | null, changed: boolean, said: string[] }
+ * | { ok: false, why: string }}
+ */
+export function tightWindow({ clip, cues, words = null, silences = null, at = null, lo = -Infinity, hi = Infinity, snap = true }) {
+ if (!clip || !fin(clip.start) || !fin(clip.end)) return { ok: false, why: "the clip has no window" };
+ const cs = (cues ?? []).filter((c) => c && fin(c.start) && fin(c.end));
+ if (!cs.length) return { ok: false, why: "no cues for this recording: nothing says where a sentence is" };
+ const hasCut = fin(clip.cutStart) && fin(clip.cutEnd);
+ /** @type {"at" | "cut" | "window" | "middle"} */
+ let how;
+ let s = null;
+ if (fin(at) && at > clip.start + AT_MARGIN && at < clip.end - AT_MARGIN) {
+ how = "at";
+ s = sentenceAround(cs, /** @type {number} */ (at), /** @type {number} */ (at));
+ } else if (hasCut) {
+ how = "cut";
+ s = sentenceAround(cs, /** @type {number} */ (clip.cutStart), /** @type {number} */ (clip.cutEnd));
+ } else {
+ how = "window";
+ s = sentencesInside(cs, clip.start, clip.end);
+ if (!s) {
+ how = "middle";
+ const mid = (clip.start + clip.end) / 2;
+ s = sentenceAround(cs, mid, mid);
+ }
+ }
+ if (!s) return { ok: false, why: "the cues around it hold no sentence boundary" };
+ // The cached window bounds the sentence itself, not only the snap: an edge
+ // past it is clamped to it (and said).
+ const said = [];
+ let start = s.start;
+ let end = s.end;
+ if (start < lo - 1e-6) {
+ said.push(`the sentence starts at ${start.toFixed(2)}, before the cached window: from ${lo.toFixed(2)}`);
+ start = lo;
+ }
+ if (end > hi + 1e-6) {
+ said.push(`the sentence ends at ${end.toFixed(2)}, past the cached window: to ${hi.toFixed(2)}`);
+ end = hi;
+ }
+ let snaps = null;
+ if (snap) {
+ const pauses = pausesNear({ words, silences }, start, end);
+ if (pauses.length) {
+ const a = snapEdge(start, "start", { pauses, words, lo, hi: end });
+ const b = snapEdge(end, "end", { pauses, words, lo: start, hi });
+ snaps = { start: a, end: b };
+ if (a.moved) start = a.at;
+ if (b.moved) end = b.at;
+ for (const [edge, x] of /** @type {const} */ ([["start", a], ["end", b]])) if (x.moved) said.push(/** @type {string} */ (snapSaid(edge, x)));
+ }
+ }
+ start = r2(start);
+ end = r2(end);
+ if (!(end - start >= 0.5)) return { ok: false, why: "the sentence is shorter than half a second" };
+ const changed = Math.abs(start - clip.start) > 0.02 || Math.abs(end - clip.end) > 0.02;
+ return { ok: true, start, end, how, sentence: { start: r2(s.start), end: r2(s.end) }, snaps, changed, said };
+}
+
+/** What the anchor was, in words. */
+export const HOW_SAID = Object.freeze({
+ at: "the sentence at the playhead",
+ cut: "the sentences the cut (its quote) touches",
+ window: "the whole sentences inside the window",
+ middle: "the sentence the window is inside",
+});
diff --git a/umtool/lib/report/tightWindow.test.mjs b/umtool/lib/report/tightWindow.test.mjs
@@ -0,0 +1,109 @@
+// tightWindow.mjs: a clip tightened to its sentence (sentenceEdges.mjs) and
+// each edge into its pause (report-to-video/pauses.mjs) -- which sentence (the
+// playhead's, the cut's, the whole ones inside the window, the one it is
+// inside), the cache as a bound, and an edge to the nearest pause.
+//
+// Run with: node --test lib/report/tightWindow.test.mjs
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { HOW_SAID, nearestPause, pausesNear, sentenceAround, sentencesInside, snapSaid, tightWindow } from "./tightWindow.mjs";
+
+// The e2e fixture's vid1 cues (e2e/fixtures/make-fixture.mjs): sentences 0-3, 3-9, 9-12, 12-15, 15-21.
+const VID1 = [
+ [0, 3, "This is a complete sentence."],
+ [3, 6, "And this one runs on and because"],
+ [6, 9, "of that it finishes here."],
+ [9, 12, "Another whole sentence entirely."],
+ [12, 15, "A fourth one, done."],
+ [15, 18, "trailing off and then"],
+ [18, 21, "it lands at last."],
+].map(([start, end, text]) => ({ start, end, text }));
+
+// Timed words over it (the tight fixture's words.json), with the silences of the fixture's tone window.
+const WORDS = [
+ ["This", 0.2, 0.5], ["is", 0.55, 0.7], ["a", 0.75, 0.8], ["complete", 0.9, 1.6], ["sentence.", 1.7, 2.8],
+ ["And", 3.2, 3.5], ["this", 3.55, 3.8], ["one", 3.85, 4.1], ["runs", 4.15, 4.5], ["on", 4.55, 4.7], ["and", 4.75, 5], ["because", 5.1, 5.85],
+ ["of", 6.2, 6.4], ["that", 6.45, 6.8], ["it", 6.85, 7], ["finishes", 7.1, 7.9], ["here.", 8, 8.8],
+ ["Another", 9.2, 9.8], ["whole", 9.9, 10.3], ["sentence", 10.4, 11], ["entirely.", 11.1, 11.8],
+].map(([text, start, end]) => ({ text, start, end }));
+const SILENCES = [{ from: 2.9, to: 3.11 }, { from: 5.92, to: 6.11 }, { from: 8.85, to: 9.15 }];
+
+test("sentenceAround: the last start at or before, the first end at or after", () => {
+ assert.deepEqual(sentenceAround(VID1, 4.5, 4.5), { start: 3, end: 9 });
+ assert.deepEqual(sentenceAround(VID1, 1, 10), { start: 0, end: 12 });
+ // On a boundary: the sentence that starts there.
+ assert.deepEqual(sentenceAround(VID1, 3, 3), { start: 3, end: 9 });
+ assert.equal(sentenceAround([{ start: 0, end: 3, text: "no end" }], 1, 1), null);
+});
+
+test("sentencesInside: partial sentences at either edge are dropped", () => {
+ assert.deepEqual(sentencesInside(VID1, 1.2, 12.4), { start: 3, end: 12 });
+ assert.equal(sentencesInside(VID1, 3.5, 8), null, "inside one sentence: nothing whole");
+});
+
+test("at the playhead: that sentence, each edge into its pause", () => {
+ const r = tightWindow({ clip: { start: 1.2, end: 10.5 }, cues: VID1, words: WORDS, silences: SILENCES, at: 4.4 });
+ assert.equal(r.ok, true);
+ if (!r.ok) return;
+ assert.equal(r.how, "at");
+ assert.deepEqual(r.sentence, { start: 3, end: 9 });
+ // The start goes back into the 2.9-3.2 pause (the hard cut's 0.1 s of quiet before "And");
+ // the end is already in the pause after "here." (8.8-9.2), and stays.
+ assert.ok(r.start >= 2.9 && r.start <= 3.2, `start ${r.start}`);
+ assert.ok(r.end >= 8.8 && r.end <= 9.2, `end ${r.end}`);
+ assert.equal(r.changed, true);
+});
+
+test("the cut anchors it when the playhead is elsewhere: every sentence the quote touches", () => {
+ const r = tightWindow({ clip: { start: 0.5, end: 11.9, cutStart: 4, cutEnd: 7.5 }, cues: VID1, at: null, snap: false });
+ assert.equal(r.ok && r.how, "cut");
+ assert.equal(r.ok && r.start, 3);
+ assert.equal(r.ok && r.end, 9);
+});
+
+test("no playhead, no cut: the whole sentences inside the window, else the one it is inside", () => {
+ const a = tightWindow({ clip: { start: 1.2, end: 12.4 }, cues: VID1, snap: false });
+ assert.equal(a.ok && a.how, "window");
+ assert.deepEqual(a.ok && [a.start, a.end], [3, 12]);
+ const b = tightWindow({ clip: { start: 3.5, end: 8 }, cues: VID1, snap: false });
+ assert.equal(b.ok && b.how, "middle");
+ assert.deepEqual(b.ok && [b.start, b.end], [3, 9]);
+ assert.match(HOW_SAID.middle, /inside/);
+});
+
+test("the cached window bounds it, and says so", () => {
+ const r = tightWindow({ clip: { start: 1.2, end: 7.4 }, cues: VID1, at: 4, lo: 0, hi: 7.5, snap: false });
+ assert.equal(r.ok, true);
+ if (!r.ok) return;
+ assert.equal(r.end, 7.5);
+ assert.match(r.said.join(" "), /past the cached window/);
+});
+
+test("already tight: unchanged", () => {
+ const r = tightWindow({ clip: { start: 3, end: 9 }, cues: VID1, snap: false });
+ assert.equal(r.ok && r.changed, false);
+});
+
+test("refusals: no cues, no boundary, a window with no edges", () => {
+ assert.equal(tightWindow({ clip: { start: 1, end: 2 }, cues: [] }).ok, false);
+ assert.equal(tightWindow({ clip: { start: 1, end: 2 }, cues: [{ start: 0, end: 3, text: "no end" }] }).ok, false);
+ assert.equal(tightWindow({ clip: /** @type {any} */ ({}), cues: VID1 }).ok, false);
+});
+
+test("nearestPause: the middle of the closest pause, within a second; bounded; said", () => {
+ const n = nearestPause(5.7, { words: WORDS, silences: SILENCES });
+ assert.equal(n.moved, true);
+ assert.ok(n.at > 5.85 && n.at < 6.2, `at ${n.at}`);
+ assert.match(String(snapSaid("end", n)), /^end 5\.70 → 6\.\d\d, into the pause/);
+ const far = nearestPause(20, { words: WORDS, silences: SILENCES });
+ assert.equal(far.moved, false);
+ assert.match(String(snapSaid("start", far)), /stays/);
+ assert.ok(pausesNear({ words: WORDS, silences: SILENCES }, 4, 5).length >= 1);
+});
+
+test("a playhead parked on an edge is not the place: the window decides", () => {
+ const r = tightWindow({ clip: { start: 1.2, end: 7.4 }, cues: VID1, at: 1.2, snap: false });
+ assert.equal(r.ok && r.how, "middle");
+ assert.deepEqual(r.ok && [r.start, r.end], [3, 9]);
+});
diff --git a/umtool/lib/report/ui-ops.test.mjs b/umtool/lib/report/ui-ops.test.mjs
@@ -0,0 +1,402 @@
+// Operations UI (UI notes 2026-10-30, #9 #10 #15 #18): the sites a cut's
+// links depend on and their deploys, the per-project link policy, the speaker
+// check, the render queue and a take's ETA.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+// SITES_DIR is read when lib/paths.mjs loads: point it at this file's own
+// sites before anything imports it.
+const SITES = await mkdtemp(path.join(tmpdir(), "ui-ops-sites-"));
+process.env.SITES_DIR = SITES;
+await mkdir(path.join(SITES, "anilyzer"), { recursive: true });
+await writeFile(path.join(SITES, "anilyzer", "site.json"), JSON.stringify({ siteTitle: "Anilyzer", siteUrl: "https://site.test/" }));
+await mkdir(path.join(SITES, "other"), { recursive: true });
+await writeFile(path.join(SITES, "other", "site.json"), JSON.stringify({ siteTitle: "Other", siteUrl: "https://other.test" }));
+test.after(() => rm(SITES, { recursive: true, force: true }));
+
+const { dayOf, deployBehindWhy, originOf, projectSites, sitesByOrigin } = await import("./siteDeploys.mjs");
+const { runLinkCheck } = await import("./linkCheck.mjs");
+const { decisionsFor } = await import("../projects/core.mjs");
+const { walkProjects } = await import("../projects/walk.mjs");
+
+const SITE = "https://site.test";
+const url = (chan, id, t, site = SITE) => `${site}/?v=${encodeURIComponent(`${chan}/${id}`)}&t=${t}`;
+const manifestOf = (timeline, extra = {}) => ({
+ schemaVersion: 1,
+ slug: "cut",
+ title: "Cut",
+ provenance: { channelSlug: "c", siteOrigin: SITE },
+ render: { width: 1920, height: 1080, fps: 30 },
+ timeline,
+ ...extra,
+});
+
+/** A fake archive: corpus.json generatedAt 2026-10-09, channel c holding `ids`. */
+function fakeSite(ids = ["v1"]) {
+ return async (u) => {
+ const p = new URL(String(u)).pathname;
+ const json = (doc) => ({ ok: true, status: 200, json: async () => doc });
+ if (p === "/corpus.json") {
+ return json({ spec: 5, generatedAt: "2026-10-09T10:00:00.000Z", site: { title: "Site" }, channels: [{ slug: "c", manifests: { transcripts: `${SITE}/transcripts/c/manifest.json` } }] });
+ }
+ if (p === "/transcripts/c/manifest.json") return json({ pageCount: 1, slugToPage: Object.fromEntries(ids.map((i) => [i, 0])) });
+ if (p === "/transcripts/c/page-0000.json") return json(ids.map((id) => ({ id })));
+ return { ok: false, status: 404, json: async () => ({}) };
+ };
+}
+
+/** A project in a temp root: channel c's v1..v3, each with cues and an upload date. */
+async function project(timeline, { uploads = {}, landed = {}, extra = {} } = {}) {
+ const root = await mkdtemp(path.join(tmpdir(), "ui-ops-"));
+ const channelsDir = path.join(root, "channels");
+ const reportsRoot = path.join(root, "reports");
+ for (const v of ["v1", "v2", "v3"]) {
+ const vdir = path.join(channelsDir, "c", "data", v);
+ await mkdir(vdir, { recursive: true });
+ const cues = Array.from({ length: 200 }, (_, i) => ({ start: i, end: i + 1, text: `Line ${i}.` }));
+ const file = path.join(vdir, "transcript.cues.json");
+ await writeFile(file, JSON.stringify({ cues, uploadDate: uploads[v] ?? "20260901", webpageUrl: `https://www.youtube.com/watch?v=${v}` }));
+ const at = new Date(landed[v] ?? "2026-09-02T00:00:00Z");
+ await utimes(file, at, at);
+ }
+ const dir = path.join(reportsRoot, "cut");
+ await mkdir(dir, { recursive: true });
+ const m = manifestOf(timeline.map((e) => ({ type: "clip", channel: "c", video: "v1", lock: true, ...e })), extra);
+ m.provenance.channelsDir = path.relative(dir, channelsDir);
+ await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(m, null, 2)}\n`);
+ const decisions = async () => {
+ const [ref] = (await walkProjects(reportsRoot)).filter((p) => p.id === "cut");
+ return decisionsFor(ref, reportsRoot);
+ };
+ const manifest = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+ return { root, reportsRoot, dir, channelsDir, decisions, manifest, done: () => rm(root, { recursive: true, force: true }) };
+}
+
+// ---- #9 the sites a cut's links depend on -----------------------------------
+
+test("originOf, dayOf, sitesByOrigin: a site is named by the origin of its siteUrl", () => {
+ assert.equal(originOf("https://site.test/"), "https://site.test");
+ assert.equal(originOf("mailto:x@y"), null);
+ assert.equal(dayOf("20261020"), "2026-10-20");
+ assert.equal(dayOf("2026-10-09T10:00:00.000Z"), "2026-10-09");
+ assert.equal(dayOf("soon"), null);
+ const s = sitesByOrigin(SITES);
+ assert.deepEqual(s.get("https://site.test"), { siteId: "anilyzer", title: "Anilyzer" });
+ assert.equal(sitesByOrigin(path.join(SITES, "nope")).size, 0);
+});
+
+test("projectSites: each origin with its deploy; videos newer than it, unless the check opened their link", () => {
+ const m = manifestOf([
+ { type: "clip", id: "a", video: "v1", start: 10, end: 20 },
+ { type: "clip", id: "b", video: "v2", start: 10, end: 20 },
+ { type: "clip", id: "c", video: "v3", start: 10, end: 20 },
+ { type: "clip", id: "d", video: "v3", start: 30, end: 40, citeUrl: url("c", "v3", 30, "https://other.test") },
+ { type: "clip", id: "y", video: "yt", start: 1, end: 2, citeUrl: "https://www.youtube.com/watch?v=yt&t=1s" },
+ ]);
+ const doc = {
+ checkedAt: "2026-11-01T10:00:00.000Z",
+ origins: { [SITE]: { state: "ok", generatedAt: "2026-10-09T10:00:00.000Z" } },
+ links: [
+ { clip: "a", url: url("c", "v1", 10), state: "ok" },
+ { clip: "b", url: url("c", "v2", 10), state: "dead" },
+ ],
+ };
+ const rec = { a: { uploadDate: "20261020" }, b: { uploadDate: "20261020" }, c: { uploadDate: "20260101", landedAt: "2026-10-21T08:00:00Z" }, d: { uploadDate: "20261030" } };
+ const sites = projectSites(m, doc, { sites: sitesByOrigin(SITES), recordOf: (id) => rec[id] ?? null });
+ assert.deepEqual(
+ sites.map((s) => [s.host, s.siteId, s.state, s.deployedAt, s.links, s.newer.map((n) => `${n.clip} ${n.why}`)]),
+ [
+ // a was opened by the check: on the site, whatever its date says.
+ ["site.test", "anilyzer", "ok", "2026-10-09T10:00:00.000Z", 3, ["b uploaded 2026-10-20", "c transcribed here 2026-10-21"]],
+ // Never checked: no deploy date, so nothing can be newer than it.
+ ["other.test", "other", "unchecked", null, 1, []],
+ ],
+ );
+ assert.equal(
+ deployBehindWhy(sites[0]),
+ "anilyzer's deploy is from 2026-10-09; 2 cited videos are newer: b (uploaded 2026-10-20), c (transcribed here 2026-10-21) — publish the site before the video ships, or link elsewhere",
+ );
+});
+
+test("the check: site-deploy-behind, one row per site with newer videos, its settle Publish <site>", async () => {
+ const p = await project(
+ [{ id: "a", video: "v1", start: 10, end: 20, cite: 10 }, { id: "b", video: "v2", start: 10, end: 20, cite: 10 }],
+ { uploads: { v2: "20261020" } },
+ );
+ try {
+ // Never checked: no deploy date, no row.
+ assert.equal((await p.decisions()).filter((d) => d.kind === "site-deploy-behind").length, 0);
+ // The site has v1 only (built 9 Oct); v2 was uploaded on the 20th.
+ await runLinkCheck(p.dir, await p.manifest(), { fetchImpl: fakeSite(["v1"]), cacheDir: null, gapMs: 0 });
+ const rows = (await p.decisions()).filter((d) => d.kind === "site-deploy-behind");
+ assert.equal(rows.length, 1);
+ assert.equal(rows[0].severity, "open");
+ assert.equal(rows[0].target, "site.test");
+ assert.match(rows[0].why, /^anilyzer's deploy is from 2026-10-09; 1 cited video is newer: b \(uploaded 2026-10-20\)/);
+ assert.deepEqual(rows[0].settle, { kind: "publish-site", siteId: "anilyzer", label: "Publish anilyzer" });
+ assert.equal(rows[0].fix, `pnpm ops build-deploy --json '{"siteId":"anilyzer"}'`);
+ assert.deepEqual(rows[0].clips, ["b"]);
+ // Redeployed with v2: the check opens it, and the row goes.
+ await runLinkCheck(p.dir, await p.manifest(), { fetchImpl: fakeSite(["v1", "v2"]), cacheDir: null, gapMs: 0 });
+ assert.equal((await p.decisions()).filter((d) => d.kind === "site-deploy-behind").length, 0);
+ } finally {
+ await p.done();
+ }
+});
+
+// ---- #10 the link policy ----------------------------------------------------
+
+const { normalizeLinkPolicy, policyBreaks, policyCiteUrl, policyFixLabel } = await import("./linkPolicy.mjs");
+const { addClip, insertEntry, updateLinkPolicy } = await import("./manifest.mjs");
+const { linkPolicyCommand } = await import("./linksCli.mjs");
+
+test("normalizeLinkPolicy: via an origin, direct slugs sorted; nothing is no policy; a stray key refuses", () => {
+ assert.deepEqual(normalizeLinkPolicy({ via: "https://site.test/x", direct: ["b", "a", "a"] }), { via: "https://site.test", direct: ["a", "b"] });
+ assert.deepEqual(normalizeLinkPolicy({ direct: "ho, side" }), { via: null, direct: ["ho", "side"] });
+ assert.equal(normalizeLinkPolicy({}), null);
+ assert.equal(normalizeLinkPolicy(null), null);
+ assert.throws(() => normalizeLinkPolicy({ via: "ftp://x" }), /a site's http\(s\) address/);
+ assert.throws(() => normalizeLinkPolicy({ sites: [] }), /has no key "sites"/);
+ assert.throws(() => normalizeLinkPolicy({ direct: ["no spaces"] }), /channel slugs/);
+});
+
+test("policyBreaks: a direct channel's archive link, another site's link, a platform link where the policy cites via; each with its fix", () => {
+ const m = manifestOf(
+ [
+ { type: "clip", id: "e1", channel: "ember", video: "v1", start: 10, end: 20, cite: 12 },
+ { type: "clip", id: "e2", channel: "ember", video: "v2", start: 10, end: 20, citeUrl: url("ember", "v2", 10, "https://other.test") },
+ { type: "clip", id: "e3", channel: "ember", video: "v3", start: 10, end: 20, citeUrl: "https://www.youtube.com/watch?v=v3&t=10s" },
+ { type: "clip", id: "h1", channel: "ho", video: "y1", start: 30, end: 40, cite: 31 },
+ { type: "clip", id: "h2", channel: "ho", video: "y2", start: 30, end: 40, citeUrl: "https://www.youtube.com/watch?v=y2&t=30s" },
+ { type: "clip", id: "h3", channel: "ho", video: "y3", start: 30, end: 40 },
+ { type: "clip", id: "s1", src: "media/own.mp4", start: 0, end: 4 },
+ ],
+ { provenance: { channelSlug: "ember", siteOrigin: SITE, linkPolicy: { direct: ["ho"] } } },
+ );
+ const web = { y1: "https://www.youtube.com/watch?v=y1", y2: "https://www.youtube.com/watch?v=y2" };
+ const b = policyBreaks(m, { webpageOf: (e) => web[e.video] ?? null });
+ assert.deepEqual(b.map((x) => [x.clip, x.want, x.fix]), [
+ ["e2", "via", url("ember", "v2", 10)],
+ ["e3", "via", url("ember", "v3", 10)],
+ ["h1", "direct", "https://www.youtube.com/watch?v=y1&t=31s"],
+ ["h3", "direct", null],
+ ]);
+ assert.match(b[0].why, /^the project's link policy cites via site\.test, but its QR opens other\.test$/);
+ assert.match(b[3].why, /^ho links direct by the project's link policy, but its QR opens site\.test — and its record names no platform page to link/);
+ assert.equal(policyFixLabel(b[0]), "Link via site.test");
+ assert.equal(policyFixLabel(b[2]), "Link its YouTube page");
+ // With no policy nothing breaks.
+ assert.deepEqual(policyBreaks({ ...m, provenance: { siteOrigin: SITE } }), []);
+});
+
+test("policyCiteUrl: a new clip of a direct channel gets its platform page; via another site gets that site; one that keeps it is left alone", () => {
+ const m = manifestOf([], { provenance: { channelSlug: "c", siteOrigin: SITE, linkPolicy: { via: "https://other.test", direct: ["ho"] } } });
+ assert.equal(policyCiteUrl(m, { type: "clip", channel: "ho", video: "y1", start: 5, end: 9, cutStart: 6 }, "https://www.youtube.com/watch?v=y1"), "https://www.youtube.com/watch?v=y1&t=6s");
+ assert.equal(policyCiteUrl(m, { type: "clip", channel: "ho", video: "y1", start: 5, end: 9 }, null), null);
+ assert.equal(policyCiteUrl(m, { type: "clip", video: "v1", start: 5, end: 9 }, null), url("c", "v1", 5, "https://other.test"));
+ assert.equal(policyCiteUrl(m, { type: "clip", video: "v1", start: 5, end: 9, citeUrl: url("c", "v1", 5, "https://other.test") }, null), undefined);
+});
+
+test("the inserters write the policy's link; the check's clip-link-policy rows and their one-press fix; the CLI", async () => {
+ const p = await project([
+ { id: "a", video: "v1", start: 10, end: 20, cite: 10 },
+ { id: "b", video: "v2", start: 10, end: 20, cite: 12 },
+ ]);
+ try {
+ // No policy: no rows.
+ assert.equal((await p.decisions()).filter((d) => d.kind === "clip-link-policy").length, 0);
+ // "These channels direct": channel c links YouTube.
+ const res = await updateLinkPolicy(p.dir, { direct: ["c"] });
+ assert.equal(res.changed, true);
+ assert.deepEqual((await p.manifest()).provenance.linkPolicy, { direct: ["c"] });
+ assert.equal((await updateLinkPolicy(p.dir, { direct: ["c"] })).changed, false, "a no-op writes nothing");
+ const rows = (await p.decisions()).filter((d) => d.kind === "clip-link-policy");
+ assert.deepEqual(rows.map((d) => [d.target, d.severity]), [["a", "open"], ["b", "open"]]);
+ assert.deepEqual(rows[1].settle, { kind: "patch", clip: "b", patch: { citeUrl: "https://www.youtube.com/watch?v=v2&t=12s" }, label: "Link its YouTube page" });
+ assert.equal(rows[1].fix, "umtool window cut b --cite-url 'https://www.youtube.com/watch?v=v2&t=12s'");
+ // A new clip (the strip's selection, an insert) is written by the policy.
+ const added = await addClip(p.dir, { video: "v3", cutStart: 40, cutEnd: 44 });
+ assert.equal(added.entry.citeUrl, "https://www.youtube.com/watch?v=v3&t=40s");
+ const ins = await insertEntry(p.dir, "a", { type: "clip", video: "v1", start: 50, end: 55, citeUrl: url("c", "v1", 50) });
+ assert.equal(ins.entry.citeUrl, "https://www.youtube.com/watch?v=v1&t=50s", "a copied archive link that breaks the policy is replaced");
+ // The CLI: what breaks it, then --fix through the window writer.
+ const lines = [];
+ const code = await linkPolicyCommand(["cut"], { root: p.reportsRoot, out: (s) => lines.push(s), err: (s) => lines.push(s) });
+ assert.equal(code, 1);
+ assert.match(lines.join("\n"), /cut: cite via provenance\.siteOrigin \(https:\/\/site\.test\); direct: c/);
+ assert.match(lines.join("\n"), /BREAKS {2}a {2}c links direct/);
+ const fixed = [];
+ assert.equal(await linkPolicyCommand(["cut", "--fix"], { root: p.reportsRoot, out: (s) => fixed.push(s), err: (s) => fixed.push(s) }), 0);
+ assert.match(fixed.join("\n"), /fixed a: https:\/\/site\.test\/\?v=c%2Fv1&t=10 -> https:\/\/www\.youtube\.com\/watch\?v=v1&t=10s/);
+ assert.equal((await p.decisions()).filter((d) => d.kind === "clip-link-policy").length, 0);
+ // --via by site id; --clear.
+ assert.equal(await linkPolicyCommand(["cut", "--via", "other", "--direct", ""], { root: p.reportsRoot, out: () => {}, err: () => {}, sitesDir: SITES }), 1);
+ assert.deepEqual((await p.manifest()).provenance.linkPolicy, { via: "https://other.test" });
+ assert.equal(await linkPolicyCommand(["cut", "--via", "nope"], { root: p.reportsRoot, out: () => {}, err: () => {}, sitesDir: SITES }), 2);
+ assert.equal(await linkPolicyCommand(["cut", "--clear"], { root: p.reportsRoot, out: () => {}, err: () => {} }), 0);
+ assert.equal("linkPolicy" in (await p.manifest()).provenance, false);
+ } finally {
+ await p.done();
+ }
+});
+
+// ---- #18 a take's ETA from the project's past renders --------------------
+
+const { etaText, parseDuration, pastRenders, projectEtas, slotWaitOf, takeEta } = await import("./takeEta.mjs");
+
+test("parseDuration / slotWaitOf: the heavy gate's waits, read from a render's log", () => {
+ assert.equal(parseDuration("35s"), 35);
+ assert.equal(parseDuration("2m10s"), 130);
+ assert.equal(parseDuration("1h02m"), 3720);
+ assert.equal(parseDuration("soon"), null);
+ assert.equal(slotWaitOf("heavy: waiting for memory — …\nheavy: 8879 MB available after 35s — admitted\nqueue-lock: the render let go after 2m10s — going on\n"), 165);
+ assert.equal(slotWaitOf("take x: done (1413.3 s)"), 0, "a take's done line is the video's length, not a wait");
+});
+
+test("pastRenders: recorded renderSeconds, else the take's files' times less its log's wait; a draft or a take with no length is not one", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "ui-ops-eta-"));
+ try {
+ const take = async (id, doc, { manifestAt = null, log = null } = {}) => {
+ const d = path.join(dir, "takes", id);
+ await mkdir(d, { recursive: true });
+ await writeFile(path.join(d, "take.json"), JSON.stringify({ id, group: "takes", order: 1, label: id, kind: "reference", preview: "preview.mp4", ...doc }));
+ if (manifestAt) {
+ await writeFile(path.join(d, "video.manifest.json"), "{}");
+ await utimes(path.join(d, "video.manifest.json"), new Date(manifestAt), new Date(manifestAt));
+ }
+ if (log) await writeFile(path.join(dir, `${id}.log`), log);
+ };
+ await take("d1", { seconds: 600, window: "full", builtAt: "2026-10-30T10:40:00.000Z" }, { manifestAt: "2026-10-30T10:00:00.000Z", log: "heavy: 9000 MB available after 4m00s — admitted\n" });
+ await take("d2", { seconds: 600, window: "full", builtAt: "2026-10-31T10:00:00.000Z", renderSeconds: 900, from: "d1" });
+ await take("d3", { seconds: 30, window: { at: 0, dur: 30 }, builtAt: "2026-10-31T11:00:00.000Z", renderSeconds: 90 });
+ await take("dr", { seconds: null, draft: true, builtAt: null });
+ const past = await pastRenders(dir);
+ assert.deepEqual(past.map((p) => [p.id, p.renderSeconds, p.how, p.window, p.from]), [
+ ["d1", 2160, "files", "full", null],
+ ["d2", 900, "recorded", "full", "d1"],
+ ["d3", 90, "recorded", "window", null],
+ ]);
+ const e = await projectEtas(dir);
+ assert.equal(e.seconds, 600);
+ assert.equal(e.newest, "d2");
+ assert.equal(e.fresh?.etaSeconds, 2160);
+ assert.equal(e.reuse?.etaSeconds, 900);
+ assert.equal(etaText(e.fresh?.etaSeconds), "36 min");
+ assert.equal(etaText(4000), "1 h 07 min");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("takeEta: the median rate of the same kind, times the length; none of its kind says so and uses the others", () => {
+ const past = [
+ { id: "a", seconds: 100, renderSeconds: 300, how: "recorded", window: "full", from: null, quick: false, builtAt: "1" },
+ { id: "b", seconds: 100, renderSeconds: 500, how: "recorded", window: "full", from: null, quick: false, builtAt: "2" },
+ { id: "c", seconds: 100, renderSeconds: 100, how: "recorded", window: "full", from: "b", quick: false, builtAt: "3" },
+ ];
+ const fresh = takeEta(past, { seconds: 200 });
+ assert.deepEqual([fresh?.etaSeconds, fresh?.rate, fresh?.basis.map((b) => b.id), fresh?.note], [800, 4, ["a", "b"], null]);
+ const reuse = takeEta(past, { seconds: 200, from: true });
+ assert.deepEqual([reuse?.etaSeconds, reuse?.basis.map((b) => b.id)], [200, ["c"]]);
+ const win = takeEta(past, { seconds: 60, window: "window" });
+ assert.equal(win?.etaSeconds, 180);
+ assert.match(String(win?.note), /no past fresh take of a window — from the project's other renders/);
+ assert.equal(takeEta([], { seconds: 60 }), null);
+});
+
+// ---- #15 the speaker check ------------------------------------------------
+
+const { execFileSync } = await import("node:child_process");
+const { fileURLToPath } = await import("node:url");
+const { encodeWav16 } = await import("yt-dlp-transcript-common/lib/montage/voiceMatch.mjs");
+const { VOICE_A, VOICE_B, syntheticVoice, withSilence } = await import("yt-dlp-transcript-common/testing/audio/syntheticVoice.mjs");
+const { PROJECT_KINDS } = await import("../projects/kinds.mjs");
+const sc = await import("./speakerCheck.mjs");
+
+const FAKE_EMBED = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "common", "testing", "audio", "fakeSpeakerEmbed.mjs");
+const hasFfmpeg = (() => {
+ try {
+ execFileSync("ffmpeg", ["-version"], { stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+})();
+
+test("speakers.json: names checked, a spec parsed, a clip added to one voice at a time", async () => {
+ assert.deepEqual(sc.normalizeSpeakers({ speakers: [{ name: " Ember ", clips: ["e01", "e01"], videos: ["ember/abc"] }] }), [{ name: "Ember", clips: ["e01"], videos: ["ember/abc"], channels: [] }]);
+ assert.throws(() => sc.normalizeSpeakers({ speakers: [{ name: "a/b" }] }), /no \/ = or comma/);
+ assert.throws(() => sc.normalizeSpeakers({ speakers: [{ name: "X" }, { name: "x" }] }), /two speakers are named "x"/);
+ assert.throws(() => sc.normalizeSpeakers({}), /speakers\.json is/);
+ assert.deepEqual(sc.parseSpeakerSpec("Kirsche=k01,kirsche/v9,channel:kirsche"), { name: "Kirsche", clips: ["k01"], videos: ["kirsche/v9"], channels: ["kirsche"] });
+ const dir = await mkdtemp(path.join(tmpdir(), "ui-ops-speakers-"));
+ try {
+ assert.deepEqual(await sc.readSpeakers(dir), []);
+ await sc.addClipToSpeaker(dir, "Ember", "e01");
+ await sc.addClipToSpeaker(dir, "Kirsche", "k01");
+ await sc.addClipToSpeaker(dir, "Kirsche", "e01");
+ assert.deepEqual((await sc.readSpeakers(dir)).map((s) => [s.name, s.clips]), [["Ember", []], ["Kirsche", ["k01", "e01"]]]);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("Check speaker is one job through the heavy slot, with its estimate", () => {
+ const plan = sc.speakerCheckSteps({ id: "reports/x" }, { clip: "k04", queueLock: "/repo/scripts/queue-lock.mjs" });
+ assert.equal(plan.kind, "speaker-check reports/x");
+ const argv = plan.steps[0].argv;
+ assert.deepEqual(argv.slice(1, 5), ["/repo/scripts/queue-lock.mjs", "--heavy", "--estimate", "800"]);
+ assert.deepEqual(argv.slice(argv.indexOf("speaker-check")), ["speaker-check", "reports/x", "--clip", "k04", "--progress", "ndjson"]);
+ assert.equal(sc.speakerCheckSteps({ id: "p" }, { queueLock: null }).steps[0].argv[0], "nice");
+});
+
+test("umtool speaker-check: each clip against the named voices, over a synthetic corpus; the walk's badge reads the row", { skip: !hasFfmpeg && "needs ffmpeg" }, async () => {
+ const root = await mkdtemp(path.join(tmpdir(), "ui-ops-speaker-"));
+ try {
+ const chans = path.join(root, "channels");
+ const encode = async (x, out) => {
+ await writeFile(`${out}.wav`, encodeWav16(x));
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-i", `${out}.wav`, "-c:a", "aac", "-b:a", "96k", out]);
+ await rm(`${out}.wav`);
+ };
+ const timeline = [];
+ for (const [id, voice, phase] of [["k01", VOICE_A, 0.3], ["k02", VOICE_A, 1.6], ["k03", VOICE_B, 0.8], ["k04", VOICE_A, 2.9]]) {
+ const d = path.join(chans, "chan", "data", `v${id}`);
+ await mkdir(path.join(d, "clips"), { recursive: true });
+ await writeFile(path.join(d, "transcript.cues.json"), JSON.stringify({ id: `v${id}`, cues: [{ start: 102.5, end: 104, text: "slow news day" }] }));
+ await encode(withSilence(syntheticVoice({ ...voice, seconds: 2.5, phase }), { before: 2, after: 3.5 }), path.join(d, "clips", "100.00-108.00.mp4"));
+ timeline.push({ type: "clip", id, channel: "chan", video: `v${id}`, start: 100, end: 108, cutStart: 102.5, cutEnd: 104, cite: 102.5, quote: "slow news day" });
+ }
+ const reportsRoot = path.join(root, "reports");
+ const dir = path.join(reportsRoot, "cut");
+ await mkdir(dir, { recursive: true });
+ const manifest = { schemaVersion: 1, slug: "cut", title: "Cut", kind: PROJECT_KINDS.find((k) => k.makesTakes).id, provenance: { channelsDir: "../../channels", channelSlug: "chan" }, render: {}, timeline };
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest));
+ const out = [];
+ const io = { reportsRoot, log: (s) => out.push(s), err: (s) => out.push(s), engine: { python: process.execPath, script: FAKE_EMBED, model: "fake.onnx" } };
+ // No voices yet: refused, saying how to name them.
+ assert.equal(await sc.speakerCheckCommand(["cut"], io), 2);
+ assert.match(out.join("\n"), /no voices to compare with: name them in speakers\.json/);
+ assert.equal(await sc.speakerCheckCommand(["cut", "--set", "Host=k01,k02", "--set", "Guest=k03"], io), 0);
+ out.length = 0;
+ assert.equal(await sc.speakerCheckCommand(["cut", "--clip", "k04"], io), 0, out.join("\n"));
+ assert.match(out.join("\n"), /k04 {3}matches Host \d\.\d\d \/ Guest 0\.\d\d/);
+ const doc = JSON.parse(await readFile(path.join(dir, "speaker-check.json"), "utf8"));
+ assert.deepEqual(Object.keys(doc.clips), ["chan/vk04@102.50"]);
+ const badge = await sc.speakerBadge(dir, manifest, "k04");
+ assert.equal(badge.result?.label, "matches");
+ assert.match(badge.result?.line ?? "", /^matches Host \d\.\d\d \/ Guest 0\.\d\d$/);
+ assert.deepEqual(badge.reference?.map((s) => [s.name, s.pieces]), [["Host", 2], ["Guest", 1]]);
+ assert.deepEqual(badge.speakers.map((s) => s.name), ["Host", "Guest"]);
+ // A clip with no row yet.
+ assert.equal((await sc.speakerBadge(dir, manifest, "k02")).result, null);
+ assert.equal(await sc.speakerCheckCommand(["cut", "--clip", "nope"], io), 2);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/variantFork.mjs b/umtool/lib/report/variantFork.mjs
@@ -0,0 +1,244 @@
+// FORK A TAKE AS A VARIANT, and the takes of a project's variants side by
+// side (UI notes 2026-10-30, item 19: "variants as separate project copies"
+// -- `emberparadox/v-a-cold-open` … `v-d-bookends`, each copied by hand from
+// the walked cut, a README saying what it was).
+//
+// HOW A VARIANT IS STORED, as those were: a project of its own BESIDE its
+// parent (a project is a leaf of the walk, lib/projects/walk.mjs, so it
+// cannot sit inside one), so every tool -- the walk, the cut, takes, Deliver
+// -- works on it unchanged. What the fork adds is the record the hand copies
+// carried only in prose:
+//
+// <folder>/<name>/video.manifest.json the take's manifest (the one it was
+// rendered from; a draft's, resolved),
+// its `slug` the variant's name
+// <folder>/<name>/variant.json { variantOf, fromTake, takeLabel,
+// forkedAt, baseHash } -- what makes it
+// a variant of <parent>, and of which take
+// <folder>/<name>/README.md the hand copies' sentence, written
+// <folder>/<name>/out/clips-raw, LINKS to the parent's (a take's own
+// out/narration out/ links them the same way): the
+// fetched media is reused, never copied
+// <folder>/<name>/<asset> a link to the parent's, for each of its
+// top-level files or folders the manifest
+// names by a relative path (shots/, posts-
+// media/ …), so those paths still resolve;
+// module-config.json is COPIED (a variant's
+// modules are its own to change)
+// <folder>/<name>/takes/<take>/ the take itself, its preview a HARD
+// LINK (no copy of the bytes), its
+// take.json naming where it came from --
+// so the variant opens with the take it
+// was forked from, already rendered
+//
+// Refused: a take that is rendering now (its manifest is being written), a
+// name that is not one path segment or is already taken.
+//
+// `variantFamily` reads it back: the parent and every project beside it whose
+// variant.json names it -- whose takes the compare page lays side by side.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { copyFile, link, lstat, mkdir, readdir, readFile, rename, stat, symlink, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { isSegment, walkProjects } from "../projects/walk.mjs";
+import { renderHolds } from "./takeHousekeeping.mjs";
+import { MANIFEST, PREVIEW, SHARED_OUT, hashText } from "./takeMaker.mjs";
+import { isTakeId, listTakes, takesDirOf, TAKE_FILE } from "./takes.mjs";
+
+export const VARIANT_FILE = "variant.json";
+/** Copied, never linked: what a variant may change of its own. */
+const COPIED = ["module-config.json"];
+/** Never linked or copied: the project's own state. */
+const OWN = new Set(["out", "takes", "revisions", "exports", "notes.json", MANIFEST, VARIANT_FILE, "README.md", ...COPIED]);
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const readJson = (file) => readFile(file, "utf8").then((t) => JSON.parse(t), () => null);
+const exists = (p) => lstat(p).then(() => true, () => false);
+async function writeAtomic(file, text) {
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, text, "utf8");
+ await rename(tmp, file);
+}
+
+export class ForkRefused extends Error {
+ /** @param {string} message @param {number} [status] */
+ constructor(message, status = 409) {
+ super(message);
+ this.status = status;
+ }
+}
+
+/** A project's variant.json, checked, or null. */
+export async function readVariant(dir) {
+ const v = await readJson(path.join(dir, VARIANT_FILE));
+ return isObj(v) && typeof v.variantOf === "string" && v.variantOf ? v : null;
+}
+
+/** The default name for a fork of `take`: `v-<take>`. */
+export const defaultVariantName = (take) => `v-${take}`.slice(0, 64);
+
+/**
+ * Every relative path a manifest names whose first segment is an entry of the
+ * project directory (`shots/x.png` → `shots`), the project's own state left out.
+ *
+ * @param {unknown} manifest
+ * @param {Set<string>} entries the project directory's entries
+ */
+export function referencedAssets(manifest, entries) {
+ const out = new Set();
+ const walk = (v) => {
+ if (typeof v === "string") {
+ if (!v || v.length > 512 || path.isAbsolute(v) || /^[a-z]+:\/\//i.test(v) || v.includes("..")) return;
+ const first = v.split(/[\\/]/)[0];
+ if (first && entries.has(first) && !OWN.has(first)) out.add(first);
+ return;
+ }
+ if (Array.isArray(v)) for (const x of v) walk(x);
+ else if (isObj(v)) for (const x of Object.values(v)) walk(x);
+ };
+ walk(manifest);
+ return [...out].sort();
+}
+
+/**
+ * Fork take `takeId` of `project` as a variant: a project beside it (see the header).
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {string} takeId
+ * @param {{ name?: string | null, now?: () => Date }} [opts]
+ * @returns {Promise<{ id: string, dir: string, name: string, take: { id: string, linked: boolean } | null, links: string[], copied: string[], variant: Record<string, unknown> }>}
+ */
+export async function forkTakeAsVariant(project, takeId, { name = null, now = () => new Date() } = {}) {
+ if (!isTakeId(takeId)) throw new ForkRefused("not a take id", 400);
+ const listing = await listTakes(project.dir);
+ const take = listing.takes.find((t) => t.id === takeId);
+ if (!take) throw new ForkRefused(`${project.id} has no take ${takeId}`, 404);
+ const holds = (await renderHolds(project.dir, takeId)).filter((h) => h.startsWith("it is rendering"));
+ if (holds.length) throw new ForkRefused(`take ${takeId} is not forked: ${holds[0]}`);
+ const vname = String(name ?? "").trim() || defaultVariantName(takeId);
+ if (!isSegment(vname) || vname.length > 64) throw new ForkRefused(`"${vname}" is not a project name: letters, digits, . _ - (one segment)`, 400);
+ const parentDir = path.dirname(project.dir);
+ const dir = path.join(parentDir, vname);
+ if (await exists(dir)) throw new ForkRefused(`${vname} exists beside ${project.id} — name the variant something else`);
+ const folder = path.posix.dirname(project.id);
+ const id = folder === "." ? vname : `${folder}/${vname}`;
+
+ // The take's manifest: the one it was rendered from, else (a draft) resolved from its patch.
+ const takeDir = path.join(takesDirOf(project.dir), takeId);
+ let manifest = await readJson(path.join(takeDir, MANIFEST));
+ if (!isObj(manifest)) {
+ const { resolveTakeManifest } = await import("./takeManifest.mjs");
+ manifest = (await resolveTakeManifest(project.dir, takeId)).manifest;
+ }
+ if (!isObj(manifest) || !Array.isArray(manifest.timeline)) throw new ForkRefused(`take ${takeId} has no manifest to fork`, 422);
+ const doc = { ...manifest, slug: vname };
+ const text = JSON.stringify(doc, null, 2) + "\n";
+
+ await mkdir(dir);
+ await writeAtomic(path.join(dir, MANIFEST), text);
+ const variant = {
+ variantOf: project.id,
+ fromTake: takeId,
+ takeLabel: take.label,
+ forkedAt: now().toISOString(),
+ baseHash: hashText(text),
+ };
+ await writeAtomic(path.join(dir, VARIANT_FILE), JSON.stringify(variant, null, 2) + "\n");
+ await writeAtomic(
+ path.join(dir, "README.md"),
+ `# ${vname}\n\nA variant of \`${project.id}\`, forked ${variant.forkedAt.slice(0, 10)} from its take \`${takeId}\` (${take.label}).\n` +
+ `Its manifest is that take's; its clips' media is the parent's (out/clips-raw is a link).\n`,
+ );
+
+ // The fetched media and the voices, linked as a take's out/ links them.
+ const links = [];
+ await mkdir(path.join(dir, "out"), { recursive: true });
+ for (const n of SHARED_OUT) {
+ const src = path.join(project.dir, "out", n);
+ if (!(await stat(src).then((s) => s.isDirectory(), () => false))) continue;
+ await symlink(src, path.join(dir, "out", n));
+ links.push(`out/${n}`);
+ }
+ // The project's files the manifest names by a relative path, linked; its own config copied.
+ const entries = new Set(await readdir(project.dir).catch(() => []));
+ for (const seg of referencedAssets(doc, entries)) {
+ await symlink(path.join(project.dir, seg), path.join(dir, seg));
+ links.push(seg);
+ }
+ const copied = [];
+ for (const n of COPIED) {
+ if (!entries.has(n)) continue;
+ await copyFile(path.join(project.dir, n), path.join(dir, n));
+ copied.push(n);
+ }
+
+ // The take itself: its preview hard-linked (a rendered take), its manifest and take.json beside it.
+ let forkedTake = null;
+ const preview = path.join(takeDir, take.preview || PREVIEW);
+ if (!take.draft && (await stat(preview).then((s) => s.isFile(), () => false))) {
+ const dst = path.join(takesDirOf(dir), takeId);
+ await mkdir(dst, { recursive: true });
+ let linked = true;
+ try {
+ await link(preview, path.join(dst, PREVIEW));
+ } catch {
+ linked = false;
+ }
+ if (linked) {
+ await writeAtomic(path.join(dst, MANIFEST), text);
+ const raw = (await readJson(path.join(takeDir, TAKE_FILE))) ?? {};
+ const tj = {
+ ...raw,
+ id: takeId,
+ preview: PREVIEW,
+ // The variant's manifest IS this take's: nothing patched over it.
+ kind: "reference",
+ patch: null,
+ style: null,
+ changes: [],
+ baseHash: variant.baseHash,
+ forkedFrom: { project: project.id, take: takeId },
+ };
+ delete tj.draft;
+ await writeAtomic(path.join(dst, TAKE_FILE), JSON.stringify(tj, null, 2) + "\n");
+ }
+ forkedTake = { id: takeId, linked };
+ }
+ return { id, dir, name: vname, take: forkedTake, links, copied, variant };
+}
+
+/**
+ * A project's variant family: its parent (itself, when it is no variant) and
+ * every project beside the parent whose variant.json names it, each with its
+ * takes. `self` is the project asked about.
+ *
+ * @param {{ id: string, dir: string }} project
+ * @param {{ root: string }} o the reports root (the walk)
+ * @returns {Promise<{ parent: string, members: Array<{ id: string, dir: string, variantOf: string | null, fromTake: string | null, takeLabel: string | null, forkedAt: string | null, takes: Array<Record<string, any>> }> }>}
+ */
+export async function variantFamily(project, { root }) {
+ const own = await readVariant(project.dir);
+ const parentId = own?.variantOf ?? project.id;
+ const all = await walkProjects(root);
+ const parent = all.find((p) => p.id === parentId) ?? null;
+ const folder = path.posix.dirname(parentId);
+ const beside = all.filter((p) => path.posix.dirname(p.id) === folder);
+ const members = [];
+ for (const p of beside) {
+ const v = p.id === parentId ? null : await readVariant(p.dir);
+ if (p.id !== parentId && v?.variantOf !== parentId) continue;
+ const listing = await listTakes(p.dir).catch(() => ({ takes: [] }));
+ members.push({
+ id: p.id,
+ dir: p.dir,
+ variantOf: v?.variantOf ?? null,
+ fromTake: typeof v?.fromTake === "string" ? v.fromTake : null,
+ takeLabel: typeof v?.takeLabel === "string" ? v.takeLabel : null,
+ forkedAt: typeof v?.forkedAt === "string" ? v.forkedAt : null,
+ takes: listing.takes,
+ });
+ }
+ // The parent first, then its variants by name.
+ members.sort((a, b) => (a.id === parentId ? -1 : b.id === parentId ? 1 : a.id.localeCompare(b.id)));
+ return { parent: parent ? parentId : parentId, members };
+}
diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts
@@ -221,6 +221,11 @@ export default defineConfig({
// so a take made here never joins — and the banner never shows — the
// machine's render mode, and a --priority take holds the stub's lanes.
`RENDER_PRIORITY_FILE=${FIXTURE}/render-priority.json ` +
+ // The heavy slot the render queue panel reads (common/lib/heavyQueue.mjs,
+ // UI notes #18): the fixture's own, so ui-ops.spec writes the tickets it
+ // asserts and never reads the machine's. A take made here still passes
+ // through the slot this suite holds (HEAVY_HELD), touching no lock.
+ `HEAVY_LOCK_FILE=${FIXTURE}/heavy/heavy-queue.lock ` +
// Two seconds of pacing per CUT, so the deliver spec can press Stop in
// the middle of a job and prove that cancelling abandons the rest while
// the next run resumes. Read only by bin/cut-from-cache.mjs.
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -27,6 +27,7 @@
"./claims": "./claims.mjs",
"./clip-audio": "./clip-audio.mjs",
"./clip-blur": "./clip-blur.mjs",
+ "./clip-words": "./clip-words.mjs",
"./compose-chrome": "./compose-chrome.mjs",
"./counter": "./counter.mjs",
"./cues": "./cues.mjs",