commit ff940e0e62715313d424ccb30f69047e64cc4d44
parent 453f353604e999710a85fd87fcb7ebd4e11ff09c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 10 Nov 2026 09:31:13 -0500
Merge main into lane/needs-you: lane/agent-to-ui (L6), lane/drive-stall
PlayCut.tsx and make-fixture.mjs: both imports kept.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
89 files changed, 5906 insertions(+), 60 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -281,7 +281,9 @@ job resume-interrupted does by hand what the editor does at boot: re-queues
get settings [<key>] is settings.json as the editor reads it (migrated and
defaulted; a secret is "<redacted>"), or one top-level key of it.
-get storage is /storage: each location, mounted or not, free space, tiers.
+get storage is /storage: each location, mounted or not, free space, tiers,
+ and its drive's health (rows[].drive: ok | slow | stalled | unmounted,
+ since, lastOkAt, latencyMs, the cause and the one-line text).
get saved-alternates [<slug>] lists every saved video holding two copies:
a download over a container already in the store keeps both — an
explicit persist (persist-videos, Persist source video, a whole-recording
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md
@@ -106,7 +106,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not
| `AUDIO_CHECK_BACKOFF_FACTOR` | the built-in factor | The audio check's interval backoff factor, in (0, 1], for a one-off run. | common/ytdlp/audioCheckedDownload.ts |
| `ARCHILYZER_STATS_ALLOW_DOWNGRADE` | off | `1` lets a stats build clear a stats cache that a NEWER build wrote, for a deliberate rollback. Unset, such a build refuses and names both versions. | common/controller/buildStats.ts |
| `ARCHILYZER_INDEX_ALLOW_HELD` | off | `1` lets a FULL index rebuild (a schema change, or no index yet) proceed while a channel's media cannot be read; that channel stays out of the index until its media is back and the index is built again. Unset, such a build refuses and names each channel. | common/controller/buildIndex.ts |
-| `UV_THREADPOOL_SIZE` | `16` for the editor (`4` is Node's own) | Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive. | Node's libuv (set by editor/package.json `start` and docker/entrypoint.sh) |
+| `UV_THREADPOOL_SIZE` | `16` for the editor (`4` is Node's own) | Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive. | Node's libuv (set by editor/package.json `start` and `dev`, the archilyzer-editor.service unit `archilyzer service install` writes, and docker/entrypoint.sh) |
| `MCP_IO_STATS` | off | `1` turns on per-call I/O accounting, for `mcp/bench`. | common/lib/archive/io-stats.ts |
| `ARCHILYZER_EDITOR_URL` | `http://localhost:3001` | Which editor `pnpm ops`, `archilyzer gen` and the MCP's editor-backed tools (`fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate`, `get_transcript`'s fallback) talk to, and whose `/api/pulse` `archilyzer storage migrate-tier` asks before it refuses to run beside it. | scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, umtool, common/bin/migrate-media-tier.ts |
| `ARCHILYZER_AGENT` | `cli` | Who is asking, recorded as the provenance of a curated-tag write through `pnpm ops`. | scripts/archilyzer-ops.mjs |
diff --git a/common/controller/operationBatch.ts b/common/controller/operationBatch.ts
@@ -41,8 +41,10 @@ import { isGateHeld } from "../lib/pauseGates";
import {
assertChannelMediaReachable,
assertChannelTextReadable,
+ readChannelMediaConfig,
readRelocationMarker,
} from "../lib/channelMedia";
+import { mediaStallHold } from "../lib/mediaStallHold";
import { runPool } from "../jobs/concurrentRunner";
import type { TaskTracker } from "../jobs/taskHooks";
import type { JobProgress } from "../jobs/registry";
@@ -1601,6 +1603,16 @@ export async function runOperationBatch(
} else {
await assertChannelMediaReachable(opts.paths, opts.channelSlug);
}
+ // THE BACKFILL LANE OPENS MEDIA, so it holds while the channel's media drive
+ // is not answering (lib/mediaStallHold.ts); the digest lane reads text only.
+ const stallHold = run.digest
+ ? null
+ : mediaStallHold(
+ await readChannelMediaConfig(opts.paths, opts.channelSlug),
+ log,
+ "backfill unit",
+ { reloadConfig: () => readChannelMediaConfig(opts.paths, opts.channelSlug) },
+ );
const dataDir = path.join(opts.paths.channelsDir, opts.channelSlug, "data");
const allDirs = await readdir(dataDir).catch(() => [] as string[]);
const onDisk = new Set(allDirs);
@@ -1851,6 +1863,7 @@ export async function runOperationBatch(
next,
run: runOne,
limit: () => {
+ if (stallHold?.check()) return 0;
const live = operationLaneLive(run, opts.concurrency);
const verdict = laneLimit(getSettings(), live);
if (verdict.hold) {
diff --git a/common/controller/operationBatchRelocation.test.ts b/common/controller/operationBatchRelocation.test.ts
@@ -26,6 +26,9 @@ const ROOT = mkdtempSync(path.join(os.tmpdir(), "batch-relocation-"));
process.env.TRANSCRIPTS_DIR = ROOT;
const SETTINGS_FILE = path.join(ROOT, "settings.json");
process.env.SETTINGS_FILE = SETTINGS_FILE;
+// No engine ever runs: the one case that dispatches (the drive-stall hold,
+// below) gets an "engine" that exits 1 at once.
+process.env.DIARIZE_BIN = "/bin/false";
// The backfill lane armed with ONE operation, and that operation's cheapest
// classification: every seeded video has a transcript and no audio, so
@@ -141,3 +144,70 @@ test("a marker written mid-run ends the batch instead of racing the copy", async
assert.ok(stop, `expected a stop line, got:\n${lines.join("\n")}`);
assert.match(stop as string, /\(out\) of omni to \/platter\/omni\/data/);
});
+
+// A DRIVE THAT STOPS ANSWERING MID-RUN HOLDS THE BATCH (lane drive-stall). The
+// start-of-work guard passed (the drive answered); the second pull finds the
+// channel's media location stalled in the health record, and the pool's limit
+// is 0 until it answers again — nothing is dispatched onto a drive that would
+// hold a file thread per unit, nothing is failed, and the run resumes.
+test("a media drive that stops answering mid-run holds the backfill batch until it answers", async () => {
+ const {
+ recordLocationHealth,
+ registerLocationHealth,
+ resetStorageHealth,
+ } = await import("../lib/storageHealth");
+ resetStorageHealth();
+ await seed("held", ["v1", "v2"]);
+ const platter = path.join(ROOT, "platter");
+ const mediaDir = path.join(platter, "held", "media");
+ await mkdir(mediaDir, { recursive: true });
+ const channelDir = path.join(getPaths().channelsDir, "held");
+ const { symlink } = await import("node:fs/promises");
+ await symlink(mediaDir, path.join(channelDir, "media"));
+ await writeFile(
+ path.join(channelDir, "config.json"),
+ JSON.stringify({ handling: "transcribe", url: "https://example.com/c", mediaDir }),
+ );
+ // Audio on both, so diarization dispatches (and fails on the fixture's
+ // missing models — what is under test is when it is dispatched).
+ for (const id of ["v1", "v2"]) {
+ await writeFile(path.join(channelDir, "data", id, "audio.mp3"), "ID3audio");
+ }
+ const loc = { id: "platter", label: "Platter", root: platter };
+ registerLocationHealth([loc]);
+
+ // The pool's idle poll is unref'd (a server keeps the loop alive; a test
+ // process would exit under a paused pool).
+ const keepAlive = setInterval(() => {}, 1_000);
+ let progressCalls = 0;
+ const lines: string[] = [];
+ const result = await runOperationBatch({
+ lane: "backfill",
+ channelSlug: "held",
+ paths: getPaths(),
+ operationIds: ["diarization"],
+ onLog: (m) => lines.push(m),
+ setProgress: () => {
+ progressCalls++;
+ if (progressCalls !== 2) return;
+ recordLocationHealth(loc, "stalled", { cause: "test: no answer" });
+ // It answers again a moment later: two clean answers clear it.
+ setTimeout(() => {
+ recordLocationHealth(loc, "ok");
+ recordLocationHealth(loc, "ok");
+ }, 300);
+ },
+ });
+ clearInterval(keepAlive);
+ // Both videos were dispatched in the end (and failed on the fake engine):
+ // held, not dropped.
+ assert.equal(result.attempted, 2);
+ const at = (prefix: string) => lines.findIndex((l) => l.startsWith(prefix));
+ const v1 = at("Diarize v1 start");
+ const hold = at("Holding: the media drive");
+ const resume = at(`The media drive "Platter" answers again — resuming.`);
+ const v2 = at("Diarize v2 start");
+ assert.ok(v1 >= 0 && hold > v1 && resume > hold && v2 > resume, `the order was:\n${lines.join("\n")}`);
+ assert.match(lines[hold], /"Platter" is not answering \(since \d\d:\d\d\) — no new backfill unit starts/);
+ resetStorageHealth();
+});
diff --git a/common/controller/persistKept.test.ts b/common/controller/persistKept.test.ts
@@ -59,6 +59,7 @@ test("persistKept is a no-op when keep-latest is off", async () => {
persisted: 0,
failed: 0,
skippedNoUrl: 0,
+ skippedStoreUnavailable: 0,
skippedLowDisk: 0,
});
});
@@ -83,3 +84,35 @@ test("persistKept counts in-window videos already saved without re-downloading",
assert.equal(res.skippedNoUrl, 0);
});
});
+
+// A STORE THAT CANNOT TAKE A CONTAINER STOPS THE PASS BEFORE ANY FETCH (review
+// of lane drive-stall): the store's drive is not answering, so nothing is
+// downloaded to land nowhere; every unsaved kept video is counted skipped.
+test("persistKept stops before fetching when the saved-video store's drive is not answering", async () => {
+ const { recordLocationHealth, resetStorageHealth } = await import("../lib/storageHealth");
+ await withPaths(async (paths) => {
+ for (const id of ["20240101_a", "20240202_b", "20240303_c"]) {
+ await mkdir(path.join(paths.channelsDir, "alpha", "data", id), { recursive: true });
+ }
+ recordLocationHealth(
+ { id: "store", label: "Store drive", root: path.dirname(paths.savedVideosDir) },
+ "stalled",
+ );
+ const lines: string[] = [];
+ try {
+ const res = await persistKept({
+ paths,
+ channelSlug: "alpha",
+ channelConfig: { handling: "transcribe", keepLatest: 2 },
+ onLog: (l: string) => lines.push(l),
+ });
+ assert.equal(res.kept, 2);
+ assert.equal(res.persisted, 0);
+ assert.equal(res.failed, 0);
+ assert.equal(res.skippedStoreUnavailable, 2);
+ assert.match(lines.join("\n"), /The saved-video store's drive "Store drive" is not answering .* — stopping/);
+ } finally {
+ resetStorageHealth();
+ }
+ });
+});
diff --git a/common/controller/persistKept.ts b/common/controller/persistKept.ts
@@ -5,6 +5,8 @@ import { getSettings } from "../lib/settings";
import { diskGate } from "../lib/diskSpace";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import { isSavedVideo } from "../lib/savedVideo-server";
+import { savedVideoDir } from "../lib/savedVideo";
+import { savedVideosStoreRefusal } from "../lib/savedVideoStore";
import { computeKeptVideoIds } from "./keptVideos";
import { findVideoSourceUrl } from "./undownloadedVideos";
import {
@@ -40,6 +42,9 @@ export type PersistKeptResult = {
failed: number;
// No resolvable source URL (no metadata + not in the playlist).
skippedNoUrl: number;
+ // Not attempted because the saved-video store could not take a container
+ // (its drive not answering, or mid-move) — asked before each fetch.
+ skippedStoreUnavailable: number;
// Not attempted because free disk fell under the floor part-way through. A
// refusal to start, not a failure — these videos are still kept, still
// unpersisted, and the next pass picks them up.
@@ -81,6 +86,7 @@ export async function persistKept({
failed: 0,
skippedNoUrl: 0,
skippedLowDisk: 0,
+ skippedStoreUnavailable: 0,
};
if (keptIds.size === 0) {
log(
@@ -105,17 +111,35 @@ export async function persistKept({
// Set once the disk gate closes mid-pass. Everything after it is counted as
// skipped rather than attempted, so the log says how much was left.
let lowDisk = false;
+ let storeUnavailable = false;
for (const videoId of ordered) {
if (signal?.aborted) break;
if (lowDisk) {
result.skippedLowDisk += 1;
continue;
}
+ if (storeUnavailable) {
+ result.skippedStoreUnavailable += 1;
+ continue;
+ }
const videoDir = path.join(dataDir, videoId);
if (await isSavedVideo(videoDir)) {
result.alreadySaved += 1;
continue;
}
+ // THE STORE MUST BE ABLE TO TAKE IT (review of lane drive-stall): asked
+ // before the fetch, so a stalled store drive or a store mid-move stops the
+ // pass instead of downloading containers that land nowhere.
+ const refusal = await savedVideosStoreRefusal(
+ paths,
+ savedVideoDir(paths, channelConfig, channelSlug, videoId),
+ );
+ if (refusal) {
+ storeUnavailable = true;
+ result.skippedStoreUnavailable += 1;
+ log(` ${videoId}: ${refusal.message} — stopping; remaining videos skipped.`);
+ continue;
+ }
// PER ITEM, not once at the start. This pass writes full source containers —
// the largest files the app produces — so the twentieth video must not
// inherit the first one's headroom. Same shape as backfillReacquire's
@@ -175,6 +199,9 @@ export async function persistKept({
(result.skippedLowDisk > 0
? `, ${result.skippedLowDisk} skipped (low disk)`
: "") +
+ (result.skippedStoreUnavailable > 0
+ ? `, ${result.skippedStoreUnavailable} skipped (saved-video store unavailable)`
+ : "") +
` of ${result.kept} kept.`,
);
return result;
diff --git a/common/controller/persistVideos.test.ts b/common/controller/persistVideos.test.ts
@@ -538,3 +538,30 @@ test("a dry run buckets every item and fetches nothing", async () => {
assert.equal(res.plan.willFetch, 2);
});
});
+
+// A STORE THAT CANNOT TAKE A CONTAINER STOPS THE RUN BEFORE THE FETCH (review
+// of lane drive-stall): its drive is not answering, so no container is
+// downloaded only to be left in the data dir.
+test("a saved-video store whose drive is not answering stops the run before any fetch", async () => {
+ const { recordLocationHealth, resetStorageHealth } = await import("../lib/storageHealth");
+ await withPaths(async (paths) => {
+ for (const id of ["aaa111", "bbb222"]) await seedVideo(paths, "demo-channel", id);
+ recordLocationHealth(
+ { id: "store", label: "Store drive", root: path.dirname(paths.savedVideosDir) },
+ "stalled",
+ );
+ try {
+ const h = harness(paths);
+ const res = await persistVideos({
+ paths,
+ items: ["aaa111", "bbb222"].map((id) => ({ slug: "demo-channel", id })),
+ deps: h.deps,
+ });
+ assert.deepEqual(h.downloads, []);
+ assert.equal(res.stopped, "store-unavailable");
+ assert.deepEqual(res.notAttempted.map((i) => i.id), ["aaa111", "bbb222"]);
+ } finally {
+ resetStorageHealth();
+ }
+ });
+});
diff --git a/common/controller/persistVideos.ts b/common/controller/persistVideos.ts
@@ -5,9 +5,10 @@ import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
import { getSettings } from "../lib/settings";
import { diskGate, type DiskGateStatus } from "../lib/diskSpace";
+import { savedVideosStoreRefusal } from "../lib/savedVideoStore";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import type { DownloadOutcomeRecord } from "../lib/downloadOutcome";
-import type { SavedVideoPointer } from "../lib/savedVideo";
+import { savedVideoDir, type SavedVideoPointer } from "../lib/savedVideo";
import {
loadSavedVideo,
restoreSavedVideoProvenance,
@@ -94,7 +95,15 @@ export type PersistVideosPlan = {
willFetch: number;
};
-export type PersistVideosStop = "low-disk" | "rate-limit" | "cancelled" | "drained";
+// `store-unavailable`: the saved-video store cannot take a container (its
+// drive is not answering, or it is being moved) — the run stops before
+// downloading one only to leave it in the data dir.
+export type PersistVideosStop =
+ | "low-disk"
+ | "rate-limit"
+ | "store-unavailable"
+ | "cancelled"
+ | "drained";
export type PersistVideosResult = {
plan: PersistVideosPlan;
@@ -459,6 +468,18 @@ export async function persistVideos({
stop("low-disk", i);
break;
}
+ // THE STORE MUST BE ABLE TO TAKE IT, asked before the fetch: a stalled
+ // drive or a store mid-move would refuse the container after a whole
+ // download. Memory and the corpus disk only.
+ const refusal = await savedVideosStoreRefusal(
+ paths,
+ savedVideoDir(paths, config, p.slug, p.id),
+ );
+ if (refusal) {
+ log(` ${label(p)}: ${refusal.message} — stopping; the rest are left for a later run.`);
+ stop("store-unavailable", i);
+ break;
+ }
const replacing = p.bucket === "wrongHeight";
log(
` ${label(p)}: ${replacing ? "replacing the saved container" : "fetching the source container"} (${quality})…`,
diff --git a/common/controller/storageWatch.test.ts b/common/controller/storageWatch.test.ts
@@ -24,6 +24,7 @@ import {
import { inspectChannelMedia } from "../lib/channelMedia";
import {
applyHealthTimings,
+ driveHealthView,
healthTimings,
locationHealth,
resetStorageHealth,
@@ -661,3 +662,98 @@ test("DT: a changed pass interval re-arms the armed pass; an explicit interval f
}
});
});
+
+// THE PASS'S WRITE WAITS FOR THE SETTINGS LOCK (lane drive-stall). The
+// editor's priority writer holds the per-process lock on settings.json for its
+// whole read-modify-write (editor/app/settings/saveSettings.ts,
+// `withSettingsLock`); a pass that wrote in the middle of it would be written
+// over by the writer's stale document, and the pause lost.
+test("the pass writes under the settings lock: a writer holding it is not interleaved", async () => {
+ const { withJsonFileLock } = await import("../lib/jsonFile-server");
+ const { getPaths } = await import("../lib/paths");
+ await withTmp(async (h) => {
+ await seedRelocated(h, "gone", { targetExists: false });
+ await seedRelocated(h, "other", { targetExists: true });
+ const pass = () => runStorageWatchPass({ paths: h.paths, io: h.io, bins: h.paths });
+ await pass(); // the suspicion
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const order: string[] = [];
+ // The "priority writer": reads, waits while holding the lock, writes.
+ const writer = withJsonFileLock(getPaths().settingsFile, async () => {
+ const before = h.io.read();
+ await gate;
+ order.push("writer");
+ await h.io.write({
+ ...before,
+ channelPriority: sanitizeChannelPriority({
+ ...before.channelPriority,
+ channels: { ...before.channelPriority.channels, other: { tier: "low" } },
+ }),
+ });
+ });
+ const confirming = pass().then((r) => {
+ order.push("pass");
+ return r;
+ });
+ // Give the pass every chance to write while the lock is held.
+ await new Promise((r) => setTimeout(r, 50));
+ assert.equal(h.writes, 0, "the pass did not write while the lock was held");
+ release();
+ await writer;
+ const second = await confirming;
+ assert.deepEqual(second.paused, ["gone"]);
+ assert.deepEqual(order, ["writer", "pass"]);
+ // Both survive: the writer's tier and the pass's pause.
+ assert.equal(tierOf(h, "other"), "low");
+ assert.equal(tierOf(h, "gone"), "paused");
+ });
+});
+
+// THE PROBE'S STATE MACHINE WITH A FAKE PROBER (lane drive-stall): the
+// verdicts a detector gives, pass by pass, and the view every surface reports
+// from them — ok, slow (an answer at half the budget or more), stalled (no
+// answer: the gate refuses), ok again after two clean passes. No drive, no
+// subprocess: the probe is a script.
+test("a fake prober walks the drive ok -> slow -> stalled -> ok, and the gate follows only the stall", async () => {
+ await withTmp(async (h) => {
+ await seedRelocated(h, "on-cold", { targetExists: true });
+ const verdicts = [
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 4 },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 2_100 },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 2_200 },
+ { answer: "stalled" as const, detector: "stat" as const, cause: "a stat of its root did not answer within 3 s" },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 6 },
+ { answer: "ok" as const, detector: "stat" as const, latencyMs: 5 },
+ ];
+ let i = 0;
+ const probe = async () => verdicts[Math.min(i++, verdicts.length - 1)];
+ const loc = { id: "cold", label: "Cold" };
+ const view = () => driveHealthView(loc, locationHealth("cold"));
+ const pass = () => runStorageHealthPass({ io: h.io, probe });
+
+ await pass();
+ assert.equal(view().state, "ok");
+ assert.equal(view().latencyMs, 4);
+ assert.equal(typeof view().lastOkAt, "number");
+
+ await pass(); // one slow reading: not yet slow
+ assert.equal(view().state, "ok");
+ await pass();
+ assert.equal(view().state, "slow");
+ assert.match(String(view().cause), /^a stat of its root took 2.2 s$/);
+ // Slow is shown, never acted on: the channel's media still answers ok.
+ assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "ok");
+
+ await pass();
+ assert.equal(view().state, "stalled");
+ assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "stalled");
+
+ await pass(); // one clean answer: still stalled
+ assert.equal(view().state, "stalled");
+ await pass(); // two in a row: answering again, and not slow
+ assert.equal(view().state, "ok");
+ assert.equal(view().latencyMs, 5);
+ assert.equal((await inspectChannelMedia(h.paths, "on-cold", undefined, { fresh: true })).status, "ok");
+ });
+});
diff --git a/common/controller/storageWatch.ts b/common/controller/storageWatch.ts
@@ -1,4 +1,5 @@
import { getPaths, type Paths } from "../lib/paths";
+import { withJsonFileLock } from "../lib/jsonFile-server";
import {
getSettings,
writeSettings,
@@ -34,6 +35,7 @@ import {
NOT_ANSWERING,
applyHealthTimings,
healthTimings,
+ noteDriveAnswer,
noteLocationDetector,
onPassIntervalChange,
pruneLocationHealth,
@@ -297,6 +299,29 @@ export async function runStorageWatchPass(
if (out.paused.length === 0 && out.restored.length === 0) return out;
if (opts.write === false) return out;
+ // UNDER THE SETTINGS LOCK (lane drive-stall, after lane editor-gaps). The
+ // editor's other read-modify-write of `channelPriority` — the priority
+ // writer, which also clears `autoPaused` on a manual tier change — runs inside
+ // `withSettingsLock` (editor/app/settings/saveSettings.ts), which is this same
+ // per-process lock on settings.json. Without it the two interleave: the
+ // operator's tier change lands between this pass's read and its write and is
+ // written over, or the pass's pause is. The lock is not re-entrant, and
+ // nothing called inside it takes it.
+ await withJsonFileLock(getPaths().settingsFile, () =>
+ writePassResult(io, paths, configs, out, pauseCauses),
+ );
+ out.wrote = true;
+ return out;
+}
+
+// THE PASS'S ONE WRITE, with the settings lock held by the caller.
+async function writePassResult(
+ io: NonNullable<StorageWatchOpts["io"]>,
+ paths: Paths,
+ configs: ReadonlyArray<{ slug: string }>,
+ out: StorageWatchResult,
+ pauseCauses: ReadonlyMap<string, AutoPauseCause>,
+): Promise<void> {
// ONE WRITE PER PASS, whatever the pass found. Ten channels on one drive that
// vanished is one settings write and one pulse bump, not ten.
//
@@ -349,8 +374,6 @@ export async function runStorageWatchPass(
}
}
await io.write({ ...latest, channelPriority: merged, autoQueue });
- out.wrote = true;
- return out;
}
// Five minutes. A drive does not come and go on a timescale a person would
@@ -436,12 +459,23 @@ function recordVerdict(
if (verdict.detector) noteLocationDetector(loc.id, verdict.detector, device);
return null;
}
- return recordLocationHealth(loc, verdict.answer, {
+ const t = recordLocationHealth(loc, verdict.answer, {
now,
cause: verdict.cause ?? statCause(),
...(verdict.detector ? { detector: verdict.detector } : {}),
...(device !== undefined ? { device } : {}),
});
+ // How long it took, when the detector measured it (lane drive-stall): the
+ // counters' average per request, or the child stat's round trip.
+ if (verdict.answer === "ok" && verdict.latencyMs !== undefined) {
+ noteDriveAnswer(
+ loc.id,
+ verdict.latencyMs,
+ verdict.detector === "counters" ? "counters" : "stat",
+ now,
+ );
+ }
+ return t;
}
export async function runStorageHealthPass(
diff --git a/common/controller/transcribeError.ts b/common/controller/transcribeError.ts
@@ -17,3 +17,25 @@ export class TranscribeError extends Error {
this.name = "TranscribeError";
}
}
+
+// THE CHANNEL'S MEDIA DRIVE IS NOT ANSWERING (lane drive-stall): the audio is
+// not opened, and the video is skipped like a "no-audio" one — never recorded
+// in failed-transcriptions, transcribed on a later pass once the drive answers.
+// Its own class so a batch's log says the drive, not "no audio file".
+export class MediaDriveHeldError extends TranscribeError {
+ // Read by `isMediaDriveHeld`, which also answers for a copy of this class
+ // from another module instance (instanceof does not).
+ readonly mediaDriveHeld = true;
+ constructor(message: string) {
+ super(message, "no-audio");
+ }
+}
+
+// A transcription refused because its channel's media drive is not answering:
+// a skip for every caller, never a failed transcription or a failed download.
+export function isMediaDriveHeld(err: unknown): err is MediaDriveHeldError {
+ return (
+ err instanceof MediaDriveHeldError ||
+ (err instanceof Error && (err as { mediaDriveHeld?: unknown }).mediaDriveHeld === true)
+ );
+}
diff --git a/common/controller/transcribeOne.test.ts b/common/controller/transcribeOne.test.ts
@@ -71,3 +71,68 @@ test("an engine that exits 0 with no output, audio gone, is a skip too", async (
assert.ok(err instanceof TranscribeError, `not a TranscribeError: ${err}`);
assert.equal(err.failureClass, "no-audio");
});
+
+// THE TRANSCRIPTION SOURCE IS NOT OPENED ON A DRIVE THAT IS NOT ANSWERING
+// (lane drive-stall). The channel's config names a media location the health
+// record has stalled: the video is refused before its audio is looked for,
+// as a skip (never failed-transcriptions), and the engine never runs.
+test("a channel whose media drive is not answering is refused before its audio is opened", async () => {
+ const { MediaDriveHeldError } = await import("./transcribeError");
+ const { recordLocationHealth, resetStorageHealth } = await import("../lib/storageHealth");
+ const { mkdir } = await import("node:fs/promises");
+ const { existsSync } = await import("node:fs");
+ const dir = await mkdtemp(path.join(tmpdir(), "transcribe-held-"));
+ try {
+ const platter = path.join(dir, "platter");
+ const channelDir = path.join(dir, "channels", "held");
+ const videoDir = path.join(channelDir, "data", "vid1");
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(
+ path.join(channelDir, "config.json"),
+ JSON.stringify({ handling: "transcribe", mediaDir: path.join(platter, "held", "media") }),
+ );
+ await writeFile(path.join(videoDir, "audio.mp3"), "not really audio");
+ const ran = path.join(dir, "engine-ran");
+ const bin = path.join(dir, "fake-engine.sh");
+ await writeFile(bin, `#!/bin/sh\ntouch ${ran}\nexit 1\n`, { mode: 0o755 });
+ recordLocationHealth({ id: "platter", label: "Platter", root: platter }, "stalled");
+ const err = await transcribeOneVideo({
+ paths: {} as Paths,
+ videoDir,
+ videoId: "vid1",
+ audioFilename: "audio.mp3",
+ worker: {
+ id: "w1",
+ name: "fake",
+ kind: "local",
+ enabled: true,
+ priority: 0,
+ appId: "whisper-cpp",
+ config: { bin, model: "model.bin" },
+ },
+ onLog: () => {},
+ }).then(
+ (v) => v,
+ (e) => e,
+ );
+ assert.ok(err instanceof MediaDriveHeldError, `not a MediaDriveHeldError: ${err}`);
+ assert.equal(err.failureClass, "no-audio");
+ assert.match(err.message, /^the media drive "Platter" is not answering \(since \d\d:\d\d\) — vid1 is left for when it answers$/);
+ assert.equal(existsSync(ran), false, "the engine never ran");
+ } finally {
+ resetStorageHealth();
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+// Every caller reads a held transcription as a skip through ONE predicate,
+// which also answers for a copy of the class from another module instance.
+test("isMediaDriveHeld: the held class, by instance or by its flag; nothing else", async () => {
+ const { isMediaDriveHeld, MediaDriveHeldError } = await import("./transcribeError");
+ assert.equal(isMediaDriveHeld(new MediaDriveHeldError("the media drive \"x\" is not answering")), true);
+ const foreign = Object.assign(new Error("copy"), { mediaDriveHeld: true });
+ assert.equal(isMediaDriveHeld(foreign), true);
+ assert.equal(isMediaDriveHeld(new TranscribeError("no audio file", "no-audio")), false);
+ assert.equal(isMediaDriveHeld(new Error("boom")), false);
+ assert.equal(isMediaDriveHeld(null), false);
+});
diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts
@@ -2,6 +2,7 @@ import path from "node:path";
import fs from "fs-extra";
import { execa } from "execa";
import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
import type { Worker } from "../lib/workers";
import { getTranscriptionApp } from "../lib/transcriptionApps";
import { detectTranscriptFormat } from "../lib/whisper";
@@ -16,7 +17,9 @@ import { normalizeTranscript } from "./normalizeTranscript";
import { diarizeOneVideo } from "./diarizeOne";
import { getSettings } from "../lib/settings";
import { pingRemoteHealth, transcribeViaRemote } from "./remoteTranscribe";
-import { TranscribeError } from "./transcribeError";
+import { MediaDriveHeldError, TranscribeError } from "./transcribeError";
+import { channelMediaStall } from "../lib/channelMedia";
+import { mediaDriveHeldText } from "../lib/mediaStallHold";
import { findSourceMedia, isRealAudioFile } from "../lib/videoStatus";
import { pickPreferredAudio } from "../lib/mediaFiles";
import { heldAudioDamage } from "../lib/audioIntegrity-server";
@@ -67,6 +70,23 @@ async function resolveAudioFile(
return null;
}
+// THE CHANNEL'S CONFIG FOR THE STALL CHECK, read at most once per 10 s per
+// channel (review of lane drive-stall): a batch transcribes a channel's videos
+// one after another, and each asked config.json again. Its media targets are
+// all the check reads, and a move rewrites them seldom; ten seconds late is
+// within the health pass's own cadence.
+const STALL_CONFIG_TTL_MS = 10_000;
+const stallConfigMemo = new Map<string, { at: number; config: ChannelConfig | null }>();
+
+async function channelConfigForStall(file: string): Promise<ChannelConfig | null> {
+ const now = Date.now();
+ const hit = stallConfigMemo.get(file);
+ if (hit && now - hit.at < STALL_CONFIG_TTL_MS) return hit.config;
+ const config = await readChannelConfigFile(file).catch(() => null);
+ stallConfigMemo.set(file, { at: now, config });
+ return config;
+}
+
// A CONTAINER TO TRANSCRIBE FROM, before any audio download (release 23 F2).
//
// The page's Transcribe (and `pnpm ops transcribe-one`) used to download the
@@ -200,6 +220,21 @@ export async function transcribeOneVideo(
return "already-exists";
}
+ // NOT OPENED ON A DRIVE THAT IS NOT ANSWERING (lane drive-stall). The audio
+ // is a tierable file, a link onto the channel's media drive; asking for it
+ // there in-process holds one of Node's file threads until the kernel gives
+ // up (~30 s). The health record is memory, the config the corpus disk's.
+ const stall = channelMediaStall(
+ await channelConfigForStall(
+ path.join(path.dirname(path.dirname(opts.videoDir)), "config.json"),
+ ),
+ );
+ if (stall) {
+ throw new MediaDriveHeldError(
+ `${mediaDriveHeldText(stall)} — ${opts.videoId} is left for when it answers`,
+ );
+ }
+
const resolvedAudio = await resolveAudioFile(
opts.videoDir,
opts.audioFilename,
diff --git a/common/controller/transcribeOneFromQueue.ts b/common/controller/transcribeOneFromQueue.ts
@@ -7,7 +7,7 @@ import {
readVideoFiles,
} from "../lib/videoStatus";
import { transcribeWithWorker } from "./transcribeOne";
-import { TranscribeError } from "./transcribeError";
+import { isMediaDriveHeld, TranscribeError } from "./transcribeError";
import type { TaskTracker } from "../jobs/taskHooks";
const { pathExists, appendFile } = fs;
@@ -157,6 +157,10 @@ export async function transcribeOneFromQueue({
// A missing audio file is a download/source problem, not a transcription
// failure — skip it (it transcribes once a good audio file exists) rather
// than permanently recording it in failed-transcriptions.
+ if (isMediaDriveHeld(err)) {
+ log(`Skipping ${videoId}: ${err.message}`);
+ return { attempted: true, outcome: "skipped" };
+ }
if (err instanceof TranscribeError && err.failureClass === "no-audio") {
log(`Skipping ${videoId}: no audio file (download/source problem)`);
return { attempted: true, outcome: "skipped" };
diff --git a/common/controller/whisperBatch.ts b/common/controller/whisperBatch.ts
@@ -13,6 +13,8 @@ import { runPool } from "../jobs/concurrentRunner";
import { pruneFailedTranscriptions } from "./failedTranscriptions";
import { resolveShardItems } from "./shard";
import { countNotYetTranscribed } from "./channels";
+import { mediaStallHold } from "../lib/mediaStallHold";
+import { readChannelMediaConfig } from "../lib/channelMedia";
import { getWorkerPool } from "../jobs/workerPool";
import type { TaskTracker } from "../jobs/taskHooks";
import type { JobProgress } from "../jobs/registry";
@@ -224,6 +226,17 @@ export async function runWhisperBatch({
// transcribe is shared with the auto-runner via transcribeOneFromQueue.
const NEVER = new AbortController().signal;
let idx = 0;
+ // HELD WHILE THE CHANNEL'S MEDIA DRIVE IS NOT ANSWERING (lib/mediaStallHold.ts):
+ // the limit is 0, the pool pauses, and it resumes when the drive answers.
+ // The check is memory; the config is re-read in the background.
+ const stallHold = mediaStallHold(
+ await readChannelMediaConfig(paths, channelSlug),
+ log,
+ "transcription",
+ // Re-read in the background (at most every 10 s): a move mid-batch is
+ // held by the drive the media is on now.
+ { reloadConfig: () => readChannelMediaConfig(paths, channelSlug) },
+ );
const runOne = async (videoDir: string, runSignal: AbortSignal): Promise<void> => {
const res = await transcribeOneFromQueue({
paths,
@@ -250,7 +263,9 @@ export async function runWhisperBatch({
// Eligible (enabled, non-degraded) worker slots — the real throughput
// ceiling. 0 ⇒ paused until a worker is re-enabled (runPool idle-waits).
limit: () =>
- pool.summary().filter((s) => s.state === "enabled" && !s.degraded).length,
+ stallHold.check()
+ ? 0
+ : pool.summary().filter((s) => s.state === "enabled" && !s.degraded).length,
signal: signal ?? NEVER,
drainSignal: drainSignal ?? NEVER,
finite: true,
diff --git a/common/lib/channelMedia.ts b/common/lib/channelMedia.ts
@@ -271,6 +271,16 @@ function configuredOf(config: ChannelMediaConfig | null | undefined): Configured
// `mediaDir` and the retired `dataDir`, read straight off config.json.
// Deliberately NOT parseChannelConfig: this runs in guards on hot paths and
// must not depend on the controller that owns the rest of the schema.
+// A channel's configured media targets (`mediaDir`, the retired `dataDir`)
+// off its config.json on the corpus disk; `{}` for none or an unreadable file.
+// What a caller with only a slug hands `channelMediaStall`.
+export function readChannelMediaConfig(
+ paths: ChannelMediaPaths,
+ slug: string,
+): Promise<ChannelMediaConfig> {
+ return readConfigured(paths, slug);
+}
+
async function readConfigured(
paths: ChannelMediaPaths,
slug: string,
diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts
@@ -142,7 +142,7 @@ const DECLARED: EnvVarDecl[] = [
{ name: "AUDIO_CHECK_BACKOFF_FACTOR", audience: "runtime", default: "the built-in factor", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "The audio check's interval backoff factor, in (0, 1], for a one-off run." },
{ name: "ARCHILYZER_STATS_ALLOW_DOWNGRADE", audience: "runtime", default: "off", readBy: "common/controller/buildStats.ts", doc: "`1` lets a stats build clear a stats cache that a NEWER build wrote, for a deliberate rollback. Unset, such a build refuses and names both versions." },
{ name: "ARCHILYZER_INDEX_ALLOW_HELD", audience: "runtime", default: "off", readBy: "common/controller/buildIndex.ts", doc: "`1` lets a FULL index rebuild (a schema change, or no index yet) proceed while a channel's media cannot be read; that channel stays out of the index until its media is back and the index is built again. Unset, such a build refuses and names each channel." },
- { name: "UV_THREADPOOL_SIZE", audience: "runtime", default: "`16` for the editor (`4` is Node's own)", readBy: "Node's libuv (set by editor/package.json `start` and docker/entrypoint.sh)", doc: "Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive." },
+ { name: "UV_THREADPOOL_SIZE", audience: "runtime", default: "`16` for the editor (`4` is Node's own)", readBy: "Node's libuv (set by editor/package.json `start` and `dev`, the archilyzer-editor.service unit `archilyzer service install` writes, and docker/entrypoint.sh)", doc: "Threads in Node's pool for filesystem calls. A call on a stalled drive holds one until the drive answers, so the editor starts with 16. It buys time for calls already in flight and isolates nothing: the storage health probe and its gate keep new calls off a stalled drive." },
{ name: "MCP_IO_STATS", audience: "runtime", default: "off", readBy: "common/lib/archive/io-stats.ts", doc: "`1` turns on per-call I/O accounting, for `mcp/bench`." },
{ name: "ARCHILYZER_EDITOR_URL", audience: "runtime", default: "`http://localhost:3001`", readBy: "scripts/archilyzer-ops.mjs, common/bin/gen.ts, mcp/src/fetchClip.ts, mcp/src/editorOps.ts, umtool, common/bin/migrate-media-tier.ts", doc: "Which editor `pnpm ops`, `archilyzer gen` and the MCP's editor-backed tools (`fetch_clip`, `enqueue`, `get_job`, `channel_coverage`, `generation_policy`, `generate`, `get_transcript`'s fallback) talk to, and whose `/api/pulse` `archilyzer storage migrate-tier` asks before it refuses to run beside it." },
{ name: "ARCHILYZER_AGENT", audience: "runtime", default: "`cli`", readBy: "scripts/archilyzer-ops.mjs", doc: "Who is asking, recorded as the provenance of a curated-tag write through `pnpm ops`." },
diff --git a/common/lib/mediaStallHold.test.ts b/common/lib/mediaStallHold.test.ts
@@ -0,0 +1,172 @@
+import { beforeEach, test } from "node:test";
+import assert from "node:assert/strict";
+import { mediaDriveHeldText, mediaStallHold } from "./mediaStallHold";
+import {
+ recordLocationHealth,
+ registerLocationHealth,
+ resetStorageHealth,
+} from "./storageHealth";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/mediaStallHold.test.ts
+//
+// The batch hold (lane drive-stall): memory only, edge-logged.
+
+beforeEach(() => resetStorageHealth());
+
+const USB = { id: "usb", label: "USB drive", root: "/mnt/usb" };
+
+test("the hold follows the channel's media location, and logs once per edge", () => {
+ registerLocationHealth([USB]);
+ const lines: string[] = [];
+ const hold = mediaStallHold({ mediaDir: "/mnt/usb/chan/media" }, (l) => lines.push(l), "transcription");
+ assert.equal(hold.check(), null);
+ recordLocationHealth(USB, "stalled", { now: Date.now() });
+ assert.equal(hold.check()?.id, "usb");
+ assert.equal(hold.check()?.id, "usb");
+ recordLocationHealth(USB, "ok");
+ recordLocationHealth(USB, "ok");
+ assert.equal(hold.check(), null);
+ assert.equal(hold.check(), null);
+ assert.equal(lines.length, 2);
+ assert.match(lines[0], /^Holding: the media drive "USB drive" is not answering \(since \d\d:\d\d\) — no new transcription starts until it answers again\.$/);
+ assert.equal(lines[1], `The media drive "USB drive" answers again — resuming.`);
+});
+
+test("a channel in place, or on another location, is never held", () => {
+ registerLocationHealth([USB]);
+ recordLocationHealth(USB, "stalled");
+ const lines: string[] = [];
+ assert.equal(mediaStallHold({}, (l) => lines.push(l), "x").check(), null);
+ assert.equal(mediaStallHold(null, (l) => lines.push(l), "x").check(), null);
+ assert.equal(mediaStallHold({ mediaDir: "/mnt/other/c/media" }, (l) => lines.push(l), "x").check(), null);
+ assert.deepEqual(lines, []);
+ // A legacy channel's retired dataDir on the location is held too.
+ assert.equal(mediaStallHold({ dataDir: "/mnt/usb/c/data" }, () => {}, "x").check()?.id, "usb");
+});
+
+test("the refusal sentence names the drive and since when", () => {
+ assert.match(mediaDriveHeldText({ label: "USB drive", since: Date.now() }), /^the media drive "USB drive" is not answering \(since \d\d:\d\d\)$/);
+});
+
+// ── the hold heals itself (review of lane drive-stall) ──────────────────────
+
+const tick = () => new Promise((r) => setImmediate(r));
+
+test("held past reprobeAfterMs with no pass keeping the record: one out-of-process probe answers and clears it", async () => {
+ const { locationHealth } = await import("./storageHealth");
+ let t = 1_000_000;
+ registerLocationHealth([USB], t);
+ // Recorded once, long ago — no pass refreshes it (a CLI, an idle record).
+ recordLocationHealth(USB, "stalled", { now: t });
+ const probed: string[] = [];
+ const lines: string[] = [];
+ const hold = mediaStallHold({ mediaDir: "/mnt/usb/chan/media" }, (l) => lines.push(l), "transcription", {
+ now: () => t,
+ reprobeAfterMs: 60_000,
+ stillHoldingEveryMs: 600_000,
+ reprobe: async (root) => {
+ probed.push(root);
+ return "ok";
+ },
+ });
+ assert.ok(hold.check());
+ t += 30_000;
+ assert.ok(hold.check());
+ await tick();
+ assert.deepEqual(probed, [], "not before reprobeAfterMs");
+ t += 31_000;
+ assert.ok(hold.check(), "the probe is asynchronous: this pull is still held");
+ await tick();
+ await tick();
+ assert.deepEqual(probed, ["/mnt/usb"]);
+ assert.notEqual(locationHealth("usb")?.state, "stalled", "a stale record is cleared by the answer");
+ assert.equal(hold.check(), null, "and the next pull resumes");
+ assert.match(lines.join("\n"), /answered a stat of its root after 1 min held — no health pass was keeping its stall record/);
+ assert.equal(lines.at(-1), `The media drive "USB drive" answers again — resuming.`);
+});
+
+test("a record a pass still keeps: the probe's answer counts once, and the pass decides", async () => {
+ const { locationHealth } = await import("./storageHealth");
+ let t = Date.now();
+ registerLocationHealth([USB], t);
+ recordLocationHealth(USB, "stalled", { now: t });
+ const hold = mediaStallHold({ mediaDir: "/mnt/usb/c/media" }, () => {}, "x", {
+ now: () => t,
+ reprobeAfterMs: 1_000,
+ reprobe: async () => "ok",
+ });
+ hold.check();
+ t += 1_500;
+ // A pass answered moments ago (the counters still say stalled).
+ recordLocationHealth(USB, "stalled", { now: t });
+ hold.check();
+ await tick();
+ await tick();
+ const h = locationHealth("usb");
+ assert.equal(h?.state, "stalled", "one clean answer does not clear (two are needed)");
+ assert.equal(h?.cleanStreak, 1);
+});
+
+test("a drive that does not answer the probe stays held, and 'still holding' is logged every interval", async () => {
+ let t = 5_000_000;
+ registerLocationHealth([USB], t);
+ recordLocationHealth(USB, "stalled", { now: t });
+ const lines: string[] = [];
+ let probes = 0;
+ const hold = mediaStallHold({ mediaDir: "/mnt/usb/c/media" }, (l) => lines.push(l), "x", {
+ now: () => t,
+ reprobeAfterMs: 300_000,
+ stillHoldingEveryMs: 600_000,
+ reprobe: async () => {
+ probes++;
+ return "stalled";
+ },
+ });
+ for (let i = 0; i < 25; i++) {
+ hold.check();
+ await tick();
+ t += 60_000;
+ }
+ assert.ok(hold.check());
+ const still = lines.filter((l) => l.startsWith("Still holding"));
+ assert.deepEqual(still, [
+ `Still holding: the media drive "USB drive" has not answered after 10 min.`,
+ `Still holding: the media drive "USB drive" has not answered after 20 min.`,
+ ]);
+ // Once per reprobeAfterMs (5 min) after the first 5 min: at 5, 10, 15, 20, 25.
+ assert.equal(probes, 5);
+});
+
+test("the config is re-read: a channel moved off the stalled drive mid-batch resumes", async () => {
+ let t = 0;
+ registerLocationHealth([USB], t);
+ recordLocationHealth(USB, "stalled", { now: t });
+ let config = { mediaDir: "/mnt/usb/c/media" };
+ const hold = mediaStallHold(config, () => {}, "x", {
+ now: () => t,
+ reloadEveryMs: 10_000,
+ reloadConfig: async () => config,
+ });
+ assert.ok(hold.check());
+ config = { mediaDir: "/mnt/other/c/media" };
+ t += 5_000;
+ hold.check();
+ await tick();
+ assert.ok(hold.check(), "not re-read before reloadEveryMs");
+ t += 6_000;
+ hold.check();
+ await tick();
+ assert.equal(hold.check(), null);
+});
+
+test("pruning a location no longer configured clears its record, and a hold on it releases", async () => {
+ const { pruneLocationHealth, locationHealth } = await import("./storageHealth");
+ registerLocationHealth([USB]);
+ recordLocationHealth(USB, "stalled");
+ const hold = mediaStallHold({ mediaDir: "/mnt/usb/c/media" }, () => {}, "x");
+ assert.ok(hold.check());
+ pruneLocationHealth(["some-other-location"]);
+ assert.equal(locationHealth("usb"), undefined);
+ assert.equal(hold.check(), null);
+});
diff --git a/common/lib/mediaStallHold.ts b/common/lib/mediaStallHold.ts
@@ -0,0 +1,179 @@
+import { channelMediaStall, type ChannelMediaConfig } from "./channelMedia";
+import {
+ healthTimings,
+ locationHealth,
+ recordLocationHealth,
+ sinceText,
+ type LocationHealth,
+ type LocationHealthState,
+} from "./storageHealth";
+import { probeLocationHealth } from "./storageVolumes";
+
+// A BATCH THAT OPENS MEDIA HOLDS WHILE ITS CHANNEL'S MEDIA DRIVE IS NOT
+// ANSWERING (lane drive-stall).
+//
+// The start-of-work guard (`assertChannelMediaReachable`) refuses a job whose
+// channel's drive is already stalled. A batch that started while the drive
+// answered, and is still pulling videos when it stops, was not asked again:
+// each next unit opened its audio in-process, held one of Node's file threads
+// for the ~30 s the drive takes to give up, and failed — over and over, a
+// thread at a time. So a batch over a channel's media asks this before every
+// pull: while the drive is stalled the pool's limit is 0 (runPool PAUSES, as
+// it does with every worker disabled), and when it answers the batch resumes.
+// The units already in flight finish or fail on their own; nothing cancels a
+// read the kernel holds.
+//
+// THE CHECK IS MEMORY: `channelMediaStall` reads the process's health record
+// (the health pass and the watchdog write it), never the drive. Edge-logged,
+// once when the hold begins and once when it ends, and "still holding" every
+// `stillHoldingEveryMs` (10 min) between.
+//
+// IT HEALS ITSELF (review of lane drive-stall). The record is cleared by the
+// health pass; a process with no pass covering the location (a CLI, a stall
+// recorded for a location the pass no longer covers) would otherwise hold for
+// ever. So once the hold has lasted `reprobeAfterMs` (5 min), and at most once
+// per that interval, it asks the drive itself — OUT OF PROCESS, a child `stat`
+// of the root raced against the probe timeout, which holds no thread of ours.
+// When the root answers:
+// - a record no pass has refreshed for three pass intervals is stale: the
+// answer clears it (as many clean answers as the clear rule needs), and
+// the batch resumes;
+// - a record a pass still keeps counts the answer once, as /storage's
+// Refresh does, and the pass decides: a child `stat` can be answered from
+// the kernel's cache while the device's own counters say stalled.
+//
+// THE CONFIG IS RE-READ (`reloadConfig`, at most every `reloadEveryMs`, 10 s,
+// in the background): a channel moved to another location mid-batch is held
+// by the drive its media is on now.
+
+export type MediaStallHold = {
+ // The stalled location now, or null. Logs on each edge.
+ check: () => LocationHealth | null;
+};
+
+export type MediaStallHoldOptions = {
+ // Re-read the channel's targets (default: never). The check uses the last
+ // answer; a read that fails keeps the one before.
+ reloadConfig?: () => Promise<ChannelMediaConfig | null | undefined>;
+ reloadEveryMs?: number;
+ // The out-of-process probe of a root (default: a child `stat`,
+ // `probeLocationHealth`). Test seam.
+ reprobe?: (root: string) => Promise<LocationHealthState>;
+ reprobeAfterMs?: number;
+ stillHoldingEveryMs?: number;
+ now?: () => number;
+};
+
+export const MEDIA_HOLD_REPROBE_AFTER_MS = 5 * 60_000;
+export const MEDIA_HOLD_STILL_EVERY_MS = 10 * 60_000;
+const RELOAD_EVERY_MS = 10_000;
+
+function minutesText(ms: number): string {
+ const m = Math.max(0, Math.round(ms / 60_000));
+ return `${m} min`;
+}
+
+export function mediaStallHold(
+ initialConfig: ChannelMediaConfig | null | undefined,
+ log: (line: string) => void,
+ what: string,
+ opts: MediaStallHoldOptions = {},
+): MediaStallHold {
+ const now = opts.now ?? Date.now;
+ const reprobeAfter = opts.reprobeAfterMs ?? MEDIA_HOLD_REPROBE_AFTER_MS;
+ const stillEvery = opts.stillHoldingEveryMs ?? MEDIA_HOLD_STILL_EVERY_MS;
+ const reloadEvery = opts.reloadEveryMs ?? RELOAD_EVERY_MS;
+ const reprobe = opts.reprobe ?? ((root: string) => probeLocationHealth({ root }));
+ let config = initialConfig;
+ let lastReload = now();
+ let reloading = false;
+ let holding: LocationHealth | null = null;
+ let heldAt = 0;
+ let lastStill = 0;
+ let lastReprobe = 0;
+ let reprobing = false;
+
+ const maybeReload = () => {
+ if (!opts.reloadConfig || reloading || now() - lastReload < reloadEvery) return;
+ reloading = true;
+ lastReload = now();
+ void opts
+ .reloadConfig()
+ .then(
+ (next) => {
+ if (next !== undefined) config = next;
+ },
+ () => {},
+ )
+ .finally(() => {
+ reloading = false;
+ });
+ };
+
+ const maybeReprobe = (stall: LocationHealth) => {
+ const t = now();
+ if (reprobing || t - heldAt < reprobeAfter || t - lastReprobe < reprobeAfter) return;
+ reprobing = true;
+ lastReprobe = t;
+ void reprobe(stall.root)
+ .then(
+ (answer) => {
+ if (answer === "stalled") return;
+ const current = locationHealth(stall.id);
+ if (!current || current.root !== stall.root || current.state !== "stalled") return;
+ const loc = { id: stall.id, label: stall.label, root: stall.root };
+ const stale = now() - current.checkedAt >= healthTimings().passIntervalMs * 3;
+ // Stale: no pass is keeping it, and the drive answered — enough
+ // clean answers to clear it. Kept by a pass: one answer.
+ const answers = stale ? healthTimings().clearAfterCleanPasses : 1;
+ for (let i = 0; i < answers; i++) {
+ recordLocationHealth(loc, answer, { detector: "stat", device: null });
+ }
+ log(
+ `The media drive "${stall.label}" answered a stat of its root after ` +
+ `${minutesText(t - heldAt)} held` +
+ (stale
+ ? " — no health pass was keeping its stall record, so the stall is cleared."
+ : "; its health pass decides when the stall ends."),
+ );
+ },
+ () => {},
+ )
+ .finally(() => {
+ reprobing = false;
+ });
+ };
+
+ return {
+ check: () => {
+ maybeReload();
+ const stall = channelMediaStall(config);
+ const t = now();
+ if (stall && !holding) {
+ heldAt = t;
+ lastStill = t;
+ log(
+ `Holding: the media drive "${stall.label}" is not answering (${sinceText(stall.since)}) — ` +
+ `no new ${what} starts until it answers again.`,
+ );
+ } else if (stall && holding) {
+ if (t - lastStill >= stillEvery) {
+ lastStill = t;
+ log(
+ `Still holding: the media drive "${stall.label}" has not answered after ${minutesText(t - heldAt)}.`,
+ );
+ }
+ } else if (!stall && holding) {
+ log(`The media drive "${holding.label}" answers again — resuming.`);
+ }
+ holding = stall;
+ if (stall) maybeReprobe(stall);
+ return stall;
+ },
+ };
+}
+
+// The sentence a unit refuses with when its channel's drive is not answering.
+export function mediaDriveHeldText(stall: Pick<LocationHealth, "label" | "since">): string {
+ return `the media drive "${stall.label}" is not answering (${sinceText(stall.since)})`;
+}
diff --git a/common/lib/savedVideoStore.test.ts b/common/lib/savedVideoStore.test.ts
@@ -166,3 +166,53 @@ async function exists(p: string): Promise<boolean> {
return (err as NodeJS.ErrnoException).code === "EISDIR";
}
}
+
+// A STORE ON A DRIVE THAT IS NOT ANSWERING IS NOT WRITTEN (lane drive-stall):
+// the corpus store through its link, a channel's own store as given; the
+// container stays in the video dir, and nothing touches the stalled drive.
+test("a store whose drive is not answering refuses the write, and the container stays put", async () => {
+ const { symlink } = await import("node:fs/promises");
+ const { recordLocationHealth, resetStorageHealth } = await import("./storageHealth");
+ const { SavedVideosStoreNotAnsweringError } = await import("./savedVideoStore");
+ await withTmp(async (paths, videoDir) => {
+ const platter = path.join(path.dirname(paths.transcriptsDir), "platter");
+ const target = path.join(platter, "saved-videos");
+ await mkdir(target, { recursive: true });
+ await rm(paths.savedVideosDir, { recursive: true, force: true });
+ await symlink(target, paths.savedVideosDir);
+ const loc = { id: "platter", label: "Platter", root: platter };
+ try {
+ // Answering: the guard passes.
+ recordLocationHealth(loc, "ok");
+ await assertSavedVideosStoreWritable(paths, path.join(paths.savedVideosDir, "chan"));
+ // Not answering: refused, for the corpus store and for a channel store on it.
+ recordLocationHealth(loc, "stalled", { cause: "test" });
+ await assert.rejects(
+ assertSavedVideosStoreWritable(paths, path.join(paths.savedVideosDir, "chan")),
+ (err: unknown) =>
+ err instanceof SavedVideosStoreNotAnsweringError &&
+ /^The saved-video store's drive "Platter" is not answering \(since \d\d:\d\d\)/.test(err.message),
+ );
+ await assert.rejects(
+ assertSavedVideosStoreWritable(paths, path.join(platter, "own-store")),
+ SavedVideosStoreNotAnsweringError,
+ );
+ // A store elsewhere is not held by this drive.
+ await assertSavedVideosStoreWritable(paths, path.join(paths.transcriptsDir, "elsewhere"));
+ await writeFile(path.join(videoDir, "source-media.mp4"), "container");
+ await assert.rejects(
+ persistSourceVideo({
+ videoDir,
+ sourceFilename: "source-media.mp4",
+ storeDir: path.join(paths.savedVideosDir, "chan"),
+ keepReason: "pin",
+ paths,
+ }),
+ SavedVideosStoreNotAnsweringError,
+ );
+ assert.equal(await readFile(path.join(videoDir, "source-media.mp4"), "utf8"), "container");
+ } finally {
+ resetStorageHealth();
+ }
+ });
+});
diff --git a/common/lib/savedVideoStore.ts b/common/lib/savedVideoStore.ts
@@ -1,7 +1,8 @@
import path from "node:path";
-import { readFile } from "node:fs/promises";
+import { readFile, readlink } from "node:fs/promises";
import type { Paths } from "./paths";
import type { RelocationMarker } from "./channelMedia";
+import { sinceText, stalledLocationForPath, type LocationHealth } from "./storageHealth";
// IS THE SAVED-VIDEO STORE SAFE TO WRITE INTO RIGHT NOW?
//
@@ -109,7 +110,58 @@ export async function assertSavedVideosStoreWritable(
paths: Pick<Paths, "transcriptsDir" | "savedVideosDir">,
storeDir: string,
): Promise<void> {
- if (!isInCorpusSavedVideoStore(paths, storeDir)) return;
+ const corpus = isInCorpusSavedVideoStore(paths, storeDir);
+ // A STORE ON A DRIVE THAT IS NOT ANSWERING IS NOT WRITTEN (lane drive-stall).
+ // The move into it is in-process (`moveFileCrossDevice`), and on a stalled
+ // drive every call of it holds one of Node's file threads until the kernel
+ // gives up. Memory only: the health record, matched against the store's
+ // path — a channel's own store as given, the corpus store through its link
+ // (`readlink` reads the corpus disk, never the target).
+ const where = corpus
+ ? await readlink(paths.savedVideosDir).catch(() => paths.savedVideosDir)
+ : storeDir;
+ const stall = stalledLocationForPath(where);
+ if (stall) throw new SavedVideosStoreNotAnsweringError(stall);
+ if (!corpus) return;
const marker = await readSavedVideosMarker(paths);
if (marker) throw new SavedVideosStoreInTransitionError(marker);
}
+
+// Thrown by assertSavedVideosStoreWritable when the store's drive is not
+// answering. Every persist caller already catches a refusal here and leaves
+// the container where it is, to be persisted on a later pass.
+export class SavedVideosStoreNotAnsweringError extends Error {
+ readonly health: LocationHealth;
+ constructor(health: LocationHealth) {
+ super(
+ `The saved-video store's drive "${health.label}" is not answering ` +
+ `(${sinceText(health.since)}) — nothing is written into it until it answers.`,
+ );
+ this.name = "SavedVideosStoreNotAnsweringError";
+ this.health = health;
+ }
+}
+
+// THE STORE'S REFUSAL, AS A VALUE (review of lane drive-stall): the error the
+// guard above would throw for a write into `storeDir` — the store's drive not
+// answering, or the store mid-move — or null. A batch that FETCHES before it
+// persists (persist-videos, persist-kept: a whole source container per video)
+// asks this before each download, so a store that cannot take the container
+// stops the run instead of downloading one only to leave it in the data dir.
+export async function savedVideosStoreRefusal(
+ paths: Pick<Paths, "transcriptsDir" | "savedVideosDir">,
+ storeDir: string,
+): Promise<SavedVideosStoreNotAnsweringError | SavedVideosStoreInTransitionError | null> {
+ try {
+ await assertSavedVideosStoreWritable(paths, storeDir);
+ return null;
+ } catch (err) {
+ if (
+ err instanceof SavedVideosStoreNotAnsweringError ||
+ err instanceof SavedVideosStoreInTransitionError
+ ) {
+ return err;
+ }
+ throw err;
+ }
+}
diff --git a/common/lib/storageHealth.test.ts b/common/lib/storageHealth.test.ts
@@ -3,6 +3,10 @@ import assert from "node:assert/strict";
import {
DriveNotAnsweringError,
allLocationHealth,
+ driveHealthView,
+ noteDriveAnswer,
+ slowThresholdMs,
+ slowWindowMs,
applyHealthTimings,
driveCallsInFlight,
healthTimings,
@@ -689,3 +693,108 @@ test("rootOfUnknownPath strips <root>/<slug>/media (release 17) and the retired
assert.equal(rootOfUnknownPath("/mnt/p/chan/data"), "/mnt/p");
assert.equal(rootOfUnknownPath("/mnt/p/chan/other"), "/mnt/p/chan/other");
});
+
+// ── answering, slow, not answering, not mounted (lane drive-stall) ──────────
+
+test("the drive's four words: ok → slow → stalled → ok, from what the watchdog measured", async () => {
+ registerLocationHealth([USB], 1_000);
+ const fresh = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(fresh.state, "ok");
+ assert.equal(fresh.lastOkAt, undefined, "a registration is not an answer");
+ assert.equal(fresh.text, "answering (not asked yet)");
+
+ // A quick unit: answered, measured, ok.
+ setDriveCallBudget(200);
+ assert.equal(slowThresholdMs(), 100);
+ await onDrive(USB, async () => "quick");
+ const ok = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(ok.state, "ok");
+ assert.equal(typeof ok.lastOkAt, "number");
+ assert.equal(ok.latencyFrom, "call");
+ assert.match(ok.text, /^answering — \d+ ms \(a read in the editor\), last at \d\d:\d\d$/);
+
+ // A unit past half the budget: answered. One is not slow (a big unit, a
+ // spin-up); two in a row are. Nothing refuses either.
+ const lateUnit = () => onDrive(USB, () => new Promise((r) => setTimeout(() => r("late"), 130)));
+ assert.equal(await lateUnit(), "late");
+ assert.equal(driveHealthView(USB, locationHealth("usb")).state, "ok", "one slow reading is not slow");
+ assert.equal(await lateUnit(), "late");
+ const slow = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(slow.state, "slow");
+ assert.match(String(slow.cause), /^a read in the editor took \d+ ms$/);
+ assert.match(slow.text, /^slow at \d\d:\d\d — a read in the editor took/);
+ assert.equal(stalledLocation(USB), null, "slow is shown, never acted on");
+
+ // A unit that never answers: stalled, and the stall supersedes slow.
+ await assert.rejects(onDrive(USB, () => new Promise(() => {})), DriveNotAnsweringError);
+ const stalled = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(stalled.state, "stalled");
+ assert.match(stalled.text, /^not answering since \d\d:\d\d — a read in the editor did not answer/);
+
+ // Two clean answers clear it — and it is ok, not slow, after.
+ recordLocationHealth(USB, "ok");
+ recordLocationHealth(USB, "ok");
+ const back = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(back.state, "ok");
+ assert.equal(locationHealth("usb")?.slowAt, undefined);
+});
+
+test("slow lasts two passes from its last sighting, then reads ok again", () => {
+ registerLocationHealth([USB], 0);
+ noteDriveAnswer("usb", 2_000, "stat", 9_000);
+ assert.equal(locationHealth("usb")?.slowAt, undefined, "one reading is not slow");
+ noteDriveAnswer("usb", 2_000, "stat", 10_000);
+ const h = locationHealth("usb");
+ assert.equal(h?.slowAt, 10_000);
+ assert.equal(h?.lastOkAt, 10_000);
+ assert.equal(slowWindowMs(), 30_000);
+ assert.equal(driveHealthView(USB, h, { now: 10_000 + 29_999 }).state, "slow");
+ assert.equal(driveHealthView(USB, h, { now: 10_000 + 30_000 }).state, "ok");
+ // The counters' average is the disk's own figure: it sets the latency and
+ // can be slow, but it is not an answer to us.
+ noteDriveAnswer("usb", 5, "counters", 50_000);
+ const after = locationHealth("usb");
+ assert.equal(after?.latencyMs, 5);
+ assert.equal(after?.latencyFrom, "counters");
+ assert.equal(after?.lastOkAt, 10_000);
+ // A location with no entry records nothing.
+ noteDriveAnswer("nowhere", 9_000, "call");
+ assert.equal(locationHealth("nowhere"), undefined);
+});
+
+test("not mounted: the health record's `absent`, or the mount probe's word; a stall wins over both", () => {
+ recordLocationHealth(USB, "absent", { now: 7 });
+ const gone = driveHealthView(USB, locationHealth("usb"));
+ assert.equal(gone.state, "unmounted");
+ assert.equal(gone.since, 7);
+ assert.equal(gone.text, "not mounted");
+ resetStorageHealth();
+ registerLocationHealth([USB]);
+ assert.equal(driveHealthView(USB, locationHealth("usb"), { mounted: false }).state, "unmounted");
+ assert.equal(driveHealthView(USB, undefined, { mounted: false }).state, "unmounted");
+ recordLocationHealth(USB, "stalled", { cause: "no answer" });
+ assert.equal(driveHealthView(USB, locationHealth("usb"), { mounted: false }).state, "stalled");
+});
+
+test("the watchdog's slow refusal is a sighting of slow, and marks nothing", async () => {
+ registerLocationHealth([USB]);
+ setDriveCallBudget(60);
+ let completed = 0;
+ setCounterReader(() => ({ completed: (completed += 5), inFlight: 1 }));
+ recordLocationHealth(USB, "ok", { detector: "counters", device: "sdz" });
+ await assert.rejects(onDrive(USB, () => new Promise(() => {})), /drive slow/);
+ const h = locationHealth("usb");
+ assert.equal(h?.state, "ok");
+ assert.match(String(h?.slowCause), /did not answer within .*still completing others/);
+ assert.equal(driveHealthView(USB, h).state, "slow");
+});
+
+test("a fast reading between two slow ones starts the count again", () => {
+ registerLocationHealth([USB], 0);
+ noteDriveAnswer("usb", 2_000, "call", 1);
+ noteDriveAnswer("usb", 3, "call", 2);
+ noteDriveAnswer("usb", 2_000, "call", 3);
+ assert.equal(locationHealth("usb")?.slowAt, undefined);
+ noteDriveAnswer("usb", 2_000, "call", 4);
+ assert.equal(locationHealth("usb")?.slowAt, 4);
+});
diff --git a/common/lib/storageHealth.ts b/common/lib/storageHealth.ts
@@ -102,6 +102,28 @@ export type LocationHealth = {
// The block device the counters detector reads for this location, when it
// could name one. The watchdog reads its counters too (see `onDrive`).
device?: string;
+ // WHEN THE DRIVE LAST ANSWERED, ms since epoch (lane drive-stall): a pass's
+ // clean verdict that found the root (`ok`), or a call through `onDrive` that
+ // answered within its budget. Absent: not yet, in this process.
+ lastOkAt?: number;
+ // HOW LONG IT TOOK, the latest measurement, in ms, and what measured it:
+ // `call`, a whole unit through `onDrive`; `stat`, the health pass's child
+ // `stat` of the root (its round trip, process start included); `counters`,
+ // the block device's own average per completed request over the pass's
+ // sample interval (`/sys/class/block/<dev>/stat` fields 4 and 8, the time
+ // its reads and writes took, over the requests that completed).
+ latencyMs?: number;
+ latencyFrom?: "call" | "stat" | "counters";
+ // WHEN IT WAS LAST SEEN SLOW, and why: answering, but two measurements in a row reached
+ // `slowThresholdMs()` (half the budget), or the watchdog refused a call as
+ // slow (its disk still completing others). Slow is shown, never acted on:
+ // nothing refuses a slow drive that the budget does not.
+ slowAt?: number;
+ slowCause?: string;
+ // Consecutive measurements at or past `slowThresholdMs()`. Slow is sighted
+ // at SLOW_READINGS_IN_A_ROW (2): one long unit (a big walk, a cold spin-up)
+ // is not a slow drive.
+ slowStreak?: number;
};
// THE DEFAULTS, and why they are what they are (lib/storageHealthTimings.ts
@@ -259,7 +281,9 @@ export function recordLocationHealth(
device?: string | null;
} = {},
): HealthTransition | null {
- const t = recordAnswer(loc, answer, opts);
+ // Every answer recorded here is a detector's (a pass, a Refresh, the
+ // watchdog); `registerLocationHealth` creates entries without one.
+ const t = recordAnswer(loc, answer, { ...opts, answered: true });
// EVERY TRANSITION TO STALLED refuses the calls waiting for a slot on the
// location, whoever decided it (the pass, the watchdog, a Refresh): they
// would otherwise wait for a slot held by a call the drive is not answering.
@@ -277,6 +301,8 @@ function recordAnswer(
cause?: string;
detector?: HealthDetector;
device?: string | null;
+ // A detector's answer, not a registration: an `ok` then sets `lastOkAt`.
+ answered?: boolean;
},
): HealthTransition | null {
const now = opts.now ?? Date.now();
@@ -296,11 +322,14 @@ function recordAnswer(
checkedAt: now,
cleanStreak: 0,
...(answer === "stalled" && opts.cause ? { cause: opts.cause } : {}),
+ ...(answer === "ok" && opts.answered ? { lastOkAt: now } : {}),
});
return { id: loc.id, from: null, to: answer };
}
prev.label = label;
prev.checkedAt = now;
+ // An `ok` from a detector is the drive answering (a registration is not).
+ if (answer === "ok" && opts.answered) prev.lastOkAt = now;
if (opts.detector) prev.detector = opts.detector;
if (opts.device === null) delete prev.device;
else if (opts.device) prev.device = opts.device;
@@ -311,6 +340,11 @@ function recordAnswer(
prev.state = "stalled";
prev.since = now;
if (opts.cause) prev.cause = opts.cause;
+ // A stall supersedes slow: once it clears, the drive starts answering
+ // afresh, and an old slow sighting is not what it is doing now.
+ delete prev.slowAt;
+ delete prev.slowCause;
+ delete prev.slowStreak;
return { id: loc.id, from, to: "stalled" };
}
if (prev.state === "stalled") {
@@ -344,7 +378,8 @@ export function registerLocationHealth(
prev.label = loc.label || loc.id;
continue;
}
- recordLocationHealth(loc, "ok", { now });
+ // Not an answer: an entry with no `lastOkAt` (nothing has asked yet).
+ recordAnswer(loc, "ok", { now });
}
}
@@ -408,10 +443,10 @@ export function stalledLocation(
return h && h.state === "stalled" && h.root === loc.root ? { ...h } : null;
}
-// "since 11:35" in the server's clock, or "since 2026-09-28 11:35" when the
-// stall began on another day than `now`.
-export function sinceText(since: number, now: number = Date.now()): string {
- const d = new Date(since);
+// "11:35" in the server's clock, or "2026-09-28 11:35" when `at` is on another
+// day than `now`.
+export function clockText(at: number, now: number = Date.now()): string {
+ const d = new Date(at);
const n = new Date(now);
const pad = (x: number) => String(x).padStart(2, "0");
const hm = `${pad(d.getHours())}:${pad(d.getMinutes())}`;
@@ -419,9 +454,13 @@ export function sinceText(since: number, now: number = Date.now()): string {
d.getFullYear() === n.getFullYear() &&
d.getMonth() === n.getMonth() &&
d.getDate() === n.getDate();
- return sameDay
- ? `since ${hm}`
- : `since ${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hm}`;
+ return sameDay ? hm : `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hm}`;
+}
+
+// "since 11:35" in the server's clock, or "since 2026-09-28 11:35" when the
+// stall began on another day than `now`.
+export function sinceText(since: number, now: number = Date.now()): string {
+ return `since ${clockText(since, now)}`;
}
// "not answering since 11:35" — the one line /storage, the /channels volume bar
@@ -431,6 +470,162 @@ export function notAnsweringText(h: Pick<LocationHealth, "since">, now?: number)
}
// ---------------------------------------------------------------------------
+// Answering, slow, not answering, not mounted: the four words a surface shows
+// ---------------------------------------------------------------------------
+//
+// THE STATE ABOVE IS WHAT THE GATE ACTS ON (`stalled` or not). A person asking
+// "is the drive all right" wants two more facts: whether it is there at all
+// (an unmounted drive answers at once, with ENOENT — not a stall, and not
+// health), and whether it is answering SLOWLY — a disk grinding through a long
+// write answers every read, a second late. Slow is shown and never acted on:
+// the budget is what refuses, and a slow drive under it is still working.
+
+// A measurement at or past this is slow: half the watchdog's budget (1.5 s by
+// default). A unit at half its budget is half way to being refused.
+export function slowThresholdMs(): number {
+ return Math.round(driveCallBudget() / 2);
+}
+
+// How long one slow measurement keeps a drive "slow": two passes (30 s by
+// default), so a single slow read is visible for a pass or two and a drive
+// slow on every read stays slow.
+export function slowWindowMs(): number {
+ return healthTimings().passIntervalMs * 2;
+}
+
+// "12 ms", "1.4 s".
+export function latencyText(ms: number): string {
+ return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
+}
+
+const LATENCY_WORDS: Record<NonNullable<LocationHealth["latencyFrom"]>, string> = {
+ call: "a read in the editor",
+ stat: "a stat of its root",
+ counters: "its disk's average request",
+};
+
+// THE DRIVE ANSWERED: a measurement of how long it took. Recorded for a
+// location that has an entry (registered or answered); a path on no
+// configured location has none, and this does nothing for it. The second
+// measurement in a row at or past `slowThresholdMs()` is a sighting of slow.
+export function noteDriveAnswer(
+ id: string,
+ latencyMs: number,
+ from: NonNullable<LocationHealth["latencyFrom"]>,
+ now: number = Date.now(),
+): void {
+ const h = healthState().byId.get(id);
+ if (!h || !Number.isFinite(latencyMs) || latencyMs < 0) return;
+ h.latencyMs = Math.round(latencyMs);
+ h.latencyFrom = from;
+ // An average per request is the disk's own figure, not an answer to us; the
+ // other two are the drive answering.
+ if (from !== "counters") h.lastOkAt = now;
+ if (latencyMs >= slowThresholdMs()) {
+ h.slowStreak = (h.slowStreak ?? 0) + 1;
+ if (h.slowStreak >= SLOW_READINGS_IN_A_ROW) {
+ h.slowAt = now;
+ h.slowCause = `${LATENCY_WORDS[from]} took ${latencyText(latencyMs)}`;
+ }
+ } else {
+ h.slowStreak = 0;
+ }
+}
+
+// Two slow measurements in a row before a drive reads slow (review of lane
+// drive-stall): one long unit must not flash the banner.
+export const SLOW_READINGS_IN_A_ROW = 2;
+
+// THE DRIVE IS SLOW, NOT STALLED: the watchdog refused a call past its budget
+// while the disk was still completing others (`onDrive`, `acquireSlot`).
+export function noteDriveSlow(id: string, cause: string, now: number = Date.now()): void {
+ const h = healthState().byId.get(id);
+ if (!h) return;
+ h.slowAt = now;
+ h.slowCause = cause;
+}
+
+export type DriveHealthState = "ok" | "slow" | "stalled" | "unmounted";
+
+// ONE LOCATION'S DRIVE, as every surface and `pnpm ops get storage` reports it.
+export type DriveHealthView = {
+ id: string;
+ label: string;
+ state: DriveHealthState;
+ // stalled: when it stopped answering; slow: when it was last seen slow;
+ // unmounted: when the health record last found the root missing (absent
+ // when only the mount probe says so).
+ since?: number;
+ // When the drive last answered (see `LocationHealth.lastOkAt`).
+ lastOkAt?: number;
+ latencyMs?: number;
+ latencyFrom?: LocationHealth["latencyFrom"];
+ detector?: HealthDetector;
+ // stalled: what did not answer; slow: what was slow.
+ cause?: string;
+ // The one line: "answering — 12 ms (a read in the editor) at 11:42",
+ // "slow at 11:42 — a read in the editor took 2.1 s", "not answering since
+ // 11:35 — …", "not mounted".
+ text: string;
+};
+
+// The view of one location's drive. `mounted: false` is the mount probe's
+// answer (`StorageLocationStatus` other than available or stalled), which
+// the health record does not carry when the counters detector watches it;
+// omitted, only the record decides.
+export function driveHealthView(
+ loc: Pick<StorageLocation, "id" | "label">,
+ h: LocationHealth | undefined,
+ opts: { now?: number; mounted?: boolean } = {},
+): DriveHealthView {
+ const now = opts.now ?? Date.now();
+ const base = {
+ id: loc.id,
+ label: loc.label || loc.id,
+ ...(h?.lastOkAt !== undefined ? { lastOkAt: h.lastOkAt } : {}),
+ ...(h?.latencyMs !== undefined ? { latencyMs: h.latencyMs } : {}),
+ ...(h?.latencyFrom ? { latencyFrom: h.latencyFrom } : {}),
+ ...(h?.detector ? { detector: h.detector } : {}),
+ };
+ if (h?.state === "stalled") {
+ return {
+ ...base,
+ state: "stalled",
+ since: h.since,
+ ...(h.cause ? { cause: h.cause } : {}),
+ text: `${notAnsweringText(h, now)}${h.cause ? ` — ${h.cause}` : ""}`,
+ };
+ }
+ if (h?.state === "absent" || opts.mounted === false) {
+ return {
+ ...base,
+ state: "unmounted",
+ ...(h?.state === "absent" ? { since: h.since } : {}),
+ text: "not mounted",
+ };
+ }
+ if (h?.slowAt !== undefined && now - h.slowAt < slowWindowMs()) {
+ return {
+ ...base,
+ state: "slow",
+ since: h.slowAt,
+ ...(h.slowCause ? { cause: h.slowCause } : {}),
+ text: `slow at ${clockText(h.slowAt, now)}${h.slowCause ? ` — ${h.slowCause}` : ""}`,
+ };
+ }
+ const measured =
+ h?.latencyMs !== undefined && h.latencyFrom
+ ? ` — ${latencyText(h.latencyMs)} (${LATENCY_WORDS[h.latencyFrom]})`
+ : "";
+ const last = h?.lastOkAt !== undefined ? `, last at ${clockText(h.lastOkAt, now)}` : "";
+ return {
+ ...base,
+ state: "ok",
+ text: h?.lastOkAt === undefined && !measured ? "answering (not asked yet)" : `answering${measured}${last}`,
+ };
+}
+
+// ---------------------------------------------------------------------------
// The watchdog: every call the gate covers, raced against the budget
// ---------------------------------------------------------------------------
//
@@ -589,11 +784,11 @@ async function acquireSlot(r: Resolved): Promise<void> {
const oldest = overdue.reduce((a, b) => (b.startedAt < a.startedAt ? b : a));
const now = readDeviceCounters(r.loc);
if (oldest.before && now && now.completed > oldest.before.completed) {
- throw new DriveNotAnsweringError(
- null,
- `drive slow (${overdue.length} reads on it are past ` +
- `${secondsText(driveCallBudget())}, while its disk is still completing others)`,
- );
+ const detail =
+ `${overdue.length} reads on it are past ` +
+ `${secondsText(driveCallBudget())}, while its disk is still completing others`;
+ if (r.loc) noteDriveSlow(r.loc.id, detail);
+ throw new DriveNotAnsweringError(null, `drive slow (${detail})`);
}
let health: LocationHealth | null = null;
if (r.loc) {
@@ -768,6 +963,9 @@ export async function onDrive<T>(where: Where, call: () => Promise<T>): Promise<
}
if (answer !== TIMED_OUT) {
release();
+ // THE DRIVE ANSWERED, and how long the unit took. A call that threw
+ // answered too, but its time says nothing (ENOENT is instant).
+ if (r.loc) noteDriveAnswer(r.loc.id, Date.now() - startedAt, "call");
return answer;
}
// The call is still waiting on the drive. Its slot stays held, and counted
@@ -784,11 +982,11 @@ export async function onDrive<T>(where: Where, call: () => Promise<T>): Promise<
const after = readDeviceCounters(r.loc);
if (before && after && after.completed > before.completed) {
// SLOW, NOT STALLED: the disk completed requests while this call waited.
- throw new DriveNotAnsweringError(
- null,
- `drive slow (a read did not answer within ${secondsText(budget)}, ` +
- `while its disk was still completing others)`,
- );
+ const detail =
+ `a read did not answer within ${secondsText(budget)}, ` +
+ `while its disk was still completing others`;
+ if (r.loc) noteDriveSlow(r.loc.id, detail);
+ throw new DriveNotAnsweringError(null, `drive slow (${detail})`);
}
if (r.loc) {
recordLocationHealth(r.loc, "stalled", {
diff --git a/common/lib/storageHealthCounters.test.ts b/common/lib/storageHealthCounters.test.ts
@@ -5,6 +5,8 @@ import { tmpdir } from "node:os";
import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import {
blockDeviceName,
+ blockStatTicksMs,
+ countersLatencyMs,
detectLocationHealth,
minCounterIntervalMs,
resetHealthDetector,
@@ -193,9 +195,13 @@ test("no device → the child stat, and the verdict says so", async () => {
const opts = { sysBlockDir: h.sys, now: 0 };
// A tmpfs or network source names no block device.
await h.control({ source: "tmpfs" });
- assert.deepEqual(await detectLocationHealth(loc(h.root), h.bins, opts), {
+ // The verdict carries the child's round trip (lane drive-stall).
+ const viaStat = await detectLocationHealth(loc(h.root), h.bins, opts);
+ assert.equal(typeof viaStat.latencyMs, "number");
+ assert.deepEqual({ ...viaStat, latencyMs: 0 }, {
answer: "ok",
detector: "stat",
+ latencyMs: 0,
});
// findmnt cannot say (no such path, a container without it).
await h.control({ exit: 1 });
@@ -258,3 +264,45 @@ test("a device already named is read without findmnt; findmnt again only when it
assert.ok(globalThis.__yttHealthDetector__);
});
});
+
+// ── the disk's own latency (lane drive-stall) ───────────────────────────────
+
+test("the stat line's request time: fields 4 + 8 (+ 15 + 17), and the average per completed request", () => {
+ // The real line above: 80435430 ms reading, 167469727 writing, 4100450
+ // discarding, 1212688 flushing.
+ assert.equal(blockStatTicksMs(LINE), 80435430 + 167469727 + 4100450 + 1212688);
+ // An 11-field line has no discard or flush time.
+ assert.equal(blockStatTicksMs("10 0 0 40 5 0 0 20 3 0 0"), 60);
+ assert.equal(blockStatTicksMs("1 2 3"), null);
+ // 30 requests completed in 900 ms of request time: 30 ms each.
+ assert.equal(countersLatencyMs({ completed: 100, ticksMs: 1000 }, { completed: 130, ticksMs: 1900 }), 30);
+ // Nothing completed: no latency to report (an idle disk, or a stalled one).
+ assert.equal(countersLatencyMs({ completed: 100, ticksMs: 1000 }, { completed: 100, ticksMs: 1000 }), undefined);
+ // No time fields on one side: nothing.
+ assert.equal(countersLatencyMs({ completed: 100 }, { completed: 130, ticksMs: 5 }), undefined);
+});
+
+test("counters: an ok verdict carries the disk's average request time; a stalled one none", async () => {
+ await withHarness(async (h) => {
+ await h.control({ source: "/dev/fakedisk2", uuid: "u-2" });
+ const at = (i: number) => ({ sysBlockDir: h.sys, now: i * 15_000 });
+ const line = async (completed: number, readMs: number, inFlight: number) => {
+ await mkdir(path.join(h.sys, "fakedisk2"), { recursive: true });
+ await writeFile(
+ path.join(h.sys, "fakedisk2", "stat"),
+ `${completed} 0 0 ${readMs} 0 0 0 0 ${inFlight} 0 0 0 0 0 0 0 0\n`,
+ );
+ };
+ await line(100, 1_000, 1);
+ assert.equal((await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(1))).answer, null);
+ // 10 completed in 20 s of request time: 2 s each — a slow disk, answering.
+ await line(110, 21_000, 1);
+ const slow = await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(2));
+ assert.equal(slow.answer, "ok");
+ assert.equal(slow.latencyMs, 2_000);
+ await line(110, 21_000, 1);
+ const stuck = await detectLocationHealth(loc(h.root, "u-2"), h.bins, at(3));
+ assert.equal(stuck.answer, "stalled");
+ assert.equal(stuck.latencyMs, undefined);
+ });
+});
diff --git a/common/lib/storageVolumes.ts b/common/lib/storageVolumes.ts
@@ -377,6 +377,10 @@ export type HealthVerdict = {
cause?: string;
// The block device the counters were read from.
device?: string;
+ // How long the drive took (lib/storageHealth.ts `noteDriveAnswer`): the
+ // counters' average per completed request between the two samples, or the
+ // child `stat`'s round trip. Absent when nothing was measured.
+ latencyMs?: number;
};
// What the health pass asks about a location. A bare state is a verdict with
@@ -473,7 +477,31 @@ export function minCounterIntervalMs(): number {
return counterSampleMinimumMs(healthTimings().passIntervalMs);
}
-type CounterSample = BlockStatSample & { device: string; at: number };
+// `ticksMs`: fields 4 + 8 (+ 15 + 17 on kernels that count discards and
+// flushes) — the milliseconds the device's completed requests took, summed.
+type CounterSample = BlockStatSample & { device: string; at: number; ticksMs?: number };
+
+// The time the device's completed requests took, summed, from a stat line:
+// fields 4 (reads), 8 (writes) and, where counted, 15 (discards) and 17
+// (flushes). Null on a line too short to carry them.
+export function blockStatTicksMs(line: string): number | null {
+ const f = line.trim().split(/\s+/).map(Number);
+ if (f.length < 9 || !Number.isFinite(f[3]) || !Number.isFinite(f[7])) return null;
+ const opt = (i: number) => (Number.isFinite(f[i]) ? f[i] : 0);
+ return f[3] + f[7] + opt(14) + opt(16);
+}
+
+// THE DISK'S OWN AVERAGE per completed request between two samples, or
+// undefined when none completed (an idle disk has no latency to report).
+export function countersLatencyMs(
+ prev: Pick<CounterSample, "completed" | "ticksMs">,
+ cur: Pick<CounterSample, "completed" | "ticksMs">,
+): number | undefined {
+ const done = cur.completed - prev.completed;
+ if (done <= 0 || prev.ticksMs === undefined || cur.ticksMs === undefined) return undefined;
+ const ticks = cur.ticksMs - prev.ticksMs;
+ return ticks >= 0 ? ticks / done : undefined;
+}
type DetectorState = {
samples: Map<string, CounterSample>;
@@ -594,9 +622,13 @@ async function blockDeviceOfRoot(
async function readBlockStat(
device: string,
sysBlockDir: string,
-): Promise<BlockStatSample | null> {
+): Promise<(BlockStatSample & { ticksMs?: number }) | null> {
try {
- return parseBlockStat(await readFile(path.join(sysBlockDir, device, "stat"), "utf8"));
+ const line = await readFile(path.join(sysBlockDir, device, "stat"), "utf8");
+ const sample = parseBlockStat(line);
+ if (!sample) return null;
+ const ticksMs = blockStatTicksMs(line);
+ return ticksMs === null ? sample : { ...sample, ticksMs };
} catch {
return null;
}
@@ -637,10 +669,12 @@ export async function detectLocationHealth(
return { answer: null, detector: "counters", device };
}
const answer = countersVerdict(prev, sample);
+ const latencyMs = answer === "ok" ? countersLatencyMs(prev, sample) : undefined;
return {
answer,
detector: "counters",
device,
+ ...(latencyMs !== undefined ? { latencyMs } : {}),
...(answer === "stalled"
? {
cause:
@@ -652,10 +686,12 @@ export async function detectLocationHealth(
}
}
detector.samples.delete(loc.id);
+ const asked = Date.now();
const answer = await probeLocationHealth(loc, opts);
return {
answer,
detector: "stat",
+ ...(answer === "ok" ? { latencyMs: Date.now() - asked } : {}),
...(answer === "stalled"
? { cause: `a stat of its root did not answer within ${secondsText(timeoutMs)}` }
: {}),
@@ -732,11 +768,24 @@ export type MemoizedProbe = StorageLocationProbe & {
export const PROBE_MEMO_MS = 10_000;
type MemoEntry = { root: string; probedAt: number; probe: StorageLocationProbe };
-const probeMemo = new Map<string, MemoEntry>();
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttStorageProbeMemo__: Map<string, MemoEntry> | undefined;
+}
+
+// ON globalThis, the house pattern (lane drive-stall): a page, a poll and the
+// e2e `invalidate-cache` route can each be a different copy of this module,
+// and a reset in one copy that leaves another's map standing answers the next
+// page with a root that is no longer there — for up to ten seconds.
+function probeMemo(): Map<string, MemoEntry> {
+ globalThis.__yttStorageProbeMemo__ ??= new Map();
+ return globalThis.__yttStorageProbeMemo__;
+}
// Test seam, and the escape hatch for a process that has just written a root.
export function resetStorageProbeMemo(): void {
- probeMemo.clear();
+ probeMemo().clear();
}
// Probe a location, at most once per PROBE_MEMO_MS.
@@ -765,7 +814,7 @@ export async function probeLocationMemo(
if (stalledLocation(loc)) {
return { status: "stalled", identity: { known: false }, probedAt: now };
}
- const hit = probeMemo.get(loc.id);
+ const hit = probeMemo().get(loc.id);
if (
!opts.refresh &&
hit &&
@@ -775,6 +824,6 @@ export async function probeLocationMemo(
return { ...hit.probe, probedAt: hit.probedAt };
}
const probe = await probeLocation(loc, bins, opts);
- probeMemo.set(loc.id, { root: loc.root, probedAt: now, probe });
+ probeMemo().set(loc.id, { root: loc.root, probedAt: now, probe });
return { ...probe, probedAt: now };
}
diff --git a/common/views/names.ts b/common/views/names.ts
@@ -30,6 +30,10 @@ export const VIEW_NAMES = [
// /review's X run console (common/controller/xRun.ts xRunConsole): the
// latest run, the X posts channels, the jar's age. Reads disk only.
"xRun",
+ // The dashboard's drive banner (editor/app/storage/lib/driveHealth.ts):
+ // every storage location whose drive is slow, not answering or not mounted.
+ // The health record is memory; the mount half is /storage's 10 s probe memo.
+ "driveHealth",
] as const;
export type ViewName = (typeof VIEW_NAMES)[number];
@@ -58,4 +62,5 @@ export const VIEW_CONTRACT: Record<ViewName, "observe" | "construct"> = {
cleanable: "construct",
cookieAlerts: "construct",
xRun: "construct",
+ driveHealth: "construct",
};
diff --git a/common/views/storage.test.ts b/common/views/storage.test.ts
@@ -507,3 +507,60 @@ test("a location whose drive is not answering reads so, and says since when", ()
}).rows[0];
assert.equal(quiet.notAnswering, undefined);
});
+
+// THE DRIVE'S HEALTH ON EACH ROW (lane drive-stall) — what `pnpm ops get
+// storage` reports: the shell's view, carried as it is; the internal row has
+// none. `probeMounted` is the mount half of it.
+test("each location row carries its drive's health view; the internal row none", async () => {
+ const { driveHealthView, recordLocationHealth, registerLocationHealth, noteDriveAnswer, locationHealth, resetStorageHealth } =
+ await import("../lib/storageHealth");
+ const { probeMounted } = await import("./storage");
+ resetStorageHealth();
+ const cold = loc("cold", "/mnt/cold");
+ const warm = loc("warm", "/mnt/warm");
+ const gone = loc("gone", "/mnt/gone");
+ registerLocationHealth([cold, warm, gone], NOW);
+ recordLocationHealth(cold, "stalled", { now: NOW, cause: "its disk (sdz) had 1 request(s) in flight and completed none in 15 s" });
+ noteDriveAnswer("warm", 2_400, "call", NOW - 1);
+ noteDriveAnswer("warm", 2_400, "call", NOW);
+ const probes = {
+ cold: { status: "stalled" as const, identity: { known: false as const }, probedAt: NOW },
+ warm: { status: "available" as const, identity: { known: false as const }, probedAt: NOW },
+ gone: { status: "unmounted" as const, identity: { known: false as const }, probedAt: NOW },
+ };
+ const drives = Object.fromEntries(
+ [cold, warm, gone].map((l) => [
+ l.id,
+ driveHealthView(l, locationHealth(l.id), { now: NOW, mounted: probeMounted(probes[l.id as keyof typeof probes].status) }),
+ ]),
+ );
+ const { rows } = buildStorageRows({
+ locations: [cold, warm, gone],
+ defaultLocationId: "",
+ probes,
+ drives,
+ rollups: {},
+ internal: { root: "/corpus/channels" },
+ registry: NO_JOBS,
+ now: NOW,
+ });
+ const by = Object.fromEntries(rows.map((r) => [r.id, r]));
+ assert.equal(by.internal.drive, undefined);
+ assert.equal(by.cold.drive?.state, "stalled");
+ assert.equal(by.cold.drive?.since, NOW);
+ assert.match(String(by.cold.drive?.text), /^not answering since \d\d:\d\d — its disk \(sdz\)/);
+ assert.equal(by.warm.drive?.state, "slow");
+ assert.equal(by.warm.drive?.latencyMs, 2_400);
+ assert.equal(by.warm.drive?.lastOkAt, NOW);
+ assert.match(String(by.warm.drive?.text), /^slow at \d\d:\d\d — a read in the editor took 2.4 s$/);
+ assert.equal(by.gone.drive?.state, "unmounted");
+ assert.equal(by.gone.drive?.text, "not mounted");
+ // The mount half: available is mounted, stalled did not ask, the rest are not.
+ assert.equal(probeMounted("available"), true);
+ assert.equal(probeMounted("stalled"), undefined);
+ assert.equal(probeMounted(undefined), undefined);
+ for (const st of ["unmounted", "absent", "missing", "mounted-elsewhere"] as const) {
+ assert.equal(probeMounted(st), false);
+ }
+ resetStorageHealth();
+});
diff --git a/common/views/storage.ts b/common/views/storage.ts
@@ -9,6 +9,7 @@ import type {
} from "../controller/storageLocations";
import type { SavedVideosStoreStatus } from "../controller/relocateSavedVideos";
import type { RegistryReader } from "./inputs";
+import type { DriveHealthView } from "../lib/storageHealth";
// THE /storage PAYLOAD — one row per storage location, and for each row the
// list of things the operator may do to it and why the rest are withheld.
@@ -115,6 +116,12 @@ export type StorageRow = {
// "not answering since 11:35 — …", while the health probe finds this
// location's drive not answering (lib/storageHealth.ts). Absent otherwise.
notAnswering?: string;
+ // THE DRIVE'S HEALTH (lane drive-stall): answering, slow, not answering or
+ // not mounted, with when it last answered and how fast
+ // (lib/storageHealth.ts `driveHealthView`). What `pnpm ops get storage`
+ // reports per location. Absent on the internal row, and when the shell
+ // passed none.
+ drive?: DriveHealthView;
warning?: string;
candidateRoot?: string;
// Why every action on this row is withheld, or null. One re-point runs at a
@@ -235,6 +242,9 @@ export type StorageRowsInputs = {
// Worded by the shell (lib/storageHealth.ts's `notAnsweringText`), because
// this module takes types only from lib/.
notAnswering?: Record<string, string | undefined>;
+ // By location id: the drive's health view, built by the shell from the
+ // health record and this probe (`driveHealthView`).
+ drives?: Record<string, DriveHealthView | undefined>;
rollups: Record<string, LocationRollup | undefined>;
registry: RegistryReader;
udisksctlAvailable?: boolean;
@@ -254,6 +264,14 @@ export const STORAGE_STATUS_LABEL: Record<StorageLocationStatus, string> = {
stalled: "Not answering",
};
+// WHETHER A PROBE STATUS MEANS THE DRIVE IS MOUNTED, for the drive's health
+// view: `available` is, `stalled` did not ask (the health record decides), and
+// every other status is a root that is not there. Undefined for no probe.
+export function probeMounted(status: StorageLocationStatus | undefined): boolean | undefined {
+ if (status === undefined || status === "stalled") return undefined;
+ return status === "available";
+}
+
export const REPOINT_JOB_KIND = "repoint-storage-location";
export const SAVED_VIDEOS_JOB_KIND = "relocate-saved-videos";
@@ -453,6 +471,7 @@ export function buildStorageRows(i: StorageRowsInputs): StorageRowsPayload {
...(i.notAnswering?.[loc.id]
? { notAnswering: i.notAnswering[loc.id] }
: {}),
+ ...(i.drives?.[loc.id] ? { drive: i.drives[loc.id] } : {}),
...(probe?.warning ? { warning: probe.warning } : {}),
...(candidateRoot ? { candidateRoot } : {}),
busy,
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -87,6 +87,7 @@ import {
} from "../lib/transcriptCoverage";
import type { Paths } from "../lib/paths";
import { transcribeWithWorker } from "../controller/transcribeOne";
+import { isMediaDriveHeld } from "../controller/transcribeError";
import { extractVideoId, outputArgsForUrl } from "./runYtdlp";
import { channelExtraArgs, channelPaceSeconds } from "./channelArgs";
import {
@@ -1855,11 +1856,21 @@ async function runManagedDownload(
});
status = "ok-auto-transcribed";
} catch (err) {
- opts.onLog(
- `Whisper failed after no-subs fallback: ${(err as Error).message}\n`,
- );
- status = "failed";
- lastSucceeded = false;
+ if (isMediaDriveHeld(err)) {
+ // THE AUDIO IS HERE; ITS DRIVE IS NOT ANSWERING (lane
+ // drive-stall). The download succeeded — the status stays the
+ // attempt's, as when inline whisper is off, and the transcription
+ // lane picks the video up once the drive answers.
+ opts.onLog(
+ `Audio downloaded for ${videoId}; not transcribed inline: ${(err as Error).message}.\n`,
+ );
+ } else {
+ opts.onLog(
+ `Whisper failed after no-subs fallback: ${(err as Error).message}\n`,
+ );
+ status = "failed";
+ lastSucceeded = false;
+ }
}
} else {
opts.onLog(
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,9 @@
# Changelog
## [Unreleased]
+- **The dashboard says when a media drive is not answering, slow, or not mounted.** A stalled external drive used to show only on `/storage` and in channel badges, so the editor looked broken with nothing on its front page saying why. The dashboard now opens with one card per storage location in trouble: **not answering** (an alert: pages and polls skip the drive, and its channels' jobs wait until it answers), **answering slowly** (everything still runs, just late), or **not mounted** (only when some channel's media is on it). Each card links to `/storage` and to that location's channels. On `/storage` each location has a **Drive** line that says when the drive last answered and how long it took (for example "answering — 12 ms (a read in the editor), last at 11:42"), and a **slow** chip appears next to Available when two reads in a row on it take half the 3-second limit or more (one long read is not enough). `pnpm ops get storage` reports the same for each location under `rows[].drive`: `state` (`ok`, `slow`, `stalled` or `unmounted`), `since`, `lastOkAt`, `latencyMs`, the cause and the one-line text.
+- **A transcription or backfill run waits while its channel's media drive is not answering.** Before, a run that started while the drive answered kept going after the drive stalled. Each next video asked the stalled drive for its audio, waited about 30 seconds and failed. Now the run pauses at the next video and says so in its log ("Holding: the media drive "…" is not answering (since 11:35) — no new transcription starts until it answers again"), then resumes by itself when the drive answers. If it has held for 5 minutes, the run checks the drive itself from a separate process, and it logs that it is still holding every 10 minutes. A run also follows a channel that is moved to another drive while it runs. A video that is refused because the drive is not answering is skipped, not added to the channel's failed-transcriptions list, and is transcribed on a later run. A downloaded video is also not moved into a saved-video store on a drive that is not answering. It stays in the video's folder, and a later pass stores it.
+- **The drive watch no longer overwrites a tier you change while it is pausing channels.** The five-minute storage watch, which pauses the channels on a drive that went away and restores them when it comes back, could save its change in the middle of yours and undo it. It now waits for the same settings lock that the channel-priority save uses. The editor's `dev` script also gives Node 16 file-access threads, as `start`, the systemd unit and the container already do.
- **Deleting a channel takes it off every site.** On 9 Nov, deleting `mooler` left it in efapalyzer's `site.json`, and the site had to be fixed by hand. Danger → Delete and `pnpm ops delete-channel` now rewrite every site whose pool (`channels`) or cited scope (`citedChannels`) names the deleted channel, each as a `patchSite` under that site's lock, so a concurrent edit of the site is not written over (a rename already re-points them through the same writer). The ops answer names those sites in `sitesUpdated`. A site whose write is refused shows up as a `warnings` line, and the delete still stands. Sites that never named the channel are not written (`common/controller/siteMemberships.ts`).
- **`pnpm ops create-site` is the New site form, without a browser.** On 9 Nov an agent had to call `writeSite` from a tsx script to make `efapalyzer`. `create-site` takes `{"siteId", "siteTitle"}` and any of the form's fields: header title (default the title), description, tagline, wordmark lead, accent, public URL, Pages project, hub URL, audience, listed, publish policy, search, archives, duplicates, transcript downloads, PWA, archive cap, groups, default group, channels, cited channels, social links and related sites. It builds the FormData the form posts and saves it through the form's own action (`saveSiteAction` → `writeSite`), so you get the same validation and the same sentences. A new site is **private and unlisted** unless the body says `"audience": "public"` / `"listed": true`. An existing id is refused (409) unless `"update": true`, which is the site page's Save with only the given keys changed; every other key, and the published page list, is kept. Unknown channels, a channel's `groupId` that names none of the site's groups, unknown keys and keys of the wrong type are refused before anything is written. The existence check, the read of the stored site and the save are one read-modify-write under the site's lock (`withSiteLock`). The site form's own Save now takes the same lock, so neither it nor an update is written over a concurrent edit such as a Reports-tab pages patch. It answers the saved site.
- **`pnpm ops channel-rank` places one channel in the order the lanes follow.** Before this, only /channels' "Add to top" moved a channel, and it also sets the tier to normal and turns the download lane on. `channel-rank` moves the rank alone: `{"slug"}` plus exactly one of `"rank": <n>` (or `null` to unrank), `"top": true`, `"bottom": true`, `"before": "<slug>"` or `"after": "<slug>"`. Every other channel keeps its order: channels after it move down only as far as they must, ties stay tied, and `after` lands immediately after its anchor even when the anchor's rank is tied. It goes through the deck's one writer, so the four lane roots are recompiled in the same write. That writer now does its read-modify-write inside a settings lock, which every `saveSettings` takes too, so a concurrent deck save or a parallel `channel-rank` is never written over. Refused before any write: an unknown channel or anchor, an anchor with no rank, a rank that is not a whole number ≥ 0, and a channel paused for every operation (its rank would not be kept). It answers the saved rank and the whole ranked order (`common/lib/channelPriority.ts` `placeChannelRank`).
diff --git a/editor/app/api/test/drive-health/route.ts b/editor/app/api/test/drive-health/route.ts
@@ -0,0 +1,53 @@
+import { NextResponse } from "next/server";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import {
+ noteDriveSlow,
+ recordLocationHealth,
+ registerLocationHealth,
+} from "yt-dlp-transcript-common/lib/storageHealth";
+import { forgetChannelMedia } from "yt-dlp-transcript-common/lib/channelMedia";
+import { resetStorageProbeMemo } from "yt-dlp-transcript-common/controller/storageLocations";
+import { testRouteDenied } from "../_guard";
+
+export const dynamic = "force-dynamic";
+
+// E2E test harness only (guarded by `E2E_TEST_ROUTES`, see _guard.ts).
+//
+// A STALLED DRIVE WITHOUT A HUNG MOUNT. No fixture can make a real drive stop
+// answering, and none should: this records what a detector would have said
+// about a configured location — `stalled` (one answer marks it, as the
+// counters or the watchdog would) or `slow` (the watchdog's slow refusal) —
+// into the process's health record, which every gate, page and poll reads.
+// The health pass then sees the fixture's drive answering and clears a stall
+// after `clearAfterCleanPasses` passes (30 s at the defaults), so a spec
+// asserts within that window. `/api/test/invalidate-cache` forgets it all.
+//
+// POST {"id": "<location id>", "state": "stalled" | "slow", "cause"?: "…"}
+export async function POST(req: Request) {
+ const denied = testRouteDenied();
+ if (denied) return denied;
+ const body = (await req.json().catch(() => ({}))) as {
+ id?: string;
+ state?: string;
+ cause?: string;
+ };
+ const loc = getSettings().storage.locations.find((l) => l.id === body.id);
+ if (!loc) {
+ return NextResponse.json({ error: `no storage location "${body.id}"` }, { status: 404 });
+ }
+ registerLocationHealth([loc]);
+ if (body.state === "stalled") {
+ recordLocationHealth(loc, "stalled", {
+ cause: body.cause ?? "a read in the editor did not answer within 3 s",
+ });
+ } else if (body.state === "slow") {
+ noteDriveSlow(loc.id, body.cause ?? "a read in the editor took 2.4 s");
+ } else {
+ return NextResponse.json({ error: `state must be "stalled" or "slow"` }, { status: 400 });
+ }
+ // The channels' five-second answers and the ten-second probes, so the next
+ // page sees the drive as it is now.
+ forgetChannelMedia();
+ resetStorageProbeMemo();
+ return NextResponse.json({ ok: true });
+}
diff --git a/editor/app/api/view/[name]/route.test.ts b/editor/app/api/view/[name]/route.test.ts
@@ -55,7 +55,7 @@ const PAIRS: Array<[string, string]> = [
// Views born after the consolidation: there is no old path to rewrite, so
// they are served only at /api/view/<name>.
-const NEW_VIEWS = ["cookieAlerts", "xRun"];
+const NEW_VIEWS = ["cookieAlerts", "xRun", "driveHealth"];
async function view(name: string): Promise<number> {
const res = await GET(new Request(`http://localhost/api/view/${name}`), {
diff --git a/editor/app/api/view/views.ts b/editor/app/api/view/views.ts
@@ -12,6 +12,7 @@ import { buildSchedulerStatusPayload } from "../../scheduler/status";
import { widgetSyncInputs } from "../../widget/lib/syncInputs";
import { cleanableChannels } from "../../cleanup/lib/loadCleanup";
import { loadCookieAlerts } from "../../lib/cookieAlerts";
+import { buildDriveHealthPayload } from "../../storage/lib/driveHealth";
import { xRunConsole } from "yt-dlp-transcript-common/controller/xRun";
import {
loadActionableSummary,
@@ -83,6 +84,11 @@ export const VIEWS: Record<ViewName, (req: Request) => Promise<Response>> = {
// recorded job's status.
cookieAlerts: async () => NextResponse.json(await loadCookieAlerts(getPaths())),
+ // The dashboard's drive banner: the storage locations whose drive is slow,
+ // not answering or not mounted. Polled slow; the health record is memory and
+ // the mount probe is memoised 10 s (no drive is asked in-process).
+ driveHealth: async () => NextResponse.json(await buildDriveHealthPayload()),
+
// /review's X run console: the latest run (each channel's state, the
// summary), the X posts channels in the default order and the jar's age
// against social.x.maxCookieAgeMinutes. Disk reads only; nothing asks X.
diff --git a/editor/app/channels/[slug]/persistActions.ts b/editor/app/channels/[slug]/persistActions.ts
@@ -122,7 +122,11 @@ export async function persistChannelVideosAction(
safeRevalidate([`/channels/${slug}`, "/saved-videos"]);
// A run that stopped short or lost a video did not do what it was asked:
// the job says so, and the re-run picks up the rest.
- if (result.stopped === "low-disk" || result.stopped === "rate-limit") {
+ if (
+ result.stopped === "low-disk" ||
+ result.stopped === "rate-limit" ||
+ result.stopped === "store-unavailable"
+ ) {
throw new Error(
`Stopped (${result.stopped}) with ${result.notAttempted.length} video(s) not attempted — run it again later.`,
);
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -82,7 +82,10 @@ import {
unpersistSavedVideo,
type DropSavedAlternateResult,
} from "yt-dlp-transcript-common/lib/savedVideo-server";
-import { SavedVideosStoreInTransitionError } from "yt-dlp-transcript-common/lib/savedVideoStore";
+import {
+ SavedVideosStoreInTransitionError,
+ SavedVideosStoreNotAnsweringError,
+} from "yt-dlp-transcript-common/lib/savedVideoStore";
import {
savedVideoPath,
type SavedVideoOrigin,
@@ -1457,7 +1460,11 @@ export async function dropSavedAlternateAction(
paths,
});
} catch (e) {
- if (e instanceof SavedAlternateRefusal || e instanceof SavedVideosStoreInTransitionError) {
+ if (
+ e instanceof SavedAlternateRefusal ||
+ e instanceof SavedVideosStoreInTransitionError ||
+ e instanceof SavedVideosStoreNotAnsweringError
+ ) {
return { ok: false, error: e.message };
}
throw e;
diff --git a/editor/app/components/dashboard/DashboardCockpit.tsx b/editor/app/components/dashboard/DashboardCockpit.tsx
@@ -10,6 +10,8 @@ import { NeedsWorkPanel } from "./NeedsWorkPanel";
import { QuickAddPanel } from "./QuickAddPanel";
import { FirstRunPanel, type FirstRunState } from "./FirstRunPanel";
import { CookieAlertsPanel } from "./CookieAlertsPanel";
+import { DriveHealthBanner } from "./DriveHealthBanner";
+import type { DriveHealthPayload } from "../../storage/lib/driveHealth";
import type { ServiceCookieAlertsPayload } from "yt-dlp-transcript-common/lib/serviceCookies";
import type { ChannelRowView } from "yt-dlp-transcript-common/views/channelRow";
import { ChannelsTable } from "../../channels/components/ChannelsTable";
@@ -40,9 +42,12 @@ export type DashboardCockpitInitial = {
firstRun?: FirstRunState | null;
// The cookie refresh alerts (lib/cookieAlerts.ts), polled SLOW after this.
cookieAlerts?: ServiceCookieAlertsPayload;
+ // The drive banner (storage/lib/driveHealth.ts), polled SLOW after this.
+ driveHealth?: DriveHealthPayload;
};
const EMPTY_COOKIE_ALERTS: ServiceCookieAlertsPayload = { alerts: [], pending: [] };
+const NO_DRIVE_TROUBLE: DriveHealthPayload = { drives: [] };
// The mission-control cockpit. A server component (app/page.tsx) SSRs the
// initial payloads for a flicker-free first paint; this client shell then polls
@@ -87,9 +92,17 @@ export function DashboardCockpit({
initial.cookieAlerts ?? EMPTY_COOKIE_ALERTS,
);
+ const { data: driveHealth } = usePolledPayload<DriveHealthPayload>(
+ "/api/view/driveHealth",
+ true,
+ SLOW_MS,
+ initial.driveHealth ?? NO_DRIVE_TROUBLE,
+ );
+
return (
<div className="flex flex-col gap-6">
<h1 className="sr-only">Dashboard</h1>
+ <DriveHealthBanner data={driveHealth ?? NO_DRIVE_TROUBLE} />
<CookieAlertsPanel
data={cookieAlerts ?? EMPTY_COOKIE_ALERTS}
onChange={() => void refetchCookieAlerts()}
diff --git a/editor/app/components/dashboard/DriveHealthBanner.tsx b/editor/app/components/dashboard/DriveHealthBanner.tsx
@@ -0,0 +1,84 @@
+"use client";
+
+// THE DRIVE BANNER (lane drive-stall): one card per storage location whose
+// drive is not answering, slow, or not mounted with channels on it — the
+// dashboard's top slot, beside the cookie banners. Not answering and not
+// mounted are different troubles with different fixes, so they read
+// differently: a drive that is here and stalled (a USB enclosure resetting)
+// is waited out, or unplugged and replugged; a drive that is not mounted is
+// mounted. The words come from the server (lib/storageHealth.ts
+// `driveHealthView`), so /storage and this banner cannot disagree.
+
+import Link from "next/link";
+import type {
+ DriveHealthBannerRow,
+ DriveHealthPayload,
+} from "../../storage/lib/driveHealth";
+
+const HEADLINE: Record<Exclude<DriveHealthBannerRow["state"], "ok">, string> = {
+ stalled: "is not answering",
+ slow: "is answering slowly",
+ unmounted: "is not mounted",
+};
+
+const WHAT_HAPPENS: Record<Exclude<DriveHealthBannerRow["state"], "ok">, string> = {
+ stalled:
+ "Pages and polls skip it and its channels' jobs are held until it answers again; nothing else in the editor waits on it.",
+ slow: "Everything still runs; reads on it take longer than they should.",
+ unmounted: "Its channels' jobs are held until it is back.",
+};
+
+function DriveCard({ drive }: { drive: DriveHealthBannerRow }) {
+ if (drive.state === "ok") return null;
+ const severe = drive.state !== "slow";
+ return (
+ <section
+ role={severe ? "alert" : "status"}
+ aria-label={`drive ${drive.id}`}
+ data-state={drive.state}
+ className={`rounded-md border bg-card px-4 py-3 ${
+ severe ? "border-destructive/50" : "border-amber-500/50"
+ }`}
+ >
+ <p
+ className={`text-sm font-medium ${
+ severe ? "text-destructive" : "text-amber-700 dark:text-amber-300"
+ }`}
+ >
+ The media drive {drive.label} {HEADLINE[drive.state]}
+ </p>
+ <p className="text-xs" aria-label={`drive ${drive.id} health`}>
+ {drive.text}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {WHAT_HAPPENS[drive.state]}
+ {" · "}
+ <Link href="/storage" className="underline underline-offset-2 hover:text-foreground">
+ Storage
+ </Link>
+ {drive.channels > 0 && (
+ <>
+ {" · "}
+ <Link
+ href={drive.channelsHref}
+ className="underline underline-offset-2 hover:text-foreground"
+ >
+ {drive.channels} channel(s) on it
+ </Link>
+ </>
+ )}
+ </p>
+ </section>
+ );
+}
+
+export function DriveHealthBanner({ data }: { data: DriveHealthPayload }) {
+ if (data.drives.length === 0) return null;
+ return (
+ <div aria-label="drive health" className="flex flex-col gap-2">
+ {data.drives.map((d) => (
+ <DriveCard key={d.id} drive={d} />
+ ))}
+ </div>
+ );
+}
diff --git a/editor/app/page.tsx b/editor/app/page.tsx
@@ -20,6 +20,7 @@ import { buildWidgetSyncPayload } from "yt-dlp-transcript-common/views/widgetSyn
import { widgetSyncInputs } from "./widget/lib/syncInputs";
import { DashboardCockpit } from "./components/dashboard/DashboardCockpit";
import { loadCookieAlerts } from "./lib/cookieAlerts";
+import { buildDriveHealthPayload } from "./storage/lib/driveHealth";
import {
buildChannelRowView,
channelVolumeOf,
@@ -134,10 +135,11 @@ export default async function Dashboard({
// active site for the SSR seed.
const actionable = buildWidgetActionablePayload(widgetActionableRows(rows));
- const [jobs, sync, cookieAlerts] = await Promise.all([
+ const [jobs, sync, cookieAlerts, driveHealth] = await Promise.all([
buildActiveJobsPayload(),
widgetSyncInputs().then(buildWidgetSyncPayload),
loadCookieAlerts(paths),
+ buildDriveHealthPayload(),
]);
const workers = buildWorkersPayload();
const changelogSource = loadChangelog();
@@ -153,6 +155,7 @@ export default async function Dashboard({
changelogSource,
firstRun: summary.rows.length === 0 ? firstRunState(paths) : null,
cookieAlerts,
+ driveHealth,
}}
/>
);
diff --git a/editor/app/storage/buildStorage.ts b/editor/app/storage/buildStorage.ts
@@ -4,11 +4,14 @@ import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
import { getFreeBytes } from "yt-dlp-transcript-common/lib/diskSpace";
import { udisksctlAvailable } from "yt-dlp-transcript-common/lib/storageVolumes";
import {
+ driveHealthView,
healthTimings,
isDriveNotAnswering,
+ locationHealth,
notAnsweringText,
onDrive,
stalledLocation,
+ type DriveHealthView,
} from "yt-dlp-transcript-common/lib/storageHealth";
import { clearRuleText } from "yt-dlp-transcript-common/lib/storageHealthTimings";
import { listChannelBriefs } from "yt-dlp-transcript-common/controller/channels";
@@ -24,6 +27,7 @@ import {
import { pathExists } from "yt-dlp-transcript-common/controller/relocateDir";
import {
buildStorageRows,
+ probeMounted,
type StorageRowsPayload,
} from "yt-dlp-transcript-common/views/storage";
@@ -136,6 +140,18 @@ export async function buildStorage(): Promise<StorageRowsPayload> {
`Pages and polls skip this drive until it answers ${clears}.${watched}`;
}
}
+ // EACH DRIVE'S HEALTH, from memory and this render's probe: answering, slow,
+ // not answering or not mounted (lib/storageHealth.ts `driveHealthView`). A
+ // record for another root under the same id (a re-point the pass has not
+ // seen yet) is not this drive's.
+ const drives: Record<string, DriveHealthView> = {};
+ for (const loc of locations) {
+ const h = locationHealth(loc.id);
+ drives[loc.id] = driveHealthView(loc, h && h.root === loc.root ? h : undefined, {
+ now,
+ mounted: probeMounted(probes[loc.id]?.status),
+ });
+ }
const store = await inspectSavedVideosStore(paths, settings);
// A store on a location walks that location's drive: through the watchdog,
// so a drive that stops answering mid-walk leaves the size at 0 (the store's
@@ -173,6 +189,7 @@ export async function buildStorage(): Promise<StorageRowsPayload> {
defaultLocationId: settings.storage.defaultLocationId,
probes,
notAnswering,
+ drives,
rollups,
registry: getRegistry(),
udisksctlAvailable: udisksctl,
diff --git a/editor/app/storage/components/StorageLocationsTable.tsx b/editor/app/storage/components/StorageLocationsTable.tsx
@@ -173,6 +173,17 @@ function LocationCard({
>
{row.statusLabel}
</span>
+ {/* SLOW IS NOT A STATUS: the drive is there and answering, a beat
+ late (lib/storageHealth.ts `driveHealthView`). A chip beside the
+ status, so "Available" stays true and the slowness is still seen. */}
+ {row.drive?.state === "slow" && (
+ <span
+ aria-label="location slow"
+ className="rounded-full border border-amber-500/50 bg-amber-500/10 px-2 py-0.5 text-xs font-medium text-amber-700 dark:text-amber-300"
+ >
+ slow
+ </span>
+ )}
{row.isDefault && (
<span className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground">
default
@@ -264,6 +275,16 @@ function LocationCard({
</dd>
<dt className="text-muted-foreground">Last probe</dt>
<dd aria-label="location last probe">{formatAge(row.lastProbeAgeMs)}</dd>
+ {/* THE DRIVE'S HEALTH in one line: answering (how fast, when last),
+ slow, not answering since, or not mounted. */}
+ {row.drive && (
+ <>
+ <dt className="text-muted-foreground">Drive</dt>
+ <dd aria-label="location drive" className="text-xs">
+ {row.drive.text}
+ </dd>
+ </>
+ )}
</dl>
{row.notAnswering && (
diff --git a/editor/app/storage/lib/driveHealth.ts b/editor/app/storage/lib/driveHealth.ts
@@ -0,0 +1,71 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { locationOfDataDir } from "yt-dlp-transcript-common/lib/storageLocations";
+import {
+ driveHealthView,
+ locationHealth,
+ type DriveHealthView,
+} from "yt-dlp-transcript-common/lib/storageHealth";
+import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels";
+import { probeAllLocations } from "yt-dlp-transcript-common/controller/storageLocations";
+import {
+ channelsHrefForLocation,
+ probeMounted,
+} from "yt-dlp-transcript-common/views/storage";
+
+// THE DASHBOARD'S DRIVE BANNER — every storage location whose drive is slow,
+// not answering or not mounted, and how many channels have their media there.
+//
+// NOTHING HERE ASKS A DRIVE IN-PROCESS. The health record is memory (the
+// health pass and the watchdog write it, lib/storageHealth.ts), and the mount
+// half is the same probe /storage renders from: memoised 10 s, a stalled
+// location answered without a call. The channel configs are read only when
+// some drive is in trouble — the corpus disk, one small file per channel —
+// because a drive nobody's media is on is not worth a banner when it is merely
+// unplugged.
+//
+// SERVER ONLY (it reaches the controller, which imports execa).
+
+export type DriveHealthBannerRow = DriveHealthView & {
+ // Channels whose media is on this location (by `mediaDir`, or a legacy
+ // channel's retired `dataDir`).
+ channels: number;
+ // `/channels?location=<id>`: the list of them.
+ channelsHref: string;
+};
+
+export type DriveHealthPayload = { drives: DriveHealthBannerRow[] };
+
+export async function buildDriveHealthPayload(): Promise<DriveHealthPayload> {
+ const paths = getPaths();
+ const locations = getSettings().storage.locations;
+ if (locations.length === 0) return { drives: [] };
+ const probes = await probeAllLocations(locations, paths);
+ const now = Date.now();
+ const troubled = locations
+ .map((loc) => {
+ const h = locationHealth(loc.id);
+ return driveHealthView(loc, h && h.root === loc.root ? h : undefined, {
+ now,
+ mounted: probeMounted(probes[loc.id]?.status),
+ });
+ })
+ .filter((v) => v.state !== "ok");
+ if (troubled.length === 0) return { drives: [] };
+ const counts = new Map<string, number>();
+ for (const { config } of await listChannelConfigs(paths)) {
+ const dir = config.mediaDir?.trim() || config.dataDir?.trim();
+ const loc = dir ? locationOfDataDir(dir, locations) : null;
+ if (loc) counts.set(loc.id, (counts.get(loc.id) ?? 0) + 1);
+ }
+ return {
+ drives: troubled
+ .map((v) => ({
+ ...v,
+ channels: counts.get(v.id) ?? 0,
+ channelsHref: channelsHrefForLocation(v.id),
+ }))
+ // An unplugged drive with nobody's media on it is not news.
+ .filter((v) => v.state !== "unmounted" || v.channels > 0),
+ };
+}
diff --git a/editor/e2e/drive-health.spec.ts b/editor/e2e/drive-health.spec.ts
@@ -0,0 +1,162 @@
+import { mkdir, rm, symlink, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { test, expect, type Page } from "@playwright/test";
+import { baseUrl } from "./baseUrl";
+import { readJson, resetData, resolvePath, testPaths, writeSettings } from "./helpers";
+
+// A DRIVE THAT IS NOT ANSWERING, ONE THAT IS SLOW, ONE THAT IS NOT MOUNTED —
+// and that /storage and the dashboard tell them apart (lane drive-stall).
+//
+// NO FIXTURE HANGS A MOUNT. `/api/test/drive-health` records what a detector
+// would have said about a configured location (a stall, or the watchdog's
+// slow refusal) into the editor's health record, which every gate, page and
+// poll reads; the health pass then sees the fixture's drive answering and
+// clears a stall after two clean passes (15–30 s), so each step marks the
+// drive again just before it looks. "Not mounted" is real: the location's
+// root is removed. The detectors and the state machine are unit-tested
+// (common/lib/storageHealth.test.ts, controller/storageWatch.test.ts).
+
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLUG = "test-youtube";
+const VIDEO = "20240101_test1234567";
+
+const channelDir = () => resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}`);
+
+// The fixture channel's media tier on `root`, as a finished move leaves it
+// (storage-locations.spec.ts builds it the same way).
+async function relocateOnDisk(root: string): Promise<void> {
+ const target = join(root, SLUG, "media");
+ await mkdir(join(target, VIDEO), { recursive: true });
+ await writeFile(join(target, VIDEO, "audio.mp3"), "ID3audio");
+ await symlink(
+ join("..", "..", "media", VIDEO, "audio.mp3"),
+ join(channelDir(), "data", VIDEO, "audio.mp3"),
+ );
+ await symlink(target, join(channelDir(), "media"));
+ const config = await readJson<Record<string, unknown>>(
+ `${testPaths().transcriptsDir}/channels/${SLUG}/config.json`,
+ );
+ await writeFile(
+ join(channelDir(), "config.json"),
+ JSON.stringify({ ...config, mediaDir: target }, null, 2) + "\n",
+ );
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+}
+
+async function mark(id: string, state: "stalled" | "slow"): Promise<void> {
+ const res = await fetch(`${baseUrl}/api/test/drive-health`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ id, state }),
+ });
+ expect(res.ok, await res.clone().text()).toBe(true);
+}
+
+async function setUp(root: string): Promise<void> {
+ await resetData("one-youtube-channel-with-data");
+ await mkdir(root, { recursive: true });
+ await relocateOnDisk(root);
+ await writeSettings({
+ adminTitle: "Test Admin",
+ minFreeDiskGB: 0,
+ storage: {
+ locations: [{ id: "cold", label: "Cold", root, autoRepoint: false }],
+ defaultLocationId: "cold",
+ },
+ });
+}
+
+function row(page: Page, id: string) {
+ return page.getByLabel(`storage location: ${id}`);
+}
+
+test("a stalled drive reads 'not answering' on /storage and the dashboard; an unmounted one 'not mounted'", async ({
+ page,
+}, testInfo) => {
+ test.setTimeout(120_000);
+ const root = testInfo.outputPath("platter");
+ await setUp(root);
+
+ // --- not answering ------------------------------------------------------
+ await mark("cold", "stalled");
+ await page.goto("/storage");
+ const cold = row(page, "cold");
+ await expect(cold.getByLabel("location status")).toHaveText("Not answering");
+ await expect(cold.getByLabel("location drive")).toHaveText(/^not answering since \d\d:\d\d — /);
+ await expect(cold.getByLabel("location slow")).toHaveCount(0);
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await cold.screenshot({ path: testInfo.outputPath("storage-not-answering.png") });
+
+ await mark("cold", "stalled");
+ await page.goto("/");
+ const card = page.getByLabel("drive cold", { exact: true });
+ await expect(card).toBeVisible();
+ await expect(card).toHaveAttribute("data-state", "stalled");
+ await expect(card).toHaveAttribute("role", "alert");
+ await expect(card).toContainText("The media drive Cold is not answering");
+ await expect(page.getByLabel("drive cold health")).toHaveText(/^not answering since \d\d:\d\d/);
+ await expect(card.getByRole("link", { name: "1 channel(s) on it" })).toHaveAttribute(
+ "href",
+ /^\/channels\?location=cold(&|$)/,
+ );
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await page.screenshot({ path: testInfo.outputPath("dashboard-not-answering.png") });
+
+ // --- the drive answers again: no banner -----------------------------------
+ await fetch(`${baseUrl}/api/test/invalidate-cache`);
+ await page.goto("/");
+ await expect(page.getByRole("heading", { name: "Dashboard" })).toBeAttached();
+ await expect(page.getByLabel("drive health")).toHaveCount(0);
+
+ // --- not mounted (the root is gone; its channel's media was on it) --------
+ await rm(root, { recursive: true, force: true });
+ await fetch(`${baseUrl}/api/test/invalidate-cache`);
+ await page.goto("/");
+ const gone = page.getByLabel("drive cold", { exact: true });
+ await expect(gone).toHaveAttribute("data-state", "unmounted");
+ await expect(gone).toContainText("The media drive Cold is not mounted");
+ await expect(page.getByLabel("drive cold health")).toHaveText("not mounted");
+ await page.goto("/storage");
+ await expect(row(page, "cold").getByLabel("location status")).not.toHaveText("Not answering");
+ await expect(row(page, "cold").getByLabel("location drive")).toHaveText("not mounted");
+});
+
+test("a slow drive stays Available with a slow chip, and its dashboard card is a status, not an alert", async ({
+ page,
+}, testInfo) => {
+ test.setTimeout(120_000);
+ const root = testInfo.outputPath("platter");
+ await setUp(root);
+
+ await mark("cold", "slow");
+ await page.goto("/storage");
+ const cold = row(page, "cold");
+ await expect(cold.getByLabel("location status")).toHaveText("Available");
+ await expect(cold.getByLabel("location slow")).toHaveText("slow");
+ await expect(cold.getByLabel("location drive")).toHaveText(
+ /^slow at \d\d:\d\d — a read in the editor took 2.4 s$/,
+ );
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await cold.screenshot({ path: testInfo.outputPath("storage-slow.png") });
+
+ await mark("cold", "slow");
+ await page.goto("/");
+ const card = page.getByLabel("drive cold", { exact: true });
+ await expect(card).toHaveAttribute("data-state", "slow");
+ await expect(card).toHaveAttribute("role", "status");
+ await expect(card).toContainText("The media drive Cold is answering slowly");
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await page.screenshot({ path: testInfo.outputPath("dashboard-slow.png") });
+
+ // `pnpm ops get storage` reports the same view per location.
+ await mark("cold", "slow");
+ const res = await page.request.get(`${baseUrl}/api/ops/storage`, { headers: AUTH });
+ expect(res.ok(), await res.text()).toBe(true);
+ const body = (await res.json()) as {
+ storage: { rows: Array<{ id: string; drive?: { state: string; text: string; lastOkAt?: number } }> };
+ };
+ const drive = body.storage.rows.find((r) => r.id === "cold")?.drive;
+ expect(drive?.state).toBe("slow");
+ expect(drive?.text).toMatch(/^slow at /);
+ expect(body.storage.rows.find((r) => r.id === "internal")?.drive).toBeUndefined();
+});
diff --git a/editor/package.json b/editor/package.json
@@ -4,7 +4,7 @@
"private": true,
"type": "module",
"scripts": {
- "dev": "next dev --port ${EDITOR_PORT:-3001}",
+ "dev": "UV_THREADPOOL_SIZE=${UV_THREADPOOL_SIZE:-16} next dev --port ${EDITOR_PORT:-3001}",
"dev:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next dev --port ${PORT:-3011}",
"start:test": "WORKER_TOKEN=test-worker-token TRANSCRIPTS_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts EXPORT_PUBLIC_DIR=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.export-public SETTINGS_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-settings.json EDITOR_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-changelog.md EXPORT_CHANGELOG_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-export-changelog.md GENERATION_USAGE_FILE=${E2E_DATA_ROOT:-$(pwd)}/test-transcripts/.generation-usage.jsonl YTDLP_BIN=$(pwd)/e2e/fixtures/bin/fake-ytdlp.mjs GALLERY_DL_BIN=$(pwd)/e2e/fixtures/bin/fake-gallery-dl.mjs WHISPER_BIN=$(pwd)/e2e/fixtures/bin/fake-whisper.mjs WHISPER_MODEL=/dev/null CHOUGH_BIN=$(pwd)/e2e/fixtures/bin/fake-chough.mjs CHOUGH_MODEL=/dev/null PARAKEET_STITCH_BIN=$(pwd)/e2e/fixtures/bin/fake-parakeet-stitch.mjs PARAKEET_CLI=/dev/null PARAKEET_MODEL=/dev/null DIARIZE_BIN=$(pwd)/e2e/fixtures/bin/fake-diarize.mjs FFMPEG_BIN=$(pwd)/e2e/fixtures/bin/fake-ffmpeg.mjs FFPROBE_BIN=$(pwd)/e2e/fixtures/bin/fake-ffprobe.mjs OLLAMA_URL=http://127.0.0.1:${OLLAMA_STUB_PORT:-11435} CLAUDE_BIN=$(pwd)/e2e/fixtures/bin/fake-claude.mjs FINDMNT_BIN=$(pwd)/e2e/fixtures/bin/fake-findmnt.mjs UDISKSCTL_BIN=$(pwd)/e2e/fixtures/bin/fake-udisksctl.mjs next start --port ${PORT:-3011}",
"build": "next build",
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -8147,6 +8147,52 @@ shipped". Anchors are at slice DT's tip (`r15/drive-timings`).
stalled at boot before the second counter sample, unless a page reaches it; per-click server
actions; the file route's stream; the corpus disk itself.
+### Lane drive-stall additions (2026-11-09, branch `lane/drive-stall`)
+
+- **The record says more than ok | stalled | absent.** `LocationHealth` gains `lastOkAt` (a pass's
+ clean `ok`, or an `onDrive` call answered in its budget; a registration sets none), `latencyMs` +
+ `latencyFrom` (`call`: the unit's time; `stat`: the child stat's round trip, process start
+ included; `counters`: the device's own average per completed request, Δ(fields 4 + 8 (+ 15 + 17)) /
+ Δcompleted between two samples — `blockStatTicksMs`, `countersLatencyMs` in `storageVolumes.ts`;
+ `parseBlockStat`'s shape is unchanged), and `slowAt`/`slowCause` (a measurement ≥
+ `slowThresholdMs()` = budget / 2 TWICE IN A ROW (`slowStreak`, `SLOW_READINGS_IN_A_ROW`; a fast one resets it), or either of the watchdog's "drive slow" refusals at once, `noteDriveSlow`). A
+ transition to stalled deletes slowAt. `noteDriveAnswer` writes only to an existing entry.
+- **`driveHealthView(loc, health, { mounted })`** (`lib/storageHealth.ts`, pure) is the one view:
+ `stalled` (the record) > `unmounted` (record `absent`, or `mounted: false`) > `slow` (slowAt within
+ `slowWindowMs()` = 2 × passIntervalMs) > `ok`. `probeMounted(status)` (`views/storage.ts`):
+ available → true, stalled/undefined → undefined, the rest → false. Slow is shown, never acted on.
+- **Surfaces.** `StorageRow.drive` (the shell passes `drives`, a record for another root under the
+ same id is dropped) → `pnpm ops get storage` `rows[].drive`; /storage's Drive line
+ (`aria-label="location drive"`) and `slow` chip (`location slow`). The dashboard banner: view
+ `driveHealth` (`storage/lib/driveHealth.ts`, `DriveHealthBanner`, cards `aria-label="drive <id>"`,
+ `data-state`, role alert for stalled/unmounted, status for slow); unmounted shows only with ≥ 1
+ channel's media on the location; configs are read only when a drive is in trouble.
+- **Batches hold mid-run.** `mediaStallHold(config, log, what)` (`lib/mediaStallHold.ts`, memory
+ only, edge-logged) is asked in the pool `limit()` of `runWhisperBatch` and of the backfill lane of
+ `runOperationBatch` (not digest): 0 while the channel's media location is stalled, so runPool
+ pauses (its idle poll is unref'd — a unit test needs a keep-alive). It heals itself: after `MEDIA_HOLD_REPROBE_AFTER_MS` (5 min) held, at most once per 5 min, a child
+ `stat` of the root (`probeLocationHealth`); answering clears a STALE record (no pass refreshed it for
+ 3 pass intervals) or counts once on a kept one. "Still holding" every 10 min; `reloadConfig` re-reads
+ the channel's targets at most every 10 s. Persist-videos and persist-kept ask
+ `savedVideosStoreRefusal` before each fetch and stop (`store-unavailable`, `skippedStoreUnavailable`);
+ `isMediaDriveHeld` is the one predicate (downloadOneManaged's inline whisper keeps the download's status). It gates DISPATCH only: the
+ batch's classification reads `data/` (readdir, the corpus disk) and never waits. The autoRunner
+ lanes were already held at pick time (`buildChannelWork`). `transcribeOneVideo` refuses before
+ `resolveAudioFile` with `MediaDriveHeldError` (`failureClass` "no-audio": skipped, never
+ failed-transcriptions; `transcribeOneFromQueue` logs its message).
+- **The five-minute watch writes under the settings lock** (`withJsonFileLock(getPaths().settingsFile)`,
+ the lock `editor/app/settings/saveSettings.ts` `withSettingsLock` takes). `storageLocations.ts`'s and
+ `relocateSavedVideos.ts`'s settings writers still do not take it.
+- **`/api/test/drive-health`** (`POST {id, state: "stalled"|"slow", cause?}`, E2E_TEST_ROUTES only)
+ records a detector's answer for a configured location; the pass clears a stall in 15–30 s.
+- **The persist guard asks the record too.** `assertSavedVideosStoreWritable` throws
+ `SavedVideosStoreNotAnsweringError` for a store on a stalled location (the corpus store via
+ `readlink(savedVideosDir)`, a channel store by its path) before the marker check; persist callers
+ already catch and leave the container in `data/<id>/`.
+- **The location probe memo is on `globalThis.__yttStorageProbeMemo__`** (was a module Map): a
+ `resetStorageProbeMemo()` from the e2e `invalidate-cache` route did not reach the page's copy, which
+ answered "available" for a removed root for up to 10 s.
+
## The source's history (stagit) (verified 2026-09-30, branch `r15/stagit`)
Release 15 slice SG ([`release-15.md`](release-15.md)); the operator-facing doc is `PUBLISH.md`, "The
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1097,7 +1097,9 @@ export function usage() {
"",
"get settings [<key>] is settings.json as the editor reads it (migrated and",
" defaulted; a secret is \"<redacted>\"), or one top-level key of it.",
- "get storage is /storage: each location, mounted or not, free space, tiers.",
+ "get storage is /storage: each location, mounted or not, free space, tiers,",
+ " and its drive's health (rows[].drive: ok | slow | stalled | unmounted,",
+ " since, lastOkAt, latencyMs, the cause and the one-line text).",
"get saved-alternates [<slug>] lists every saved video holding two copies:",
" a download over a container already in the store keeps both — an",
" explicit persist (persist-videos, Persist source video, a whole-recording",
diff --git a/umtool/app/api/report/embed-ids/route.ts b/umtool/app/api/report/embed-ids/route.ts
@@ -0,0 +1,61 @@
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, StructureRefused, manifestToken } from "@/lib/report/manifest.mjs";
+import { embedIdFixes, embedIdRows } from "@/lib/report/embedIds.mjs";
+import { setSiteVideos } from "@/lib/report/inspectorEdits.mjs";
+import { readLinkCheck } from "@/lib/report/linkCheck.mjs";
+import { readManifest } from "@/lib/projects/report.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE PUBLISHED EMBED ID (umtool redesign L6, the Links panel's "Use the published embed id"; 4 and 8 Nov: a
+// Rumble clip's QR named the URL-slug folder the corpus keeps it under, and the archive serves the EMBED id):
+// every clip of the cut citing such a folder, its embed id read from the folder's metadata.info.json through L1's
+// one mapping (shareLine.mjs siteVideoFor), with what the last link check (out/links.json) said of its QR. The
+// fix writes `siteVideo` (and a citeUrl that named the folder) -- one write, one undo point. No network: the
+// check is `umtool links <p>`'s; `umtool links <p> --embed-ids` is this route's twin.
+//
+// GET ?project=<id> { rows: [{ clip, channel, video, siteVideo, url, fixedUrl, citeUrl, state }], checkedAt, token }
+// POST { project, token, clips?: [id…] } those rows fixed (no clips: every row)
+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 doc = await readLinkCheck(r.project.dir);
+ const rows = await embedIdRows(r.project.dir, r.manifest as Record<string, unknown>, { doc });
+ return Response.json({ rows, checkedAt: doc?.checkedAt ?? null, token: await manifestToken(r.project.dir) }, { headers: noStore });
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/embed-ids");
+ if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ if (typeof body.token !== "string" || !body.token) return Response.json({ error: "token is required: GET the route first (a write over a newer draft is refused, never silent)" }, { status: 400 });
+ const clips = Array.isArray(body.clips) ? body.clips.map(String) : null;
+ try {
+ const { result, editNotes } = await withEditNotes(r.project, async () => {
+ // The rows as the manifest is NOW (read inside the request, the writer checks the token).
+ const m = (await readManifest(r.project.dir)) as Record<string, unknown>;
+ const rows = await embedIdRows(r.project.dir, m, { doc: await readLinkCheck(r.project.dir) });
+ return setSiteVideos(r.project.dir, embedIdFixes(rows, clips), { token: body.token as string });
+ });
+ return Response.json({ ok: true, fixed: result.fixed, token: result.token, editNotes }, { headers: noStore });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/app/api/report/ledger/route.ts b/umtool/app/api/report/ledger/route.ts
@@ -0,0 +1,110 @@
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, addLedgerRow, manifestToken, removeLedgerRow, updateLedgerRow } from "@/lib/report/manifest.mjs";
+import { isMeasureLedger, parseLedgerValue } from "@/lib/report/ledgerRows.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
+import { EVENTS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, VALUE_KINDS, measureSchema } from "umtool-report-to-video/ledger-totals";
+
+export const dynamic = "force-dynamic";
+
+// A MEASURE LEDGER's ROWS (umtool redesign L6, the inspector's Ledger panel; weight video rev 9): the rows the
+// instruments draw from (`manifest.ledger`, read by the build through ledgerSchema), added, changed and removed
+// through the manifest's own writers -- addLedgerRow / updateLedgerRow / removeLedgerRow, each row checked by
+// ledgerRows.mjs ledgerRowOf against the schema (the CLI's checks, word for word), one undo point each.
+// `umtool ledger <p> add|set|rm` is the same writer.
+//
+// GET ?project=<id>[&entry=<timeline id>] the schema's vocabulary (tracks, forms, regimes, declared fields,
+// events, the six adjudication words), the rows (those pinned to the
+// entry when one is named), the token
+// POST { project, token, op: "add", row } a new row (its id in it)
+// POST { project, token, op: "set", id, patch, unset?: [key…] } a row changed
+// POST { project, token, op: "rm", id } a row removed (refused while anything names it)
+// A string value is read as the CLI reads a flag's text (ledgerRows.mjs parseLedgerValue: a number key a
+// number, true/false, "a|b" a list for flags, "null" clears).
+const noStore = { "cache-control": "no-store" };
+type Row = Record<string, unknown> & { id?: string; entryId?: string };
+
+const parsed = (patch: unknown) => {
+ const out: Record<string, unknown> = {};
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) return out;
+ for (const [k, v] of Object.entries(patch as Record<string, unknown>)) out[k] = typeof v === "string" ? parseLedgerValue(k, v) : v;
+ return out;
+};
+
+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 { ledgerSchema?: Record<string, unknown>; ledger?: Row[] };
+ const rows = Array.isArray(m.ledger) ? m.ledger : [];
+ const entry = url.searchParams.get("entry");
+ let schema = null;
+ let schemaError = null;
+ if (isMeasureLedger(m)) {
+ try {
+ const s = measureSchema(m.ledgerSchema);
+ schema = {
+ unit: (m.ledgerSchema?.unit as string | undefined) ?? "",
+ tracks: s.tracks.map((t: { key: string; label: string; role: string; regimes: string[] | null }) => ({ key: t.key, label: t.label, role: t.role, regimes: t.regimes })),
+ forms: s.forms,
+ regimes: s.regimes.map((x: { key: string; label: string }) => ({ key: x.key, label: x.label })),
+ fields: s.fields.map((f: { key: string; label?: string; kind?: string; options?: unknown }) => ({ key: f.key, label: f.label ?? f.key, kind: f.kind ?? "text", options: Array.isArray(f.options) ? f.options : null })),
+ events: EVENTS, promiseForms: PROMISE_FORMS, outcomes: PROMISE_OUTCOMES, scopeConfidence: SCOPE_CONFIDENCE, valueKinds: VALUE_KINDS,
+ };
+ } catch (e) {
+ schemaError = e instanceof Error ? e.message : String(e);
+ }
+ }
+ return Response.json(
+ {
+ kind: isMeasureLedger(m) ? "measure" : rows.length || m.ledgerSchema ? "headcount" : null,
+ schema,
+ schemaError,
+ total: rows.length,
+ rows: entry ? rows.filter((x) => x?.entryId === entry) : rows,
+ entries: ((r.manifest as { timeline?: { id?: string; type?: string }[] }).timeline ?? []).map((e) => String(e?.id ?? "")).filter(Boolean),
+ token: await manifestToken(r.project.dir),
+ },
+ { headers: noStore },
+ );
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/ledger");
+ if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const token = typeof body.token === "string" ? body.token : null;
+ const id = String(body.id ?? "");
+ try {
+ if (body.op === "add") {
+ const row = parsed(body.row);
+ const { result, editNotes } = await withEditNotes(r.project, () => addLedgerRow(r.project.dir, row, { token }));
+ return Response.json({ ok: true, row: result.row, token: result.token, editNotes }, { headers: noStore });
+ }
+ if (body.op === "set") {
+ const unset = Array.isArray(body.unset) ? body.unset.map(String) : [];
+ const { result, editNotes } = await withEditNotes(r.project, () => updateLedgerRow(r.project.dir, id, parsed(body.patch), { token, unset }));
+ return Response.json({ ok: true, row: result.row, token: result.token, editNotes }, { headers: noStore });
+ }
+ if (body.op === "rm") {
+ // A removal is checked against the draft this panel read: never a blind delete.
+ if (!token) return Response.json({ error: "token is required to remove a row: GET the route first" }, { status: 400 });
+ const { result, editNotes } = await withEditNotes(r.project, () => removeLedgerRow(r.project.dir, id, { token }));
+ return Response.json({ ok: true, removed: result.row?.id ?? id, token: result.token, editNotes }, { headers: noStore });
+ }
+ return Response.json({ error: "op is add, set or rm" }, { status: 400 });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/app/api/report/post-item/inspector/route.ts b/umtool/app/api/report/post-item/inspector/route.ts
@@ -0,0 +1,121 @@
+import { readdir, stat } from "node:fs/promises";
+import path from "node:path";
+import { cardText, excerptErrors, excerptRanges, excerptSpansOf } from "umtool-report-to-video/post-item";
+import { pickedTake } from "umtool-report-to-video/post-narration";
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, StructureRefused, manifestToken, updatePostItem } from "@/lib/report/manifest.mjs";
+import { attachmentOf } from "@/lib/report/postsCli.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
+
+export const dynamic = "force-dynamic";
+
+// A POST ITEM, AS THE INSPECTOR EDITS IT (umtool redesign L6, item 4; 6-8 Nov these were `posts set-item
+// excerpt=…` and `posts narrate --recording` by hand): the card's words as the excerpt reads them (cardText),
+// the excerpt's spans and where they stand, the item's attachments and the post's files it does not carry, and
+// its narration's takes. Its writes are the post bench's: POST /api/report/post-item {op: "set"} (the excerpt,
+// an attachment off or its sound), the multipart POST /api/report/post-narration (a recording), and here:
+//
+// GET ?project=<id>&id=<item> the view above, and the token
+// POST { project, token, id, op: "media-on", file: "posts-media/…" } a file of the post the item never carried put
+// on it, measured as `posts set-item media.add=` measures one (refused
+// when the item carries it, shown or switched off)
+// POST { project, token, id, op: "media-off", i } attachment i switched OFF, kept whole in `mediaOff` (its crop,
+// blur, trim, sound kept; nothing draws it) -- `set-item media.<i>.shown=off`
+// POST { project, token, id, op: "media-show", j } the attachment switched off at j shown again, as it was
+// -- `set-item media-off.<j>.shown=on`
+const noStore = { "cache-control": "no-store" };
+const MEDIA_RE = /\.(png|jpe?g|webp|gif|mp4|m4v|mov|webm)$/i;
+type Entry = Record<string, unknown> & { id: string; type?: string; post?: string; media?: Array<Record<string, unknown>>; mediaOff?: Array<Record<string, unknown>>; narration?: Record<string, unknown> };
+
+/** The post's own files in the project (posts-media/<channel>/<postId>/), pictures and videos, its screenshots left out. */
+async function postFiles(dir: string, e: Entry): Promise<string[]> {
+ const roots = new Set<string>();
+ if (typeof e.post === "string" && /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/.test(e.post)) roots.add(`posts-media/${e.post}`);
+ for (const m of [...(e.media ?? []), ...(e.mediaOff ?? [])]) if (typeof m?.src === "string" && m.src.startsWith("posts-media/")) roots.add(path.posix.dirname(m.src));
+ const out: string[] = [];
+ for (const rel of roots) {
+ if (rel.split("/").includes("..")) continue;
+ const names = await readdir(path.join(dir, ...rel.split("/"))).catch(() => [] as string[]);
+ for (const n of names.sort()) {
+ if (!MEDIA_RE.test(n) || /^shot/i.test(n) || n.startsWith(".")) continue;
+ const st = await stat(path.join(dir, ...rel.split("/"), n)).catch(() => null);
+ if (st?.isFile()) out.push(`${rel}/${n}`);
+ }
+ }
+ return out;
+}
+
+export async function GET(request: Request) {
+ const q = new URL(request.url).searchParams;
+ const r = await resolveReport(q.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const tl = ((r.manifest as { timeline?: Entry[] }).timeline ?? []) as Entry[];
+ const id = q.get("id") ?? "";
+ const e = tl.find((x) => x?.type === "post" && x.id === id);
+ if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 });
+ const text = cardText(e) as string;
+ const spans = excerptSpansOf(e) as string[] | null;
+ const media = (e.media ?? []).map((m, i) => ({
+ i, src: typeof m?.src === "string" ? m.src : null, kind: typeof m?.kind === "string" ? m.kind : null,
+ mute: m?.mute === true, seconds: typeof m?.seconds === "number" ? m.seconds : null, audio: m?.audio === true,
+ }));
+ const off = (e.mediaOff ?? []).map((m, j) => ({ j, src: typeof m?.src === "string" ? m.src : null, kind: typeof m?.kind === "string" ? m.kind : null }));
+ const carried = new Set([...media.map((m) => m.src), ...off.map((m) => m.src)]);
+ const takes = Array.isArray(e.narration?.takes) ? (e.narration.takes as Array<Record<string, unknown>>) : [];
+ const picked = pickedTake(e) as (Record<string, unknown> & { file: string; index: number }) | null;
+ return Response.json(
+ {
+ id: e.id, post: e.post ?? null, author: e.author ?? null, handle: e.handle ?? null, text,
+ excerpt: spans, ranges: spans ? excerptRanges(text, spans) : null, excerptErrors: excerptErrors(e),
+ media, off, files: (await postFiles(r.project.dir, e)).filter((f) => !carried.has(f)),
+ narration: {
+ takes: takes.map((t, i) => ({ i, file: String(t.file ?? ""), engine: typeof t.engine === "string" ? t.engine : null, voice: typeof t.voice === "string" ? t.voice : null, seconds: typeof t.seconds === "number" ? t.seconds : null })),
+ picked: picked ? picked.index : null,
+ off: e.narration?.off === true,
+ },
+ token: await manifestToken(r.project.dir),
+ },
+ { headers: noStore },
+ );
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/post-item/inspector");
+ if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ if (!["media-on", "media-off", "media-show"].includes(String(body.op))) return Response.json({ error: "op is media-on, media-off or media-show" }, { status: 400 });
+ const id = String(body.id ?? "");
+ const tl = ((r.manifest as { timeline?: Entry[] }).timeline ?? []) as Entry[];
+ const e = tl.find((x) => x?.type === "post" && x.id === id);
+ if (!e) return Response.json({ error: `no post item ${id}` }, { status: 404 });
+ const token = typeof body.token === "string" ? body.token : null;
+ try {
+ let patch: Record<string, unknown>;
+ if (body.op === "media-on") {
+ const file = String(body.file ?? "");
+ // Only one of the post's own files (the list GET gives): never a path from elsewhere in the project.
+ if (!(await postFiles(r.project.dir, e)).includes(file)) return Response.json({ error: `${file} is not one of ${id}'s post files` }, { status: 400 });
+ // A file the item carries already -- shown, or switched off with its knobs -- is not added twice.
+ if ([...(e.media ?? []), ...(e.mediaOff ?? [])].some((m) => m?.src === file)) return Response.json({ error: `${id} carries ${file} already (switched off: show it again)` }, { status: 400 });
+ patch = { mediaAdd: [await attachmentOf(r.project.dir, file)] };
+ } else if (body.op === "media-off") patch = { mediaHide: [Number(body.i)] };
+ else patch = { mediaShow: [Number(body.j)] };
+ const { result, editNotes } = await withEditNotes(r.project, () => updatePostItem(r.project.dir, id, patch, { token }));
+ return Response.json({ ok: true, entry: result.entry, token: result.token, editNotes }, { headers: noStore });
+ } catch (e2) {
+ if (e2 instanceof StaleToken) return Response.json({ error: e2.message, stale: true }, { status: 409 });
+ if (e2 instanceof StructureRefused) return Response.json({ error: e2.message, errors: e2.errors }, { status: 400 });
+ return Response.json({ error: e2 instanceof Error ? e2.message : String(e2) }, { status: 400 });
+ }
+}
diff --git a/umtool/app/api/report/post-narration/route.ts b/umtool/app/api/report/post-narration/route.ts
@@ -354,7 +354,9 @@ async function record(request: Request) {
const parts = [];
for (const [k, b] of blobs.entries()) {
if (b.size > 200 * 1024 * 1024) return Response.json({ error: "a part is larger than 200 MB" }, { status: 413 });
- const f = path.join(up, `p${k + 1}.${/ogg/.test(b.type) ? "ogg" : /wav/.test(b.type) ? "wav" : "webm"}`);
+ // A file chosen from disk (the inspector's "Use my recording") keeps its own extension; a browser recording its type's.
+ const own = /\.(wav|mp3|m4a|aac|ogg|opus|flac|webm|mp4|mov)$/i.exec(typeof b.name === "string" ? b.name : "")?.[1]?.toLowerCase();
+ const f = path.join(up, `p${k + 1}.${own ?? (/ogg/.test(b.type) ? "ogg" : /wav/.test(b.type) ? "wav" : "webm")}`);
await writeFile(f, new Uint8Array(await b.arrayBuffer()));
parts.push({ file: f, text: texts[k] ?? "", para: Number.isInteger(paras[k]) ? paras[k] : k });
}
diff --git a/umtool/app/api/report/provenance/route.ts b/umtool/app/api/report/provenance/route.ts
@@ -0,0 +1,71 @@
+import { readdir } from "node:fs/promises";
+import { invalidateProjects } from "@/lib/projects";
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs";
+import { provenanceView, updateProvenance } from "@/lib/report/inspectorEdits.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
+import { sitesByOrigin } from "@/lib/report/siteDeploys.mjs";
+import { CHANNELS_DIR, SITES_DIR } from "@/lib/paths.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE PROJECT'S PROVENANCE (umtool redesign L6, the inspector's Provenance panel; `umtool provenance` is the
+// same writer): provenance.siteOrigin, channelSlug and channel -- the keys agents set by hand this week (a
+// `umtool new` with no --from leaves channelSlug empty, and `check` blocks on it). The link policy beside them
+// is /api/report/link-policy's.
+//
+// GET ?project=<id> the three keys, the link policy, the cut's channels (with their clip counts) and the
+// corpus's, the sites (SITES_DIR, each with a siteUrl), the token
+// PUT { project, token, patch: { siteOrigin?, channelSlug?, channel? } } set them ("" or null removes one)
+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>();
+ for (const e of m.timeline ?? []) if (e?.type === "clip" && typeof e.channel === "string" && e.channel) counts.set(e.channel, (counts.get(e.channel) ?? 0) + 1);
+ const corpus = await readdir(/* turbopackIgnore: true */ CHANNELS_DIR, { withFileTypes: true }).then(
+ (d) => d.filter((x) => x.isDirectory() && !x.name.startsWith(".")).map((x) => x.name).sort().slice(0, 4000),
+ () => [] as string[],
+ );
+ return Response.json(
+ {
+ provenance: provenanceView(m),
+ linkPolicy: m.provenance?.linkPolicy ?? null,
+ channels: [...counts].map(([slug, clips]) => ({ slug, clips })).sort((a, b) => b.clips - a.clips || a.slug.localeCompare(b.slug)),
+ corpusChannels: corpus,
+ 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/provenance");
+ if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ try {
+ const { result, editNotes } = await withEditNotes(r.project, () =>
+ updateProvenance(r.project.dir, (body.patch ?? {}) as Record<string, unknown>, { token: typeof body.token === "string" ? body.token : null }),
+ );
+ invalidateProjects();
+ return Response.json({ ok: true, ...result, editNotes }, { headers: noStore });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/app/api/report/still-frame/route.ts b/umtool/app/api/report/still-frame/route.ts
@@ -0,0 +1,58 @@
+import { readFile, stat } from "node:fs/promises";
+import { resolveClip, resolveReport } from "@/lib/report/serve.mjs";
+import { StillRefused, grabStill, listShots, shotFileOf } from "@/lib/report/stillGrab.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
+
+export const dynamic = "force-dynamic";
+
+// A STILL AT SECOND N (umtool redesign L6: Play's Still button; `umtool still` is the twin): one frame of the
+// clip on screen at the playhead's SOURCE second, grabbed from its fetched window (lib/report/stillGrab.mjs: a
+// single `ffmpeg -ss -frames:v 1`, not heavy work) into the project's shots/ beside its other shots -- where a
+// clip's fx.zoom / fx.receipts read pictures from. Nothing is fetched, and nothing in the cut is written.
+//
+// GET ?project=<id> { shots: [{ rel, name, bytes, mtime, still: { clip, at } | null }] }
+// GET ?project=<id>&file=shots/<name> the picture
+// POST { project, clip, at, take? } grab it -> { rel, clip, video, at, bytes }
+const noStore = { "cache-control": "no-store" };
+const TYPES: Record<string, string> = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };
+
+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 file = url.searchParams.get("file");
+ if (file) {
+ const abs = shotFileOf(r.project.dir, file);
+ if (!abs) return new Response("not a picture in shots/", { status: 404 });
+ const st = await stat(abs).catch(() => null);
+ if (!st?.isFile()) return new Response("gone", { status: 404 });
+ const ext = abs.slice(abs.lastIndexOf(".")).toLowerCase();
+ return new Response(new Uint8Array(await readFile(abs)), { headers: { "content-type": TYPES[ext] ?? "application/octet-stream", "cache-control": "no-cache" } });
+ }
+ return Response.json({ shots: await listShots(r.project.dir) }, { headers: noStore });
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/still-frame");
+ if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const take = typeof body.take === "string" && body.take ? body.take : null;
+ const r = await resolveClip(String(body.project ?? ""), String(body.clip ?? ""), { take });
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ try {
+ const done = await grabStill(r.project, r.manifest, r.clip.id, Number(body.at));
+ const { file: _abs, ...rest } = done;
+ return Response.json({ ok: true, ...rest }, { headers: noStore });
+ } catch (e) {
+ if (e instanceof StillRefused) return Response.json({ error: e.message }, { status: e.status });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500 });
+ }
+}
diff --git a/umtool/app/api/report/teaser/route.ts b/umtool/app/api/report/teaser/route.ts
@@ -0,0 +1,73 @@
+import { invalidateProjects } from "@/lib/projects";
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, StructureRefused, manifestToken, updateTeaser } from "@/lib/report/manifest.mjs";
+import { insertTeaser, teaserLimits, teaserLineOf } from "@/lib/report/inspectorEdits.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
+
+export const dynamic = "force-dynamic";
+
+// A TEASER OR CLOSING CARD (umtool redesign L6, the inspector's Insert a card): a `type: "teaser"` entry -- its
+// lines (the first its title; each with a break and a hold), its beat -- inserted at the start, the end, or
+// beside an entry, or an existing one's lines and beat changed. Checked by the build's validateTeaser; one write,
+// one undo point each. `umtool timeline <p> teaser-insert` / `timeline <p> teaser <id> <patch>` are the twins.
+//
+// GET ?project=<id> the cut's entries (id, type, a label) for the position,
+// its teasers as written, the limits, the token
+// POST { project, token, op: "insert", spec: { id?, lines, beat? }, position: "start" | "end" | { after } | { before } }
+// POST { project, token, op: "set", id, patch: { lines?, beat? } }
+const noStore = { "cache-control": "no-store" };
+type Entry = { id?: string; type?: string; heading?: string; title?: string; label?: string; lines?: unknown[]; beat?: number; video?: string };
+
+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 tl = (Array.isArray((r.manifest as { timeline?: unknown }).timeline) ? (r.manifest as { timeline: Entry[] }).timeline : []) as Entry[];
+ return Response.json(
+ {
+ entries: tl.map((e, at) => ({ id: String(e?.id ?? ""), type: String(e?.type ?? "?"), at, label: e?.heading ?? e?.title ?? e?.label ?? e?.video ?? null })),
+ teasers: tl.flatMap((e, at) => (e?.type === "teaser" ? [{ id: String(e.id), at, lines: e.lines ?? [], beat: typeof e.beat === "number" ? e.beat : null }] : [])),
+ limits: teaserLimits(),
+ token: await manifestToken(r.project.dir),
+ },
+ { headers: noStore },
+ );
+}
+
+export async function POST(request: Request) {
+ const refused = refuseCaller(request, "/api/report/teaser");
+ if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ if (typeof body.token !== "string" || !body.token) return Response.json({ error: "token is required: GET the route first (a write over a newer draft is refused, never silent)" }, { status: 400 });
+ const token = body.token as string;
+ try {
+ if (body.op === "insert") {
+ const { result, editNotes } = await withEditNotes(r.project, () => insertTeaser(r.project.dir, (body.spec ?? {}) as Record<string, unknown>, body.position ?? "end", { token }));
+ invalidateProjects();
+ return Response.json({ ok: true, id: result.id, at: result.at, entry: result.entry, token: result.token, editNotes }, { headers: noStore });
+ }
+ if (body.op === "set") {
+ const patch = { ...((body.patch ?? {}) as Record<string, unknown>) };
+ // The lines as the insert writes them: a line that is only its words is a string, empty keys left out.
+ if (Array.isArray(patch.lines)) patch.lines = patch.lines.map((l: unknown) => teaserLineOf(l));
+ const { result, editNotes } = await withEditNotes(r.project, () => updateTeaser(r.project.dir, String(body.id ?? ""), patch, { token }));
+ return Response.json({ ok: true, id: result.id, entry: result.entry, token: result.token, editNotes }, { headers: noStore });
+ }
+ return Response.json({ error: "op is insert or set" }, { status: 400 });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ if (e instanceof StructureRefused) return Response.json({ error: e.message, errors: e.errors }, { status: 400 });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/app/api/report/title/route.ts b/umtool/app/api/report/title/route.ts
@@ -0,0 +1,58 @@
+import { invalidateProjects } from "@/lib/projects";
+import { withEditNotes } from "@/lib/report/guard";
+import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs";
+import { SUBTITLE_MAX, TITLE_MAX, updateTitle } from "@/lib/report/inspectorEdits.mjs";
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { refuseCaller } from "@/lib/report/caller";
+import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE PROJECT'S TITLE AND SUBTITLE (umtool redesign L6, item 7; 9 Nov: four news projects' were set with jq):
+// the manifest's `title` and `subtitle`. `umtool title <p> "<title>" [--subtitle "…"]` is the same writer.
+//
+// GET ?project=<id> { title, subtitle, limits, token }
+// PUT { project, token, title?, subtitle? } set them (subtitle "" or null removes it); one undo point
+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 { title?: unknown; subtitle?: unknown };
+ return Response.json(
+ {
+ title: typeof m.title === "string" ? m.title : null,
+ subtitle: typeof m.subtitle === "string" ? m.subtitle : null,
+ limits: { title: TITLE_MAX, subtitle: SUBTITLE_MAX },
+ token: await manifestToken(r.project.dir),
+ },
+ { headers: noStore },
+ );
+}
+
+export async function PUT(request: Request) {
+ const refused = refuseCaller(request, "/api/report/title");
+ if (refused) return refused;
+ const cross = crossSiteRefusal(request.headers);
+ if (cross) return Response.json({ error: cross }, { status: 403 });
+ let body: Record<string, unknown>;
+ try {
+ body = await request.json();
+ } catch {
+ return Response.json({ error: "expected JSON" }, { status: 400 });
+ }
+ const r = await resolveReport(String(body.project ?? ""));
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ const patch: Record<string, unknown> = {};
+ if ("title" in body) patch.title = body.title;
+ if ("subtitle" in body) patch.subtitle = body.subtitle;
+ try {
+ const { result, editNotes } = await withEditNotes(r.project, () => updateTitle(r.project.dir, patch, { token: typeof body.token === "string" ? body.token : null }));
+ invalidateProjects();
+ return Response.json({ ok: true, ...result, editNotes }, { headers: noStore });
+ } catch (e) {
+ if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -931,6 +931,10 @@ const COMMANDS = {
vertical: async () => process.exit(await (await import("../lib/report/verticalCli.mjs")).verticalCommand(argv.slice(argv.indexOf("vertical") + 1))),
// Quick clip (lane output-modes): one moment to a basic-mode mp4 and its share line: lib/report/quickClip.mjs.
clip: async () => process.exit(await (await import("../lib/report/quickClip.mjs")).quickClipCommand(argv.slice(argv.indexOf("clip") + 1))),
+ // The inspector's twins (umtool redesign L6): provenance, title, a still at second N -- lib/report/inspectorCli.mjs.
+ provenance: async () => process.exit(await (await import("../lib/report/inspectorCli.mjs")).provenanceCommand(argv.slice(argv.indexOf("provenance") + 1))),
+ title: async () => process.exit(await (await import("../lib/report/inspectorCli.mjs")).titleCommand(argv.slice(argv.indexOf("title") + 1))),
+ still: async () => process.exit(await (await import("../lib/report/inspectorCli.mjs")).stillCommand(argv.slice(argv.indexOf("still") + 1))),
// A clip's share line (lane output-modes): lib/report/shareLineCli.mjs.
share: async () => process.exit(await (await import("../lib/report/shareLineCli.mjs")).shareCommand(argv.slice(argv.indexOf("share") + 1))),
// Do the QR links open on their sites (UI notes #8): lib/report/linksCli.mjs.
diff --git a/umtool/components/projects/inspector/LedgerInspector.tsx b/umtool/components/projects/inspector/LedgerInspector.tsx
@@ -0,0 +1,253 @@
+"use client";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import { Field, Input, Select, Textarea } from "@/components/ui/field";
+import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared";
+
+// A MEASURE LEDGER's ROWS (umtool redesign L6, item 3; agents added and fixed them with jq this week): the rows the
+// instruments draw from, each with its date, scope (a track), form, value (a number, or a regime and its event on
+// a regime track), basis (the phrase that settles the scope) and source (src, channel/video, cite) -- added,
+// changed or removed through POST /api/report/ledger, the ledger CLI's checks word for word, one undo point each.
+// `umtool ledger <p> add|set|rm` is the twin. With `block` (a timeline entry's id): the rows pinned to it, and a
+// new row pinned to it.
+
+type Track = { key: string; label: string; role: string; regimes: string[] | null };
+type Schema = {
+ unit: string; tracks: Track[]; forms: string[]; regimes: { key: string; label: string }[];
+ fields: { key: string; label: string; kind: string; options: unknown[] | null }[];
+ events: string[]; promiseForms: string[]; outcomes: string[]; scopeConfidence: string[]; valueKinds: string[];
+};
+type Row = Record<string, unknown> & { id: string };
+type View = { kind: "measure" | "headcount" | null; schema: Schema | null; schemaError: string | null; total: number; rows: Row[]; entries: string[]; token: string | null };
+
+/** The keys the form shows, in order: what a row needs, then its source. */
+const BASE_KEYS = ["id", "date", "scope", "population", "value", "event", "scopeBasis", "label", "quote", "src", "channel", "video", "cite", "entryId"] as const;
+const REQUIRED = new Set(["id", "date", "scope", "population", "scopeBasis"]);
+const PAGE = 40;
+
+const textOf = (v: unknown) => (v === undefined || v === null ? "" : Array.isArray(v) ? v.join("|") : String(v));
+
+export default function LedgerInspector({ project, block = null }: InspectorProps) {
+ const router = useRouter();
+ const [view, setView] = useState<View | null>(null);
+ const [editing, setEditing] = useState<string | null>(null); // a row id, or "" for a new row
+ const [form, setForm] = useState<Record<string, string>>({});
+ const [filter, setFilter] = useState("");
+ const [shown, setShown] = useState(PAGE);
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<Said>(null);
+ const load = useCallback(async () => {
+ const q = new URLSearchParams({ project, ...(block ? { entry: block } : {}) });
+ const { ok, j } = await call<View>(`/api/report/ledger?${q.toString()}`);
+ if (ok) setView(j);
+ return ok ? j : null;
+ }, [project, block]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+ useOnManifestChanged(project, load);
+ const declared = view?.schema?.fields ?? [];
+ const keys = useMemo(() => [...BASE_KEYS, ...declared.map((f) => f.key)], [declared]);
+ const rows = useMemo(() => {
+ const all = [...(view?.rows ?? [])].sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? "")) || a.id.localeCompare(b.id));
+ const f = filter.trim().toLowerCase();
+ return f ? all.filter((r) => [r.id, r.date, r.scope, r.population, r.display, r.label, r.quote].some((v) => String(v ?? "").toLowerCase().includes(f))) : all;
+ }, [view, filter]);
+ if (!view || !view.kind) return null;
+ if (view.kind !== "measure" || !view.schema) {
+ return (
+ <InspectorFrame kind="ledger" title={`Ledger — ${view.total} rows`}>
+ <p className="m-0 text-muted">{view.schemaError ?? "This ledger is not a measure ledger (ledgerSchema.kind \"measure\"): its rows are written by its own tools."}</p>
+ </InspectorFrame>
+ );
+ }
+ const s = view.schema;
+ const track = s.tracks.find((t) => t.key === form.scope) ?? null;
+ const regimeTrack = track?.role === "regime";
+
+ const open = (id: string | null) => {
+ setSaid(null);
+ if (id === null) {
+ setEditing(null);
+ return;
+ }
+ if (id === "") {
+ const today = new Date().toISOString().slice(0, 10);
+ setForm({ id: "", date: today, scope: s.tracks[0]?.key ?? "", population: s.forms[0] ?? "", ...(block ? { entryId: block } : {}) });
+ } else {
+ const r = view.rows.find((x) => x.id === id);
+ setForm(Object.fromEntries(keys.map((k) => [k, textOf(r?.[k])])));
+ }
+ setEditing(id);
+ };
+ const set = (k: string, v: string) => {
+ setSaid(null);
+ setForm((f) => ({ ...f, [k]: v }));
+ };
+ const save = async () => {
+ setBusy(true);
+ setSaid(null);
+ try {
+ let body: Record<string, unknown>;
+ if (editing === "") {
+ const row = Object.fromEntries(Object.entries(form).filter(([, v]) => v.trim() !== "").map(([k, v]) => [k, v.trim()]));
+ body = { project, token: view.token, op: "add", row };
+ } else {
+ const was = view.rows.find((x) => x.id === editing);
+ const patch: Record<string, string> = {};
+ const unset: string[] = [];
+ for (const k of keys) {
+ if (k === "id") continue;
+ const now = (form[k] ?? "").trim();
+ if (now === textOf(was?.[k])) continue;
+ if (now === "" && !REQUIRED.has(k)) unset.push(k);
+ else patch[k] = now;
+ }
+ // A new value (or form, or event) is drawn by its own words again: the display is recomputed from it.
+ if (["value", "population", "event", "scope"].some((k) => k in patch || unset.includes(k))) unset.push("display");
+ if (!Object.keys(patch).length && !unset.length) {
+ setSaid({ ok: true, text: "Nothing changed." });
+ return;
+ }
+ body = { project, token: view.token, op: "set", id: editing, patch, unset };
+ }
+ const { ok, status, j } = await call<{ row?: Row }>("/api/report/ledger", { method: "POST", body: JSON.stringify(body) });
+ if (!ok) {
+ setSaid({ ok: false, text: refusal(j, status) });
+ if (j.stale) await load();
+ return;
+ }
+ await load();
+ setEditing(null);
+ setSaid({ ok: true, text: `${editing === "" ? "Added" : "Saved"} ${j.row?.id ?? ""}: ${String(j.row?.display ?? "")} — in the draft.` });
+ announceManifestChanged(project);
+ router.refresh();
+ } finally {
+ setBusy(false);
+ }
+ };
+ const remove = async (id: string) => {
+ setBusy(true);
+ setSaid(null);
+ try {
+ const { ok, status, j } = await call("/api/report/ledger", { method: "POST", body: JSON.stringify({ project, token: view.token, op: "rm", id }) });
+ if (!ok) {
+ setSaid({ ok: false, text: refusal(j, status) });
+ if (j.stale) await load();
+ return;
+ }
+ await load();
+ setEditing(null);
+ setSaid({ ok: true, text: `Removed ${id}.` });
+ announceManifestChanged(project);
+ router.refresh();
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const input = (k: string, label: string, hint?: string, extra?: React.ComponentProps<"input">) => (
+ <Field key={k} label={label} hint={hint}>
+ <Input data-ledger-field={k} value={form[k] ?? ""} onChange={(e) => set(k, e.target.value)} {...extra} />
+ </Field>
+ );
+ const select = (k: string, label: string, options: { value: string; label: string }[], blank?: string) => (
+ <Field key={k} label={label}>
+ <Select data-ledger-field={k} value={form[k] ?? ""} onChange={(e) => set(k, e.target.value)}>
+ {blank !== undefined && <option value="">{blank}</option>}
+ {options.map((o) => (
+ <option key={o.value} value={o.value}>
+ {o.label}
+ </option>
+ ))}
+ </Select>
+ </Field>
+ );
+ const regimes = regimeTrack ? (track?.regimes ?? s.regimes.map((r) => r.key)) : [];
+ const editor = editing !== null && (
+ <div data-ledger-editor={editing || "new"} className="mt-2 rounded border border-[var(--color-line)] px-2 py-2">
+ <div className="grid gap-2 sm:grid-cols-4">
+ {editing === "" ? input("id", "Id", "a letter, then letters, digits . : - _") : <Field label="Id"><span className="font-mono text-[12.5px]">{editing}</span></Field>}
+ {input("date", "Date", "YYYY-MM-DD")}
+ {select("scope", "Scope", s.tracks.map((t) => ({ value: t.key, label: `${t.label} (${t.key})` })))}
+ {select("population", "Form", s.forms.map((f) => ({ value: f, label: f })))}
+ {regimeTrack
+ ? select("value", "Value", regimes.map((k) => ({ value: k, label: s.regimes.find((r) => r.key === k)?.label ?? k })), "—")
+ : input("value", "Value", s.unit ? `a number in ${s.unit}` : "a number")}
+ {regimeTrack ? select("event", "Event", s.events.map((e) => ({ value: e, label: e })), "—") : null}
+ {select("entryId", "Pinned to", view.entries.map((id) => ({ value: id, label: id })), "no entry")}
+ {input("cite", "Cite", "source second")}
+ {input("channel", "Channel", "source channel slug")}
+ {input("video", "Video", "source video id")}
+ <div className="sm:col-span-2">{input("src", "Source", "what it is: a title @ a time")}</div>
+ <div className="sm:col-span-4">{input("scopeBasis", "Basis", "the phrase that settles the scope (never defaulted)")}</div>
+ <div className="sm:col-span-2">{input("label", "Label")}</div>
+ <div className="sm:col-span-2">
+ <Field label="Quote">
+ <Textarea data-ledger-field="quote" rows={2} value={form.quote ?? ""} onChange={(e) => set("quote", e.target.value)} />
+ </Field>
+ </div>
+ {declared.map((f) =>
+ f.options ? select(f.key, f.label, f.options.map((o) => ({ value: String(o), label: String(o) })), "—") : input(f.key, f.label, `declared (${f.kind})`),
+ )}
+ </div>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <Button type="button" size="sm" variant="go" data-ledger-save={editing || "new"} disabled={busy} onClick={() => void save()}>
+ {editing === "" ? "Add row" : "Save row"}
+ </Button>
+ <Button type="button" size="sm" variant="quiet" data-ledger-cancel="" disabled={busy} onClick={() => open(null)}>
+ Cancel
+ </Button>
+ {editing !== "" && (
+ <Button type="button" size="sm" variant="quiet" className="ml-auto" data-ledger-remove={editing} disabled={busy} onClick={() => void remove(editing)}>
+ Remove row
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+ return (
+ <InspectorFrame
+ kind="ledger"
+ title={`Ledger — ${block ? `${view.rows.length} pinned to ${block} · ` : ""}${view.total} rows`}
+ aside={
+ <>
+ <Input data-ledger-filter="" placeholder="filter" className="h-7 w-[12rem]" value={filter} onChange={(e) => { setFilter(e.target.value); setShown(PAGE); }} />
+ <Button type="button" size="sm" variant="outline" data-ledger-add="" onClick={() => open("")}>
+ Add a row
+ </Button>
+ </>
+ }
+ >
+ {editing === "" && editor}
+ <ul className="flex max-h-[320px] flex-col gap-0.5 overflow-y-auto">
+ {rows.slice(0, shown).map((r) => (
+ <li key={r.id} data-ledger-row={r.id} className="flex flex-col">
+ <div className="flex flex-wrap items-baseline gap-2 text-[12px]">
+ <span className="w-[4.5rem] font-mono text-text">{r.id}</span>
+ <span className="num font-mono text-[11.5px] text-muted">{String(r.date ?? "")}</span>
+ <span className="text-[11.5px] text-text-2">{String(r.scope ?? "")} · {String(r.population ?? "")}</span>
+ <span className="font-mono text-[12px]">{String(r.display ?? r.value ?? "—")}</span>
+ {r.entryId ? <span className="text-[11px] text-muted">@{String(r.entryId)}</span> : null}
+ <span className="min-w-0 flex-1 truncate text-[11.5px] text-muted">{String(r.label ?? "")}</span>
+ <Button type="button" size="sm" variant={editing === r.id ? "pressed" : "quiet"} data-ledger-edit={r.id} onClick={() => open(editing === r.id ? null : r.id)}>
+ {editing === r.id ? "Close" : "Edit"}
+ </Button>
+ </div>
+ {editing === r.id && editor}
+ </li>
+ ))}
+ </ul>
+ {rows.length > shown && (
+ <Button type="button" size="sm" variant="quiet" data-ledger-more="" onClick={() => setShown((n) => n + PAGE)}>
+ {rows.length - shown} more
+ </Button>
+ )}
+ <div className="mt-1.5">
+ <SaidLine said={said} testid="ledger-said" />
+ </div>
+ </InspectorFrame>
+ );
+}
diff --git a/umtool/components/projects/inspector/LinksInspector.tsx b/umtool/components/projects/inspector/LinksInspector.tsx
@@ -0,0 +1,98 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared";
+
+// THE RUMBLE CITE FIX (umtool redesign L6, item 5; 4 and 8 Nov: a Rumble clip's QR named the URL-slug folder the
+// corpus keeps it under, and the archive serves the EMBED id -- 15/15 dead on quartering-midterms): each clip of
+// the cut that cites such a folder, with its published embed id read from the folder's metadata through L1's one
+// mapping, and "Use the published embed id" -- per row, and once for every dead Rumble row (every row only when no
+// check has read any of them). It writes `siteVideo` (a citeUrl naming the folder moves with it): POST /api/report/embed-ids,
+// one write, one undo point. No network; `umtool links <p>` checks the sites, `umtool links <p> --embed-ids` is
+// this panel's twin. With `block`, only that clip's row.
+
+type Row = { clip: string; channel: string | null; video: string; siteVideo: string; url: string | null; fixedUrl: string | null; citeUrl: string | null; state: string };
+type View = { rows: Row[]; checkedAt: string | null; token: string | null };
+
+export default function LinksInspector({ project, block = null }: InspectorProps) {
+ const router = useRouter();
+ const [view, setView] = useState<View | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<Said>(null);
+ const load = useCallback(async () => {
+ const { ok, j } = await call<View>(`/api/report/embed-ids?project=${encodeURIComponent(project)}`);
+ if (ok) setView(j);
+ return ok ? j : null;
+ }, [project]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+ useOnManifestChanged(project, load);
+ if (!view) return null;
+ const rows = block ? view.rows.filter((r) => r.clip === block) : view.rows;
+ const dead = rows.filter((r) => r.state === "dead");
+ // Once a check has read these rows, "all" is the dead ones only (a row it found open is left as it is); with no
+ // check yet, every row.
+ const checked = rows.some((r) => r.state !== "unchecked");
+ const allOf = checked ? dead : rows;
+ const use = async (clips: string[]) => {
+ setBusy(true);
+ setSaid(null);
+ try {
+ const { ok, status, j } = await call<{ fixed?: { clip: string; siteVideo: string }[] }>("/api/report/embed-ids", { method: "POST", body: JSON.stringify({ project, token: view.token, clips }) });
+ if (!ok) {
+ setSaid({ ok: false, text: refusal(j, status) });
+ if (j.stale) await load();
+ return;
+ }
+ await load();
+ const fixed = j.fixed ?? [];
+ setSaid({ ok: true, text: `${fixed.map((f) => `${f.clip} → ${f.siteVideo}`).join(", ")}: saved to the draft — Check links on the Overview reads the site again.` });
+ announceManifestChanged(project);
+ router.refresh();
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <InspectorFrame
+ kind="links"
+ title={`Rumble cites — ${rows.length} clip${rows.length === 1 ? "" : "s"} naming a folder id`}
+ aside={
+ checked && rows.length && !dead.length ? (
+ <span className="text-[11.5px] text-muted" data-embed-no-dead="">no dead links at the last check</span>
+ ) : allOf.length > 1 ? (
+ <Button type="button" size="sm" variant="go" data-embed-use-all={allOf.length} disabled={busy} onClick={() => void use(allOf.map((r) => r.clip))}>
+ {checked ? `Use the published embed id for all ${dead.length} dead` : `Use the published embed id for all ${rows.length}`}
+ </Button>
+ ) : null
+ }
+ >
+ {rows.length === 0 ? (
+ <p className="m-0 text-muted" data-embed-none="">
+ Every clip names the id its archive serves{view.checkedAt ? ` (links last checked ${view.checkedAt.slice(0, 16).replace("T", " ")})` : ""}.
+ </p>
+ ) : (
+ <ul className="flex flex-col gap-1">
+ {rows.map((r) => (
+ <li key={r.clip} data-embed-row={r.clip} data-embed-state={r.state} className="flex flex-wrap items-baseline gap-2">
+ <span className="font-mono text-text">{r.clip}</span>
+ <span className="font-mono text-[11.5px] text-muted">
+ {r.channel ?? "?"}/{r.video} → <span className="text-text-2">{r.siteVideo}</span>
+ </span>
+ <span className={r.state === "dead" ? "text-[11.5px] text-[var(--color-bad)]" : "text-[11.5px] text-muted"}>{r.state === "unchecked" ? "not checked" : r.state}</span>
+ <Button type="button" size="sm" variant="outline" className="ml-auto" data-embed-use={r.clip} disabled={busy} onClick={() => void use([r.clip])} title={r.fixedUrl ?? undefined}>
+ Use the published embed id
+ </Button>
+ </li>
+ ))}
+ </ul>
+ )}
+ <div className="mt-1.5">
+ <SaidLine said={said} testid="embed-said" />
+ </div>
+ </InspectorFrame>
+ );
+}
diff --git a/umtool/components/projects/inspector/PostItemInspector.tsx b/umtool/components/projects/inspector/PostItemInspector.tsx
@@ -0,0 +1,259 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import { addRange, piecesOf, rangesOf, settleRanges, snapToWords, spansOf } from "@/lib/report/excerptPick.mjs";
+import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared";
+
+// A POST ITEM (umtool redesign L6, item 4; 6-8 Nov these were `posts set-item excerpt=…` and `posts narrate
+// --recording` by hand), with `block` the item's id:
+// THE EXCERPT select words of the post and Add them: the selection snapped to whole words, merged with the
+// spans already picked, settled where the build will find each one (excerptPick.mjs), saved as
+// `entry.excerpt` -- verbatim spans in the post's order, read joined with " … ", the card still
+// showing the whole post with the rest dimmed (POST /api/report/post-item {op: "set"}).
+// ITS MEDIA each attachment shown or not (off keeps it whole in `mediaOff` -- crop, blur, trim, sound -- and
+// on puts it back as it was; a file of the post the item never carried can be put on) and a video's
+// sound on or off.
+// MY RECORDING a sound file of your own read of it, kept as a recorded take and picked (the multipart POST
+// /api/report/post-narration: trimmed, levelled; `umtool posts narrate <p> <item> --recording <file>
+// --no-clean --no-convert` is the twin).
+
+type Range = { start: number; end: number };
+type View = {
+ id: string; post: string | null; author: string | null; handle: string | null; text: string;
+ excerpt: string[] | null; ranges: Range[] | null; excerptErrors: string[];
+ media: { i: number; src: string | null; kind: string | null; mute: boolean; seconds: number | null; audio: boolean }[];
+ off: { j: number; src: string | null; kind: string | null }[];
+ files: string[];
+ narration: { takes: { i: number; file: string; engine: string | null; voice: string | null; seconds: number | null }[]; picked: number | null; off: boolean };
+ token: string | null;
+};
+
+/** A (node, offset) of the selection as a character offset into `root`'s text. */
+function offsetIn(root: HTMLElement, node: Node, off: number): number | null {
+ if (!root.contains(node)) return null;
+ const r = document.createRange();
+ r.selectNodeContents(root);
+ r.setEnd(node, off);
+ return r.toString().length;
+}
+
+export default function PostItemInspector({ project, block = null }: InspectorProps) {
+ const router = useRouter();
+ const [view, setView] = useState<View | null>(null);
+ const [missing, setMissing] = useState<string | null>(null);
+ const [ranges, setRanges] = useState<Range[]>([]);
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<Said>(null);
+ const [file, setFile] = useState<File | null>(null);
+ const textRef = useRef<HTMLDivElement>(null);
+ const fileRef = useRef<HTMLInputElement>(null);
+ const load = useCallback(async (reset = true) => {
+ if (!block) return null;
+ const { ok, j } = await call<View>(`/api/report/post-item/inspector?${new URLSearchParams({ project, id: block }).toString()}`);
+ if (!ok) {
+ setMissing(j.error ?? "not a post item");
+ return null;
+ }
+ setMissing(null);
+ setView(j);
+ if (reset) setRanges(j.ranges ?? []);
+ return j;
+ }, [project, block]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+ useOnManifestChanged(project, () => load(false));
+ if (!block) return null;
+ if (missing) return <InspectorFrame kind="post-item" title={`Post item ${block}`}><p className="m-0 text-muted">{missing}</p></InspectorFrame>;
+ if (!view) return null;
+
+ const saved = view.ranges ?? [];
+ const dirty = JSON.stringify(ranges) !== JSON.stringify(saved);
+ const write = async (url: string, body: Record<string, unknown>, ok: string) => {
+ setBusy(true);
+ setSaid(null);
+ try {
+ const r = await call(url, { method: "POST", body: JSON.stringify({ project, token: view.token, id: view.id, ...body }) });
+ if (!r.ok) {
+ setSaid({ ok: false, text: refusal(r.j, r.status) });
+ if (r.j.stale) await load();
+ return false;
+ }
+ await load();
+ setSaid({ ok: true, text: ok });
+ announceManifestChanged(project);
+ router.refresh();
+ return true;
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const addSelection = () => {
+ const sel = window.getSelection();
+ const root = textRef.current;
+ if (!sel || sel.rangeCount === 0 || !root) return;
+ const range = sel.getRangeAt(0);
+ const a = offsetIn(root, range.startContainer, range.startOffset);
+ const b = offsetIn(root, range.endContainer, range.endOffset);
+ if (a === null || b === null) {
+ setSaid({ ok: false, text: "select words inside the post's text first" });
+ return;
+ }
+ const r = snapToWords(view.text, a, b);
+ if (!r) {
+ setSaid({ ok: false, text: "the selection holds no words" });
+ return;
+ }
+ setSaid(null);
+ setRanges((rs) => settleRanges(view.text, addRange(rs, r)));
+ sel.removeAllRanges();
+ };
+ const saveExcerpt = () => {
+ const spans = spansOf(view.text, ranges);
+ // The build's own rule, checked before the write: each span found where it was picked.
+ const back = rangesOf(view.text, spans);
+ if (spans.length && JSON.stringify(back) !== JSON.stringify(ranges)) {
+ setSaid({ ok: false, text: "a span could not be placed where it was picked — clear and pick again" });
+ return;
+ }
+ void write("/api/report/post-item", { op: "set", patch: { excerpt: spans.length ? spans : null } }, spans.length ? `Excerpt saved to the draft: ${spans.length} span${spans.length === 1 ? "" : "s"}, read joined with " … ".` : "Excerpt cleared: the whole post is read.");
+ };
+ const keepMyRecording = async () => {
+ if (!file) return;
+ setBusy(true);
+ setSaid(null);
+ try {
+ const form = new FormData();
+ form.set("project", project);
+ form.set("id", view.id);
+ form.set("label", "operator");
+ form.append("part", file, file.name);
+ form.append("text", (view.excerpt?.length ? view.excerpt.join(" … ") : view.text).slice(0, 4000));
+ form.append("para", "0");
+ form.set("note", `my recording (${file.name})`);
+ const r = await fetch("/api/report/post-narration", { method: "POST", body: form });
+ const j = (await r.json().catch(() => ({}))) as { take?: { file: string; seconds?: number }; gain?: number; error?: string };
+ if (!r.ok || !j.take) {
+ setSaid({ ok: false, text: j.error ?? `HTTP ${r.status}` });
+ return;
+ }
+ setFile(null);
+ if (fileRef.current) fileRef.current.value = "";
+ await load();
+ announceManifestChanged(project);
+ setSaid({ ok: true, text: `Kept as ${j.take.file}${typeof j.take.seconds === "number" ? ` (${j.take.seconds.toFixed(1)} s` : " ("}${typeof j.gain === "number" ? `, levelled ${j.gain >= 0 ? "+" : ""}${j.gain} dB)` : ")"} and picked.` });
+ router.refresh();
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const pieces = piecesOf(view.text, ranges);
+ const picked = view.narration.picked !== null ? view.narration.takes[view.narration.picked] : null;
+ return (
+ <InspectorFrame kind="post-item" title={`Post item ${view.id}${view.author ? ` — ${view.author}` : ""}${view.handle ? ` @${view.handle}` : ""}`}>
+ <div className="grid gap-3 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]">
+ <div className="flex min-w-0 flex-col gap-1.5" data-post-excerpt={view.excerpt?.length ?? 0}>
+ <span className="micro">excerpt — select words, then Add</span>
+ <div
+ ref={textRef}
+ data-post-text=""
+ className="max-h-[220px] overflow-y-auto whitespace-pre-wrap rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-2 py-1.5 text-[12.5px] leading-relaxed text-text-2 select-text"
+ >
+ {pieces.map((p) =>
+ p.picked ? (
+ <mark key={p.start} data-excerpt-piece={p.start} className="rounded-[2px] bg-[color-mix(in_srgb,var(--signal)_30%,transparent)] text-text">
+ {p.text}
+ </mark>
+ ) : (
+ <span key={p.start} className={ranges.length ? "opacity-60" : undefined}>
+ {p.text}
+ </span>
+ ),
+ )}
+ </div>
+ {ranges.length > 0 && (
+ <ol className="flex flex-col gap-0.5">
+ {spansOf(view.text, ranges).map((s, i) => (
+ <li key={`${ranges[i].start}`} data-excerpt-span={i} className="flex items-baseline gap-2 text-[11.5px]">
+ <span className="min-w-0 flex-1 truncate">“{s}”</span>
+ <Button type="button" size="sm" variant="quiet" data-excerpt-span-remove={i} onClick={() => setRanges((rs) => rs.filter((_, k) => k !== i))}>
+ Remove
+ </Button>
+ </li>
+ ))}
+ </ol>
+ )}
+ {view.excerptErrors.length > 0 && <p className="m-0 text-[11.5px] text-[var(--color-bad)]">{view.excerptErrors.join("; ")}</p>}
+ <div className="flex flex-wrap items-center gap-2">
+ <Button type="button" size="sm" variant="outline" data-excerpt-add="" onMouseDown={(e) => e.preventDefault()} onClick={addSelection}>
+ Add the selection
+ </Button>
+ <Button type="button" size="sm" variant="go" data-excerpt-save="" disabled={busy || !dirty} onClick={saveExcerpt}>
+ {ranges.length ? "Save excerpt" : "Save: read it whole"}
+ </Button>
+ <Button type="button" size="sm" variant="quiet" data-excerpt-clear="" disabled={busy || !ranges.length} onClick={() => setRanges([])}>
+ Clear
+ </Button>
+ <Button type="button" size="sm" variant="quiet" data-excerpt-revert="" disabled={busy || !dirty} onClick={() => setRanges(saved)}>
+ Revert
+ </Button>
+ </div>
+ </div>
+ <div className="flex min-w-0 flex-col gap-2">
+ <div className="flex flex-col gap-1" data-post-media-list={view.media.length}>
+ <span className="micro">media</span>
+ {view.media.length === 0 && view.off.length === 0 && view.files.length === 0 && <span className="text-muted">no attachment</span>}
+ {view.media.map((m) => (
+ <div key={`${m.i}:${m.src}`} data-post-media={m.i} className="flex flex-wrap items-center gap-x-3 gap-y-0.5">
+ <label className="inline-flex min-w-0 items-center gap-1.5">
+ <input type="checkbox" data-post-media-shown="" checked disabled={busy} onChange={() => void write("/api/report/post-item/inspector", { op: "media-off", i: m.i }, `${m.src ?? `attachment ${m.i}`}: off (kept as it was set; on puts it back).`)} />
+ <span className="truncate font-mono text-[11.5px]" title={m.src ?? ""}>{m.src?.split("/").pop() ?? `attachment ${m.i}`}</span>
+ <span className="text-[11px] text-muted">{m.kind}{m.seconds ? ` ${m.seconds.toFixed(1)} s` : ""}</span>
+ </label>
+ {m.kind === "video" && m.audio && (
+ <label className="inline-flex items-center gap-1.5 text-[11.5px] text-text-2">
+ <input type="checkbox" data-post-media-sound="" checked={!m.mute} disabled={busy} onChange={(e) => void write("/api/report/post-item", { op: "set", patch: { media: { [m.i]: { mute: e.target.checked ? null : true } } } }, e.target.checked ? "Sound on." : "Sound off.")} />
+ sound
+ </label>
+ )}
+ </div>
+ ))}
+ {view.off.map((m) => (
+ <label key={`off:${m.j}:${m.src}`} data-post-media-off={m.j} className="inline-flex min-w-0 items-center gap-1.5 text-muted">
+ <input type="checkbox" data-post-media-off-shown="" checked={false} disabled={busy} onChange={() => void write("/api/report/post-item/inspector", { op: "media-show", j: m.j }, `${m.src?.split("/").pop() ?? `attachment ${m.j}`}: on again, as it was.`)} />
+ <span className="truncate font-mono text-[11.5px]" title={m.src ?? ""}>{m.src?.split("/").pop() ?? `attachment ${m.j}`}</span>
+ <span className="text-[11px]">off</span>
+ </label>
+ ))}
+ {view.files.map((f) => (
+ <label key={f} data-post-file={f} className="inline-flex min-w-0 items-center gap-1.5 text-muted">
+ <input type="checkbox" data-post-file-shown="" checked={false} disabled={busy} onChange={() => void write("/api/report/post-item/inspector", { op: "media-on", file: f }, `${f.split("/").pop()}: on the item.`)} />
+ <span className="truncate font-mono text-[11.5px]" title={f}>{f.split("/").pop()}</span>
+ <span className="text-[11px]">not shown</span>
+ </label>
+ ))}
+ </div>
+ <div className="flex flex-col gap-1" data-post-recording={view.narration.takes.length}>
+ <span className="micro">my recording</span>
+ <span className="text-[11.5px] text-muted" data-post-takes="">
+ {view.narration.takes.length ? `${view.narration.takes.length} take${view.narration.takes.length === 1 ? "" : "s"}; plays ${picked ? `${picked.file.split("/").pop()}${picked.engine ? ` (${picked.engine})` : ""}` : "none"}` : "not narrated yet"}
+ </span>
+ <input ref={fileRef} type="file" accept="audio/*,video/*" data-post-recording-file="" className="text-[11.5px]" onChange={(e) => setFile(e.target.files?.[0] ?? null)} />
+ <div>
+ <Button type="button" size="sm" variant="outline" data-post-recording-use="" disabled={busy || !file} onClick={() => void keepMyRecording()} title="your read of it, trimmed and levelled, kept as a recorded take and picked">
+ Use my recording
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className="mt-1.5">
+ <SaidLine said={said} testid="post-said" />
+ </div>
+ </InspectorFrame>
+ );
+}
diff --git a/umtool/components/projects/inspector/ProvenanceInspector.tsx b/umtool/components/projects/inspector/ProvenanceInspector.tsx
@@ -0,0 +1,109 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import { Field, Input } from "@/components/ui/field";
+import LinkPolicyPanel from "../report/LinkPolicyPanel";
+import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared";
+
+// THE PROJECT'S PROVENANCE (umtool redesign L6, item 1; the owed provenance writer): where the cut's QRs open
+// (provenance.siteOrigin), the channel a clip with no `channel` of its own is from (provenance.channelSlug --
+// `check` blocks without it), the sweep's display name (provenance.channel); and, under them, the link policy per
+// channel (LinkPolicyPanel, its own writer). PUT /api/report/provenance; `umtool provenance <p> set` is the twin.
+
+type Prov = { siteOrigin: string | null; channelSlug: string | null; channel: string | null };
+type View = {
+ provenance: Prov;
+ channels: { slug: string; clips: number }[];
+ corpusChannels: string[];
+ sites: { origin: string; siteId: string; title: string | null }[];
+ token: string | null;
+};
+const KEYS = ["siteOrigin", "channelSlug", "channel"] as const;
+
+export default function ProvenanceInspector({ project }: InspectorProps) {
+ const router = useRouter();
+ const [view, setView] = useState<View | null>(null);
+ const [draft, setDraft] = useState<Record<(typeof KEYS)[number], string>>({ siteOrigin: "", channelSlug: "", channel: "" });
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<Said>(null);
+ const [policyKey, setPolicyKey] = useState(0);
+ const load = useCallback(async (reset = true) => {
+ const { ok, j } = await call<View>(`/api/report/provenance?project=${encodeURIComponent(project)}`);
+ if (!ok) return null;
+ setView(j);
+ if (reset) setDraft({ siteOrigin: j.provenance.siteOrigin ?? "", channelSlug: j.provenance.channelSlug ?? "", channel: j.provenance.channel ?? "" });
+ return j;
+ }, [project]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+ useOnManifestChanged(project, () => load(false));
+ if (!view) return null;
+ const changed = KEYS.filter((k) => draft[k].trim() !== (view.provenance[k] ?? ""));
+ const set = (k: (typeof KEYS)[number], v: string) => {
+ setSaid(null);
+ setDraft((d) => ({ ...d, [k]: v }));
+ };
+ const save = async () => {
+ setBusy(true);
+ setSaid(null);
+ try {
+ const patch = Object.fromEntries(changed.map((k) => [k, draft[k].trim() || null]));
+ const { ok, status, j } = await call<{ changed?: Record<string, unknown> }>("/api/report/provenance", { method: "PUT", body: JSON.stringify({ project, token: view.token, patch }) });
+ if (!ok) {
+ setSaid({ ok: false, text: refusal(j, status) });
+ if (j.stale) await load();
+ return;
+ }
+ await load();
+ setPolicyKey((n) => n + 1);
+ setSaid({ ok: true, text: `Saved to the draft: ${Object.keys(j.changed ?? {}).join(", ") || "nothing changed"}.` });
+ announceManifestChanged(project);
+ router.refresh();
+ } finally {
+ setBusy(false);
+ }
+ };
+ const slugs = [...view.channels.map((c) => c.slug), ...view.corpusChannels.filter((s) => !view.channels.some((c) => c.slug === s))];
+ return (
+ <InspectorFrame kind="provenance" title="Provenance">
+ <div className="grid gap-2 sm:grid-cols-3">
+ <Field label="Site origin" hint="the archive its QRs open">
+ <Input data-provenance-field="siteOrigin" list={`prov-sites-${project}`} placeholder="https://…" value={draft.siteOrigin} onChange={(e) => set("siteOrigin", e.target.value)} />
+ </Field>
+ <Field label="Channel slug" hint={view.provenance.channelSlug ? "a clip with no channel is from it" : "empty: check blocks until it is set"}>
+ <Input data-provenance-field="channelSlug" list={`prov-channels-${project}`} value={draft.channelSlug} onChange={(e) => set("channelSlug", e.target.value)} />
+ </Field>
+ <Field label="Channel name" hint="the sweep's display name">
+ <Input data-provenance-field="channel" value={draft.channel} onChange={(e) => set("channel", e.target.value)} />
+ </Field>
+ </div>
+ <datalist id={`prov-sites-${project}`}>
+ {view.sites.map((s) => (
+ <option key={s.origin} value={s.origin}>
+ {s.title ?? s.siteId}
+ </option>
+ ))}
+ </datalist>
+ <datalist id={`prov-channels-${project}`}>
+ {slugs.map((s) => (
+ <option key={s} value={s} />
+ ))}
+ </datalist>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <Button type="button" size="sm" variant="go" data-provenance-save="" disabled={busy || !changed.length} onClick={() => void save()}>
+ Save provenance
+ </Button>
+ <Button type="button" size="sm" variant="quiet" data-provenance-revert="" disabled={busy || !changed.length} onClick={() => void load().then(() => setSaid(null))}>
+ Revert
+ </Button>
+ <SaidLine said={said} testid="provenance-said" />
+ </div>
+ <div className="mt-2" data-provenance-link-policy="">
+ <LinkPolicyPanel key={policyKey} project={project} />
+ </div>
+ </InspectorFrame>
+ );
+}
diff --git a/umtool/components/projects/inspector/StillInspector.tsx b/umtool/components/projects/inspector/StillInspector.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { InspectorFrame, SaidLine, call, type InspectorProps, type Said } from "./shared";
+
+// A STILL AT SECOND N (umtool redesign L6, item 6): one frame of the clip on screen at the playhead's SOURCE
+// second, from its fetched window, saved in the project's shots/ (POST /api/report/still-frame; a single ffmpeg
+// frame, nothing fetched, nothing in the cut written). `StillButton` sits by Play's controls; `StillInspector`
+// lists the project's shots (with `block` a clip's id: that clip's stills). `umtool still` is the twin.
+
+type Shot = { rel: string; name: string; bytes: number; mtime: string; still: { clip: string; at: number } | null };
+
+const shotUrl = (project: string, rel: string, v = "") => `/api/report/still-frame?${new URLSearchParams({ project, file: rel }).toString()}${v ? `&v=${encodeURIComponent(v)}` : ""}`;
+
+export default function StillInspector({ project, block = null }: InspectorProps) {
+ const [shots, setShots] = useState<Shot[] | null>(null);
+ const load = useCallback(async () => {
+ const { ok, j } = await call<{ shots: Shot[] }>(`/api/report/still-frame?project=${encodeURIComponent(project)}`);
+ if (ok) setShots(j.shots);
+ }, [project]);
+ useEffect(() => {
+ void load();
+ // A still grabbed in Play (another component) is listed here once it lands.
+ const on = () => void load();
+ window.addEventListener("umtool:still-grabbed", on);
+ return () => window.removeEventListener("umtool:still-grabbed", on);
+ }, [load]);
+ if (!shots) return null;
+ const list = block ? shots.filter((s) => s.still?.clip === block) : shots;
+ return (
+ <InspectorFrame kind="still" title={`Shots — ${list.length}`} aside={<span className="font-mono text-[11px] text-muted">umtool still {project} <clip> --at <s></span>}>
+ {list.length === 0 ? (
+ <p className="m-0 text-muted">No pictures in shots/ yet — Play’s Still button grabs the frame on screen.</p>
+ ) : (
+ <ul className="flex flex-wrap gap-2">
+ {list.map((s) => (
+ <li key={s.rel} data-shot={s.rel} className="flex w-[160px] flex-col gap-0.5">
+ <a href={shotUrl(project, s.rel, s.mtime)} target="_blank" rel="noreferrer">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={shotUrl(project, s.rel, s.mtime)} alt={s.name} className="h-[90px] w-[160px] rounded border border-[var(--color-line)] object-contain" loading="lazy" />
+ </a>
+ <span className="truncate font-mono text-[10.5px] text-muted" title={s.rel}>
+ {s.still ? `${s.still.clip} @ ${s.still.at.toFixed(2)} s` : s.name}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </InspectorFrame>
+ );
+}
+
+/**
+ * Play's STILL button: the frame of the clip on screen at the playhead (`source()` -- the clip's id and the SOURCE
+ * second, or null on a card) grabbed into shots/.
+ */
+export function StillButton({ project, take = null, source, className }: { project: string; take?: string | null; source: () => { clip: string; at: number } | null; className?: string }) {
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<Said>(null);
+ const [last, setLast] = useState<string | null>(null);
+ const grab = async () => {
+ const s = source();
+ if (!s) {
+ setSaid({ ok: false, text: "a card has no frame to keep: pause on a clip" });
+ return;
+ }
+ setBusy(true);
+ setSaid(null);
+ try {
+ const { ok, j } = await call<{ rel?: string; at?: number }>("/api/report/still-frame", { method: "POST", body: JSON.stringify({ project, clip: s.clip, at: s.at, ...(take ? { take } : {}) }) });
+ if (!ok || !j.rel) {
+ setSaid({ ok: false, text: j.error ?? "the frame could not be grabbed" });
+ return;
+ }
+ setLast(j.rel);
+ setSaid({ ok: true, text: `${j.rel} (${s.clip} @ ${(j.at ?? s.at).toFixed(2)} s)` });
+ window.dispatchEvent(new CustomEvent("umtool:still-grabbed", { detail: { rel: j.rel } }));
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <span className={cn("inline-flex flex-wrap items-center gap-1.5", className)} data-play-still-box="">
+ <Button type="button" size="sm" variant="outline" data-play-still="" disabled={busy} onClick={() => void grab()} title="keep the frame on screen as a picture in the project's shots/ (umtool still): from the clip's fetched window, at the playhead's source second">
+ {busy ? "Grabbing…" : "Still"}
+ </Button>
+ {said && (
+ <span className="inline-flex items-center gap-1.5">
+ <SaidLine said={said} testid="play-still-said" />
+ {said.ok && last && (
+ <a className="ink-link text-[11.5px]" href={shotUrl(project, last, String(Date.now()))} target="_blank" rel="noreferrer" data-play-still-open="">
+ open
+ </a>
+ )}
+ </span>
+ )}
+ </span>
+ );
+}
diff --git a/umtool/components/projects/inspector/TeaserInspector.tsx b/umtool/components/projects/inspector/TeaserInspector.tsx
@@ -0,0 +1,168 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import { Field, Input, Select } from "@/components/ui/field";
+import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared";
+
+// A TEASER OR CLOSING CARD (umtool redesign L6, item 2): with no `block`, a NEW card -- where it goes (the end: a
+// closing card; the start: a cold open; after an entry), its lines (the first its title; each with the end of
+// its words as a second tier, `break`, and a `hold`), its beat -- inserted; with `block` a teaser's id, its lines
+// and beat changed. POST /api/report/teaser (op insert | set); the build's teaser rules refuse in their words.
+// `umtool timeline <p> teaser-insert` / `timeline <p> teaser <id> <patch>` are the twins.
+
+type Line = { text: string; break: string; hold: string; keep?: Record<string, unknown> };
+type View = {
+ entries: { id: string; type: string; at: number; label: string | null }[];
+ teasers: { id: string; at: number; lines: unknown[]; beat: number | null }[];
+ limits: { lines: [number, number]; rows: number; chars: number; hold: number; beat: { min: number; max: number } };
+ token: string | null;
+};
+
+const blank = (): Line => ({ text: "", break: "", hold: "" });
+/** A line as written into the editor's fields (keys it does not show kept as they are). */
+function lineOf(l: unknown): Line {
+ if (typeof l === "string") return { text: l, break: "", hold: "" };
+ const o = (l && typeof l === "object" ? l : {}) as Record<string, unknown>;
+ const { text, break: brk, hold, ...keep } = o;
+ return { text: typeof text === "string" ? text : "", break: typeof brk === "string" ? brk : "", hold: typeof hold === "number" ? String(hold) : "", ...(Object.keys(keep).length ? { keep } : {}) };
+}
+/** The line as the writer takes it: a string when it is only its words. */
+function valueOf(l: Line): unknown {
+ const o: Record<string, unknown> = { ...(l.keep ?? {}), text: l.text.trim() };
+ if (l.break.trim()) o.break = l.break.trim();
+ if (l.hold.trim()) o.hold = Number(l.hold);
+ return Object.keys(o).length === 1 ? o.text : o;
+}
+
+export default function TeaserInspector({ project, block = null }: InspectorProps) {
+ const router = useRouter();
+ const [view, setView] = useState<View | null>(null);
+ const [lines, setLines] = useState<Line[]>([blank()]);
+ const [id, setId] = useState("");
+ const [beat, setBeat] = useState("");
+ const [position, setPosition] = useState("end");
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<Said>(null);
+ const editing = block ? view?.teasers.find((t) => t.id === block) ?? null : null;
+ const load = useCallback(async (reset = true) => {
+ const { ok, j } = await call<View>(`/api/report/teaser?project=${encodeURIComponent(project)}`);
+ if (!ok) return null;
+ setView(j);
+ const t = block ? j.teasers.find((x) => x.id === block) : null;
+ if (t && reset) {
+ setLines(t.lines.length ? t.lines.map(lineOf) : [blank()]);
+ setBeat(t.beat === null ? "" : String(t.beat));
+ }
+ return j;
+ }, [project, block]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+ useOnManifestChanged(project, () => load(false));
+ if (!view) return null;
+ if (block && !editing) return <InspectorFrame kind="teaser" title="Teaser"><p className="m-0 text-muted">No teaser {block} in the draft.</p></InspectorFrame>;
+
+ const setLine = (i: number, patch: Partial<Line>) => {
+ setSaid(null);
+ setLines((ls) => ls.map((l, k) => (k === i ? { ...l, ...patch } : l)));
+ };
+ // "after:<id>@<at>": the entry's index names one of an id's twins (a variant's), as the writer's `at` does.
+ const posValue = () => {
+ if (position === "end" || position === "start") return position;
+ const m = /^after:(.*)@(\d+)$/.exec(position);
+ return m ? { after: m[1], at: Number(m[2]) } : { after: position.slice("after:".length) };
+ };
+ const submit = async () => {
+ setBusy(true);
+ setSaid(null);
+ try {
+ const values = lines.filter((l) => l.text.trim()).map(valueOf);
+ const beatV = beat.trim() ? Number(beat) : null;
+ const body = editing
+ ? { project, token: view.token, op: "set", id: editing.id, patch: { lines: values, beat: beatV } }
+ : { project, token: view.token, op: "insert", position: posValue(), spec: { lines: values, ...(id.trim() ? { id: id.trim() } : {}), ...(beatV !== null ? { beat: beatV } : {}) } };
+ const { ok, status, j } = await call<{ id?: string; at?: number }>("/api/report/teaser", { method: "POST", body: JSON.stringify(body) });
+ if (!ok) {
+ setSaid({ ok: false, text: refusal(j, status) });
+ if (j.stale) await load();
+ return;
+ }
+ if (editing) {
+ await load();
+ setSaid({ ok: true, text: `Saved ${j.id} to the draft.` });
+ } else {
+ await load();
+ setLines([blank()]);
+ setId("");
+ setBeat("");
+ setSaid({ ok: true, text: `Inserted ${j.id} at ${(j.at ?? 0) + 1} — Undo last edit takes it back.` });
+ }
+ announceManifestChanged(project);
+ router.refresh();
+ } finally {
+ setBusy(false);
+ }
+ };
+ const lim = view.limits;
+ return (
+ <InspectorFrame kind="teaser" title={editing ? `Teaser ${editing.id}` : "Insert a teaser or closing card"}>
+ {!editing && (
+ <div className="grid gap-2 sm:grid-cols-[minmax(0,1fr)_minmax(0,10rem)_minmax(0,7rem)]">
+ <Field label="Where">
+ <Select data-teaser-position="" value={position} onChange={(e) => { setPosition(e.target.value); setSaid(null); }}>
+ <option value="end">At the end (a closing card)</option>
+ <option value="start">At the start (a cold open)</option>
+ {view.entries.map((e) => (
+ <option key={`${e.id}@${e.at}`} value={`after:${e.id}@${e.at}`}>
+ After {e.id} ({e.type}{e.label ? `: ${String(e.label).slice(0, 40)}` : ""})
+ </option>
+ ))}
+ </Select>
+ </Field>
+ <Field label="Id" hint={position === "start" ? "blank: cold" : position === "end" ? "blank: close" : "blank: teaser"}>
+ <Input data-teaser-id="" value={id} onChange={(e) => setId(e.target.value)} />
+ </Field>
+ <Field label="Beat" hint={`${lim.beat.min}–${lim.beat.max} s`}>
+ <Input data-teaser-beat="" type="number" step={0.1} min={lim.beat.min} max={lim.beat.max} value={beat} onChange={(e) => setBeat(e.target.value)} />
+ </Field>
+ </div>
+ )}
+ {editing && (
+ <div className="max-w-[10rem]">
+ <Field label="Beat" hint={`${lim.beat.min}–${lim.beat.max} s`}>
+ <Input data-teaser-beat="" type="number" step={0.1} min={lim.beat.min} max={lim.beat.max} value={beat} onChange={(e) => setBeat(e.target.value)} />
+ </Field>
+ </div>
+ )}
+ <ol className="mt-2 flex flex-col gap-1.5">
+ {lines.map((l, i) => (
+ <li key={i} data-teaser-line={i} className="grid items-end gap-1.5 sm:grid-cols-[minmax(0,1fr)_minmax(0,11rem)_minmax(0,5rem)_auto]">
+ <Field label={i === 0 ? `Title line (≤ ${lim.chars} characters a line)` : `Line ${i + 1}`}>
+ <Input data-teaser-line-field="text" value={l.text} maxLength={lim.chars} onChange={(e) => setLine(i, { text: e.target.value })} />
+ </Field>
+ <Field label={i === 0 ? "Break (its words' end)" : "Break"}>
+ <Input data-teaser-line-field="break" value={l.break} onChange={(e) => setLine(i, { break: e.target.value })} />
+ </Field>
+ <Field label={i === 0 ? `Hold (0–${lim.hold} s)` : "Hold"}>
+ <Input data-teaser-line-field="hold" type="number" step={0.1} min={0} max={lim.hold} value={l.hold} onChange={(e) => setLine(i, { hold: e.target.value })} />
+ </Field>
+ <Button type="button" size="sm" variant="quiet" data-teaser-line-remove={i} disabled={lines.length === 1} onClick={() => setLines((ls) => ls.filter((_, k) => k !== i))}>
+ Remove
+ </Button>
+ </li>
+ ))}
+ </ol>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <Button type="button" size="sm" variant="outline" data-teaser-add-line="" disabled={lines.length >= lim.lines[1]} onClick={() => setLines((ls) => [...ls, blank()])}>
+ Add a line
+ </Button>
+ <Button type="button" size="sm" variant="go" data-teaser-insert={editing ? "set" : "insert"} disabled={busy || !lines.some((l) => l.text.trim())} onClick={() => void submit()}>
+ {editing ? "Save teaser" : "Insert card"}
+ </Button>
+ <SaidLine said={said} testid="teaser-said" />
+ </div>
+ </InspectorFrame>
+ );
+}
diff --git a/umtool/components/projects/inspector/TitleInspector.tsx b/umtool/components/projects/inspector/TitleInspector.tsx
@@ -0,0 +1,76 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useRouter } from "next/navigation";
+import { Button } from "@/components/ui/button";
+import { Field, Input } from "@/components/ui/field";
+import { InspectorFrame, SaidLine, announceManifestChanged, call, refusal, useOnManifestChanged, type InspectorProps, type Said } from "./shared";
+
+// THE PROJECT'S TITLE AND SUBTITLE (umtool redesign L6, item 7): the manifest's `title` and `subtitle`, through
+// PUT /api/report/title (`umtool title <p> "<title>" [--subtitle "…"]`). An empty subtitle removes it.
+
+type View = { title: string | null; subtitle: string | null; limits: { title: number; subtitle: number }; token: string | null };
+
+export default function TitleInspector({ project }: InspectorProps) {
+ const router = useRouter();
+ const [view, setView] = useState<View | null>(null);
+ const [title, setTitle] = useState("");
+ const [subtitle, setSubtitle] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [said, setSaid] = useState<Said>(null);
+ const load = useCallback(async (reset = true) => {
+ const { ok, j } = await call<View>(`/api/report/title?project=${encodeURIComponent(project)}`);
+ if (!ok) return null;
+ setView(j);
+ if (reset) {
+ setTitle(j.title ?? "");
+ setSubtitle(j.subtitle ?? "");
+ }
+ return j;
+ }, [project]);
+ useEffect(() => {
+ void load();
+ }, [load]);
+ useOnManifestChanged(project, () => load(false));
+ if (!view) return null;
+ const dirty = title.trim() !== (view.title ?? "") || subtitle.trim() !== (view.subtitle ?? "");
+ const save = async () => {
+ setBusy(true);
+ setSaid(null);
+ try {
+ const { ok, status, j } = await call("/api/report/title", { method: "PUT", body: JSON.stringify({ project, token: view.token, title, subtitle }) });
+ if (!ok) {
+ setSaid({ ok: false, text: refusal(j, status) });
+ if (j.stale) await load();
+ return;
+ }
+ await load();
+ setSaid({ ok: true, text: "Saved to the draft." });
+ announceManifestChanged(project);
+ router.refresh();
+ } finally {
+ setBusy(false);
+ }
+ };
+ return (
+ <InspectorFrame kind="title" title="Title">
+ <div className="grid gap-2 sm:grid-cols-2">
+ <Field label="Title">
+ <Input data-title-field="title" value={title} maxLength={view.limits.title} onChange={(e) => { setTitle(e.target.value); setSaid(null); }} />
+ </Field>
+ <Field label="Subtitle" hint="blank: none">
+ <Input data-title-field="subtitle" value={subtitle} maxLength={view.limits.subtitle} onChange={(e) => { setSubtitle(e.target.value); setSaid(null); }} />
+ </Field>
+ </div>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <Button type="button" size="sm" variant="go" data-title-save="" disabled={busy || !dirty || !title.trim()} onClick={() => void save()}>
+ Save title
+ </Button>
+ <Button type="button" size="sm" variant="quiet" data-title-revert="" disabled={busy || !dirty} onClick={() => { setTitle(view.title ?? ""); setSubtitle(view.subtitle ?? ""); setSaid(null); }}>
+ Revert
+ </Button>
+ <SaidLine said={said} testid="title-said" />
+ </div>
+ </InspectorFrame>
+ );
+}
diff --git a/umtool/components/projects/inspector/shared.tsx b/umtool/components/projects/inspector/shared.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { MANIFEST_CHANGED, announceManifestChanged } from "../timelineApi";
+
+export { announceManifestChanged };
+
+// ---------------------------------------------------------------------------
+// THE INSPECTOR PANELS' COMMON PARTS (umtool redesign L6). Every panel in this directory is self-contained: it
+// takes `{ project, block? }` (the project id; the block -- a timeline entry's id -- it inspects, when it is about
+// one), reads its own state from its API route and writes through it, so L7 can mount it in the workspace's
+// inspector unchanged. Today they are mounted in the Cut tab (and Play's Still button). Every write lands in the
+// working draft (video.manifest.json) with its own undo point; none touches a take's patch. No AI anywhere.
+// ---------------------------------------------------------------------------
+
+export type InspectorProps = { project: string; block?: string | null };
+
+/** What a write said: a sentence, good or bad. */
+export type Said = { ok: boolean; text: string } | null;
+
+/** A JSON request; the parsed body (or {}) and whether it was 2xx. A stale token says so. */
+export async function call<T = Record<string, unknown>>(url: string, init?: RequestInit): Promise<{ ok: boolean; status: number; j: T & { error?: string; errors?: string[]; stale?: boolean } }> {
+ const r = await fetch(url, { cache: "no-store", ...init, headers: init?.body && typeof init.body === "string" ? { "content-type": "application/json", ...(init.headers ?? {}) } : init?.headers });
+ const j = (await r.json().catch(() => ({}))) as T & { error?: string; errors?: string[]; stale?: boolean };
+ return { ok: r.ok, status: r.status, j };
+}
+
+/** The sentence for a refused write. */
+export const refusal = (j: { error?: string; errors?: string[]; stale?: boolean }, status: number) =>
+ j.stale ? "The draft changed since this panel read it — it has been read again; check and save once more." : (j.errors?.length ? j.errors.join("; ") : j.error) ?? `HTTP ${status}`;
+
+/** A panel's frame: a heading, the body. */
+export function InspectorFrame({ kind, title, aside, className, children }: { kind: string; title: React.ReactNode; aside?: React.ReactNode; className?: string; children: React.ReactNode }) {
+ return (
+ <section data-inspector={kind} className={cn("min-w-0 rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2 text-[12px]", className)}>
+ <div className="mb-1.5 flex flex-wrap items-baseline gap-2">
+ <h3 className="micro">{title}</h3>
+ {aside ? <span className="ml-auto flex flex-wrap items-center gap-2">{aside}</span> : null}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+/** The line under a panel's buttons. */
+export function SaidLine({ said, testid }: { said: Said; testid: string }) {
+ if (!said) return null;
+ return (
+ <span role="status" {...{ [`data-${testid}`]: said.ok ? "ok" : "refused" }} className={cn("text-[11.5px]", said.ok ? "text-text-2" : "text-[var(--color-bad)]")}>
+ {said.text}
+ </span>
+ );
+}
+
+/**
+ * A row's "Edit" that opens a panel under it (the Cut tab's per-row inspector, until L7's workspace has one
+ * inspector for the selected block).
+ */
+export function InspectorToggle({ label = "Edit", testid, children, className }: { label?: string; testid: string; children: React.ReactNode; className?: string }) {
+ const [open, setOpen] = useState(false);
+ return (
+ <>
+ <Button type="button" size="sm" variant={open ? "pressed" : "quiet"} className={className} aria-expanded={open} {...{ [`data-${testid}`]: open ? "open" : "" }} onClick={() => setOpen((o) => !o)}>
+ {open ? "Close" : label}
+ </Button>
+ {open ? <div className="basis-full pt-1.5">{children}</div> : null}
+ </>
+ );
+}
+
+/**
+ * Read again whenever the draft changed under the panel (the page's MANIFEST_CHANGED: another panel's write, the
+ * timeline's Undo), so its token is never the stale one. `reread` keeps a form being typed in (it refreshes the
+ * view, not the fields).
+ */
+export function useOnManifestChanged(project: string, reread: () => unknown) {
+ const fn = useRef(reread);
+ fn.current = reread;
+ useEffect(() => {
+ const on = (e: Event) => {
+ if ((e as CustomEvent).detail?.project === project) void fn.current();
+ };
+ window.addEventListener(MANIFEST_CHANGED, on);
+ return () => window.removeEventListener(MANIFEST_CHANGED, on);
+ }, [project]);
+}
+
+/**
+ * Its children only once the `<details>` it sits in has been opened (an Options panel): the panels inside read
+ * nothing until somebody looks. Outside a `<details>`, at once.
+ */
+export function WhenOpen({ children }: { children: React.ReactNode }) {
+ const ref = useRef<HTMLSpanElement>(null);
+ const [open, setOpen] = useState(false);
+ useEffect(() => {
+ const d = ref.current?.closest("details");
+ if (!d) {
+ setOpen(true);
+ return;
+ }
+ const on = () => {
+ if (d.open) setOpen(true);
+ };
+ on();
+ d.addEventListener("toggle", on);
+ return () => d.removeEventListener("toggle", on);
+ }, []);
+ return (
+ <>
+ <span ref={ref} hidden />
+ {open ? children : null}
+ </>
+ );
+}
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -38,6 +38,15 @@ import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/
import { clipMomentKey } from "umtool-report-to-video/montage-rulings";
import { trailerCandidates } from "@/lib/report/trailerCandidates.mjs";
import IntroRow from "./IntroEditor";
+// The inspector panels for this week's hand edits (umtool redesign L6), mounted here until L7's workspace inspector.
+import { InspectorToggle, WhenOpen } from "../inspector/shared";
+import TitleInspector from "../inspector/TitleInspector";
+import ProvenanceInspector from "../inspector/ProvenanceInspector";
+import TeaserInspector from "../inspector/TeaserInspector";
+import LedgerInspector from "../inspector/LedgerInspector";
+import PostItemInspector from "../inspector/PostItemInspector";
+import LinksInspector from "../inspector/LinksInspector";
+import StillInspector from "../inspector/StillInspector";
// The Cut tab: the timeline, read back -- the walk into it, its takes, every
// entry with what is wrong with it, and the corrections the walk collected.
@@ -219,6 +228,10 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
<Link href={postBenchHref(project.id, e.id)} className="ink-link text-[11px]" data-post-bench-link={e.id}>
bench
</Link>
+ {/* Its excerpt by selection, its media on/off, my recording (the inspector, L6). */}
+ <InspectorToggle testid="post-edit" label="Edit">
+ <PostItemInspector project={project.id} block={e.id} />
+ </InspectorToggle>
</div>
{words && <div className="mt-0.5 text-[12px] text-[var(--color-dim)]">{words.length > 160 ? `${words.slice(0, 157)}…` : words}</div>}
<div className="basis-full">
@@ -244,6 +257,11 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
</span>
{e.seconds != null && <span className="num micro ml-auto">{e.seconds}s</span>}
<PlayLink project={project.id} clip={e.id} where="row" variant="icon" className={e.seconds != null ? "" : "ml-auto"} />
+ {e.kind === "teaser" && (
+ <InspectorToggle testid="teaser-edit" label="Edit">
+ <TeaserInspector project={project.id} block={e.id} />
+ </InspectorToggle>
+ )}
<div className="basis-full">
<RowNotes id={e.id} project={project.id} />
</div>
@@ -498,6 +516,16 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
<PronunciationPanel project={project.id} />
</Options>
)}
+ {/* The project's own facts, each an inspector panel (L6): what agents set by hand this week. */}
+ <Options id="cut-project" label="Project" hint="title · provenance · Rumble cites · ledger · shots" bodyClassName="w-[min(1100px,calc(100vw-3rem))] flex-col items-stretch">
+ <WhenOpen>
+ <TitleInspector project={project.id} />
+ <ProvenanceInspector project={project.id} />
+ {clips.length > 0 && <LinksInspector project={project.id} />}
+ {(Array.isArray(m?.ledger) || m?.ledgerSchema) && <LedgerInspector project={project.id} />}
+ <StillInspector project={project.id} />
+ </WhenOpen>
+ </Options>
<Advanced id="cut" hint="voices · tight windows · bench prep">
{clips.length > 0 && (
<VoiceMatchPanel
@@ -544,6 +572,12 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
)}
{/* The intro the cut opens on (render.intro), first, and its editor with a live preview (lane intro-play). */}
<IntroRow project={project.id} written={m?.render?.intro ?? null} open={search.intro === "1"} />
+ {/* A teaser or closing card, inserted (the inspector, L6; `umtool timeline <p> teaser-insert`). */}
+ <div className="mb-1.5 flex flex-wrap items-center gap-2" data-cut-insert-card-row="">
+ <InspectorToggle testid="cut-insert-card" label="Insert a teaser or closing card">
+ <TeaserInspector project={project.id} />
+ </InspectorToggle>
+ </div>
<TimelineList project={project.id} count={entries.length} groupCount={groupBars.list.length}>
{sectionBars.opening && <SectionBar section={sectionBars.opening} />}
{entries.map((e, at) => (
diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx
@@ -42,6 +42,7 @@ import { videoStageAt, type VideoEntryPlay } from "@/lib/report/playVideo.mjs";
import ComboBadge, { type ComboInfo } from "./ComboBadge";
import CopyShareLine from "../CopyShareLine";
import VersionVerdict from "./VersionVerdict";
+import { StillButton } from "../inspector/StillInspector";
// ---------------------------------------------------------------------------
// THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The
@@ -713,6 +714,14 @@ export default function PlayCut({
if (take) return openInDraftHref(project, take, { clip: it.id, play: { at } });
return clipBenchHref(project, it.id, { play: { at, take: null } });
}, [project, take, now]);
+ // ---- a still at second N (the inspector, L6): the clip on screen at the playhead's SOURCE second ----
+ const stillSource = useCallback(() => {
+ const e = now();
+ const it = planRef.current.items[e.cur];
+ if (!it?.clip) return null;
+ const src = sourceAt(it, e.t);
+ return src === null ? null : { clip: it.id, at: Math.round(src * 100) / 100 };
+ }, [now]);
/** Play's place as its own URL: the clip on screen, the offset into it, the cut second, the toggle. */
const placeHref = useCallback(() => {
const e = now();
@@ -1395,6 +1404,8 @@ export default function PlayCut({
>
{postNow ? "Edit this post" : "Edit this clip"}
</button>
+ {/* The frame on screen kept as a picture in shots/ (umtool still): never a write to the cut. */}
+ {item?.clip && <StillButton project={project} take={take ?? null} source={stillSource} />}
{/* The clip's source across its life cycle (lane L5): found, downloaded, … published. */}
{item?.clip && entry?.video && entry.sourceChannel && (
<Link
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -20,6 +20,7 @@ Inbox cannot disagree about what is wrong with one.
| `ls [--kind --template --state --open --blocking --q --sort --json]` | the index, as text or JSON |
| `show <project> [--json]` | one project: summary, the cut, per-clip status, decisions |
| `check [<project>] [--json]` | **exit 1 on anything blocking** — including an `out/`, `clips/` or `share-*/` link whose drive is not there (`storage-unreachable`) |
+| `links <project> --embed-ids [--clips a,b] [--dry-run] [--json]` | the **published embed id**: every clip citing a Rumble URL-slug folder the archive does not serve gets `siteVideo` (the folder's `metadata.info.json` id, shareLine.mjs `siteVideoFor`), a citeUrl naming the folder moved with it; no network, one write, one undo point. The Cut tab's Project › Rumble cites ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
| `links <project> [--json] [--fix]` | do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on)) |
| `cast [ls] \| add <id> --name … --voice <engine:voice> [--handles a,b] [--speakers …] [--convert-engine e] [--convert-voice v] [--narrator] \| set <id> … \| rm <id> \| undo [--json]` | **THE CAST** (`<reports>/.umtool/cast.json`, [knobs.md](knobs.md#the-cast-each-characters-voice-in-every-project-and-the-voices-page)): the characters across projects and their STOCK voices, a layer under each project's voice map; one writer, an undo point a write |
| `cast project <project> [--json]` · `cast use <project> <character\|@handle> <voice> [--everywhere]` · `cast reread <project> <character> [--dry-run]` | a project's characters (each voice now, where it comes from, its stale reads), the voice for this project or everywhere, and the re-reads that asks for |
@@ -99,7 +100,11 @@ Inbox cannot disagree about what is wrong with one.
| `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) |
| `refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]` · `refresh --check [<article>] [--force]` | the refresh's plan, `--yes` starts it; the daily check now ([refresh.md](refresh.md)) |
| `clip <channel>/<video>@<start>-<end> [--snap words] [--title T] [--site <id>] [--folder F] [--json] [--progress ndjson]` | **quick clip**: a basic-mode project (`quick-clips/<slug>`, the footage alone), its window asked of the editor (fetch-windows, followed to its end; Rumble fetched whole), `--snap words` its edges snapped to the words heard (the editor's transcribe op), rendered as the take `clip` (`take <p> --id clip --full`: the heavy slot), then the mp4's path and the share line. `--json`: `{project, output, share: {platform, archive, text}, snapped?}`; `--progress ndjson`: events, the last `quick-clip` (the app's `POST /api/report/quick-clip` job). **Exit 0 · 1 failed (the editor, the render) · 2 usage** ([knobs.md](knobs.md#basic-output-the-footage-alone)) |
+| `provenance <project> [ls] [--json]` · `provenance <project> set [--site-origin URL] [--channel-slug S] [--channel "…"] [--json]` | the project's **provenance**: `siteOrigin` (the archive its QRs open), `channelSlug` (a clip with no channel is from it; `check` blocks without it), `channel` (the display name); `""` removes one. One write, one undo point; the Cut tab's Project › Provenance. The link policy is `link-policy` ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
+| `title <project> ["<title>"] [--subtitle "…" \| --no-subtitle] [--json]` | the project's **title and subtitle** (the manifest's `title`/`subtitle`); no words prints them. One write to the draft, one undo point; the Cut tab's Project › Title ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
+| `still <project> <clip> --at <source s> [--take <take>] [--json]` · `still <project> ls [--json]` | a **still at second N**: one frame of the clip's fetched window at that source second into `shots/still-<clip>-<s>s.png` (nothing fetched; the cut not written); `ls` the project's shots. Play's **Still** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
| `share <project> [<clip>] [--take <t>] [--site <id>] [--json]` | a clip's **share line** (the clip named, else the first): its platform page at the first second it plays and its archive moment, a Rumble folder id as the embed id the archive serves — the twin of **Copy share line** (`GET /api/report/share-line`). `--json`: `{clip, seconds, platform, archive, text}` |
+| `timeline <project> teaser-insert [--at start\|end \| --after <id> \| --before <id>] [--id ID] [--beat S] --line "…" [--break "…"] [--hold S] [--line …] \| --lines-json <json\|@file> [--json]` | a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui)) |
| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) |
| `timeline <project> insert (--to-section N \| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` | a clip at the **end of section N**, or **after group G's last clip and one of its clips** (the run stays together): one write, the marker that followed that last clip re-anchored after the new one, so the clip lands in the section and every other clip keeps its own; the attribution as `insert --after`'s. The Candidates panel's Insert is this ([knobs.md](knobs.md#the-candidates-inbox-proposed-clips-picked-by-a-press)) |
| `timeline <project> groups [ls] [--json]` · `groups import <file> [--skip-missing] [--drop-empty]` · `groups set <gid\|-> <id…> [--claim C]` · `groups move <gid> --to <index>` · `groups move <gid> --to after <gid>` · `groups label <gid> <claim…>` · `groups promote <gid> [--label L]` · `groups remove <gid>` · `order <file\|@file\|id…>` | **claim groups** (`groups` beside the timeline; the Cut tab's group bars): runs of clips inside one section making one claim — `ls` by section, each group's id, claim and clips (`--json` with the token); `import` a claim-groups file (`{sections: [{label, groups: [{claim, ids}]}]}`) in ONE write — the cut re-ordered to it, its groups the cut's, the markers following; a file section is the deck section of its name, else the one most of its clips are in; **exit 1** for an id the cut lacks (`--skip-missing`) or a section left with no clip (`--drop-empty` removes its marker); `set` (the clips already together), `label`, `remove` (ungroup), `move` the whole group (before the group at that index, or after one, in its section), `promote` (a level-2 marker at its first clip titled with its claim — the one group edit the render sees; `--label` when the claim is over 24); `order` the named entries in the places they hold (every clip keeping its section). A clip moved out of its group's run leaves it; moved alone into the middle of one, it joins. Every write an undo point (`undo`) ([knobs.md](knobs.md#claim-groups-runs-of-clips-that-make-one-claim)) |
@@ -156,7 +161,12 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `ls [--kind KIND] [--template TEMPLATE] [--state STATE] [--open] [--blocking] [--q Q] [--sort recent\|name]` | every project, as text | form · *corpus* |
| `show <project>` | one project: summary, the cut, per-clip status, decisions | form · *project* |
| `check [<project>] [--all-severities]` | what blocks a build (exit 1 on anything blocking) | form · *project* |
-| `links <project> [--fix]` | do the clip QRs open on their sites (out/links.json) | form · *project* |
+| `links <project> [--fix] [--embed-ids] [--clips CLIPS] [--dry-run]` | do the clip QRs open on their sites (out/links.json) | form · *project* |
+| `provenance <project> ls` | the project's provenance: site origin, channel slug, channel, link policy | form · *project* |
+| `provenance <project> set [--site-origin SITE-ORIGIN] [--channel-slug CHANNEL-SLUG] [--channel CHANNEL]` | the project's site origin, channel slug and channel name ("" removes one) | form · *draft* |
+| `title <project> [<title>] [--subtitle SUBTITLE] [--no-subtitle]` | the project's title and subtitle (no words: print them) | form · *draft* |
+| `still <project> <clip> --at N [--take TAKE]` | one frame of a clip's fetched window at a source second, into shots/ | form · *project* |
+| `still <project> ls` | the pictures in the project's shots/ | form · *project* |
| `cast ls` | the characters' voices across projects | form · *corpus* |
| `cast add <id> --name NAME --voice VOICE [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--narrator]` | a character: name, stock voice, handles | form · *corpus* |
| `cast set <id> [--name NAME] [--voice VOICE] [--handles HANDLES] [--speakers SPEAKERS] [--convert-engine openvoice\|seed-vc] [--convert-voice CONVERT-VOICE] [--note NOTE] [--add-handle ADD-HANDLE] [--remove-handle REMOVE-HANDLE] [--no-convert] [--narrator] [--no-narrator]` | change a character | form · *corpus* |
@@ -304,6 +314,7 @@ draft (the project's manifest); *project*: a project's other files, or reads; *c
| `timeline <project> post <post>` | a post added, or the one with its id replaced | form · *draft* |
| `timeline <project> post-remove <id>` | a post out of the cut | form · *draft* |
| `timeline <project> teaser <id> <patch>` | a teaser's lines, beat, dip, tail | form · *draft* |
+| `timeline <project> teaser-insert [--at end\|start] [--after AFTER] [--before BEFORE] [--id ID] [--beat N] [--line LINE…] [--lines-json JSON]` | a teaser or closing card inserted (default at the end) | form · *draft* |
| `timeline <project> undo [--take TAKE]` | the newest automatic snapshot back | form · *draft* |
| `timeline <project> sections` | the deck's sections and their clips | form · *project* |
| `timeline <project> section-move <ids>… --to-section N [--start]` | clips to the end (or start) of section N | form · *draft* |
diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md
@@ -2304,3 +2304,21 @@ A days-since counter for a promise (`render.chrome.deck.promise`, measure-extras
| a timeline entry's `hideModules` | `["promise", …]` on an entry hides it over that entry's span, with its own fade, whatever it would otherwise do there (text in the footage no dodge can know of) · any entry, a post item too | `umtool set <p> <entry> hideModules=promise` (`--take <t>` for a take) |
<!-- modules:end -->
+
+## The inspector panels (this week's hand edits, in the UI)
+
+Umtool redesign L6: what agents set by hand in the week of 2–9 Nov, each now a panel of
+`components/projects/inspector/` (`{project, block?}`, mounted today in the Cut tab and Play; L7 moves them into the
+workspace's inspector) and a command, through ONE writer (`lib/report/inspectorEdits.mjs`, or the manifest's own).
+Every write lands in the **working draft** (`video.manifest.json`, never a take's patch) with its own undo point
+(`auto-before-<op>`): the Cut tab's **Undo last edit** / `umtool timeline <p> undo` takes exactly it back.
+
+| Panel (where) | What it sets | From a terminal | Route |
+|---|---|---|---|
+| **Title** (Cut tab › Project) | `title` (one line, ≤ 200) and `subtitle` (≤ 300; empty removes it) | `umtool title <p> "<title>" [--subtitle "…" \| --no-subtitle] [--json]` | `GET/PUT /api/report/title` |
+| **Provenance** (Cut tab › Project) | `provenance.siteOrigin` (an http(s) origin, no path), `provenance.channelSlug` (a slug; `check` blocks without it), `provenance.channel` (the display name); empty removes one. The **Link policy** per channel under it (its own writer, above) | `umtool provenance <p> [ls] \| set [--site-origin URL] [--channel-slug S] [--channel "…"] [--json]` | `GET/PUT /api/report/provenance` |
+| **Insert a teaser or closing card** (Cut tab, beside the intro row; a teaser row's **Edit**) | a `teaser` entry: where (the end, id `close`; the start, `cold`; after an entry), its lines (the first its title; each a `break` — the end of its words, a second tier — and a `hold`, 0–4 s), its `beat` (0.4–2.5 s); the build's teaser rules refuse in their words. A row's Edit changes its lines and beat | `umtool timeline <p> teaser-insert [--at start\|end \| --after <id> \| --before <id>] [--id ID] [--beat S] --line "…" [--break "…"] [--hold S] [--line …] \| --lines-json …` · `umtool timeline <p> teaser <id> <patch>` | `GET/POST /api/report/teaser` (`op: insert \| set`) |
+| **Ledger** (Cut tab › Project, a measure ledger) | a row's `date`, `scope` (a track), form, `value` (a number; a regime and its `event` on a regime track), `scopeBasis`, its source (`src`, `channel`, `video`, `cite`), `label`, `quote`, `entryId` and the schema's declared fields — added, changed (a new value redraws its `display`), removed; the ledger CLI's checks word for word | `umtool ledger <p> add\|set\|rm …` | `GET/POST /api/report/ledger` (`op: add \| set \| rm`) |
+| **Post item** (a post row's **Edit**) | its **excerpt**: select words of the post and **Add the selection** — snapped to whole words, merged, a span whose words come earlier too widened to where it was picked (`lib/report/excerptPick.mjs`), saved as `excerpt` (verbatim spans, read joined " … "); its **media** on/off (off keeps the attachment whole — crop, blur, trim, sound — in the item's `mediaOff`, which nothing draws or plays; on puts it back as it was) and a video's **sound** (`mute`); **Use my recording**: a sound file of your own read, trimmed and levelled, kept as `take-<n>.recorded-operator.wav` and picked | `umtool posts set-item <p> <item> excerpt='[…]' media.<i>.shown=off media-off.<j>.shown=on media.add=<file> media.<i>.mute=on` · `umtool posts narrate <p> <item> --recording <file> --no-clean --no-convert` | `POST /api/report/post-item` (`op: set`), `GET/POST /api/report/post-item/inspector` (`op: media-on \| media-off \| media-show`), multipart `POST /api/report/post-narration` |
+| **Rumble cites** (Cut tab › Project) | each clip naming a Rumble URL-slug FOLDER the archive does not serve, with its embed id (L1's `siteVideoFor`, from the folder's `metadata.info.json`) and what the last link check said; **Use the published embed id** (a row) and **… for all N dead** (every row only when no check has read any; after a check that found none dead it says so) write `siteVideo` (a citeUrl naming the folder moves with it), one write. No network | `umtool links <p> --embed-ids [--clips a,b] [--dry-run] [--json]` | `GET/POST /api/report/embed-ids` |
+| **Still** (Play, beside Edit this clip; Cut tab › Project › Shots lists them) | the frame on screen — the clip's fetched window at the playhead's SOURCE second, one `ffmpeg -ss -frames:v 1` (not heavy) — as `shots/still-<clip>-<s>s.png`; nothing fetched, the cut not written | `umtool still <p> <clip> --at <source s> [--take <t>] [--json]` · `umtool still <p> ls` | `GET/POST /api/report/still-frame` |
diff --git a/umtool/e2e/fixtures/inspector-fixture.mjs b/umtool/e2e/fixtures/inspector-fixture.mjs
@@ -0,0 +1,129 @@
+// THE INSPECTOR PANELS (umtool redesign L6; e2e/inspector-*.spec.ts): one WRITABLE project per panel, each
+// play-cut-fixture's cut (c01 c02 k01 c03 c04 on playvid, its window cached in out/clips-raw) unless said, each
+// with a made take (takes/short/take.json) the specs check is never written -- every UI edit lands in the draft.
+//
+// inspector-provenance-fixture provenance with no channelSlug (the gap `umtool new` leaves) and an old origin
+// inspector-title-fixture the title, a subtitle
+// inspector-teaser-fixture no teaser yet
+// inspector-ledger-fixture a MEASURE ledger (one value track, one regime track) with two rows, w01 pinned to c01
+// inspector-post-fixture two post items -- p-long (a long text post, an excerpt picked by selection) and
+// p-vid (a video with sound, and a picture of the post it does not carry) -- from
+// post-items-fixture's archive files
+// inspector-rumble-fixture three Rumble clips on inspectrumble, two naming a URL-slug FOLDER the archive does not
+// serve (v7slug1 -> v7emb01, v7slug2 -> v7emb02, in the project's .shadow-channels),
+// one its own; out/links.json records both folder links dead
+// inspector-still-fixture the cut alone (Play's Still button)
+//
+// Synthetic, like every fixture.
+import { spawnSync } from "node:child_process";
+import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+const TAKE = (dir) => JSON.parse(readFileSync(path.join(dir, "takes", "short", "take.json"), "utf8"));
+
+/**
+ * @param {{ reports: string, channels: string, deckManifest: Function, cachedWindow: string, makePlayCutFixture: Function }} o
+ */
+export async function makeInspectorFixtures({ reports, channels, deckManifest, cachedWindow, makePlayCutFixture }) {
+ const cut = (name, title, edit = (m) => m) => {
+ const { dir } = makePlayCutFixture({ reports, deckManifest, cachedWindow, name, title });
+ const file = path.join(dir, "video.manifest.json");
+ const m = edit(JSON.parse(readFileSync(file, "utf8")));
+ writeFileSync(file, JSON.stringify(m, null, 2) + "\n");
+ TAKE(dir); // the take is there to be left alone
+ return dir;
+ };
+
+ cut("inspector-provenance-fixture", "The Inspector Provenance Fixture", (m) => ({ ...m, provenance: { siteOrigin: "https://old.example" } }));
+ cut("inspector-title-fixture", "The Inspector Title Fixture", (m) => ({ ...m, subtitle: "an old subtitle" }));
+ cut("inspector-teaser-fixture", "The Inspector Teaser Fixture");
+ cut("inspector-still-fixture", "The Inspector Still Fixture");
+ cut("inspector-ledger-fixture", "The Inspector Ledger Fixture", (m) => ({
+ ...m,
+ ledgerSchema: {
+ kind: "measure", unit: "lb", yLabel: "POUNDS", yMin: 200, yMax: 400,
+ tracks: [
+ { key: "weight", role: "value", label: "What he says he weighs" },
+ { key: "regime", role: "regime", label: "The diet he names", regimes: ["keto", "off"] },
+ ],
+ forms: ["current", "past", "delta", "status"],
+ regimes: [{ key: "keto", label: "Keto" }, { key: "off", label: "No diet" }],
+ fields: [],
+ },
+ ledger: [
+ { id: "w01", date: "2026-10-01", asOf: null, scope: "weight", population: "current", value: 291, display: "291 lb", label: "on the scale", scopeBasis: "his words: I weigh 291", scopeConfidence: "read", valueKind: "uttered", flags: [], entryId: "c01", channel: "inspchan", video: "playvid", cite: 1 },
+ { id: "d01", date: "2026-09-01", asOf: null, scope: "regime", population: "status", value: "keto", event: "start", display: "keto", label: "starts keto", scopeBasis: "I'm doing keto", scopeConfidence: "read", valueKind: "uttered", flags: [] },
+ ],
+ }));
+
+ // ---- post items --------------------------------------------------------------------------------------------
+ {
+ const name = "inspector-post-fixture";
+ const dir = path.join(reports, name);
+ const media = path.join(dir, "posts-media", "postchan-x", "3");
+ mkdirSync(media, { recursive: true });
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "playvid_0.00-9.00.mp4"));
+ const cap = path.join(channels, "postchan-x", "posts-media");
+ copyFileSync(path.join(cap, "3", "3_1.mp4"), path.join(media, "3_1.mp4"));
+ copyFileSync(path.join(cap, "2", "2_1.png"), path.join(media, "3_2.png"));
+ const base = (id, text, o = {}) => ({
+ type: "post", id, post: `postchan-x/${id.slice(2)}`, platform: "x", author: "Post Subject", handle: "postsubject",
+ date: "2026-10-30T12:00:00.000Z", text, url: `https://x.com/postsubject/status/${id.slice(2)}`, subjects: ["postsubject"], ...o,
+ });
+ const timeline = [
+ { type: "clip", id: "c01", video: "playvid", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "This is a complete sentence." },
+ base("p-5", "The scale said 291 this morning. I said the scale was broken, and then the scale said 290 by the evening. Nobody believes the scale anyway."),
+ base("p-3", "@someone_private Yes, and here is the video.", { media: [{ src: "posts-media/postchan-x/3/3_1.mp4", kind: "video", seconds: 4, width: 320, height: 180, audio: true }] }),
+ ];
+ const m = deckManifest(name, "The Inspector Post Fixture", timeline);
+ m.provenance = { ...m.provenance, channelSlug: "postchan-x" };
+ m.render.fetchPad = 0;
+ m.render.lockedEdges = false;
+ writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+ // "Use my recording"'s file: a second and a half of a tone with silence either side (the trim keeps the tone).
+ const wav = path.join(path.dirname(reports), "inspector-recording.wav");
+ const ff = spawnSync("ffmpeg", ["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=330:duration=1.5", "-af", "adelay=400|400,apad=pad_dur=0.4", "-ar", "48000", "-ac", "1", wav], { encoding: "utf8" });
+ if (ff.status !== 0) throw new Error(`ffmpeg failed: ${ff.stderr}`);
+ mkdirSync(path.join(dir, "takes", "short"), { recursive: true });
+ writeFileSync(path.join(dir, "takes", "short", "take.json"), JSON.stringify({ id: "short", group: "takes", order: 1, label: "Short", kind: "different", preview: "preview.mp4", window: "full", style: null, patch: { timeline: [timeline[1]] } }, null, 2) + "\n");
+ }
+
+ // ---- Rumble clips naming the URL-slug folder ---------------------------------------------------------------
+ {
+ const dir = cut("inspector-rumble-fixture", "The Inspector Rumble Fixture", (m) => ({
+ ...m,
+ provenance: { siteOrigin: "https://archive.example", channelSlug: "inspectrumble", channelsFallback: false },
+ timeline: [
+ { type: "clip", id: "r01", video: "v7slug1", start: 1.0, end: 3.0, cite: 1, section: 0, lock: true, quote: "the first" },
+ { type: "clip", id: "r02", video: "v7slug2", start: 3.5, end: 5.5, cite: 4, section: 0, lock: true, quote: "the second" },
+ { type: "clip", id: "r03", video: "v7own03", start: 6.0, end: 8.0, cite: 6, section: 0, lock: true, quote: "its own id" },
+ ],
+ }));
+ const ch = path.join(dir, ".shadow-channels", "inspectrumble");
+ writeFileSync(path.join(mkdirP(ch), "config.json"), JSON.stringify({ platform: "rumble", handling: "transcribe", url: "https://rumble.com/c/inspectrumble", name: "Inspect Rumble" }, null, 2));
+ for (const [folder, id] of [["v7slug1", "v7emb01"], ["v7slug2", "v7emb02"], ["v7own03", "v7own03"]]) {
+ writeFileSync(path.join(mkdirP(path.join(ch, "data", folder)), "metadata.info.json"), JSON.stringify({ id, extractor: "Rumble", webpage_url: `https://rumble.com/${folder}-a-title.html`, title: `Recording ${folder}` }));
+ }
+ // The last link check: both folder links dead (the archive serves the embed ids), the own id open -- each
+ // QR's link as the build draws it (linkCheck.mjs linksOf), so the panel reads them against the cut as it is.
+ const { linksOf, withArchiveId } = await import("../../lib/report/linkCheck.mjs");
+ const m = JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8"));
+ const embed = { r01: ["v7slug1", "v7emb01"], r02: ["v7slug2", "v7emb02"] };
+ writeFileSync(path.join(mkdirP(path.join(dir, "out")), "links.json"), JSON.stringify({
+ version: 1, checkedAt: "2026-11-08T10:00:00.000Z", fetched: 3,
+ origins: { "https://archive.example": { state: "ok", generatedAt: "2026-11-07T10:00:00.000Z", title: "Archive" } },
+ links: linksOf(m).map((l) => {
+ const e = embed[l.clip];
+ return e
+ ? { clip: l.clip, url: l.url, state: "dead", origin: "https://archive.example", why: `no record ${e[0]}`, fix: withArchiveId(l.url, e[0], e[1]), fixSiteVideo: e[1] }
+ : { clip: l.clip, url: l.url, state: "ok", origin: "https://archive.example" };
+ }),
+ }, null, 2) + "\n");
+ }
+}
+
+function mkdirP(d) {
+ mkdirSync(d, { recursive: true });
+ return d;
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -68,6 +68,7 @@ import { makeMediaScenesFixture } from "./media-scenes-fixture.mjs";
import { makeInstrumentsFixture } from "./instruments-fixture.mjs";
import { makeIntroPlayFixture } from "./intro-play-fixture.mjs";
import { makeNeedsYouFixture } from "./needs-you-fixture.mjs";
+import { makeInspectorFixtures } from "./inspector-fixture.mjs";
import { makeIngredientRailFixture } from "./ingredient-rail-fixture.mjs";
const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song");
@@ -2150,6 +2151,10 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out
rmSync(path.join(dvDir, "takes"), { recursive: true, force: true });
}
+// The inspector panels (inspector-*.spec.ts, umtool redesign L6, WRITE): one project per panel
+// (inspector-fixture.mjs), each with a take the specs check is never written.
+await makeInspectorFixtures({ reports, channels: CHANNELS, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), makePlayCutFixture });
+
// One undo stack (undo.spec.ts, WRITES): two trims a moment apart, then two undos -- its own copy.
{
const { dir: unDir } = makePlayCutFixture({
diff --git a/umtool/e2e/inspector-ledger.spec.ts b/umtool/e2e/inspector-ledger.spec.ts
@@ -0,0 +1,99 @@
+import { test, expect as baseExpect } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { openPanel } from "./panels";
+import * as urls from "./urls";
+
+// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it.
+const expect = baseExpect.configure({ timeout: 15_000 });
+
+// ---------------------------------------------------------------------------
+// THE LEDGER PANEL (umtool redesign L6, item 3; components/projects/inspector/LedgerInspector.tsx and the new
+// /api/report/ledger): a measure ledger's rows -- date, scope, value, basis, source -- added, changed and removed
+// from the Cut tab's Project panel through the ledger CLI's own checks (`umtool ledger <p> add|set|rm`), each in
+// the draft with its undo point, no take touched. inspector-ledger-fixture (WRITES): w01 (weight, pinned to c01),
+// d01 (keto, a regime row).
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial", timeout: 120_000 });
+
+const P = "reports/inspector-ledger-fixture";
+const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-ledger-fixture");
+type Row = Record<string, unknown> & { id: string };
+const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8");
+const ledger = () => (JSON.parse(manifestText()) as { ledger: Row[] }).ledger;
+const row = (id: string) => ledger().find((r) => r.id === id);
+const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8");
+
+test("add a row (date, scope, value, basis, source), refused without its basis; change one; remove one", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const take = takeText();
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ await openPanel(page, "options", "cut-project");
+ const panel = page.locator('[data-inspector="ledger"]');
+ await expect(panel.locator("[data-ledger-row]")).toHaveCount(2);
+ await expect(panel.locator('[data-ledger-row="w01"]')).toContainText("291 lb");
+
+ // A new row with no basis: the writer's sentence, nothing written.
+ await panel.locator("[data-ledger-add]").click();
+ const ed = panel.locator('[data-ledger-editor="new"]');
+ await ed.locator('[data-ledger-field="id"]').fill("w02");
+ await ed.locator('[data-ledger-field="date"]').fill("2026-11-01");
+ await ed.locator('[data-ledger-field="scope"]').selectOption("weight");
+ await ed.locator('[data-ledger-field="population"]').selectOption("current");
+ await ed.locator('[data-ledger-field="value"]').fill("288");
+ const before = manifestText();
+ await ed.locator('[data-ledger-save="new"]').click();
+ await expect(panel.locator('[data-ledger-said="refused"]')).toContainText("scopeBasis");
+ expect(manifestText()).toBe(before);
+
+ await ed.locator('[data-ledger-field="scopeBasis"]').fill("his words: down to 288");
+ await ed.locator('[data-ledger-field="channel"]').fill("inspchan");
+ await ed.locator('[data-ledger-field="video"]').fill("playvid");
+ await ed.locator('[data-ledger-field="cite"]').fill("2");
+ await ed.locator('[data-ledger-field="src"]').fill("A weigh-in @ 0:02");
+ await page.screenshot({ path: test.info().outputPath("ledger-add.png") });
+ await ed.locator('[data-ledger-save="new"]').click();
+ await expect(panel.locator('[data-ledger-said="ok"]')).toContainText("Added w02: 288 lb");
+ expect(row("w02")).toMatchObject({ id: "w02", date: "2026-11-01", scope: "weight", population: "current", value: 288, display: "288 lb", scopeBasis: "his words: down to 288", channel: "inspchan", video: "playvid", cite: 2, src: "A weigh-in @ 0:02", scopeConfidence: "read", valueKind: "uttered" });
+
+ // Change w01's value: its display is drawn from the new value; a cleared label is removed.
+ await panel.locator('[data-ledger-edit="w01"]').click();
+ const e1 = panel.locator('[data-ledger-editor="w01"]');
+ await expect(e1.locator('[data-ledger-field="value"]')).toHaveValue("291");
+ await e1.locator('[data-ledger-field="value"]').fill("290");
+ await e1.locator('[data-ledger-field="label"]').fill("");
+ await e1.locator('[data-ledger-save="w01"]').click();
+ await expect(panel.locator('[data-ledger-said="ok"]')).toContainText("Saved w01");
+ expect(row("w01")).toMatchObject({ value: 290, display: "290 lb", entryId: "c01" });
+ expect(row("w01")?.label).toBeUndefined();
+
+ // A regime row: its value a regime, its event.
+ await panel.locator('[data-ledger-edit="d01"]').click();
+ const e2 = panel.locator('[data-ledger-editor="d01"]');
+ await expect(e2.locator('[data-ledger-field="value"]')).toHaveValue("keto");
+ await e2.locator('[data-ledger-field="event"]').selectOption("stop");
+ await e2.locator('[data-ledger-save="d01"]').click();
+ await expect(panel.locator('[data-ledger-said="ok"]')).toContainText("Saved d01");
+ expect(row("d01")?.event).toBe("stop");
+
+ // A removal without the token the panel read is refused.
+ const bare = await page.request.post("/api/report/ledger", { data: { project: P, op: "rm", id: "d01" } });
+ expect(bare.status()).toBe(400);
+ expect(row("d01")).toBeDefined();
+
+ await panel.locator('[data-ledger-edit="d01"]').click();
+ await panel.locator('[data-ledger-remove="d01"]').click();
+ await expect(panel.locator('[data-ledger-said="ok"]')).toContainText("Removed d01");
+ expect(row("d01")).toBeUndefined();
+ await expect(panel.locator("[data-ledger-row]")).toHaveCount(2);
+ expect(takeText()).toBe(take);
+});
+
+test("each ledger write is one undo step", async ({ request }) => {
+ const r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } });
+ expect(r.ok(), await r.text()).toBe(true);
+ expect((await r.json()).op).toBe("ledger");
+ expect(row("d01")).toMatchObject({ event: "stop" });
+});
diff --git a/umtool/e2e/inspector-post-item.spec.ts b/umtool/e2e/inspector-post-item.spec.ts
@@ -0,0 +1,162 @@
+import { test, expect as baseExpect, type Page } from "@playwright/test";
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it.
+const expect = baseExpect.configure({ timeout: 15_000 });
+
+// ---------------------------------------------------------------------------
+// THE POST ITEM PANEL (umtool redesign L6, item 4; components/projects/inspector/PostItemInspector.tsx): a post
+// row's Edit on the Cut tab -- the EXCERPT picked by selecting the post's words (snapped to words, settled where
+// the build finds each span; was `posts set-item excerpt=…`), its MEDIA on/off and a video's sound, and "Use my
+// recording" (a sound file kept as a recorded take and picked; was `posts narrate --recording`). Every write
+// lands in the draft; no take touched. inspector-post-fixture (WRITES): p-5 (a long text post), p-3 (a video with
+// sound, and a picture of the post it does not carry).
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial", timeout: 120_000 });
+
+const P = "reports/inspector-post-fixture";
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const DIR = path.join(HERE, "..", ".e2e-song", "reports", "inspector-post-fixture");
+type Post = Record<string, unknown> & { id: string; excerpt?: string[]; media?: Record<string, unknown>[]; narration?: { takes?: { file: string; engine?: string }[]; pick?: number } };
+const item = (id: string) => (JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { timeline: Post[] }).timeline.find((e) => e.id === id) as Post;
+const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8");
+
+/** Select the `nth` occurrence of `needle` in the element's text, as a person dragging over it would. */
+async function selectText(page: Page, selector: string, needle: string, nth = 0) {
+ await page.evaluate(
+ ({ selector, needle, nth }) => {
+ const root = document.querySelector(selector) as HTMLElement;
+ const full = root.textContent ?? "";
+ let at = -1;
+ for (let i = 0; i <= nth; i++) at = full.indexOf(needle, at + 1);
+ if (at < 0) throw new Error(`no "${needle}" in the post's text`);
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ let pos = 0;
+ let sN: Node | null = null;
+ let sO = 0;
+ let eN: Node | null = null;
+ let eO = 0;
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
+ const len = (n.textContent ?? "").length;
+ if (!sN && at < pos + len) {
+ sN = n;
+ sO = at - pos;
+ }
+ if (sN && at + needle.length <= pos + len) {
+ eN = n;
+ eO = at + needle.length - pos;
+ break;
+ }
+ pos += len;
+ }
+ const r = document.createRange();
+ r.setStart(sN as Node, sO);
+ r.setEnd(eN as Node, eO);
+ const sel = window.getSelection() as Selection;
+ sel.removeAllRanges();
+ sel.addRange(r);
+ },
+ { selector, needle, nth },
+ );
+}
+
+test("the excerpt, picked by selecting the post's words: a span whose words come earlier too is widened to where it was picked", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const take = takeText();
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ const row = page.locator('[data-entry="p-5"]');
+ await row.locator("[data-post-edit]").click();
+ const panel = row.locator('[data-inspector="post-item"]');
+ await expect(panel.locator("[data-post-text]")).toContainText("The scale said 291 this morning.");
+ // "scale said" is said twice: the second one, picked, is read as "the scale said" so the build finds it there.
+ await selectText(page, '[data-entry="p-5"] [data-post-text]', "scale said", 1);
+ await panel.locator("[data-excerpt-add]").click();
+ await selectText(page, '[data-entry="p-5"] [data-post-text]', "obody believ");
+ await panel.locator("[data-excerpt-add]").click();
+ await expect(panel.locator("[data-excerpt-span]")).toHaveCount(2);
+ await expect(panel.locator('[data-excerpt-span="0"]')).toContainText("“the scale said”");
+ await expect(panel.locator('[data-excerpt-span="1"]')).toContainText("“Nobody believes”");
+ await page.screenshot({ path: test.info().outputPath("post-excerpt.png") });
+ await panel.locator("[data-excerpt-save]").click();
+ await expect(panel.locator('[data-post-said="ok"]')).toContainText("Excerpt saved to the draft: 2 spans");
+ expect(item("p-5").excerpt).toEqual(["the scale said", "Nobody believes"]);
+ await expect(panel.locator("[data-excerpt-piece]")).toHaveCount(2);
+
+ // Removing a span and saving keeps the other; Clear and save reads it whole.
+ await panel.locator('[data-excerpt-span-remove="1"]').click();
+ await panel.locator("[data-excerpt-save]").click();
+ await expect(panel.locator('[data-post-said="ok"]')).toContainText("1 span");
+ expect(item("p-5").excerpt).toEqual(["the scale said"]);
+ expect(takeText()).toBe(take);
+});
+
+test("media on/off and a video's sound: off keeps the attachment whole (its crop), on puts it back as it was", async ({ page, request }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const take = takeText();
+ // A crop set on the bench first: the knob off->on must not lose.
+ let r = await request.post("/api/report/post-item", { data: { project: P, op: "set", id: "p-3", patch: { media: { 0: { crop: [0.1, 0.1, 0.8, 0.8] } } } } });
+ expect(r.ok(), await r.text()).toBe(true);
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ const row = page.locator('[data-entry="p-3"]');
+ await row.locator("[data-post-edit]").click();
+ const panel = row.locator('[data-inspector="post-item"]');
+ await expect(panel.locator('[data-post-media="0"]')).toContainText("3_1.mp4");
+ await expect(panel.locator('[data-post-file="posts-media/postchan-x/3/3_2.png"]')).toBeVisible();
+
+ // Each box is the draft's state: a click asks for the change, the box shows it once it is written.
+ await panel.locator('[data-post-media="0"] [data-post-media-sound]').click();
+ await expect(panel.locator('[data-post-said="ok"]')).toContainText("Sound off.");
+ expect(item("p-3").media?.[0]).toMatchObject({ src: "posts-media/postchan-x/3/3_1.mp4", mute: true, crop: [0.1, 0.1, 0.8, 0.8] });
+ await expect(panel.locator('[data-post-media="0"] [data-post-media-sound]')).not.toBeChecked();
+
+ // The picture of the post it never carried, put on.
+ await panel.locator('[data-post-file="posts-media/postchan-x/3/3_2.png"] [data-post-file-shown]').click();
+ await expect(panel.locator('[data-post-said="ok"]')).toContainText("3_2.png: on the item.");
+ expect(item("p-3").media?.map((m) => [m.src, m.kind])).toEqual([["posts-media/postchan-x/3/3_1.mp4", "video"], ["posts-media/postchan-x/3/3_2.png", "image"]]);
+ // A file the item carries already is not added twice.
+ r = await request.post("/api/report/post-item/inspector", { data: { project: P, op: "media-on", id: "p-3", file: "posts-media/postchan-x/3/3_2.png" } });
+ expect(r.status()).toBe(400);
+ expect((await r.json()).error).toContain("carries posts-media/postchan-x/3/3_2.png already");
+
+ // The video OFF: out of what plays, kept whole in mediaOff -- its crop, its sound off.
+ await panel.locator('[data-post-media="0"] [data-post-media-shown]').click();
+ await expect(panel.locator('[data-post-said="ok"]')).toContainText("off (kept as it was set");
+ expect(item("p-3").media?.map((m) => m.src)).toEqual(["posts-media/postchan-x/3/3_2.png"]);
+ expect((item("p-3") as Post & { mediaOff?: Record<string, unknown>[] }).mediaOff).toEqual([
+ { src: "posts-media/postchan-x/3/3_1.mp4", kind: "video", seconds: 4, width: 320, height: 180, audio: true, crop: [0.1, 0.1, 0.8, 0.8], mute: true },
+ ]);
+ await expect(panel.locator('[data-post-media-off="0"]')).toContainText("3_1.mp4");
+ await expect(panel.locator('[data-post-file="posts-media/postchan-x/3/3_1.mp4"]')).toHaveCount(0);
+ // ON again: back as it was, crop and all.
+ await panel.locator('[data-post-media-off="0"] [data-post-media-off-shown]').click();
+ await expect(panel.locator('[data-post-said="ok"]')).toContainText("on again, as it was");
+ expect(item("p-3").media?.[1]).toEqual({ src: "posts-media/postchan-x/3/3_1.mp4", kind: "video", seconds: 4, width: 320, height: 180, audio: true, crop: [0.1, 0.1, 0.8, 0.8], mute: true });
+ expect("mediaOff" in item("p-3")).toBe(false);
+ expect(existsSync(path.join(DIR, "posts-media", "postchan-x", "3", "3_1.mp4"))).toBe(true);
+ expect(takeText()).toBe(take);
+});
+
+test("Use my recording: a sound file kept as a recorded take of the item and picked", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const take = takeText();
+ expect(item("p-5").narration).toBeUndefined();
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ const row = page.locator('[data-entry="p-5"]');
+ await row.locator("[data-post-edit]").click();
+ const panel = row.locator('[data-inspector="post-item"]');
+ await expect(panel.locator("[data-post-takes]")).toContainText("not narrated yet");
+ await panel.locator("[data-post-recording-file]").setInputFiles(path.join(HERE, "..", ".e2e-song", "inspector-recording.wav"));
+ await panel.locator("[data-post-recording-use]").click();
+ await expect(panel.locator('[data-post-said="ok"]')).toContainText("Kept as", { timeout: 30_000 });
+ const n = item("p-5").narration;
+ expect(n?.takes).toHaveLength(1);
+ expect(n?.takes?.[0].file).toMatch(/take-1\.recorded-operator\.wav$/);
+ expect(existsSync(path.join(DIR, ...String(n?.takes?.[0].file).split("/")))).toBe(true);
+ await expect(panel.locator("[data-post-takes]")).toContainText("1 take; plays take-1.recorded-operator.wav");
+ await page.screenshot({ path: test.info().outputPath("post-recording.png") });
+ expect(takeText()).toBe(take);
+});
diff --git a/umtool/e2e/inspector-provenance.spec.ts b/umtool/e2e/inspector-provenance.spec.ts
@@ -0,0 +1,70 @@
+import { test, expect as baseExpect } from "@playwright/test";
+import { readFileSync, readdirSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { openPanel } from "./panels";
+import * as urls from "./urls";
+
+// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it.
+const expect = baseExpect.configure({ timeout: 15_000 });
+
+// ---------------------------------------------------------------------------
+// THE PROVENANCE PANEL (umtool redesign L6, item 1; components/projects/inspector/ProvenanceInspector.tsx): the
+// Cut tab's Project panel sets provenance.siteOrigin, channelSlug and channel in the DRAFT -- the owed provenance
+// writer (`umtool provenance <p> set` is its twin) -- one undo point, no take touched; a bad origin is refused in
+// the writer's words. inspector-provenance-fixture (WRITES): no channelSlug, an old origin.
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial", timeout: 120_000 });
+
+const P = "reports/inspector-provenance-fixture";
+const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-provenance-fixture");
+const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8");
+const manifest = () => JSON.parse(manifestText()) as { provenance: Record<string, unknown> };
+const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8");
+const undoPoints = (op: string) => readdirSync(path.join(DIR, "revisions")).filter((f) => f.endsWith(`auto-before-${op}.manifest.json`)).length;
+
+test("set the site origin, channel slug and name from the Cut tab: the draft written, no take", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const take = takeText();
+ expect(manifest().provenance.channelSlug).toBeUndefined();
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ await openPanel(page, "options", "cut-project");
+ const panel = page.locator('[data-inspector="provenance"]');
+ await expect(panel.locator('[data-provenance-field="siteOrigin"]')).toHaveValue("https://old.example");
+ await expect(panel).toContainText("empty: check blocks until it is set");
+ await page.screenshot({ path: test.info().outputPath("provenance-panel.png") });
+
+ // A bad origin: refused, the draft untouched.
+ const before = manifestText();
+ await panel.locator('[data-provenance-field="siteOrigin"]').fill("https://jeralyzer.pages.dev/some/path");
+ await panel.locator("[data-provenance-save]").click();
+ await expect(panel.locator('[data-provenance-said="refused"]')).toContainText("siteOrigin is the archive's origin, with no path");
+ expect(manifestText()).toBe(before);
+
+ await panel.locator('[data-provenance-field="siteOrigin"]').fill("https://jeralyzer.pages.dev/");
+ await panel.locator('[data-provenance-field="channelSlug"]').fill("inspchan");
+ await panel.locator('[data-provenance-field="channel"]').fill("Inspector Channel");
+ await panel.locator("[data-provenance-save]").click();
+ await expect(panel.locator('[data-provenance-said="ok"]')).toContainText("Saved to the draft: siteOrigin, channelSlug, channel");
+ expect(manifest().provenance).toMatchObject({ siteOrigin: "https://jeralyzer.pages.dev", channelSlug: "inspchan", channel: "Inspector Channel" });
+ expect(undoPoints("provenance")).toBe(1);
+ expect(takeText()).toBe(take);
+ // The link policy per channel, under it: the cut's clips are now inspchan's.
+ await expect(panel.locator('[data-provenance-link-policy] [data-link-policy-direct="inspchan"]')).toBeVisible();
+ await page.screenshot({ path: test.info().outputPath("provenance-saved.png") });
+
+ // Clearing a key removes it.
+ await panel.locator('[data-provenance-field="channel"]').fill("");
+ await panel.locator("[data-provenance-save]").click();
+ await expect(panel.locator('[data-provenance-said="ok"]')).toContainText("channel");
+ expect(manifest().provenance.channel).toBeUndefined();
+ expect(takeText()).toBe(take);
+});
+
+test("one Undo takes the last provenance write back", async ({ request }) => {
+ const r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } });
+ expect(r.ok(), await r.text()).toBe(true);
+ expect((await r.json()).op).toBe("provenance");
+ expect(manifest().provenance.channel).toBe("Inspector Channel");
+});
diff --git a/umtool/e2e/inspector-rumble-cite.spec.ts b/umtool/e2e/inspector-rumble-cite.spec.ts
@@ -0,0 +1,93 @@
+import { test, expect as baseExpect } from "@playwright/test";
+import { readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { openPanel } from "./panels";
+import * as urls from "./urls";
+
+// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it.
+const expect = baseExpect.configure({ timeout: 15_000 });
+
+// ---------------------------------------------------------------------------
+// THE RUMBLE CITE FIX (umtool redesign L6, item 5; components/projects/inspector/LinksInspector.tsx): the Cut
+// tab's Project panel lists each clip citing a Rumble URL-slug FOLDER the archive does not serve, with the embed
+// id it does (L1's siteVideoFor, from the folder's metadata), and "Use the published embed id" writes `siteVideo`
+// into the draft -- per row, and once for every dead Rumble row; one undo point per press, no network, no take
+// touched (`umtool links <p> --embed-ids` is the twin). inspector-rumble-fixture (WRITES): r01 v7slug1 -> v7emb01,
+// r02 v7slug2 -> v7emb02 (both dead at the last check), r03 its own id.
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial", timeout: 120_000 });
+
+const P = "reports/inspector-rumble-fixture";
+const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-rumble-fixture");
+type Clip = { id: string; video: string; siteVideo?: string };
+const clips = () => (JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { timeline: Clip[] }).timeline;
+const sv = () => Object.fromEntries(clips().map((c) => [c.id, c.siteVideo ?? null]));
+const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8");
+
+test("one row: Use the published embed id -- siteVideo in the draft, the folder id kept", async ({ page, request }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const take = takeText();
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ await openPanel(page, "options", "cut-project");
+ const panel = page.locator('[data-inspector="links"]');
+ await expect(panel.locator("[data-embed-row]")).toHaveCount(2);
+ await expect(panel.locator('[data-embed-row="r01"]')).toHaveAttribute("data-embed-state", "dead");
+ await expect(panel.locator('[data-embed-row="r01"]')).toContainText("inspectrumble/v7slug1 → v7emb01");
+ await expect(panel.locator('[data-embed-row="r03"]')).toHaveCount(0);
+ await expect(panel.locator("[data-embed-use-all]")).toContainText("for all 2 dead");
+ await page.screenshot({ path: test.info().outputPath("rumble-cites.png") });
+
+ await panel.locator('[data-embed-use="r01"]').click();
+ await expect(panel.locator('[data-embed-said="ok"]')).toContainText("r01 → v7emb01");
+ expect(sv()).toEqual({ r01: "v7emb01", r02: null, r03: null });
+ expect(clips().find((c) => c.id === "r01")?.video).toBe("v7slug1");
+ await expect(panel.locator("[data-embed-row]")).toHaveCount(1);
+ expect(takeText()).toBe(take);
+
+ // A write without the token the panel read is refused, never blind.
+ const bare = await request.post("/api/report/embed-ids", { data: { project: P, clips: ["r02"] } });
+ expect(bare.status()).toBe(400);
+ expect(sv().r02).toBeNull();
+
+ // One press, one undo step.
+ const r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } });
+ expect(r.ok(), await r.text()).toBe(true);
+ expect((await r.json()).op).toBe("embed-ids");
+ expect(sv()).toEqual({ r01: null, r02: null, r03: null });
+});
+
+test("every dead Rumble row in one press", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const take = takeText();
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ await openPanel(page, "options", "cut-project");
+ const panel = page.locator('[data-inspector="links"]');
+ await expect(panel.locator("[data-embed-row]")).toHaveCount(2);
+ await panel.locator("[data-embed-use-all]").click();
+ await expect(panel.locator('[data-embed-said="ok"]')).toContainText("r01 → v7emb01, r02 → v7emb02");
+ expect(sv()).toEqual({ r01: "v7emb01", r02: "v7emb02", r03: null });
+ await expect(panel.locator("[data-embed-none]")).toBeVisible();
+ expect(takeText()).toBe(take);
+});
+
+test("a check that found the folder links open: no 'all' press, a row is fixed only by its own", async ({ page, request }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ // Back to the folder ids, then a check that read both links open.
+ const r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } });
+ expect(r.ok(), await r.text()).toBe(true);
+ expect(sv()).toEqual({ r01: null, r02: null, r03: null });
+ const file = path.join(DIR, "out", "links.json");
+ const doc = JSON.parse(readFileSync(file, "utf8")) as { links: { state: string; fix?: string; fixSiteVideo?: string; why?: string }[] };
+ doc.links = doc.links.map(({ fix: _f, fixSiteVideo: _s, why: _w, ...l }) => ({ ...l, state: "ok" }));
+ writeFileSync(file, JSON.stringify(doc, null, 2) + "\n");
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ await openPanel(page, "options", "cut-project");
+ const panel = page.locator('[data-inspector="links"]');
+ await expect(panel.locator("[data-embed-row]")).toHaveCount(2);
+ await expect(panel.locator('[data-embed-row="r01"]')).toHaveAttribute("data-embed-state", "ok");
+ await expect(panel.locator("[data-embed-no-dead]")).toContainText("no dead links at the last check");
+ await expect(panel.locator("[data-embed-use-all]")).toHaveCount(0);
+ expect(sv()).toEqual({ r01: null, r02: null, r03: null });
+});
diff --git a/umtool/e2e/inspector-still.spec.ts b/umtool/e2e/inspector-still.spec.ts
@@ -0,0 +1,52 @@
+import { test, expect as baseExpect } from "@playwright/test";
+import { readFileSync, readdirSync, statSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { openPanel } from "./panels";
+import * as urls from "./urls";
+
+// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it.
+const expect = baseExpect.configure({ timeout: 15_000 });
+
+// ---------------------------------------------------------------------------
+// A STILL AT SECOND N (umtool redesign L6, item 6; components/projects/inspector/StillInspector.tsx): Play's Still
+// button keeps the frame on screen -- the clip's fetched window at the playhead's source second, one ffmpeg frame --
+// as shots/still-<clip>-<s>s.png, listed on the Cut tab's Project panel; the cut itself is never written
+// (`umtool still` is the twin). inspector-still-fixture (WRITES shots/): play-cut-fixture's cut, its window cached.
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ timeout: 120_000 });
+
+const P = "reports/inspector-still-fixture";
+const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-still-fixture");
+const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8");
+const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8");
+
+test("Still in Play: the frame at the playhead into shots/, listed on the Cut tab, the draft untouched", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const before = manifestText();
+ const take = takeText();
+ await page.goto(urls.playHref(P, { clip: "c01", at: 0.5 }));
+ const root = page.locator("[data-play-cut]");
+ await expect(root).toHaveAttribute("data-play-state", "paused", { timeout: 30_000 });
+ await expect(page.locator("[data-play-readout]")).toContainText("c01");
+ await page.locator("[data-play-still]").click();
+ const said = page.locator('[data-play-still-said="ok"]');
+ await expect(said).toContainText("shots/still-c01-", { timeout: 20_000 });
+ await page.screenshot({ path: test.info().outputPath("play-still.png") });
+ const shots = readdirSync(path.join(DIR, "shots")).filter((f) => f.startsWith("still-c01-"));
+ expect(shots).toHaveLength(1);
+ expect(statSync(path.join(DIR, "shots", shots[0])).size).toBeGreaterThan(100);
+ // Its second is the clip's source second (c01 plays 1.0-3.0): inside the clip.
+ const at = Number(/still-c01-(\d+)_(\d{2})s\.png/.exec(shots[0])?.slice(1, 3).join("."));
+ expect(at).toBeGreaterThanOrEqual(1);
+ expect(at).toBeLessThanOrEqual(3);
+ expect(manifestText()).toBe(before);
+ expect(takeText()).toBe(take);
+
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ await openPanel(page, "options", "cut-project");
+ const panel = page.locator('[data-inspector="still"]');
+ await expect(panel.locator(`[data-shot="shots/${shots[0]}"]`)).toBeVisible();
+ await expect(panel.locator(`[data-shot="shots/${shots[0]}"] img`)).toHaveJSProperty("complete", true);
+});
diff --git a/umtool/e2e/inspector-teaser-insert.spec.ts b/umtool/e2e/inspector-teaser-insert.spec.ts
@@ -0,0 +1,87 @@
+import { test, expect as baseExpect } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it.
+const expect = baseExpect.configure({ timeout: 15_000 });
+
+// ---------------------------------------------------------------------------
+// INSERT A TEASER OR CLOSING CARD (umtool redesign L6, item 2; components/projects/inspector/TeaserInspector.tsx):
+// the Cut tab's "Insert a teaser or closing card" -- where, the lines with a break and a hold, the beat -- writes
+// a `teaser` entry into the draft (`umtool timeline <p> teaser-insert` is the twin), refused in the build's teaser
+// words, its row's Edit changes it after; no take touched. inspector-teaser-fixture (WRITES).
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ mode: "serial", timeout: 120_000 });
+
+const P = "reports/inspector-teaser-fixture";
+const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-teaser-fixture");
+const manifestText = () => readFileSync(path.join(DIR, "video.manifest.json"), "utf8");
+const timeline = () => (JSON.parse(manifestText()) as { timeline: Record<string, unknown>[] }).timeline;
+const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8");
+
+test("a closing card at the end: its lines, a break and a hold, its beat -- and a bad break refused", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const take = takeText();
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ await page.locator("[data-cut-insert-card]").click();
+ const panel = page.locator('[data-inspector="teaser"]');
+ await expect(panel.locator("[data-teaser-position]")).toHaveValue("end");
+ await panel.locator('[data-teaser-line="0"] [data-teaser-line-field="text"]').fill("The 291 scale bet");
+ await panel.locator("[data-teaser-add-line]").click();
+ const l1 = panel.locator('[data-teaser-line="1"]');
+ await l1.locator('[data-teaser-line-field="text"]').fill("Scale video: not posted as of Nov 8");
+ // A break that is not the end of its words: the build's rule, said; nothing written.
+ await l1.locator('[data-teaser-line-field="break"]').fill("not posted");
+ const before = manifestText();
+ await panel.locator('[data-teaser-insert="insert"]').click();
+ await expect(panel.locator('[data-teaser-said="refused"]')).toContainText("break must be the end of its text");
+ expect(manifestText()).toBe(before);
+
+ await l1.locator('[data-teaser-line-field="break"]').fill("as of Nov 8");
+ await l1.locator('[data-teaser-line-field="hold"]').fill("1.6");
+ await panel.locator("[data-teaser-beat]").fill("1.3");
+ await page.screenshot({ path: test.info().outputPath("teaser-insert.png") });
+ await panel.locator('[data-teaser-insert="insert"]').click();
+ await expect(panel.locator('[data-teaser-said="ok"]')).toContainText("Inserted close at 6");
+ expect(timeline().at(-1)).toEqual({ type: "teaser", id: "close", lines: ["The 291 scale bet", { text: "Scale video: not posted as of Nov 8", break: "as of Nov 8", hold: 1.6 }], beat: 1.3 });
+ expect(takeText()).toBe(take);
+ // Its row is in the cut.
+ await expect(page.locator('[data-entry="close"][data-kind="teaser"]')).toBeVisible();
+});
+
+test("a cold open at the start, then its row's Edit changes its beat; Undo takes that edit back", async ({ page, request }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const take = takeText();
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ await page.locator("[data-cut-insert-card]").click();
+ const panel = page.locator('[data-inspector="teaser"]');
+ await panel.locator("[data-teaser-position]").selectOption("start");
+ await panel.locator('[data-teaser-line="0"] [data-teaser-line-field="text"]').fill("Cold open");
+ await panel.locator('[data-teaser-insert="insert"]').click();
+ await expect(panel.locator('[data-teaser-said="ok"]')).toContainText("Inserted cold at 1");
+ expect(timeline()[0]).toEqual({ type: "teaser", id: "cold", lines: ["Cold open"] });
+
+ await page.reload();
+ const row = page.locator('[data-entry="cold"]');
+ await row.locator("[data-teaser-edit]").click();
+ const edit = row.locator('[data-inspector="teaser"]');
+ await expect(edit.locator('[data-teaser-line="0"] [data-teaser-line-field="text"]')).toHaveValue("Cold open");
+ await edit.locator("[data-teaser-beat]").fill("0.9");
+ await edit.locator('[data-teaser-insert="set"]').click();
+ await expect(edit.locator('[data-teaser-said="ok"]')).toContainText("Saved cold to the draft.");
+ expect(timeline()[0]).toEqual({ type: "teaser", id: "cold", lines: ["Cold open"], beat: 0.9 });
+ expect(takeText()).toBe(take);
+
+ // The route wants the token it handed out: a write without one is refused.
+ const bare = await request.post("/api/report/teaser", { data: { project: P, op: "set", id: "cold", patch: { beat: 1.1 } } });
+ expect(bare.status()).toBe(400);
+ expect(timeline()[0]).toEqual({ type: "teaser", id: "cold", lines: ["Cold open"], beat: 0.9 });
+
+ const r = await request.post("/api/report/timeline", { data: { project: P, op: "undo" } });
+ expect(r.ok(), await r.text()).toBe(true);
+ expect((await r.json()).op).toBe("teaser");
+ expect(timeline()[0]).toEqual({ type: "teaser", id: "cold", lines: ["Cold open"] });
+});
diff --git a/umtool/e2e/inspector-title.spec.ts b/umtool/e2e/inspector-title.spec.ts
@@ -0,0 +1,49 @@
+import { test, expect as baseExpect } from "@playwright/test";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { openPanel } from "./panels";
+import * as urls from "./urls";
+
+// A write is a request under the app's lock, and this machine runs other suites beside this one: room for it.
+const expect = baseExpect.configure({ timeout: 15_000 });
+
+// ---------------------------------------------------------------------------
+// THE TITLE PANEL (umtool redesign L6, item 7; 9 Nov: four news projects' title/subtitle set with jq): the Cut
+// tab's Project panel writes the manifest's `title` and `subtitle` in the draft (`umtool title` is the twin),
+// an empty subtitle removes it, no take touched. inspector-title-fixture (WRITES).
+// ---------------------------------------------------------------------------
+
+test.describe.configure({ timeout: 120_000 });
+
+const P = "reports/inspector-title-fixture";
+const DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", ".e2e-song", "reports", "inspector-title-fixture");
+const manifest = () => JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")) as { title?: string; subtitle?: string };
+const takeText = () => readFileSync(path.join(DIR, "takes", "short", "take.json"), "utf8");
+
+test("retitle the project and drop its subtitle from the Cut tab", async ({ page }) => {
+ await page.setViewportSize({ width: 1366, height: 768 });
+ const take = takeText();
+ await page.goto(urls.projectHref(P, { tab: "cut" }));
+ await openPanel(page, "options", "cut-project");
+ const panel = page.locator('[data-inspector="title"]');
+ await expect(panel.locator('[data-title-field="title"]')).toHaveValue("The Inspector Title Fixture");
+ await expect(panel.locator('[data-title-field="subtitle"]')).toHaveValue("an old subtitle");
+ await panel.locator('[data-title-field="title"]').fill("Losing the same hundred pounds");
+ await panel.locator('[data-title-field="subtitle"]').fill("Every weight he has given on camera");
+ await panel.locator("[data-title-save]").click();
+ await expect(panel.locator('[data-title-said="ok"]')).toContainText("Saved to the draft.");
+ expect(manifest()).toMatchObject({ title: "Losing the same hundred pounds", subtitle: "Every weight he has given on camera" });
+ // The head follows (the crumb is the title).
+ await expect(page.locator("body")).toContainText("Losing the same hundred pounds");
+ await page.screenshot({ path: test.info().outputPath("title-panel.png") });
+
+ await panel.locator('[data-title-field="subtitle"]').fill("");
+ await panel.locator("[data-title-save]").click();
+ await expect(panel.locator('[data-title-said="ok"]')).toBeVisible();
+ expect("subtitle" in manifest()).toBe(false);
+ // An empty title cannot be saved.
+ await panel.locator('[data-title-field="title"]').fill(" ");
+ await expect(panel.locator("[data-title-save]")).toBeDisabled();
+ expect(takeText()).toBe(take);
+});
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -53,8 +53,12 @@ export const GROUPS = [
usage: [
" umtool links <project> [--json] [--fix] do the clip QRs open on their sites? (corpus.json -> slugToPage",
" -> the shard's record; polite, cached; out/links.json, which check reads); exit 1 when one is dead",
+ " umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json] the published Rumble embed id (siteVideo)",
+ " on every clip citing a URL-slug folder; no network, one write (the Cut tab's Project > Rumble cites)",
],
docs: [
+ ["`links <project> --embed-ids [--clips a,b] [--dry-run] [--json]`",
+ "the **published embed id**: every clip citing a Rumble URL-slug folder the archive does not serve gets `siteVideo` (the folder's `metadata.info.json` id, shareLine.mjs `siteVideoFor`), a citeUrl naming the folder moved with it; no network, one write, one undo point. The Cut tab's Project › Rumble cites ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"],
["`links <project> [--json] [--fix]`",
"do the clip QRs open on their sites? `corpus.json` → the channel's manifest → `slugToPage` → the shard's record, one request at a time, shards from the cue cache; recorded in `out/links.json`, which `check` reads (`link-dead` blocking, `links-unverified`, `links-unchecked`); `--fix` rewrites a Twitch id the site serves as `v<id>`, and a Rumble folder id (the URL slug) as the embed id the site serves (the clip gets `siteVideo`); **exit 1** when a link is dead ([knobs.md](knobs.md#do-the-qr-links-open)). The same record dates each site's deploy: a cited video newer than it is `site-deploy-behind` ([knobs.md](knobs.md#the-sites-the-links-depend-on))"],
],
@@ -843,6 +847,38 @@ export const GROUPS = [
],
},
{
+ cmd: "provenance",
+ usage: [
+ " umtool provenance <project> [ls] | set [--site-origin URL] [--channel-slug S] [--channel \"Name\"] [--json]",
+ " the project's provenance (where its QRs open, the channel its clips are from); \"\" removes one",
+ ],
+ docs: [
+ ["`provenance <project> [ls] [--json]` · `provenance <project> set [--site-origin URL] [--channel-slug S] [--channel \"…\"] [--json]`",
+ "the project's **provenance**: `siteOrigin` (the archive its QRs open), `channelSlug` (a clip with no channel is from it; `check` blocks without it), `channel` (the display name); `\"\"` removes one. One write, one undo point; the Cut tab's Project › Provenance. The link policy is `link-policy` ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"],
+ ],
+ },
+ {
+ cmd: "title",
+ usage: [
+ " umtool title <project> [\"<title>\"] [--subtitle \"…\" | --no-subtitle] [--json] the project's title and subtitle",
+ ],
+ docs: [
+ ["`title <project> [\"<title>\"] [--subtitle \"…\" \\| --no-subtitle] [--json]`",
+ "the project's **title and subtitle** (the manifest's `title`/`subtitle`); no words prints them. One write to the draft, one undo point; the Cut tab's Project › Title ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"],
+ ],
+ },
+ {
+ cmd: "still",
+ usage: [
+ " umtool still <project> <clip> --at <source s> [--take <id>] [--json] | ls a frame of the clip's fetched",
+ " window into shots/ (Play's Still button)",
+ ],
+ docs: [
+ ["`still <project> <clip> --at <source s> [--take <take>] [--json]` · `still <project> ls [--json]`",
+ "a **still at second N**: one frame of the clip's fetched window at that source second into `shots/still-<clip>-<s>s.png` (nothing fetched; the cut not written); `ls` the project's shots. Play's **Still** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"],
+ ],
+ },
+ {
cmd: "share",
usage: [
" umtool share <project> [<clip>] [--take <id>] [--site <id>] [--json] a clip's share line: its platform",
@@ -866,8 +902,12 @@ export const GROUPS = [
" manifest first (revisions/…-auto-before-<op>), is checked by the build, notes a generated cut",
" umtool timeline <project> --take <id> [ls | move <id> --to <index> | remove <id> | undo] a take's timeline:",
" the writes go into its patch (takes/<id>/take.json), each with an undo point of its own",
+ " umtool timeline <project> teaser-insert [--at start|end | --after <id>] [--id ID] [--beat S] --line \"…\" [--break \"…\"]",
+ " [--hold S] [--line …] | --lines-json <json|@file> a teaser or closing card inserted (default at the end)",
],
docs: [
+ ["`timeline <project> teaser-insert [--at start\\|end \\| --after <id> \\| --before <id>] [--id ID] [--beat S] --line \"…\" [--break \"…\"] [--hold S] [--line …] \\| --lines-json <json\\|@file> [--json]`",
+ "a **teaser or closing card** inserted: the first line its title, `--break`/`--hold` after a `--line` that line's; default at the end (id `close`; at the start `cold`); the build's teaser rules refuse it; one undo point. The Cut tab's **Insert a teaser or closing card** ([knobs.md](knobs.md#the-inspector-panels-this-weeks-hand-edits-in-the-ui))"],
["`timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `place <id>… --before <id\\|-> [--section N]` · `remove <id>` · `reject <id> <why> [--note T]` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\\|@file>` · `undo`",
"the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. `place` is Play's drag on the reel strip: the entries land before that entry (`-`: the end), their clips joining section N (default: the section of the clip they land after), every other clip keeping its own and the markers following, an emptied section refused, each place its own undo point ([knobs.md](knobs.md#the-reel-strip-zoom-and-reorder)). A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `reject` rejects the clip for `<why>` — `not-matching` or `wrong-speaker` (fact errors: `incorrect`, the note its correction) or `irrelevant`, `repeats`, `weak`, `privacy`, `other` (`rejected`, never a correction) — and removes it, on record in `removed.json` with the reason and the note; `wrong-speaker <id>` is `reject <id> wrong-speaker`; `ls` marks a clip rejected but still in the cut (`[rejected — irrelevant]`) ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits))"],
["`timeline <project> insert (--to-section N \\| --group G) <channel>/<video>@<start>-<end> [--id ID] [--lock] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]`",
diff --git a/umtool/lib/cli/verbs.mjs b/umtool/lib/cli/verbs.mjs
@@ -95,7 +95,23 @@ export const VERBS = Object.freeze([
]),
form("show", "project", "one project: summary, the cut, per-clip status, decisions", [project()]),
form("check", "project", "what blocks a build (exit 1 on anything blocking)", [project({ required: false, help: "one project; none: every project" }), bool("--all-severities", "the info rows too")]),
- form("links", "project", "do the clip QRs open on their sites (out/links.json)", [project(), bool("--fix", "rewrite the dead links it knows the fix for")], { timeoutMin: 30 }),
+ form("links", "project", "do the clip QRs open on their sites (out/links.json)", [
+ project(), bool("--fix", "rewrite the dead links it knows the fix for"),
+ bool("--embed-ids", "no check: every clip citing a Rumble URL-slug folder gets the embed id the archive serves (siteVideo), one write to the draft"),
+ opt("--clips", { help: "with --embed-ids: a,b (none: every such clip)" }), dry(),
+ ], { timeoutMin: 30 }),
+ // The inspector's twins (umtool redesign L6): the project's provenance, its title, a still at second N.
+ form("provenance ls", "project", "the project's provenance: site origin, channel slug, channel, link policy", [project()], { shape: "provenance <project> ls" }),
+ form("provenance set", "draft", "the project's site origin, channel slug and channel name (\"\" removes one)", [
+ project(), opt("--site-origin", { help: "https://… (the archive its QRs open)" }), opt("--channel-slug", { help: "the channel a clip with no channel is from" }), opt("--channel", { help: "the display name" }),
+ ], { shape: "provenance <project> set" }),
+ form("title", "draft", "the project's title and subtitle (no words: print them)", [
+ project(), arg("title", { required: false, help: "the new title (none: print them)" }), opt("--subtitle"), bool("--no-subtitle", "remove the subtitle"),
+ ]),
+ form("still", "project", "one frame of a clip's fetched window at a source second, into shots/", [
+ project(), clip(), num("--at", { required: true, help: "the SOURCE second" }), takeOpt({ help: "a take's (version's) clip" }),
+ ], { confirm: { what: "write the frame into shots/ (a file, no undo point; a still of the same second is replaced)" } }),
+ form("still ls", "project", "the pictures in the project's shots/", [project()], { shape: "still <project> ls" }),
// ---- the cast ----
form("cast ls", "corpus", "the characters' voices across projects", [], { shape: "cast ls" }),
@@ -367,6 +383,11 @@ function timeline() {
tl("post", "draft", "a post added, or the one with its id replaced", [arg("post", { type: "text", atFile: true, help: "JSON (@file: from a terminal)" })]),
tl("post-remove", "draft", "a post out of the cut", [arg("id", { context: "post" })]),
tl("teaser", "draft", "a teaser's lines, beat, dip, tail", [id(), arg("patch", { type: "text", atFile: true, help: "a JSON patch (@file: from a terminal)" })]),
+ tl("teaser-insert", "draft", "a teaser or closing card inserted (default at the end)", [
+ pick("--at", ["end", "start"]), opt("--after", { help: "an entry's id: after it" }), opt("--before", { help: "an entry's id: before it" }), opt("--id"), num("--beat"),
+ many("--line", { repeat: true, help: "its lines, one per line (the first its title)" }),
+ opt("--lines-json", { type: "json", atFile: true, help: "the lines as JSON, each a string or {text, break?, hold?} (@file: from a terminal)" }),
+ ]),
tl("undo", "draft", "the newest automatic snapshot back", [takeOpt({ help: "a take's own undo" })]),
tl("sections", "project", "the deck's sections and their clips", []),
tl("section-move", "draft", "clips to the end (or start) of section N", [ids(), num("--to-section", { required: true }), bool("--start")]),
diff --git a/umtool/lib/report/embedIds.mjs b/umtool/lib/report/embedIds.mjs
@@ -0,0 +1,79 @@
+// THE PUBLISHED EMBED ID, found on this disk (umtool redesign L6, the Links panel's "use the published embed id";
+// owed 4 and 8 Nov: `umtool links` showed 15/15 DEAD on quartering-midterms, a QR naming the Rumble URL-slug folder
+// the corpus keeps a recording under while the archive serves its EMBED id).
+//
+// `embedIdRows` lists every clip of the cut that cites a folder id the archive does not serve -- the id
+// shareLine.mjs siteVideoFor (L1's one mapping) reads from the folder's metadata.info.json -- with the QR it draws
+// now, the QR it would draw with `siteVideo`, and what the last link check (out/links.json) said of it. No network:
+// the check is the `links` command's; this is the fix, which needs only the corpus. `embedIdFixes` is what
+// setSiteVideos (inspectorEdits.mjs) writes for the rows asked: `siteVideo`, and a citeUrl that named the folder id
+// moved to the embed id (linkCheck.mjs withArchiveId).
+//
+// Plain ESM: the CLI (`umtool links <p> --embed-ids`) runs it under bare node.
+import { archiveLinkOf, linksOf, withArchiveId } from "./linkCheck.mjs";
+import { siteVideoFor } from "./shareLine.mjs";
+
+/**
+ * @typedef {{ clip: string, channel: string | null, video: string, siteVideo: string, url: string | null, fixedUrl: string | null,
+ * citeUrl: string | null, state: "dead" | "ok" | "unverified" | "direct" | "unchecked" }} EmbedRow
+ */
+
+/**
+ * The clips whose folder id is not the archive's, read from the project's channels trees (its shadow, then the
+ * corpus behind it). A clip that pins `siteVideo` already is never looked up.
+ *
+ * @param {string} dir the project's directory
+ * @param {Record<string, any>} manifest
+ * @param {{ doc?: { links?: Array<{ clip: string, url: string, state: string }> } | null, layers?: string[] | null }} [opts]
+ * @returns {Promise<EmbedRow[]>}
+ */
+export async function embedIdRows(dir, manifest, { doc = null, layers = null } = {}) {
+ let trees = layers;
+ if (!trees) {
+ const { channelsLayersFor, hasShadowChannels } = await import("../projects/report.mjs");
+ trees = channelsLayersFor(dir, manifest, { shadowExists: await hasShadowChannels(dir) });
+ }
+ const qr = new Map(linksOf(manifest).map((l) => [l.clip, l.url]));
+ const checked = new Map((doc?.links ?? []).map((l) => [`${l.clip}\u0000${l.url}`, l.state]));
+ /** @type {EmbedRow[]} */
+ const rows = [];
+ for (const e of manifest?.timeline ?? []) {
+ if (e?.type !== "clip" || e.siteVideo || e.video == null) continue;
+ const slug = e.channel ?? manifest?.provenance?.channelSlug ?? null;
+ const video = String(e.video);
+ let embed = null;
+ for (const d of trees) {
+ embed = await siteVideoFor({ channelsDir: d, slug, video }).catch(() => null);
+ if (embed) break;
+ }
+ if (!embed) continue;
+ const url = qr.get(e.id) ?? null;
+ const cite = typeof e.citeUrl === "string" && e.citeUrl ? e.citeUrl : null;
+ const citeNamesFolder = cite ? archiveLinkOf(cite)?.id === video : false;
+ // The QR after the fix: a citeUrl naming the folder moves to the embed id; a QR built from the moment follows
+ // `siteVideo` by itself (site-links.mjs archiveMomentUrl).
+ const fixedUrl = url && archiveLinkOf(url)?.id === video ? withArchiveId(url, video, embed) : url;
+ rows.push({
+ clip: String(e.id), channel: slug, video, siteVideo: embed, url, fixedUrl,
+ citeUrl: citeNamesFolder ? withArchiveId(cite, video, embed) : null,
+ state: /** @type {EmbedRow["state"]} */ (url ? checked.get(`${e.id}\u0000${url}`) ?? "unchecked" : "unchecked"),
+ });
+ }
+ return rows;
+}
+
+/**
+ * The writes for `clips` (null: every row), as setSiteVideos takes them. A clip named that is not a row is refused.
+ * @param {EmbedRow[]} rows
+ * @param {string[] | null} clips
+ */
+export function embedIdFixes(rows, clips = null) {
+ const by = new Map(rows.map((r) => [r.clip, r]));
+ const want = clips ?? rows.map((r) => r.clip);
+ const missing = want.filter((c) => !by.has(c));
+ if (missing.length) throw new Error(`${missing.join(", ")}: no published embed id to use (not a Rumble folder id, or siteVideo is set already)`);
+ return want.map((c) => {
+ const r = /** @type {EmbedRow} */ (by.get(c));
+ return { clip: r.clip, siteVideo: r.siteVideo, ...(r.citeUrl ? { citeUrl: r.citeUrl } : {}) };
+ });
+}
diff --git a/umtool/lib/report/excerptPick.mjs b/umtool/lib/report/excerptPick.mjs
@@ -0,0 +1,112 @@
+// PICKING A POST ITEM's EXCERPT BY SELECTING ITS WORDS (umtool redesign L6, item 4): a selection in the post's
+// text (character offsets into cardText, post-item.mjs) made into the excerpt's span format the build reads --
+// `entry.excerpt`, VERBATIM strings of the post's words in the post's order, each found by indexOf from the end
+// of the one before (post-item.mjs excerptRanges). Pure, no imports: the inspector's client component runs it,
+// and pnpm test:scripts checks it.
+
+const isWordChar = (c) => !!c && !/\s/.test(c);
+
+/**
+ * A selection snapped OUT to whole words and trimmed of the space at its ends: `[start, end)` in `text`, or null
+ * when it holds no word.
+ * @param {string} text
+ * @param {number} start
+ * @param {number} end
+ */
+export function snapToWords(text, start, end) {
+ let a = Math.max(0, Math.min(start, end));
+ let b = Math.min(text.length, Math.max(start, end));
+ while (a < b && /\s/.test(text[a])) a += 1;
+ while (b > a && /\s/.test(text[b - 1])) b -= 1;
+ if (a >= b) return null;
+ while (a > 0 && isWordChar(text[a - 1])) a -= 1;
+ while (b < text.length && isWordChar(text[b])) b += 1;
+ return { start: a, end: b };
+}
+
+/**
+ * The ranges with `r` added, in the post's order, overlapping or touching ranges merged.
+ * @param {Array<{ start: number, end: number }>} ranges
+ * @param {{ start: number, end: number }} r
+ */
+export function addRange(ranges, r) {
+ const all = [...ranges, r].sort((x, y) => x.start - y.start);
+ const out = [];
+ for (const x of all) {
+ const last = out.at(-1);
+ if (last && x.start <= last.end) last.end = Math.max(last.end, x.end);
+ else out.push({ ...x });
+ }
+ return out;
+}
+
+/**
+ * Where the build will FIND each span (indexOf from the end of the one before): a span whose words occur earlier
+ * in the post too would be read there, so it is widened a word to the left until it is found where it was
+ * picked. Returns the ranges (possibly widened) in order.
+ * @param {string} text
+ * @param {Array<{ start: number, end: number }>} ranges
+ */
+export function settleRanges(text, ranges) {
+ const out = [];
+ let from = 0;
+ for (const r0 of ranges) {
+ let r = { ...r0 };
+ // Widen left, a word at a time, until the span is found where it stands (it always is at worst at `from`).
+ while (text.indexOf(text.slice(r.start, r.end), from) !== r.start && r.start > from) {
+ // The start of the word before: back over the space, then over its letters.
+ let a = r.start;
+ while (a > from && /\s/.test(text[a - 1])) a -= 1;
+ while (a > from && isWordChar(text[a - 1])) a -= 1;
+ if (a === r.start) break;
+ r = { start: a, end: r.end };
+ }
+ const last = out.at(-1);
+ if (last && r.start <= last.end) last.end = Math.max(last.end, r.end);
+ else out.push(r);
+ from = r.end;
+ }
+ return out;
+}
+
+/**
+ * The excerpt (the strings) the ranges spell.
+ * @param {string} text
+ * @param {Array<{ start: number, end: number }>} ranges
+ * @returns {string[]}
+ */
+export const spansOf = (text, ranges) => ranges.map((r) => text.slice(r.start, r.end));
+
+/**
+ * The ranges an excerpt stands at (post-item.mjs excerptRanges' rule), or null when a span is not found.
+ * @param {string} text
+ * @param {string[]} spans
+ */
+export function rangesOf(text, spans) {
+ const out = [];
+ let from = 0;
+ for (const sp of spans) {
+ const at = text.indexOf(sp, from);
+ if (at < 0) return null;
+ out.push({ start: at, end: at + sp.length });
+ from = at + sp.length;
+ }
+ return out;
+}
+
+/**
+ * The text cut into pieces for drawing: each `{ text, start, end, picked }`, a picked piece one range.
+ * @param {string} text
+ * @param {Array<{ start: number, end: number }>} ranges
+ */
+export function piecesOf(text, ranges) {
+ const out = [];
+ let at = 0;
+ for (const r of ranges) {
+ if (r.start > at) out.push({ text: text.slice(at, r.start), start: at, end: r.start, picked: false });
+ out.push({ text: text.slice(r.start, r.end), start: r.start, end: r.end, picked: true });
+ at = r.end;
+ }
+ if (at < text.length) out.push({ text: text.slice(at), start: at, end: text.length, picked: false });
+ return out;
+}
diff --git a/umtool/lib/report/excerptPick.test.mjs b/umtool/lib/report/excerptPick.test.mjs
@@ -0,0 +1,43 @@
+// Picking a post item's excerpt by selecting its words (excerptPick.mjs): snapped to words, merged, settled
+// where the build's indexOf will find each span. Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import test from "node:test";
+import { addRange, piecesOf, rangesOf, settleRanges, snapToWords, spansOf } from "./excerptPick.mjs";
+import { excerptRanges } from "umtool-report-to-video/post-item";
+
+const T = "The scale said 291. I said the scale was broken. Then the scale said 290.";
+
+test("a selection snaps out to whole words, trimmed", () => {
+ const r = snapToWords(T, T.indexOf("cale said 2"), T.indexOf("291") + 2);
+ assert.deepEqual(spansOf(T, [r]), ["scale said 291."]);
+ assert.equal(snapToWords(T, 3, 4), null);
+ assert.deepEqual(snapToWords(T, 0, 1), { start: 0, end: 3 });
+});
+
+test("ranges merge in the post's order", () => {
+ let rs = addRange([], { start: 20, end: 30 });
+ rs = addRange(rs, { start: 0, end: 5 });
+ rs = addRange(rs, { start: 28, end: 40 });
+ assert.deepEqual(rs, [{ start: 0, end: 5 }, { start: 20, end: 40 }]);
+});
+
+test("a span whose words come earlier too is widened until the build finds it where it was picked", () => {
+ const W = "scale said";
+ const second = T.lastIndexOf(W);
+ assert.ok(T.indexOf(W) < second);
+ const picked = [{ start: second, end: second + W.length }];
+ const settled = settleRanges(T, picked);
+ const spans = spansOf(T, settled);
+ assert.deepEqual(excerptRanges(T, spans).map((r) => r.end), [second + W.length]);
+ assert.deepEqual(spans, ["the scale said"]);
+ // Two spans: the second found after the first.
+ const two = settleRanges(T, [{ start: 0, end: 9 }, picked[0]]);
+ assert.deepEqual(excerptRanges(T, spansOf(T, two)), two);
+ assert.deepEqual(rangesOf(T, spansOf(T, two)), two);
+});
+
+test("the pieces cover the text, the picked ones marked", () => {
+ const p = piecesOf(T, [{ start: 4, end: 9 }]);
+ assert.equal(p.map((x) => x.text).join(""), T);
+ assert.deepEqual(p.filter((x) => x.picked).map((x) => x.text), ["scale"]);
+});
diff --git a/umtool/lib/report/inspectorCli.mjs b/umtool/lib/report/inspectorCli.mjs
@@ -0,0 +1,309 @@
+// The inspector's CLI twins (umtool redesign L6; every knob the UI sets has one, docs/knobs.md):
+//
+// umtool provenance <project> [ls] [--json]
+// umtool provenance <project> set [--site-origin URL|""] [--channel-slug SLUG|""] [--channel "Name"|""] [--json]
+// umtool title <project> ["<title>"] [--subtitle "…" | --no-subtitle] [--json]
+// umtool still <project> <clip> --at <source s> [--take <take>] [--json] | umtool still <project> ls [--json]
+// umtool timeline <project> teaser-insert [--at start|end | --after <id> | --before <id>] [--id ID] [--beat S]
+// --line "<text>" [--break "<words>"] [--hold S] [--line …] | --lines-json <json|@file> [--json]
+// umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json]
+//
+// Each the same writer as its inspector panel (inspectorEdits.mjs, stillGrab.mjs): the draft written, one undo
+// point per write (`umtool timeline <p> undo` takes it back). Exit 0 done, 1 refused, 2 a usage error.
+// Plain ESM: the CLI runs it under bare node.
+import { readFile } from "node:fs/promises";
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { readManifest } from "../projects/report.mjs";
+import { withEditNotes } from "./edit-guard.mjs";
+import { StaleToken, StructureRefused, manifestToken } from "./manifest.mjs";
+import { insertTeaser, provenanceView, setSiteVideos, updateProvenance, updateTitle } from "./inspectorEdits.mjs";
+
+class CliError extends Error {}
+
+export const PROVENANCE_USAGE = [
+ "usage: umtool provenance <project> [ls] [--json]",
+ " umtool provenance <project> set [--site-origin <https://…>] [--channel-slug <slug>] [--channel \"<name>\"] [--json]",
+ " THE PROJECT'S PROVENANCE: provenance.siteOrigin (the archive its QRs open), provenance.channelSlug (the channel a",
+ " clip with no `channel` is from -- `check` blocks without it), provenance.channel (the sweep's display name). An",
+ " empty value removes a key. One write, one undo point. The link policy: umtool link-policy <p>.",
+].join("\n");
+
+export const TITLE_USAGE = [
+ "usage: umtool title <project> [\"<title>\"] [--subtitle \"<line>\" | --no-subtitle] [--json]",
+ " the project's TITLE and SUBTITLE (the manifest's `title` / `subtitle`: the head, the intro's title card, the",
+ " posting artifacts). With no words, prints them. One write, one undo point.",
+].join("\n");
+
+export const STILL_USAGE = [
+ "usage: umtool still <project> <clip> --at <source seconds> [--take <take>] [--json]",
+ " umtool still <project> ls [--json]",
+ " A STILL AT SECOND N: one frame of the clip's fetched window at that SOURCE second (the second Play's Still",
+ " button reads off the playhead), saved as shots/still-<clip>-<s>s.png beside the project's other shots; nothing",
+ " fetched (a second no fetched window holds is refused). ls: the project's shots/, newest first.",
+].join("\n");
+
+export const TEASER_INSERT_USAGE = [
+ "usage: umtool timeline <project> teaser-insert [--at start|end | --after <id> | --before <id>] [--id ID] [--beat S]",
+ " --line \"<text>\" [--break \"<its end>\"] [--hold S] [--line …] | --lines-json '<json>'|@file [--json]",
+ " A TEASER OR CLOSING CARD inserted (type teaser): the first line its title, each --line the next, a --break / --hold",
+ " after a --line that line's; default at the end (id \"close\"; at the start \"cold\"). Checked by the build's teaser",
+ " rules; one write, one undo point.",
+].join("\n");
+
+async function projectOf(arg, root) {
+ if (!arg) throw new CliError("which project?");
+ const r = await resolveProject(arg, root);
+ if (r.ambiguous) throw new CliError(`"${arg}" is the name of ${r.ambiguous.length} projects — pass its id`);
+ if (!r.project) throw new CliError(`no project matches "${arg}"`);
+ return r.project;
+}
+
+/** Words, and `--key value` / `--key=value` flags (the booleans named), in order (a repeated flag kept each time). */
+function parse(args, booleans = []) {
+ const words = [];
+ /** @type {Array<[string, string | true]>} */
+ const seq = [];
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (!a.startsWith("--")) {
+ words.push(a);
+ continue;
+ }
+ const eq = a.indexOf("=");
+ if (eq > 0) seq.push([a.slice(2, eq), a.slice(eq + 1)]);
+ else if (booleans.includes(a.slice(2))) seq.push([a.slice(2), true]);
+ else {
+ if (i + 1 >= args.length) throw new CliError(`${a} needs a value`);
+ seq.push([a.slice(2), args[i + 1]]);
+ i += 1;
+ }
+ }
+ const flags = new Map(seq);
+ return { words, flags, seq };
+}
+
+/** The exit code for a writer's refusal, said on stderr. */
+function refused(err, who, e) {
+ if (e instanceof StructureRefused) err(`umtool ${who}: refused — the build would not take it:\n${e.errors.map((x) => ` ${x}`).join("\n")}`);
+ else if (e instanceof StaleToken) err(`umtool ${who}: ${e.message} — somebody else wrote it; run it again`);
+ else err(`umtool ${who}: ${e instanceof Error ? e.message : String(e)}`);
+ return e instanceof CliError ? 2 : 1;
+}
+
+const undoLine = (r) => (r?.snapshot?.rel && !r.snapshot.skipped ? ` undo point: ${r.snapshot.rel}` : null);
+const write = (project, fn) => withEditNotes(project, async () => fn(await manifestToken(project.dir)));
+
+/** `umtool provenance`. */
+export async function provenanceCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ try {
+ const { words, flags } = parse(args, ["json", "help"]);
+ const [projectArg, verb = "ls"] = words;
+ if (!projectArg || flags.has("help")) {
+ err(PROVENANCE_USAGE);
+ return 2;
+ }
+ const json = flags.get("json") === true;
+ const project = await projectOf(projectArg, root);
+ if (verb === "ls") {
+ const m = await readManifest(project.dir);
+ if (!m) throw new CliError(`${project.id} has no video.manifest.json`);
+ const view = { ...provenanceView(m), linkPolicy: m.provenance?.linkPolicy ?? null };
+ if (json) out(JSON.stringify({ project: project.id, provenance: view, token: await manifestToken(project.dir) }, null, 2));
+ else for (const [k, v] of Object.entries(view)) out(`${k.padEnd(12)} ${v === null ? "—" : typeof v === "string" ? v : JSON.stringify(v)}`);
+ return 0;
+ }
+ if (verb !== "set") throw new CliError(`unknown: provenance ${verb} — ls or set`);
+ /** @type {Record<string, string>} */
+ const keys = { "--site-origin": "siteOrigin", "--channel-slug": "channelSlug", "--channel": "channel" };
+ const patch = {};
+ for (const [f, v] of flags) {
+ if (f === "json") continue;
+ if (!(`--${f}` in keys)) throw new CliError(`unknown flag --${f} (--site-origin, --channel-slug, --channel)`);
+ patch[keys[`--${f}`]] = v === true ? "" : v;
+ }
+ if (!Object.keys(patch).length) throw new CliError("set needs --site-origin, --channel-slug or --channel");
+ const { result } = await write(project, (token) => updateProvenance(project.dir, patch, { token }));
+ if (json) out(JSON.stringify({ ok: true, project: project.id, ...result }, null, 2));
+ else {
+ const changed = Object.entries(result.changed);
+ out(changed.length ? changed.map(([k, [a, b]]) => `${k}: ${a ?? "—"} -> ${b ?? "—"}`).join("\n") : "unchanged");
+ const u = undoLine(result);
+ if (u) out(u);
+ }
+ return 0;
+ } catch (e) {
+ return refused(err, "provenance", e);
+ }
+}
+
+/** `umtool title`. */
+export async function titleCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ try {
+ const { words, flags } = parse(args, ["json", "help", "no-subtitle"]);
+ const [projectArg, ...rest] = words;
+ if (!projectArg || flags.has("help")) {
+ err(TITLE_USAGE);
+ return 2;
+ }
+ for (const f of flags.keys()) if (!["json", "subtitle", "no-subtitle"].includes(f)) throw new CliError(`unknown flag --${f}`);
+ const json = flags.get("json") === true;
+ const project = await projectOf(projectArg, root);
+ const patch = {};
+ if (rest.length) patch.title = rest.join(" ");
+ const SUBTITLE = "--subtitle";
+ if (flags.has(SUBTITLE.slice(2))) patch.subtitle = String(flags.get(SUBTITLE.slice(2)));
+ if (flags.has("no-subtitle")) patch.subtitle = null;
+ if (!Object.keys(patch).length) {
+ const m = await readManifest(project.dir);
+ if (!m) throw new CliError(`${project.id} has no video.manifest.json`);
+ const view = { title: m.title ?? null, subtitle: typeof m.subtitle === "string" ? m.subtitle : null };
+ if (json) out(JSON.stringify({ project: project.id, ...view, token: await manifestToken(project.dir) }, null, 2));
+ else out(`${view.title ?? "—"}${view.subtitle ? `\n ${view.subtitle}` : ""}`);
+ return 0;
+ }
+ const { result } = await write(project, (token) => updateTitle(project.dir, patch, { token }));
+ if (json) out(JSON.stringify({ ok: true, project: project.id, ...result }, null, 2));
+ else {
+ out(`title: ${result.title}${result.subtitle ? `\nsubtitle: ${result.subtitle}` : "\nsubtitle: —"}`);
+ const u = undoLine(result);
+ if (u) out(u);
+ }
+ return 0;
+ } catch (e) {
+ return refused(err, "title", e);
+ }
+}
+
+/** `umtool still`. */
+export async function stillCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ try {
+ const { words, flags } = parse(args, ["json", "help"]);
+ const [projectArg, clip] = words;
+ if (!projectArg || !clip || flags.has("help")) {
+ err(STILL_USAGE);
+ return 2;
+ }
+ for (const f of flags.keys()) if (!["json", "at", "take"].includes(f)) throw new CliError(`unknown flag --${f}`);
+ const json = flags.get("json") === true;
+ const project = await projectOf(projectArg, root);
+ const { grabStill, listShots } = await import("./stillGrab.mjs");
+ if (clip === "ls") {
+ const shots = await listShots(project.dir);
+ if (json) out(JSON.stringify({ project: project.id, shots }, null, 2));
+ else {
+ for (const s of shots) out(`${s.rel} ${s.still ? `${s.still.clip} @ ${s.still.at} s` : ""} ${s.mtime.slice(0, 16).replace("T", " ")}`);
+ out(`${shots.length} picture(s) in shots/`);
+ }
+ return 0;
+ }
+ if (!flags.has("at")) throw new CliError("--at <source seconds> is the second to grab");
+ const take = flags.has("take") ? String(flags.get("take")) : null;
+ let m = take ? (await (await import("./takeManifest.mjs")).resolveTakeManifest(project.dir, take)).manifest : await readManifest(project.dir);
+ if (!m) throw new CliError(`${project.id} has no video.manifest.json`);
+ const r = await grabStill(project, m, clip, Number(flags.get("at")));
+ if (json) out(JSON.stringify({ ok: true, project: project.id, ...r }, null, 2));
+ else out(`${r.rel} (${r.clip} @ ${r.at} s of ${r.video}, ${r.bytes} bytes)`);
+ return 0;
+ } catch (e) {
+ return refused(err, "still", e);
+ }
+}
+
+/** A `--lines-json` value: JSON, or `@file` of it. */
+async function jsonArg(v) {
+ const text = String(v).startsWith("@") ? await readFile(String(v).slice(1), "utf8") : String(v);
+ try {
+ return JSON.parse(text);
+ } catch (e) {
+ throw new CliError(`--lines-json is not JSON: ${e instanceof Error ? e.message : e}`);
+ }
+}
+
+/** The flags teaser-insert reads besides --line / --break / --hold (lib/cli/verbs.mjs's form names them). */
+const TEASER_INSERT_FLAGS = ["--json", "--at", "--after", "--before", "--id", "--beat", "--lines-json"];
+
+/** `umtool timeline <p> teaser-insert …` (timelineCli.mjs hands it the words after the verb). */
+export async function teaserInsertVerb(project, args, { out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ try {
+ const { flags, seq, words } = parse(args, ["json", "help"]);
+ if (flags.has("help")) {
+ err(TEASER_INSERT_USAGE);
+ return 2;
+ }
+ if (words.length) throw new CliError(`teaser-insert takes flags, not ${words.join(" ")} (--line "…")`);
+ const json = flags.get("json") === true;
+ /** @type {Array<string | Record<string, unknown>>} */
+ let lines = [];
+ for (const [k, v] of seq) {
+ if (k === "line") lines.push({ text: String(v) });
+ else if (k === "break" || k === "hold") {
+ const last = lines.at(-1);
+ if (!last || typeof last === "string") throw new CliError(`--${k} goes after the --line it belongs to`);
+ last[k] = k === "hold" ? Number(v) : String(v);
+ } else if (!TEASER_INSERT_FLAGS.includes(`--${k}`)) throw new CliError(`unknown flag --${k}`);
+ }
+ if (flags.has("lines-json")) {
+ if (lines.length) throw new CliError("--lines-json or --line, not both");
+ const j = await jsonArg(flags.get("lines-json"));
+ if (!Array.isArray(j)) throw new CliError("--lines-json is a list of lines");
+ lines = j;
+ }
+ lines = lines.map((l) => (typeof l === "object" && l && Object.keys(l).length === 1 && "text" in l ? String(l.text) : l));
+ const at = flags.get("at");
+ const position = flags.has("after") ? { after: String(flags.get("after")) } : flags.has("before") ? { before: String(flags.get("before")) } : at === "start" ? "start" : at === undefined || at === "end" ? "end" : null;
+ if (position === null) throw new CliError("--at is start or end (--after <id> / --before <id> for elsewhere)");
+ const spec = { lines, ...(flags.has("id") ? { id: String(flags.get("id")) } : {}), ...(flags.has("beat") ? { beat: Number(flags.get("beat")) } : {}) };
+ const { result } = await write(project, (token) => insertTeaser(project.dir, spec, position, { token }));
+ if (json) out(JSON.stringify({ ok: true, project: project.id, op: "teaser-insert", inserted: { id: result.id, at: result.at, entry: result.entry }, token: result.token }, null, 2));
+ else {
+ out(`inserted teaser ${result.id} at ${result.at}: ${JSON.stringify(result.entry.lines)}`);
+ const u = undoLine(result);
+ if (u) out(u);
+ }
+ return 0;
+ } catch (e) {
+ return refused(err, "timeline teaser-insert", e);
+ }
+}
+
+/** `umtool links <p> --embed-ids [--clips a,b] [--dry-run] [--json]` (linksCli.mjs hands it over). */
+export async function embedIdsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ try {
+ const { words, flags } = parse(args, ["json", "help", "dry-run"]);
+ if (!words[0] || flags.has("help")) {
+ err("usage: umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json]\n every clip citing a Rumble URL-slug folder the archive does not serve gets the EMBED id it serves (siteVideo),\n read from the folder's metadata.info.json; a citeUrl naming the folder moves with it. No network; one write.");
+ return 2;
+ }
+ for (const f of flags.keys()) if (!["json", "clips", "dry-run"].includes(f)) throw new CliError(`unknown flag --${f}`);
+ const json = flags.get("json") === true;
+ const project = await projectOf(words[0], root);
+ const m = await readManifest(project.dir);
+ if (!m) throw new CliError(`${project.id} has no video.manifest.json`);
+ const { embedIdFixes, embedIdRows } = await import("./embedIds.mjs");
+ const { readLinkCheck } = await import("./linkCheck.mjs");
+ const rows = await embedIdRows(project.dir, m, { doc: await readLinkCheck(project.dir) });
+ const clips = flags.has("clips") ? String(flags.get("clips")).split(",").map((s) => s.trim()).filter(Boolean) : null;
+ if (!rows.length && !clips) {
+ if (json) out(JSON.stringify({ ok: true, project: project.id, rows: [], fixed: [] }, null, 2));
+ else out("no clip cites a folder id the archive does not serve");
+ return 0;
+ }
+ const fixes = embedIdFixes(rows, clips);
+ if (flags.has("dry-run")) {
+ if (json) out(JSON.stringify({ ok: true, project: project.id, rows, would: fixes }, null, 2));
+ else for (const f of fixes) out(`would: ${f.clip} siteVideo ${f.siteVideo}${f.citeUrl ? ` citeUrl ${f.citeUrl}` : ""}`);
+ return 0;
+ }
+ const { result } = await write(project, (token) => setSiteVideos(project.dir, fixes, { token }));
+ if (json) out(JSON.stringify({ ok: true, project: project.id, rows, fixed: result.fixed, token: result.token }, null, 2));
+ else {
+ for (const f of result.fixed) out(`fixed ${f.clip}: ${f.video} -> siteVideo ${f.siteVideo} (the Rumble embed id)${f.citeUrl ? `, citeUrl ${f.citeUrl}` : ""}`);
+ out(" `umtool links <p>` checks them against the site");
+ const u = undoLine(result);
+ if (u) out(u);
+ }
+ return 0;
+ } catch (e) {
+ return refused(err, "links --embed-ids", e);
+ }
+}
diff --git a/umtool/lib/report/inspectorEdits.mjs b/umtool/lib/report/inspectorEdits.mjs
@@ -0,0 +1,284 @@
+// THE INSPECTOR'S WRITERS (umtool redesign L6, "inspector panels for this week's hand edits"): what agents did by
+// hand this week, each now one write the UI and its CLI twin share -- the project's provenance (siteOrigin,
+// channelSlug, channel), its title and subtitle, a teaser or closing card inserted, and the published Rumble embed
+// ids (`siteVideo`) written onto the clips that cite a URL-slug folder.
+//
+// Every one lands in the WORKING DRAFT (video.manifest.json; L3: never a take's patch) through manifest.mjs's
+// structural door (`structuralEdit`): the mtime token, the read inside the lock, the build's own checks, an undo
+// point `auto-before-<op>` (every op its own in the app -- the Cut tab's Undo takes exactly it back), the atomic
+// write. The checks of a value are pure and exported, so the route and the CLI refuse in the same words.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { StructureRefused, entryIndex, freshEntryId, patchClipEntry, structuralEdit } from "./manifest.mjs";
+import { TEASER_BEAT, TEASER_LIMITS, validateTeaser } from "umtool-report-to-video/deck";
+
+const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
+const round2 = (n) => Math.round(n * 100) / 100;
+
+// ---------------------------------------------------------------------------
+// PROVENANCE: where the cut's clips come from and where its QRs open.
+// ---------------------------------------------------------------------------
+
+/** The provenance keys the inspector writes (the link policy has its own writer, updateLinkPolicy). */
+export const PROVENANCE_EDIT_KEYS = Object.freeze(["siteOrigin", "channelSlug", "channel"]);
+const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
+const CHANNEL_NAME_MAX = 120;
+
+/**
+ * A provenance patch checked and normalised: each key a string to set, or null / "" to remove it. siteOrigin is
+ * an http(s) origin (a path, query or hash refused; the trailing slash dropped), channelSlug a corpus slug,
+ * channel the sweep's display name (one line). Throws a sentence naming every problem.
+ *
+ * @param {unknown} patch
+ * @returns {Record<string, string | null>}
+ */
+export function provenancePatchOf(patch) {
+ if (!isObj(patch)) throw new Error("a provenance patch is an object: { siteOrigin?, channelSlug?, channel? }");
+ const errors = [];
+ const out = {};
+ for (const k of Object.keys(patch)) {
+ if (!PROVENANCE_EDIT_KEYS.includes(k)) errors.push(`${k} is not a provenance key this writer sets (${PROVENANCE_EDIT_KEYS.join(", ")}; the link policy: umtool link-policy)`);
+ }
+ for (const k of PROVENANCE_EDIT_KEYS) {
+ if (!(k in patch)) continue;
+ const raw = patch[k];
+ if (raw === null || raw === undefined || (typeof raw === "string" && !raw.trim())) {
+ out[k] = null;
+ continue;
+ }
+ if (typeof raw !== "string") {
+ errors.push(`${k} must be text`);
+ continue;
+ }
+ const v = raw.trim();
+ if (k === "siteOrigin") {
+ let u = null;
+ try {
+ u = new URL(v);
+ } catch {
+ /* below */
+ }
+ if (!u || (u.protocol !== "http:" && u.protocol !== "https:")) errors.push(`siteOrigin must be an http:// or https:// address (got \`${v}\`)`);
+ else if ((u.pathname && u.pathname !== "/") || u.search || u.hash) errors.push(`siteOrigin is the archive's origin, with no path (\`${u.origin}\`, not \`${v}\`)`);
+ else out[k] = u.origin;
+ } else if (k === "channelSlug") {
+ if (!SLUG_RE.test(v)) errors.push(`channelSlug must be a channel's slug (letters, digits, . _ -), not \`${v}\``);
+ else out[k] = v;
+ } else {
+ if (/[\r\n]/.test(v)) errors.push("channel must be one line");
+ else if (v.length > CHANNEL_NAME_MAX) errors.push(`channel is ${v.length} characters (at most ${CHANNEL_NAME_MAX})`);
+ else out[k] = v;
+ }
+ }
+ if (errors.length) throw new Error(errors.join("; "));
+ if (!Object.keys(out).length) throw new Error("nothing to change");
+ return out;
+}
+
+/** The patch applied to a manifest in memory; returns what changed (`{ key: [from, to] }`). */
+export function applyProvenancePatch(m, patch) {
+ const p = provenancePatchOf(patch);
+ const prov = isObj(m.provenance) ? m.provenance : {};
+ const changed = {};
+ for (const [k, v] of Object.entries(p)) {
+ const was = typeof prov[k] === "string" ? prov[k] : null;
+ if (v === null) delete prov[k];
+ else prov[k] = v;
+ if (was !== v) changed[k] = [was, v];
+ }
+ m.provenance = prov;
+ return changed;
+}
+
+/** What the inspector reads: the three keys as written (null when absent). */
+export const provenanceView = (m) =>
+ Object.fromEntries(PROVENANCE_EDIT_KEYS.map((k) => [k, typeof m?.provenance?.[k] === "string" && m.provenance[k] ? m.provenance[k] : null]));
+
+/**
+ * Set the project's provenance keys (one write, one undo point `auto-before-provenance`).
+ *
+ * @param {string} dir
+ * @param {Record<string, unknown>} patch
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function updateProvenance(dir, patch, { token = null } = {}) {
+ provenancePatchOf(patch); // refused before the lock is taken
+ return structuralEdit(dir, "provenance", token, (m) => {
+ const changed = applyProvenancePatch(m, patch);
+ return { provenance: provenanceView(m), changed };
+ });
+}
+
+// ---------------------------------------------------------------------------
+// THE TITLE AND SUBTITLE (9 Nov: four news projects' title/subtitle were set with jq -- no verb existed).
+// ---------------------------------------------------------------------------
+
+export const TITLE_MAX = 200;
+export const SUBTITLE_MAX = 300;
+
+/**
+ * A title patch checked: `title` one line, not empty, at most TITLE_MAX; `subtitle` one line at most SUBTITLE_MAX,
+ * null or "" removes it. A key not given is kept.
+ *
+ * @param {unknown} patch
+ * @returns {{ title?: string, subtitle?: string | null }}
+ */
+export function titlePatchOf(patch) {
+ if (!isObj(patch)) throw new Error("a title patch is an object: { title?, subtitle? }");
+ const errors = [];
+ const out = {};
+ for (const k of Object.keys(patch)) if (k !== "title" && k !== "subtitle") errors.push(`${k} is not title or subtitle`);
+ if ("title" in patch) {
+ const v = typeof patch.title === "string" ? patch.title.trim() : null;
+ if (!v) errors.push("title must be words (a project always has one)");
+ else if (/[\r\n]/.test(v)) errors.push("title must be one line");
+ else if (v.length > TITLE_MAX) errors.push(`title is ${v.length} characters (at most ${TITLE_MAX})`);
+ else out.title = v;
+ }
+ if ("subtitle" in patch) {
+ const raw = patch.subtitle;
+ if (raw === null || raw === undefined || (typeof raw === "string" && !raw.trim())) out.subtitle = null;
+ else if (typeof raw !== "string") errors.push("subtitle must be text");
+ else if (/[\r\n]/.test(raw.trim())) errors.push("subtitle must be one line");
+ else if (raw.trim().length > SUBTITLE_MAX) errors.push(`subtitle is ${raw.trim().length} characters (at most ${SUBTITLE_MAX})`);
+ else out.subtitle = raw.trim();
+ }
+ if (errors.length) throw new Error(errors.join("; "));
+ if (!Object.keys(out).length) throw new Error("nothing to change: give a title, a subtitle, or both");
+ return out;
+}
+
+/**
+ * Set the project's title and/or subtitle (one write, one undo point `auto-before-title`).
+ *
+ * @param {string} dir
+ * @param {{ title?: unknown, subtitle?: unknown }} patch
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function updateTitle(dir, patch, { token = null } = {}) {
+ const p = titlePatchOf(patch);
+ return structuralEdit(dir, "title", token, (m) => {
+ if (p.title !== undefined) m.title = p.title;
+ if (p.subtitle === null) delete m.subtitle;
+ else if (p.subtitle !== undefined) m.subtitle = p.subtitle;
+ return { title: m.title ?? null, subtitle: typeof m.subtitle === "string" ? m.subtitle : null };
+ });
+}
+
+// ---------------------------------------------------------------------------
+// A TEASER OR CLOSING CARD INSERTED (a "cold" open, a "close" at the end): `{type: "teaser", id, lines, beat?}`,
+// checked by the build's validateTeaser before it is written.
+// ---------------------------------------------------------------------------
+
+/** The teaser line keys the inspector writes (the rest -- role, lead, replace, together -- through `timeline teaser`). */
+export const TEASER_INSERT_LINE_KEYS = Object.freeze(["text", "break", "hold", "replace", "together", "role", "lead"]);
+
+/**
+ * One line as written: a string when it is only its text, else `{ text, break?, hold?, … }` with empty keys left out.
+ * @param {unknown} l
+ */
+export function teaserLineOf(l) {
+ if (typeof l === "string") return l.trim();
+ if (!isObj(l)) throw new Error("a teaser line is its words, or { text, break?, hold? }");
+ const out = {};
+ for (const k of Object.keys(l)) if (!TEASER_INSERT_LINE_KEYS.includes(k)) throw new Error(`${k} is not a teaser line key (${TEASER_INSERT_LINE_KEYS.join(", ")})`);
+ out.text = typeof l.text === "string" ? l.text.trim() : l.text;
+ if (typeof l.break === "string" && l.break.trim()) out.break = l.break.trim();
+ if (l.hold !== undefined && l.hold !== null && l.hold !== "") out.hold = round2(Number(l.hold));
+ for (const k of ["replace", "together"]) if (l[k] === true) out[k] = true;
+ if (typeof l.role === "string" && l.role) out.role = l.role;
+ if (typeof l.lead === "string" && l.lead.trim()) out.lead = l.lead.trim();
+ return Object.keys(out).length === 1 ? out.text : out;
+}
+
+/**
+ * Where an insert lands, as an index of the timeline BEFORE the insert: "start" (0), "end" (its length),
+ * `{ after: <id> }` or `{ before: <id> }` (an id the timeline holds once; `at` names it when it repeats).
+ *
+ * @param {Array<Record<string, unknown>>} timeline
+ * @param {unknown} position
+ */
+export function insertIndexOf(timeline, position) {
+ if (position === "start" || position === 0) return 0;
+ if (position === "end" || position === undefined || position === null) return timeline.length;
+ if (isObj(position) && typeof position.after === "string") return entryIndex(timeline, position.after, position.at ?? null) + 1;
+ if (isObj(position) && typeof position.before === "string") return entryIndex(timeline, position.before, position.at ?? null);
+ throw new Error('a position is "start", "end", { after: <id> } or { before: <id> }');
+}
+
+/**
+ * The teaser entry a spec makes, its id fresh in the timeline (the spec's, else "close" at the end / "cold" at
+ * the start / "teaser"), checked by the build's validateTeaser (throws StructureRefused with its sentences).
+ *
+ * @param {Array<Record<string, unknown>>} timeline
+ * @param {{ id?: unknown, lines?: unknown, beat?: unknown }} spec
+ * @param {number} index where it will be inserted (names the default id)
+ */
+export function teaserEntryOf(timeline, spec, index) {
+ if (!isObj(spec)) throw new Error("a teaser is { id?, lines: [...], beat? }");
+ const lines = Array.isArray(spec.lines) ? spec.lines.map(teaserLineOf).filter((l) => (typeof l === "string" ? l : l.text)) : null;
+ if (!lines || !lines.length) throw new StructureRefused([`a teaser needs ${TEASER_LIMITS.lines[0]} to ${TEASER_LIMITS.lines[1]} lines (the first is its title)`]);
+ const base = typeof spec.id === "string" && spec.id.trim() ? spec.id.trim() : index === 0 ? "cold" : index >= timeline.length ? "close" : "teaser";
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(base)) throw new StructureRefused([`id must be letters, digits, dashes or underscores (got \`${base}\`)`]);
+ if (typeof spec.id === "string" && spec.id.trim() && timeline.some((e) => e?.id === base)) {
+ throw new StructureRefused([`the cut already has an entry ${base}: name the card something else`]);
+ }
+ const entry = { type: "teaser", id: freshEntryId(timeline, base), lines };
+ if (spec.beat !== undefined && spec.beat !== null && spec.beat !== "") {
+ const b = Number(spec.beat);
+ entry.beat = Number.isFinite(b) ? round2(b) : spec.beat;
+ }
+ const errors = validateTeaser(entry, `the new teaser ${entry.id}`);
+ if (errors.length) throw new StructureRefused(errors);
+ return entry;
+}
+
+/**
+ * INSERT A TEASER OR CLOSING CARD (`umtool timeline <p> teaser-insert`, the inspector's Insert a card): one
+ * structural write, one undo point `auto-before-teaser-insert`.
+ *
+ * @param {string} dir
+ * @param {{ id?: unknown, lines?: unknown, beat?: unknown }} spec
+ * @param {unknown} position "start" | "end" | { after } | { before }
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function insertTeaser(dir, spec, position, { token = null } = {}) {
+ return structuralEdit(dir, "teaser-insert", token, (m) => {
+ const i = insertIndexOf(m.timeline, position);
+ const entry = teaserEntryOf(m.timeline, spec, i);
+ m.timeline.splice(i, 0, entry);
+ return { id: entry.id, at: i, entry };
+ });
+}
+
+/** The teaser's limits, for a form's hints (the build's numbers). */
+export const teaserLimits = () => ({ lines: [...TEASER_LIMITS.lines], rows: TEASER_LIMITS.rows, chars: TEASER_LIMITS.chars, hold: TEASER_LIMITS.hold, beat: { ...TEASER_BEAT } });
+
+// ---------------------------------------------------------------------------
+// THE PUBLISHED EMBED ID (a Rumble clip whose `video` is the URL-slug folder the corpus keeps it under, while the
+// archive serves the EMBED id: shareLine.mjs siteVideoFor). `siteVideo` written on each, a citeUrl that named the
+// folder id moved with it -- every clip in ONE write, one undo point `auto-before-embed-ids`.
+// ---------------------------------------------------------------------------
+
+/**
+ * @param {string} dir
+ * @param {Array<{ clip: string, siteVideo: string, citeUrl?: string | null }>} fixes
+ * @param {{ token?: string | null }} [opts]
+ */
+export async function setSiteVideos(dir, fixes, { token = null } = {}) {
+ if (!Array.isArray(fixes) || !fixes.length) throw new Error("nothing to fix");
+ for (const f of fixes) {
+ if (!isObj(f) || typeof f.clip !== "string" || typeof f.siteVideo !== "string" || !f.siteVideo) throw new Error("a fix is { clip, siteVideo, citeUrl? }");
+ }
+ return structuralEdit(dir, "embed-ids", token, (m) => {
+ const done = [];
+ for (const f of fixes) {
+ const e = m.timeline[entryIndex(m.timeline, f.clip)];
+ if (e?.type !== "clip") throw new Error(`${f.clip} is not a clip`);
+ const patch = { siteVideo: f.siteVideo, ...(typeof f.citeUrl === "string" && f.citeUrl ? { citeUrl: f.citeUrl } : {}) };
+ const { entry } = patchClipEntry(m, f.clip, patch);
+ done.push({ clip: f.clip, video: String(entry.video), siteVideo: entry.siteVideo, ...(patch.citeUrl ? { citeUrl: entry.citeUrl } : {}) });
+ }
+ return { fixed: done };
+ });
+}
diff --git a/umtool/lib/report/inspectorEdits.test.mjs b/umtool/lib/report/inspectorEdits.test.mjs
@@ -0,0 +1,279 @@
+// The inspector's writers (umtool redesign L6): provenance, title, a teaser inserted, the published embed ids, the
+// ledger's undo points, and a still grabbed from a fetched window -- each one write to the draft with its own
+// undo point, refused in the build's words. Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-inspector-"));
+process.env.REPORTS_DIR = path.join(ROOT, "reports");
+process.env.CHANNELS_DIR = path.join(ROOT, "channels");
+process.env.CHANNELS_FALLBACK = "1";
+const ed = await import("./inspectorEdits.mjs");
+const { embedIdFixes, embedIdRows } = await import("./embedIds.mjs");
+const { grabStill, listShots, shotFileOf, stillNameOf } = await import("./stillGrab.mjs");
+const { addLedgerRow, manifestToken, setUndoEveryMs, undoStructural, StaleToken, StructureRefused } = await import("./manifest.mjs");
+// The app's rule (instrumentation.ts): every op its own undo point.
+setUndoEveryMs(0);
+
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const MANIFEST = () => ({
+ schemaVersion: 1,
+ slug: "insp",
+ title: "The Inspector",
+ provenance: { siteOrigin: "https://old.example", channelSlug: "chan" },
+ render: { fps: 30, transition: 0 },
+ timeline: [
+ { type: "clip", id: "c01", video: "vid1", start: 1, end: 3, cite: 1 },
+ { type: "clip", id: "c02", video: "v7slug1", channel: "rumblechan", start: 4, end: 6, cite: 4 },
+ { type: "clip", id: "c03", video: "v7slug2", channel: "rumblechan", start: 1, end: 2, cite: 1, citeUrl: "https://site.example/?v=rumblechan/v7slug2&t=1" },
+ ],
+});
+
+let n = 0;
+async function project(m = MANIFEST()) {
+ n += 1;
+ const dir = path.join(ROOT, "reports", `p${n}`);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n");
+ return { id: `p${n}`, dir };
+}
+const read = async (dir) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8"));
+const undoPoints = async (dir) => (await readdir(path.join(dir, "revisions")).catch(() => [])).filter((f) => f.includes("auto-before-"));
+
+test("provenance: checked, normalised, one write with its own undo point", async () => {
+ assert.deepEqual(ed.provenancePatchOf({ siteOrigin: "https://jeralyzer.pages.dev/", channelSlug: " the-quartering ", channel: "" }), {
+ siteOrigin: "https://jeralyzer.pages.dev", channelSlug: "the-quartering", channel: null,
+ });
+ assert.throws(() => ed.provenancePatchOf({ siteOrigin: "https://x.example/path" }), /no path/);
+ assert.throws(() => ed.provenancePatchOf({ siteOrigin: "ftp://x" }), /http/);
+ assert.throws(() => ed.provenancePatchOf({ channelSlug: "a b" }), /slug/);
+ assert.throws(() => ed.provenancePatchOf({ linkPolicy: {} }), /link-policy/);
+ assert.throws(() => ed.provenancePatchOf({}), /nothing to change/);
+
+ const p = await project();
+ const token = await manifestToken(p.dir);
+ const r = await ed.updateProvenance(p.dir, { siteOrigin: "https://new.example", channel: "The Channel" }, { token });
+ assert.deepEqual(r.provenance, { siteOrigin: "https://new.example", channelSlug: "chan", channel: "The Channel" });
+ assert.deepEqual(r.changed.siteOrigin, ["https://old.example", "https://new.example"]);
+ const m = await read(p.dir);
+ assert.equal(m.provenance.siteOrigin, "https://new.example");
+ assert.equal(m.provenance.channel, "The Channel");
+ assert.equal((await undoPoints(p.dir)).filter((f) => f.endsWith("auto-before-provenance.manifest.json")).length, 1);
+ // A stale token is refused, the draft untouched.
+ await assert.rejects(ed.updateProvenance(p.dir, { channelSlug: "x" }, { token }), (e) => e instanceof StaleToken);
+ // Undo takes exactly it back.
+ await undoStructural(p.dir);
+ assert.equal((await read(p.dir)).provenance.siteOrigin, "https://old.example");
+});
+
+test("title and subtitle: one line each, the subtitle removable", async () => {
+ assert.throws(() => ed.titlePatchOf({ title: " " }), /words/);
+ assert.throws(() => ed.titlePatchOf({ title: "a\nb" }), /one line/);
+ assert.throws(() => ed.titlePatchOf({}), /nothing to change/);
+ const p = await project();
+ let r = await ed.updateTitle(p.dir, { title: " A New Title ", subtitle: "and its line" });
+ assert.deepEqual(r, { ...r, title: "A New Title", subtitle: "and its line" });
+ r = await ed.updateTitle(p.dir, { subtitle: "" });
+ assert.equal(r.subtitle, null);
+ const m = await read(p.dir);
+ assert.equal(m.title, "A New Title");
+ assert.equal("subtitle" in m, false);
+ assert.equal((await undoPoints(p.dir)).length, 2);
+});
+
+test("teaser insert: start, end, after; the id fresh; refused in the build's words", async () => {
+ const lines = ["The 291 scale bet", { text: "Oct 23: bet at 291", hold: "" }, { text: "Scale video: not posted as of Nov 8", break: "as of Nov 8", hold: 1.6 }];
+ assert.deepEqual(ed.teaserLineOf({ text: " x ", break: "", hold: "" }), "x");
+ assert.deepEqual(ed.teaserLineOf({ text: "a b", break: "b", hold: "1.234" }), { text: "a b", break: "b", hold: 1.23 });
+ assert.throws(() => ed.teaserLineOf({ text: "a", colour: "red" }), /not a teaser line key/);
+
+ const p = await project();
+ let r = await ed.insertTeaser(p.dir, { lines, beat: 1.3 }, "end");
+ assert.equal(r.id, "close");
+ assert.equal(r.at, 3);
+ r = await ed.insertTeaser(p.dir, { lines: ["Cold open"] }, "start");
+ assert.equal(r.id, "cold");
+ r = await ed.insertTeaser(p.dir, { lines: ["Between"] }, { after: "c01" });
+ assert.equal(r.id, "teaser");
+ r = await ed.insertTeaser(p.dir, { lines: ["Again"] }, "start");
+ assert.equal(r.id, "cold-2");
+ const m = await read(p.dir);
+ assert.deepEqual(m.timeline.map((e) => e.id), ["cold-2", "cold", "c01", "teaser", "c02", "c03", "close"]);
+ assert.deepEqual(m.timeline.at(-1), { type: "teaser", id: "close", lines: ["The 291 scale bet", "Oct 23: bet at 291", { text: "Scale video: not posted as of Nov 8", break: "as of Nov 8", hold: 1.6 }], beat: 1.3 });
+ assert.equal((await undoPoints(p.dir)).filter((f) => f.includes("teaser-insert")).length, 4);
+
+ await assert.rejects(ed.insertTeaser(p.dir, { lines: [] }, "end"), (e) => e instanceof StructureRefused);
+ await assert.rejects(ed.insertTeaser(p.dir, { id: "c01", lines: ["x"] }, "end"), /already has an entry c01/);
+ await assert.rejects(ed.insertTeaser(p.dir, { lines: [{ text: "abc", break: "zzz" }] }, "end"), /break must be the end of its text/);
+ await assert.rejects(ed.insertTeaser(p.dir, { lines: ["x"], beat: 9 }, "end"), /beat must be from/);
+ await assert.rejects(ed.insertTeaser(p.dir, { lines: ["x"] }, { after: "nope" }), /no timeline entry with id nope/);
+ assert.equal((await read(p.dir)).timeline.length, 7);
+});
+
+async function rumbleChannel() {
+ const ch = path.join(ROOT, "channels", "rumblechan");
+ for (const [dirId, id] of [["v7slug1", "v7emb01"], ["v7slug2", "v7emb02"], ["v7same3", "v7same3"]]) {
+ await mkdir(path.join(ch, "data", dirId), { recursive: true });
+ await writeFile(path.join(ch, "data", dirId, "metadata.info.json"), JSON.stringify({ id, extractor: "Rumble", webpage_url: `https://rumble.com/${dirId}-x.html` }));
+ }
+ await writeFile(path.join(ch, "config.json"), JSON.stringify({ platform: "rumble", url: "https://rumble.com/c/rumblechan" }));
+}
+
+test("the published embed id: found on disk, written as siteVideo (a citeUrl naming the folder moved), one undo point", async () => {
+ await rumbleChannel();
+ const p = await project();
+ const m = await read(p.dir);
+ const rows = await embedIdRows(p.dir, m, { layers: [path.join(ROOT, "channels")] });
+ assert.deepEqual(rows.map((r) => [r.clip, r.video, r.siteVideo]), [["c02", "v7slug1", "v7emb01"], ["c03", "v7slug2", "v7emb02"]]);
+ assert.equal(rows[1].citeUrl, "https://site.example/?v=rumblechan/v7emb02&t=1");
+ assert.equal(rows[1].fixedUrl, "https://site.example/?v=rumblechan/v7emb02&t=1");
+ assert.equal(rows[0].state, "unchecked");
+ assert.throws(() => embedIdFixes(rows, ["c01"]), /no published embed id/);
+
+ const r = await ed.setSiteVideos(p.dir, embedIdFixes(rows, ["c02"]));
+ assert.deepEqual(r.fixed, [{ clip: "c02", video: "v7slug1", siteVideo: "v7emb01" }]);
+ let after = await read(p.dir);
+ assert.equal(after.timeline[1].siteVideo, "v7emb01");
+ assert.equal(after.timeline[1].video, "v7slug1");
+ // The rest, in one write.
+ const left = await embedIdRows(p.dir, after, { layers: [path.join(ROOT, "channels")] });
+ assert.deepEqual(left.map((x) => x.clip), ["c03"]);
+ await ed.setSiteVideos(p.dir, embedIdFixes(left));
+ after = await read(p.dir);
+ assert.equal(after.timeline[2].siteVideo, "v7emb02");
+ assert.equal(after.timeline[2].citeUrl, "https://site.example/?v=rumblechan/v7emb02&t=1");
+ assert.deepEqual(await embedIdRows(p.dir, after, { layers: [path.join(ROOT, "channels")] }), []);
+ assert.equal((await undoPoints(p.dir)).filter((f) => f.includes("embed-ids")).length, 2);
+});
+
+test("the ledger's writers take an undo point each", async () => {
+ const m = MANIFEST();
+ m.ledgerSchema = { kind: "measure", unit: "lb", yMin: 200, yMax: 400, tracks: [{ key: "weight", role: "value", label: "Weight" }], forms: ["current"], regimes: [], fields: [] };
+ m.ledger = [];
+ const p = await project(m);
+ await addLedgerRow(p.dir, { id: "w01", date: "2026-10-01", scope: "weight", population: "current", value: 291, scopeBasis: "his words" });
+ assert.equal((await undoPoints(p.dir)).filter((f) => f.endsWith("auto-before-ledger.manifest.json")).length, 1);
+ await undoStructural(p.dir);
+ assert.deepEqual((await read(p.dir)).ledger, []);
+});
+
+const hasFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0;
+
+test("a still at second N: one frame of the fetched window into shots/, listed; a second no window holds refused", { skip: !hasFfmpeg && "no ffmpeg" }, async () => {
+ const p = await project();
+ await mkdir(path.join(p.dir, "out", "clips-raw"), { recursive: true });
+ const win = path.join(p.dir, "out", "clips-raw", "vid1_0.00-9.00.mp4");
+ const ff = spawnSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=10:duration=9", "-pix_fmt", "yuv420p", win]);
+ assert.equal(ff.status, 0, String(ff.stderr));
+ const m = await read(p.dir);
+ const before = await readFile(path.join(p.dir, "video.manifest.json"), "utf8");
+ const r = await grabStill(p, m, "c01", 2.5);
+ assert.equal(r.rel, `shots/${stillNameOf("c01", 2.5)}`);
+ assert.equal(r.rel, "shots/still-c01-2_50s.png");
+ assert.ok((await stat(r.file)).size > 100);
+ // A still never edits the cut.
+ assert.equal(await readFile(path.join(p.dir, "video.manifest.json"), "utf8"), before);
+ const shots = await listShots(p.dir);
+ assert.deepEqual(shots.map((s) => [s.rel, s.still]), [["shots/still-c01-2_50s.png", { clip: "c01", at: 2.5 }]]);
+ assert.equal(shotFileOf(p.dir, "shots/still-c01-2_50s.png"), path.join(p.dir, "shots", "still-c01-2_50s.png"));
+ assert.equal(shotFileOf(p.dir, "shots/../video.manifest.json"), null);
+ assert.equal(shotFileOf(p.dir, "posts-media/x.png"), null);
+ await assert.rejects(grabStill(p, m, "c01", 30), /no fetched window/);
+ await assert.rejects(grabStill(p, m, "nope", 1), /no clip nope/);
+});
+
+// ---- the CLI twins (inspectorCli.mjs; timelineCli.mjs teaser-insert; linksCli.mjs --embed-ids) ----
+const cli = await import("./inspectorCli.mjs");
+const { timelineCommand } = await import("./timelineCli.mjs");
+const { linksCommand } = await import("./linksCli.mjs");
+const run = async (fn, args) => {
+ const outs = [];
+ const errs = [];
+ const code = await fn(args, { root: path.join(ROOT, "reports"), out: (s) => outs.push(s), err: (s) => errs.push(s) });
+ return { code, out: outs.join("\n"), err: errs.join("\n") };
+};
+
+test("umtool provenance / title: print, set, refuse", async () => {
+ const p = await project();
+ let r = await run(cli.provenanceCommand, [p.id, "--json"]);
+ assert.equal(r.code, 0, r.err);
+ assert.equal(JSON.parse(r.out).provenance.siteOrigin, "https://old.example");
+ r = await run(cli.provenanceCommand, [p.id, "set", "--site-origin", "https://jeralyzer.pages.dev/", "--channel-slug", "the-quartering", "--json"]);
+ assert.equal(r.code, 0, r.err);
+ assert.equal(JSON.parse(r.out).provenance.channelSlug, "the-quartering");
+ r = await run(cli.provenanceCommand, [p.id, "set", "--site-origin", "nope"]);
+ assert.equal(r.code, 1);
+ assert.match(r.err, /siteOrigin must be/);
+ r = await run(cli.provenanceCommand, [p.id, "set", "--bogus", "x"]);
+ assert.equal(r.code, 2);
+ r = await run(cli.titleCommand, [p.id, "Losing the same hundred pounds", "--subtitle", "Every weight", "--json"]);
+ assert.equal(r.code, 0, r.err);
+ assert.deepEqual([JSON.parse(r.out).title, JSON.parse(r.out).subtitle], ["Losing the same hundred pounds", "Every weight"]);
+ r = await run(cli.titleCommand, [p.id, "--no-subtitle"]);
+ assert.equal(r.code, 0, r.err);
+ const m = await read(p.dir);
+ assert.equal(m.provenance.siteOrigin, "https://jeralyzer.pages.dev");
+ assert.equal(m.title, "Losing the same hundred pounds");
+ assert.equal("subtitle" in m, false);
+});
+
+test("umtool timeline teaser-insert: --line/--break/--hold, at the end by default", async () => {
+ const p = await project();
+ let r = await run(timelineCommand, [p.id, "teaser-insert", "--line", "The 291 scale bet", "--line", "Scale video: not posted as of Nov 8", "--break", "as of Nov 8", "--hold", "1.6", "--beat", "1.3", "--json"]);
+ assert.equal(r.code, 0, r.err);
+ const j = JSON.parse(r.out);
+ assert.equal(j.inserted.id, "close");
+ assert.deepEqual(j.inserted.entry, { type: "teaser", id: "close", lines: ["The 291 scale bet", { text: "Scale video: not posted as of Nov 8", break: "as of Nov 8", hold: 1.6 }], beat: 1.3 });
+ r = await run(timelineCommand, [p.id, "teaser-insert", "--at", "start", "--lines-json", '["Cold open", {"text": "a b", "break": "b"}]']);
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /inserted teaser cold at 0/);
+ r = await run(timelineCommand, [p.id, "teaser-insert", "--break", "x"]);
+ assert.equal(r.code, 2);
+ r = await run(timelineCommand, [p.id, "teaser-insert", "--line", "abc", "--break", "zzz"]);
+ assert.equal(r.code, 1);
+ assert.match(r.err, /refused/);
+ assert.deepEqual((await read(p.dir)).timeline.map((e) => e.id), ["cold", "c01", "c02", "c03", "close"]);
+});
+
+test("umtool links --embed-ids: dry run, then the fix; no network", async () => {
+ await rumbleChannel();
+ const p = await project();
+ let r = await run(linksCommand, [p.id, "--embed-ids", "--dry-run", "--json"]);
+ assert.equal(r.code, 0, r.err);
+ assert.deepEqual(JSON.parse(r.out).would.map((f) => f.clip), ["c02", "c03"]);
+ r = await run(linksCommand, [p.id, "--embed-ids", "--clips", "c02"]);
+ assert.equal(r.code, 0, r.err);
+ assert.match(r.out, /fixed c02: v7slug1 -> siteVideo v7emb01/);
+ assert.equal((await read(p.dir)).timeline[2].siteVideo, undefined);
+ r = await run(linksCommand, [p.id, "--embed-ids", "--clips", "c01"]);
+ assert.equal(r.code, 1);
+});
+
+test("an attachment switched off keeps its knobs in mediaOff, and on puts it back as it was", async () => {
+ const { updatePostItem } = await import("./manifest.mjs");
+ const { validatePostItem } = await import("umtool-report-to-video/post-item");
+ const m = MANIFEST();
+ const vid = { src: "posts-media/x/3/3_1.mp4", kind: "video", seconds: 4, width: 320, height: 180, audio: true };
+ const pic = { src: "posts-media/x/3/3_2.png", kind: "image", width: 320, height: 180 };
+ m.timeline.push({ type: "post", id: "p-3", post: "x/3", platform: "x", author: "A", handle: "a", date: "2026-10-30T12:00:00.000Z", text: "words", media: [vid, pic] });
+ const p = await project(m);
+ await updatePostItem(p.dir, "p-3", { media: { 0: { crop: [0.1, 0.1, 0.8, 0.8], mute: true, start: 1 } } });
+ let r = await updatePostItem(p.dir, "p-3", { mediaHide: [0] });
+ assert.deepEqual(r.entry.media, [pic]);
+ assert.deepEqual(r.entry.mediaOff, [{ ...vid, crop: [0.1, 0.1, 0.8, 0.8], mute: true, start: 1 }]);
+ assert.deepEqual(validatePostItem(r.entry), []);
+ r = await updatePostItem(p.dir, "p-3", { mediaShow: [0] });
+ assert.deepEqual(r.entry.media, [pic, { ...vid, crop: [0.1, 0.1, 0.8, 0.8], mute: true, start: 1 }]);
+ assert.equal("mediaOff" in r.entry, false);
+ await assert.rejects(updatePostItem(p.dir, "p-3", { mediaShow: [0] }), /no attachment switched off at 0/);
+ await assert.rejects(updatePostItem(p.dir, "p-3", { mediaHide: [5] }), /shows no attachment 5/);
+ await assert.rejects(updatePostItem(p.dir, "p-3", { mediaHide: [0], hold: 3 }), /go alone/);
+ // The build's check: a bad switched-off attachment is refused as a shown one is.
+ assert.match(validatePostItem({ ...r.entry, mediaOff: [{ src: 7 }] }).join(" "), /mediaOff\[0\]/);
+ assert.match(validatePostItem({ ...r.entry, mediaOff: [] }).join(" "), /mediaOff must be a list/);
+});
diff --git a/umtool/lib/report/linksCli.mjs b/umtool/lib/report/linksCli.mjs
@@ -28,6 +28,9 @@ export const LINKS_USAGE = [
"links-unverified and links-unchecked from it. --fix rewrites the dead links it knows the fix for",
"(a Twitch id the site serves as v<id>) through the window writer, then checks again.",
"Exit 1 when a link is dead.",
+ " umtool links <project> --embed-ids [--clips a,b] [--dry-run] [--json]",
+ "every clip citing a Rumble URL-slug folder the archive does not serve gets the embed id it serves (siteVideo,",
+ "from the folder's metadata.info.json; a citeUrl naming the folder moves with it): no network, one write.",
].join("\n");
class CliError extends Error {}
@@ -57,6 +60,8 @@ export function linksSummary(doc) {
* @returns {Promise<number>}
*/
export async function linksCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), fetchImpl, cacheDir, gapMs } = {}) {
+ // The published embed ids, from this disk (the Links panel's "use the published embed id"; inspectorCli.mjs).
+ if (args.includes("--embed-ids")) return (await import("./inspectorCli.mjs")).embedIdsCommand(args.filter((a) => a !== "--embed-ids"), { root, out, err });
try {
const words = args.filter((a) => !a.startsWith("--"));
const flags = new Set(args.filter((a) => a.startsWith("--")));
@@ -122,6 +127,8 @@ export const PATCH_MARKERS_USAGE = [
* @returns {Promise<number>}
*/
export async function patchMarkersCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) {
+ // The published embed ids, from this disk (the Links panel's "use the published embed id"; inspectorCli.mjs).
+ if (args.includes("--embed-ids")) return (await import("./inspectorCli.mjs")).embedIdsCommand(args.filter((a) => a !== "--embed-ids"), { root, out, err });
try {
const words = args.filter((a) => !a.startsWith("--"));
const flags = new Set(args.filter((a) => a.startsWith("--")));
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -1344,7 +1344,9 @@ export async function addLedgerRow(dir, row, { token = null } = {}) {
const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8"));
const made = ledgerRowOf(manifest, null, row);
manifest.ledger = [...(Array.isArray(manifest.ledger) ? manifest.ledger : []), made];
- return { row: made, token: await writeManifestAtomic(dir, manifest) };
+ // An undo point first (one undo stack, L3 S5; the inspector's ledger rows, L6): the Cut tab's Undo takes it back.
+ const snapshot = await autoSnapshot(dir, "ledger");
+ return { row: made, snapshot, token: await writeManifestAtomic(dir, manifest) };
});
}
@@ -1368,7 +1370,8 @@ export async function updateLedgerRow(dir, id, patch, { token = null, unset = []
if (patch.id !== undefined && patch.id !== id) throw new Error("a row's id is not changed by set (add the new row, then rm the old)");
const made = ledgerRowOf(manifest, ledger[i], patch, { unset });
ledger[i] = made;
- return { row: made, token: await writeManifestAtomic(dir, manifest) };
+ const snapshot = await autoSnapshot(dir, "ledger");
+ return { row: made, snapshot, token: await writeManifestAtomic(dir, manifest) };
});
}
@@ -1392,7 +1395,8 @@ export async function removeLedgerRow(dir, id, { token = null } = {}) {
const refs = ledgerRowReferences(manifest, id);
if (refs.length) throw new Error(`${id} is still named: ${refs.join("; ")}`);
manifest.ledger = ledger.filter((r) => r?.id !== id);
- return { row, token: await writeManifestAtomic(dir, manifest) };
+ const snapshot = await autoSnapshot(dir, "ledger");
+ return { row, snapshot, token: await writeManifestAtomic(dir, manifest) };
});
}
@@ -2729,8 +2733,12 @@ const POST_REF_FIELDS = Object.freeze(["id", "author", "handle", "badge", "date"
export async function updatePostItem(dir, id, patch, { token = null } = {}) {
if (!isObj(patch)) throw new Error("a post item's patch is an object");
for (const k of Object.keys(patch)) {
- if (!["media", "mediaAdd", "quoted", "parents", "links", "linksAdd"].includes(k) && !POST_ITEM_KNOBS.includes(k)) throw new Error(`${k} is not a post item knob (${[...POST_ITEM_KNOBS, "media", "mediaAdd", "quoted", "parents", "links", "linksAdd"].join(", ")})`);
+ if (!["media", "mediaAdd", "mediaHide", "mediaShow", "quoted", "parents", "links", "linksAdd"].includes(k) && !POST_ITEM_KNOBS.includes(k)) throw new Error(`${k} is not a post item knob (${[...POST_ITEM_KNOBS, "media", "mediaAdd", "mediaHide", "mediaShow", "quoted", "parents", "links", "linksAdd"].join(", ")})`);
}
+ // An attachment SWITCHED OFF and back ON (`mediaHide: [i]` / `mediaShow: [j]`, the inspector's media on/off): it moves
+ // whole between `media` and `mediaOff` (post-item.mjs), its knobs kept -- alone in its write, so no index moves under it.
+ const toggles = ["mediaHide", "mediaShow"].filter((k) => k in patch);
+ if (toggles.length && Object.keys(patch).length !== toggles.length) throw new Error("mediaHide / mediaShow go alone in a write");
return structural(dir, "post-item", token, (m) => {
const i = entryIndex(m.timeline, id);
const e = m.timeline[i];
@@ -2802,6 +2810,24 @@ export async function updatePostItem(dir, id, patch, { token = null } = {}) {
if (!Array.isArray(patch.mediaAdd)) throw new Error("mediaAdd is a list of attachments");
e.media = [...(Array.isArray(e.media) ? e.media : []), ...patch.mediaAdd];
}
+ if (toggles.length) {
+ const idx = (v, k) => {
+ if (!Array.isArray(v) || !v.every((n) => Number.isInteger(n))) throw new Error(`${k} is a list of indices`);
+ return new Set(v);
+ };
+ const on = Array.isArray(e.media) ? e.media : [];
+ const off = Array.isArray(e.mediaOff) ? e.mediaOff : [];
+ const hide = patch.mediaHide !== undefined ? idx(patch.mediaHide, "mediaHide") : new Set();
+ const show = patch.mediaShow !== undefined ? idx(patch.mediaShow, "mediaShow") : new Set();
+ for (const n of hide) if (!isObj(on[n])) throw new Error(`${id} shows no attachment ${n}${on.length ? ` (0–${on.length - 1})` : ""}`);
+ for (const n of show) if (!isObj(off[n])) throw new Error(`${id} has no attachment switched off at ${n}${off.length ? ` (0–${off.length - 1})` : ""}`);
+ const media = [...on.filter((_, n) => !hide.has(n)), ...off.filter((_, n) => show.has(n))];
+ const mediaOff = [...off.filter((_, n) => !show.has(n)), ...on.filter((_, n) => hide.has(n))];
+ if (media.length) e.media = media;
+ else delete e.media;
+ if (mediaOff.length) e.mediaOff = mediaOff;
+ else delete e.mediaOff;
+ }
// A context post's paraphrase (`quoted`, `parents[i]`): its text is never touched. A hand-made ref (`ref`), its
// attachments (`media`) and the words read off its picture (`transcript`) are set here too.
const setContext = (ref, cp, what) => {
@@ -4760,3 +4786,20 @@ export async function undoStructural(dir, { token = null } = {}) {
return { restored: target.rel, op, saved, token: await manifestToken(dir), ...(draft !== undefined ? { draft } : {}) };
});
}
+
+/**
+ * THE ONE DOOR FOR A WRITER OUTSIDE THIS FILE (umtool redesign L6: inspectorEdits.mjs -- the
+ * provenance, the title, a teaser inserted, the published embed ids): `structural`'s write as it is --
+ * the token, the read inside the lock, `mutate` (which throws to refuse), the build's checks, the
+ * undo point `auto-before-<op>` (every op its own in the app), the atomic write.
+ *
+ * @template T
+ * @param {string} dir
+ * @param {string} op
+ * @param {string | null} token
+ * @param {(m: Record<string, any>) => T} mutate
+ */
+export async function structuralEdit(dir, op, token, mutate) {
+ if (!/^[a-z0-9-]{1,40}$/.test(op)) throw new Error(`not an op name: ${op}`);
+ return structural(dir, op, token, mutate);
+}
diff --git a/umtool/lib/report/postsCli.mjs b/umtool/lib/report/postsCli.mjs
@@ -110,6 +110,7 @@ export const POSTS_USAGE = [
" [media.<i>.start=<s>] [media.<i>.end=<s>] [media.<i>.mute=on|off] [media.<i>.crop=x,y,w,h|off]",
" [media.<i>.push=on|off] [media.<i>.trim=off] [media.<i>.enter=post|item] [quoted.paraphrase=\"…\"|off]",
" [media.<i>.blur=on|off] [media.<i>.blur.strength=1–10] [media.<i>.blur.label=\"…\"|off]",
+ " [media.<i>.shown=off] [media-off.<j>.shown=on] an attachment switched off, kept whole (mediaOff), and on again",
" [media.<i>.blur.boxes=x,y,w,h;…|off] [media.<i>.blur.band=below:<f>|above:<f>|between:<a>,<b>[:left:<f>|:right:<f>]|off]",
" [media.<i>.blur.style=blur|black|pixelate|off] [media.<i>.censor=<edge>:<f>[:<style>][:<strength>]|off]",
" [parent.<i>.paraphrase=\"…\"|off] [narration.rate=0.8–1.5|narration.<mix knob>=…]",
@@ -1018,6 +1019,14 @@ export function postItemPatchOf(pairs) {
}
// AN ATTACHMENT FROM A PROJECT FILE (operator, 4 Nov: "this needs to include the cat video"): measured when it goes in.
else if (k === "media.add") (out.mediaAdd ??= []).push(fileArg(raw, k));
+ // An attachment switched OFF, kept whole (mediaOff: its knobs kept), and back ON (the inspector's media on/off).
+ else if (/^media\.\d+\.shown$/.test(k)) {
+ if (!OFF.has(v)) throw new CliError(`${k}= takes off (on: media-off.<j>.shown=on)`);
+ (out.mediaHide ??= []).push(Number(k.split(".")[1]));
+ } else if (/^media-off\.\d+\.shown$/.test(k)) {
+ if (v !== "on") throw new CliError(`${k}= takes on (the attachment switched off at <j> shown again, as it was)`);
+ (out.mediaShow ??= []).push(Number(k.split(".")[1]));
+ }
else if (/^media\.\d+$/.test(k)) {
if (!OFF.has(v)) throw new CliError(`${k}= takes off (the attachment removed)`);
((out.media ??= {})[k.split(".")[1]] = null);
diff --git a/umtool/lib/report/stillGrab.mjs b/umtool/lib/report/stillGrab.mjs
@@ -0,0 +1,129 @@
+// A STILL AT SECOND N (umtool redesign L6: Play's "Still" button, `umtool still`): one frame of a clip's fetched
+// window, grabbed with ffmpeg (`-ss <offset> -i <window> -frames:v 1`) and saved beside the project's shots --
+// `shots/`, where a clip's fx.zoom / fx.receipts and a still entry read their pictures from -- as
+// `shots/still-<clip>-<seconds>.png`. A single-frame grab: not heavy work, never the heavy slot.
+//
+// What it reads is a window ALREADY ON DISK (serve.mjs windowsFor: the project's out/clips-raw and the corpus clips
+// dirs the editor fetched into, a long recording's own file when the window is an excerpt of it). Nothing is
+// fetched: a second no fetched window holds is refused, and says to fetch it first.
+//
+// Plain ESM: the CLI runs it under bare node.
+import { execFile } from "node:child_process";
+import { mkdir, readdir, rename, rm, stat } from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+import { FFMPEG_BIN } from "umtool-report-to-video/build-video";
+import { resolveInRoots } from "../paths.mjs";
+import { clipsOf } from "../projects/report.mjs";
+import { windowsFor } from "./serve.mjs";
+
+const execFileP = promisify(execFile);
+
+/** The project's shots directory (relative to the project), where stills land. */
+export const SHOTS_DIR = "shots";
+const PICTURE_RE = /\.(png|jpe?g|webp)$/i;
+
+export class StillRefused extends Error {
+ /** @param {string} message @param {number} [status] */
+ constructor(message, status = 400) {
+ super(message);
+ this.name = "StillRefused";
+ this.status = status;
+ }
+}
+
+/** The file name a still of `clip` at `seconds` gets: `still-<clip>-<s>s.png`, the second to 2 dp (a dot as "_"). */
+export const stillNameOf = (clip, seconds) => `still-${String(clip).replace(/[^A-Za-z0-9_-]+/g, "-")}-${(Math.round(seconds * 100) / 100).toFixed(2).replace(".", "_")}s.png`;
+
+/**
+ * The window file a frame at `at` (a SOURCE second) is read from, and its offset: the fetched window that holds
+ * it (an excerpt's own recording, which holds it too; a window laid in pieces is skipped -- its filler is black).
+ *
+ * @param {{ dir: string, id: string }} project
+ * @param {Record<string, any>} clip
+ * @param {number} at
+ */
+export async function stillSourceOf(project, clip, at) {
+ const windows = await windowsFor(project, clip);
+ for (const w of windows) {
+ if (w.piecesOf) continue;
+ const src = w.excerptOf ? { path: w.excerptOf.path, from: w.excerptOf.from } : { path: w.path, from: w.from };
+ const to = w.excerptOf ? Infinity : w.to;
+ if (!(at >= src.from - 0.01 && at <= to + 0.01)) continue;
+ const abs = resolveInRoots(src.path);
+ if (!abs) continue;
+ if (!(await stat(abs).catch(() => null))?.isFile()) continue;
+ return { file: abs, offset: Math.max(0, at - src.from) };
+ }
+ return null;
+}
+
+/**
+ * Grab the frame of `clipId` at source second `at` into `shots/`. Returns `{ rel, file, clip, at, bytes }`.
+ * Refused (StillRefused) for a clip not in the cut, a second outside every fetched window, or a window with
+ * no picture.
+ *
+ * @param {{ dir: string, id: string }} project
+ * @param {Record<string, any>} manifest the cut the clip is in (the draft, or a version's)
+ * @param {string} clipId
+ * @param {number} at a source second
+ * @param {{ ffmpeg?: string, name?: string | null }} [opts]
+ */
+export async function grabStill(project, manifest, clipId, at, { ffmpeg = FFMPEG_BIN, name = null } = {}) {
+ const clip = clipsOf(manifest).find((e) => e.id === clipId);
+ if (!clip) throw new StillRefused(`no clip ${clipId} in ${project.id}`, 404);
+ const t = Number(at);
+ if (!Number.isFinite(t) || t < 0) throw new StillRefused("at is a source second, 0 or more");
+ const src = await stillSourceOf(project, clip, t);
+ if (!src) throw new StillRefused(`no fetched window of ${clip.video} holds ${t.toFixed(2)} s -- fetch ${clipId} first (umtool fetch ${project.id} --clips ${clipId})`, 409);
+ const file = name ?? stillNameOf(clipId, t);
+ if (!/^[A-Za-z0-9_.-]{1,120}\.png$/.test(file)) throw new StillRefused(`a still's name is letters, digits, . _ - and .png (got ${file})`);
+ const dir = path.join(project.dir, SHOTS_DIR);
+ await mkdir(dir, { recursive: true });
+ const out = path.join(dir, file);
+ // Two grabs of one second at once never share a temp file.
+ const tmp = path.join(dir, `.${file}.part-${process.pid}-${Math.random().toString(36).slice(2, 10)}.png`);
+ try {
+ await execFileP(ffmpeg, ["-v", "error", "-y", "-ss", src.offset.toFixed(3), "-i", src.file, "-frames:v", "1", "-an", tmp], { timeout: 60_000 });
+ const st = await stat(tmp).catch(() => null);
+ if (!st?.size) throw new StillRefused(`the window of ${clip.video} has no picture at ${t.toFixed(2)} s (an audio-only fetch?)`, 409);
+ await rename(tmp, out);
+ return { rel: `${SHOTS_DIR}/${file}`, file: out, clip: clipId, video: String(clip.video), at: Math.round(t * 100) / 100, bytes: st.size };
+ } catch (e) {
+ if (e instanceof StillRefused) throw e;
+ const msg = String(/** @type {any} */ (e)?.stderr || (e instanceof Error ? e.message : e)).trim().split("\n").slice(-2).join(" ");
+ throw new StillRefused(`ffmpeg could not grab the frame: ${msg}`, 500);
+ } finally {
+ await rm(tmp, { force: true });
+ }
+}
+
+/**
+ * The pictures in the project's shots/ (newest first): `{ rel, name, bytes, mtime, still }`, `still` when it is one
+ * of these grabs (`still-*`), with its clip and second read back from its name.
+ *
+ * @param {string} dir
+ */
+export async function listShots(dir) {
+ const root = path.join(dir, SHOTS_DIR);
+ const names = await readdir(root).catch(() => []);
+ const out = [];
+ for (const n of names) {
+ if (n.startsWith(".") || !PICTURE_RE.test(n)) continue;
+ const st = await stat(path.join(root, n)).catch(() => null);
+ if (!st?.isFile()) continue;
+ const m = /^still-(.+)-(\d+)_(\d{2})s\.png$/.exec(n);
+ out.push({
+ rel: `${SHOTS_DIR}/${n}`, name: n, bytes: st.size, mtime: new Date(st.mtimeMs).toISOString(),
+ still: m ? { clip: m[1], at: Number(`${m[2]}.${m[3]}`) } : null,
+ });
+ }
+ return out.sort((a, b) => b.mtime.localeCompare(a.mtime) || a.name.localeCompare(b.name));
+}
+
+/** A shots/ file's absolute path, never outside shots/ (null when it is not a picture there). */
+export function shotFileOf(dir, rel) {
+ const r = String(rel ?? "");
+ if (!r.startsWith(`${SHOTS_DIR}/`) || r.split("/").length !== 2 || r.includes("..") || !PICTURE_RE.test(r)) return null;
+ return path.join(dir, ...r.split("/"));
+}
diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs
@@ -127,6 +127,9 @@ export const TIMELINE_USAGE = [
" umtool timeline <project> post <json|@file> add a post, or replace the one with its id",
" umtool timeline <project> post-remove <id>",
" umtool timeline <project> teaser <id> <patch-json|@file> lines, beat, dip, tail, tailWait (null removes one)",
+ " umtool timeline <project> teaser-insert [--at start|end | --after <id> | --before <id>] [--id ID] [--beat S]",
+ " --line \"<text>\" [--break \"<its end>\"] [--hold S] [--line …] | --lines-json <json|@file>",
+ " a TEASER OR CLOSING CARD inserted (default at the end, id close; at the start, cold)",
" umtool timeline <project> undo restore the newest automatic snapshot",
" umtool timeline <project> sections [--json] the deck's sections: §, label, colour, its marker, its clips",
" umtool timeline <project> section-move <id> [<id>…] --to-section N [--start]",
@@ -540,7 +543,12 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) =>
err(TIMELINE_USAGE);
return 2;
}
- if (!VERBS.includes(verb)) throw new CliError(`unknown: timeline ${verb} — ${VERBS.join(", ")}`);
+ // A teaser or closing card inserted (the inspector's twin, inspectorCli.mjs): its own flags (--line repeats).
+ if (verb === "teaser-insert") {
+ if (flags.has("--take")) throw new CliError("teaser-insert writes the draft (the project's manifest), not a take");
+ return await (await import("./inspectorCli.mjs")).teaserInsertVerb(await projectOf(projectArg, root), args.slice(args.indexOf("teaser-insert") + 1), { out, err });
+ }
+ if (!VERBS.includes(verb)) throw new CliError(`unknown: timeline ${verb} — ${VERBS.join(", ")}, teaser-insert`);
const project = await projectOf(projectArg, root);
// A video entry (video-entry.mjs), into the cut or a take's timeline.
if (verb === "add-video" || verb === "set-video") return await videoVerb(project, verb, rest, flags, { out, json });
diff --git a/umtool/report-to-video/post-item.mjs b/umtool/report-to-video/post-item.mjs
@@ -705,6 +705,16 @@ export function validatePostItem(e) {
e.media.forEach((m, i) => errors.push(...mediaErrors(m, `${w}.media[${i}]`)));
}
}
+ // ITS ATTACHMENTS SWITCHED OFF (umtool redesign L6, the inspector's media on/off): each kept whole -- its crop,
+ // blur, trim, sound -- in `mediaOff`, which nothing draws or plays (only `media` is read), so "on" puts it back as
+ // it was. Checked as an attachment is.
+ if (e.mediaOff !== undefined) {
+ if (!Array.isArray(e.mediaOff) || !e.mediaOff.length) errors.push(`${w}.mediaOff must be a list of attachments switched off (absent: none)`);
+ else {
+ if (e.mediaOff.length > POST_MEDIA_MAX) errors.push(`${w}.mediaOff: at most ${POST_MEDIA_MAX} attachments`);
+ e.mediaOff.forEach((m, i) => errors.push(...mediaErrors(m, `${w}.mediaOff[${i}]`)));
+ }
+ }
// Its narration (post-narration.mjs): the script, the takes, the mix's knobs.
errors.push(...validatePostNarration(e));
// Its effects (word-zoom.mjs): a word zoomed on as it is read.