commit ca0b02408b0e976e939c21b511ebf483d0720d91
parent f466d5b90060ddb640009b37e1051c702a2fef1f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 28 Oct 2026 22:43:47 -0400
Merge lane/live-preclip: a live stream transcribed and clipped while it still records
- editor: the live-preclip job (one per stream; a worker lease per tick,
coalesced; the overlap splice, the RMS clock check, the landing check and
supersede), lib/livePreclip.ts + -server.ts, controller/liveClip.ts.
- pnpm ops live-preclip {start|stop|status|finalize} and live-clip;
record-live "preclip"; /api/media/live-window (WORKER_TOKEN, no network);
settings.livePreclip; the video page's live panel.
- umtool: clips mode "live" grows the stream's project from the live
transcript; /api/report/live-share cuts a short from the recording in
progress; the clip editor's live banner and Share now.
- Docs: plans/live-preclip.md, OPERATING.md, SETTINGS.md, COMMANDS.md, CHANGELOG.
Conflicts: editor/CHANGELOG.md -- both sides' Unreleased bullets kept.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
44 files changed, 4405 insertions(+), 14 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -120,7 +120,9 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `remote-listing` | remote-listing lists an Odysee or BitChute channel upstream and diffs it against what it holds: {"slug"}. One flat-playlist read on the platform's queue (refused while it is held or cooling down; a 429 backs it off), nothing written. `get remote-listing <slug>` waits for the job and prints {listed, held, notHeld: \[{id, url}\], heldNotListed: \[id\], ...} on stdout. | |
| `attach-media` | attach-media copies each held video's file out of a LOCAL archive into the saved-video store, as its source container (nothing fetched): {"slug", "source"} — an absolute path to a directory, a .zip (read in place) or a .7z. The id is the folder's trailing "(<id>)", else the file's yt-dlp suffix; "items": \[{"id", "path"}\] names exact files (path inside the source), "match" narrows the folders by regex. "createRecords": true writes a record for a video the channel does not hold; "replace": true re-attaches over a saved container. "fillDates": true gives a held record attach-media made (saved-video.json origin "local-archive") that has no upload\_date the date from its folder's description.txt, through the metadata history ("dated" in the log and summary); a record with a date, or one attach-media did not make, is never touched. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous, and dated) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | `pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa\|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait` |
| `import-media` | import-media makes ONE file from outside the archive a normal transcribed item: {"slug", "path"} (absolute) and which record — "url" (the source page: one metadata-only pass makes or refreshes the record, under the id the archive keys it by — Rumble's URL id), "id" (a record already here) or "meta": {"title", "date"?, "duration"?, "description"?} (by hand). ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to mp4 (+faststart), never re-encoded. It lands in the saved-video store only when longer than a container already there ("replace": true lands it anyway), then audio.<fmt>, the archive line and media-import.json. "move": true removes the original once the copy verifies; "audio": false lands the container only; "transcribe": true queues a transcribe-one job (held by any pause; without it the transcription lane takes it by its rules); "doNotClean": true marks it, with "note". "dryRun": true says what it would do and writes nothing. A directory, a .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only). | `pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait`<br>`pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait` |
-| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'` |
+| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'` |
+| `live-preclip` | live-preclip transcribes and mines a recording WHILE it records: {"slug", "id", "action"?: "start" (default) \| "stop" \| "status" \| "finalize"}, and for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"? (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the umtool project, <id>-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/<id>/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` |
+| `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (<id>-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` |
| `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | |
| `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` |
| `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` |
diff --git a/OPERATING.md b/OPERATING.md
@@ -483,6 +483,47 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":
`channels/<slug>/pending-keep.json`; it is marked when its record is first written — a download, an import, a
recording. The channel's Cleanup stage → **Keep videos by id** lists the pending ids.
+### Pre-clip a stream while it records
+
+```sh
+pnpm ops record-live --json '{"slug":"example-youtube","url":"https://www.youtube.com/watch?v=abcdefghijk","preclip":true}'
+pnpm ops live-preclip --json '{"slug":"example-rumble","id":"v1abcde","everyMinutes":5}' # on a recording already running
+pnpm ops live-preclip --json '{"slug":"example-rumble","id":"v1abcde","action":"status"}'
+pnpm ops live-clip --json '{"slug":"example-rumble","id":"v1abcde","start":3605,"end":3660}' --wait
+pnpm ops live-preclip --json '{"slug":"example-rumble","id":"v1abcde","action":"stop"}' # the recording goes on
+pnpm ops live-preclip --json '{"slug":"example-rumble","id":"v1abcde","action":"finalize"}' # by hand, once the final transcript is here
+```
+
+- `"preclip"` on record-live (or `live-preclip` on a recording already running; the video page's **Live
+ pre-clip** panel) runs a `live-preclip` job beside the recorder. Every `everyMinutes` (10; `settings.livePreclip`)
+ a tick reads ONLY the new span of the growing file — by time, `ffmpeg -ss <from> -i <the part>`, the MPEG-TS a
+ muxed recorder writes or the audio stream of YouTube's separate pair — transcribes it on a worker lease (with
+ word timings, at most `maxChunkMinutes` a tick, `overlapSeconds` re-read so a word the boundary cut is heard
+ whole) and splices it into `data/<id>/live-transcript.json`, PROVISIONAL, on the clock the landed video will
+ have. Its laugh scan runs on the same audio. Then umtool's clip finder grows the project `<id>-live`: open it in
+ umtool's clip editor and walk the windows while the stream goes on (the live words are its captions; one
+ speaker until the landing; the strip, the trim and the rulings work as on any project; no model is needed —
+ without the CED model the laughs come from the transcript and the sound's energy).
+- Nothing is copied and the recorder is never touched: the bytes it wrote do not change. The tick's WAV is in
+ `.<id>.preclip/` beside the parts on the store's disk (never /tmp), gone after the tick. No network request.
+- Its log says each tick and each skip: under 30 s new ("no new data"), MemAvailable under the heavy slot's floor
+ (`HEAVY_MIN_FREE_MB`, 6000 — re-checked every minute), the store's disk under 2 GB. One transcription is in
+ flight at a time: a busy worker means the next tick takes everything since (coalesced, never queued up), and a
+ tick far behind is followed by the next at once. `"action": "status"` prints live-preclip.json and the
+ transcript's last cues; `"stop"` cancels the job only.
+- A recorder restart or the Rumble fallback writes a new part: when its audio at 60–90 s matches the fingerprint
+ taken live, the transcript goes on; else it starts again on the new part and the project's windows are flagged.
+- When the stream lands: the clock check (the landed part is the one followed → nothing to check; else the
+ landed video's audio against the fingerprint), then — once the final transcript is there (the landing handed the
+ audio to the transcription lane) — the live transcript is marked superseded and the project reads the corpus:
+ its windows stay where they are by source second, flagged in the clip editor when the check did not match. Find
+ clips on the landed video later re-analyzes the same project with the speakers and the sound.
+- A shareable clip while it is still live: `live-clip` (`start`/`end` in stream seconds, or `"clip"`: a clip id of
+ the project), the panel's **Share this clip**, or the clip editor's **Share now (live)** — the window is cut from
+ what is recorded at that moment (`/api/media/live-window`; from the saved video once landed) into the clip cache,
+ and the clip's short is made with the live captions, offline. At most 2:20 and 512 MiB (X); past the live edge
+ it says how many seconds to wait.
+
## Find clips in a recording
```sh
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -21,6 +21,7 @@ A copied example PINS every default it spells — including each lane's `autoQue
| [`cookieMode`](#cookiemode) | `"when-required"` |
| [`social`](#social) | object — see below |
| [`sleepBetweenDownloadsSeconds`](#sleepbetweendownloadsseconds) | `10` |
+| [`livePreclip`](#livepreclip) | object — see below |
| [`pacing`](#pacing) | object — see below |
| [`downloadFormat`](#downloadformat) | `"auto"` |
| [`sourceVideoQuality`](#sourcevideoquality) | `"original"` |
@@ -210,6 +211,32 @@ Pause (seconds) inserted between per-video yt-dlp invocations in managed batch d
Default: `10`
+## `livePreclip`
+
+The defaults of LIVE PRE-CLIP (plans/live-preclip.md): a live recording transcribed and mined while it records — record-live's `"preclip": true`, `pnpm ops live-preclip`. A request's own `preclip` keys override these. See common/controller/livePreclip.ts.
+
+#### `livePreclip`
+
+| Key | Default | Description |
+|---|---|---|
+| `everyMinutes` | `10` | Minutes between two pre-clip ticks of a live recording. A tick transcribes only what was recorded since the last one; a tick with under 30 s new is skipped. Clamped 1–120; default 10. |
+| `maxChunkMinutes` | `20` | The most one tick transcribes, minutes of audio. A recording further behind (pre-clip started late, the worker was busy) is caught up in ticks of this size, back to back. Clamped 2–60; default 20. |
+| `overlapSeconds` | `15` | Seconds each tick re-reads before the end of what is transcribed, so a word the boundary cut is heard whole once; the splice keeps each side's half. Clamped 0–60; default 15. |
+| `scan` | `true` | Run the clip finder's laugh scan (CED when its model is installed, the energy always) on each tick's span. Default true. |
+| `mine` | `true` | Hand the live transcript to umtool's clip finder after each tick (`POST /api/report/clips {mode: "live"}`), growing the stream's project. Default true. |
+
+Default:
+
+```json
+{
+ "everyMinutes": 10,
+ "maxChunkMinutes": 20,
+ "overlapSeconds": 15,
+ "scan": true,
+ "mine": true
+}
+```
+
## `pacing`
How the download pace adapts to rate limits, per platform (release 17). Every yt-dlp spawn against a platform paces its requests (`--sleep-requests`) at the platform's adaptive pace, and the download lane waits sleepBetweenDownloadsSeconds plus the pace above its fixed value between units. A rate limit doubles the pace; clean units ease it back; a rate limit that outlasts the cooldown cap holds the platform to one probe at a time. The live pace, cooldowns and holds are in `.auto-queue/state.json`, shown on /operations/download. See common/jobs/platformBackoff.ts.
diff --git a/common/controller/autoRunner.settings.fixture.ts b/common/controller/autoRunner.settings.fixture.ts
@@ -0,0 +1,33 @@
+// autoRunner.test.ts's OWN settings.json, imported FIRST by it: a module of
+// its own because getPaths() memoizes on its first call, and some module the
+// test imports makes that call while it loads — an env var set in the test's
+// body would come too late.
+//
+// computeLeafPending reads getSettings(). With no SETTINGS_FILE that is the
+// checkout's own settings.json: the operator's in the primary checkout (a
+// transcription tree with leaves), none in a fresh worktree (the runner lanes'
+// built-in EMPTY tree) — so two tests passed in one checkout and failed in the
+// other. This is the minimal tree they need: one catch-all leaf on each runner
+// lane (the digest and backfill lanes default to one already).
+
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+const dir = mkdtempSync(path.join(tmpdir(), "auto-runner-settings-"));
+process.env.SETTINGS_FILE = path.join(dir, "settings.json");
+
+const CATCH_ALL_ROOT = {
+ id: "root",
+ mode: "strict",
+ weight: 1,
+ maxWorkers: null,
+ children: [{ id: "all", match: { type: "all" }, weight: 1, maxWorkers: null }],
+};
+
+writeFileSync(
+ process.env.SETTINGS_FILE,
+ JSON.stringify({ autoQueue: { transcription: { root: CATCH_ALL_ROOT }, download: { root: CATCH_ALL_ROOT } } }),
+);
+
+process.on("exit", () => rmSync(dir, { recursive: true, force: true }));
diff --git a/common/controller/autoRunner.test.ts b/common/controller/autoRunner.test.ts
@@ -1,3 +1,5 @@
+// FIRST: this test's own settings.json, so it passes the same in any checkout.
+import "./autoRunner.settings.fixture";
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
diff --git a/common/controller/liveClip.test.ts b/common/controller/liveClip.test.ts
@@ -0,0 +1,116 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { execa } from "execa";
+import type { ChannelConfig } from "../lib/channelConfig";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/liveClip.test.ts
+//
+// A share of a stream still live (controller/liveClip.ts): the window cut now
+// from a recording in progress (a real, tiny MPEG-TS), the cache, the live
+// edge; and the ops job's conversation with umtool (a stub fetch).
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-clip-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+
+const { getPaths } = await import("../lib/paths");
+const { liveWindow, parseLiveClipBody, runLiveClip } = await import("./liveClip");
+const { liveRecordingSidecar } = await import("../lib/mediaImport-server");
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-live";
+const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth", platform: "youtube", name: "Synth" } as ChannelConfig;
+
+test("parseLiveClipBody: start/end or clip, 2:20, the project's default", () => {
+ assert.deepEqual(parseLiveClipBody({ slug: "s", id: "Ab1", start: 10, end: 70 }), { ok: true, value: { slug: "s", id: "Ab1", project: "ab1-live", start: 10, end: 70 } });
+ assert.deepEqual(parseLiveClipBody({ slug: "s", id: "Ab1", clip: "r003", project: "mine" }), { ok: true, value: { slug: "s", id: "Ab1", project: "mine", clip: "r003" } });
+ assert.match((parseLiveClipBody({ slug: "s", id: "a", start: 0, end: 200 }) as { error: string }).error, /2:20/);
+ assert.match((parseLiveClipBody({ slug: "s", id: "a", clip: "r1", start: 1, end: 2 }) as { error: string }).error, /not both/);
+ assert.match((parseLiveClipBody({ slug: "s", id: "a" }) as { error: string }).error, /"start" and "end"/);
+});
+
+test("liveWindow: cut now from the part being recorded, then the cache; past the edge says how long to wait", async (t) => {
+ const id = "win001";
+ const videoDir = path.join(CORPUS, "channels", SLUG, "data", id);
+ await mkdir(videoDir, { recursive: true });
+ const store = path.join(paths.savedVideosDir, SLUG);
+ await mkdir(store, { recursive: true });
+ const stem = `.${id}.live-2026-10-27T12-00-00-000Z.ytdlp`;
+ try {
+ await execa(paths.ffmpegBin, [
+ "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=10:d=40", "-f", "lavfi", "-i", "sine=f=300:d=40:r=16000",
+ "-c:v", "libx264", "-preset", "ultrafast", "-g", "20", "-c:a", "aac", "-b:a", "48k", "-f", "mpegts", path.join(store, `${stem}.ts`),
+ ]);
+ } catch {
+ return t.skip("no ffmpeg with libx264 here");
+ }
+ await liveRecordingSidecar.write(videoDir, {
+ status: "recording",
+ url: "u",
+ platform: "youtube",
+ fromStart: true,
+ startedAt: "2026-10-27T12:00:00Z",
+ parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt: "2026-10-27T12:00:00Z", stem }],
+ });
+ const a = await liveWindow({ paths, slug: SLUG, id, channelConfig: CONFIG, from: 10, to: 20 });
+ assert.ok(a.ok, JSON.stringify(a));
+ if (!a.ok) return;
+ assert.equal(a.source, "live-recording");
+ assert.equal(a.window.file, "10.00-20.00.mp4");
+ const again = await liveWindow({ paths, slug: SLUG, id, channelConfig: CONFIG, from: 12, to: 18 });
+ assert.ok(again.ok && again.source === "cache", "the tightest window already cut serves it");
+ const late = await liveWindow({ paths, slug: SLUG, id, channelConfig: CONFIG, from: 30, to: 45 });
+ assert.ok(!late.ok && late.status === 409 && /ask again in \d+ s/.test(late.error), JSON.stringify(late));
+ const none = await liveWindow({ paths, slug: SLUG, id: "nothing", channelConfig: CONFIG, from: 1, to: 5 });
+ assert.ok(!none.ok && none.status === 404);
+});
+
+function umtoolStub(o: { states: string[]; size: number }) {
+ const seen: { method: string; url: string; body?: unknown }[] = [];
+ const doFetch = (async (url: string, init?: RequestInit) => {
+ const u = String(url);
+ seen.push({ method: init?.method ?? "GET", url: u, ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}) });
+ const json = (b: unknown, status = 200) => new Response(JSON.stringify(b), { status, headers: { "content-type": "application/json" } });
+ if (u.endsWith("/api/report/live-share")) return json({ ok: true, clip: "stream-3605", added: true, window: { from: 3600.5, to: 3666.5 }, windowSource: "live-recording", job: { id: "j1" } });
+ if (u.includes("?job=j1")) {
+ const state = o.states.shift() ?? "done";
+ return json({ state, log: [`state ${state}`], next: 1 });
+ }
+ if (u.includes("/api/report/shorts?project=")) return json({ shorts: [{ clip: "stream-3605", size: o.size }] });
+ return json({ error: "?" }, 404);
+ }) as typeof fetch;
+ return { seen, doFetch };
+}
+
+test("runLiveClip: asks umtool's live share, follows the short, gives its URL; over 512 MiB is refused", async () => {
+ const s = umtoolStub({ states: ["running", "done"], size: 40 * 1024 * 1024 });
+ const lines: string[] = [];
+ const r = await runLiveClip(
+ { slug: SLUG, id: "stream", project: "stream-live", start: 3605, end: 3660 },
+ { onLog: (l) => lines.push(l), signal: new AbortController().signal, deps: { fetch: s.doFetch, umtoolUrl: "http://umtool", workerToken: "tok", pollMs: 0, sleep: async () => {} } },
+ );
+ assert.equal(r.clip, "stream-3605");
+ assert.equal(r.bytes, 40 * 1024 * 1024);
+ assert.match(r.url, /shorts\?project=stream-live&clip=stream-3605&file=1/);
+ assert.deepEqual(s.seen[0]!.body, { project: "stream-live", from: `${SLUG}/stream`, start: 3605, end: 3660 });
+ assert.ok(lines.some((l) => /window 3600.5–3666.5 s cut from the live-recording/.test(l)));
+
+ const big = umtoolStub({ states: ["done"], size: 600 * 1024 * 1024 });
+ await assert.rejects(
+ runLiveClip({ slug: SLUG, id: "stream", project: "stream-live", clip: "stream-3605" }, { onLog: () => {}, signal: new AbortController().signal, deps: { fetch: big.doFetch, umtoolUrl: "http://umtool", workerToken: "tok", pollMs: 0, sleep: async () => {} } }),
+ /over X's 512 MiB/,
+ );
+ const failed = umtoolStub({ states: ["failed"], size: 1 });
+ await assert.rejects(
+ runLiveClip({ slug: SLUG, id: "stream", project: "stream-live", clip: "c" }, { onLog: () => {}, signal: new AbortController().signal, deps: { fetch: failed.doFetch, umtoolUrl: "http://umtool", workerToken: "tok", pollMs: 0, sleep: async () => {} } }),
+ /job j1 failed/,
+ );
+});
diff --git a/common/controller/liveClip.ts b/common/controller/liveClip.ts
@@ -0,0 +1,278 @@
+// A SHAREABLE CLIP OF A STREAM STILL LIVE (plans/live-preclip.md, "Shareable
+// clips from a partial") — the operator's "in case something really
+// interesting happens on a long stream".
+//
+// liveWindow `POST /api/media/live-window` (umtool asks it, WORKER_TOKEN):
+// a window of the recording cut NOW into the clip cache,
+// data/<id>/clips/<from>-<to>.mp4 — from the part being
+// recorded while it records (the snapshot on demand: it reads
+// the bytes written so far, so it is never older than the
+// request), from the saved video once it has landed, or the
+// window already in the cache. No network request; the
+// recorder is only read.
+// runLiveClipJob `pnpm ops live-clip {slug, id, start, end | clip, project?,
+// replace?}`: umtool's `POST /api/report/live-share` — which
+// asks the window above, adds the clip to the stream's
+// project when it is given by seconds, and makes its short
+// (build-video --short, no network, the live words as its
+// captions) — followed to the end. The clip editor's Share now
+// is the same umtool call.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { liveRecordingSidecar } from "../lib/mediaImport-server";
+import { savedVideoDir } from "../lib/savedVideo";
+import { findContainingClipWindow, type ClipWindow } from "../lib/clipWindow-server";
+import { cutSavedVideoWindow, savedWindowSource } from "../lib/savedVideoWindow-server";
+import { checkLiveWindow, liveClipTooLong, liveProjectSlug, LIVE_SHARE_MAX_BYTES, PROJECT_SLUG_RE } from "../lib/livePreclip";
+import { cutLiveWindow, findLiveSource, probeWith } from "../lib/livePreclip-server";
+import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl";
+import { getWorkerToken } from "../lib/workerToken";
+import { getRegistry } from "../jobs/registry";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+
+export const LIVE_CLIP_JOB_KIND = "live-clip";
+export const LIVE_CLIP_QUEUE = "live-clip";
+export const LIVE_CLIP_RESULT_MARKER = "@@live-clip ";
+export const LIVE_CLIP_BODY_KEYS = ["slug", "id", "start", "end", "clip", "project", "replace"] as const;
+export const LIVE_WINDOW_BODY_KEYS = ["slug", "id", "from", "to", "requestedBy", "manifest", "clipId", "reason"] as const;
+
+export type LiveWindowOutcome =
+ | { ok: true; window: Pick<ClipWindow, "path" | "file" | "from" | "to" | "bytes">; source: "cache" | "live-recording" | "saved-video"; recordedSeconds: number | null }
+ | { ok: false; status: number; error: string };
+
+export async function liveWindow(o: {
+ paths: Paths;
+ slug: string;
+ id: string;
+ channelConfig: ChannelConfig;
+ from: number;
+ to: number;
+ requestedBy?: string;
+ manifest?: string;
+ clipId?: string;
+ reason?: string;
+ signal?: AbortSignal;
+}): Promise<LiveWindowOutcome> {
+ const videoDir = path.join(o.paths.channelsDir, o.slug, "data", o.id);
+ const shape = checkLiveWindow(o.from, o.to, null);
+ if ("error" in shape) return { ok: false, status: 400, error: shape.error };
+ const cached = await findContainingClipWindow(videoDir, shape.from, shape.to);
+ if (cached) return { ok: true, window: cached, source: "cache", recordedSeconds: null };
+ const record = await liveRecordingSidecar.load(videoDir);
+ if (record?.status === "recording") {
+ const slugStore = path.dirname(savedVideoDir(o.paths, o.channelConfig, o.slug, o.id));
+ const probe = probeWith(o.paths.ffprobeBin);
+ const src = await findLiveSource({ slugStore, id: o.id, record, probe });
+ if ("wait" in src) return { ok: false, status: 409, error: `the recording cannot be read yet: ${src.wait}` };
+ // Both files of a separate pair must hold the window.
+ const a = (await probe(src.audioPath))?.seconds ?? null;
+ const v = src.videoPath && src.videoPath !== src.audioPath ? ((await probe(src.videoPath))?.seconds ?? null) : a;
+ const recorded = a === null || v === null ? null : Math.min(a, v);
+ if (recorded === null) return { ok: false, status: 409, error: `the recording's length cannot be read yet (${src.stem})` };
+ const win = checkLiveWindow(o.from, o.to, recorded);
+ if ("error" in win) return { ok: false, status: 409, error: win.error };
+ const cut = await cutLiveWindow({
+ ffmpegBin: o.paths.ffmpegBin,
+ videoDir,
+ source: src,
+ from: win.from,
+ to: win.to,
+ requestedBy: o.requestedBy ?? "live-clip",
+ ...(o.reason ? { reason: o.reason } : {}),
+ ...(o.clipId ? { clipId: o.clipId } : {}),
+ ...(o.manifest ? { manifest: o.manifest } : {}),
+ ...(o.signal ? { signal: o.signal } : {}),
+ });
+ return { ok: true, window: cut, source: "live-recording", recordedSeconds: recorded };
+ }
+ // Landed (or never recorded here): the saved video, as any window is cut.
+ const saved = await savedWindowSource({ paths: o.paths, slug: o.slug, videoDir, from: shape.from, to: shape.to });
+ if (saved.kind === "unreadable") return { ok: false, status: 503, error: saved.error };
+ if (saved.kind === "none") {
+ return { ok: false, status: 404, error: `${o.slug}/${o.id} is not being recorded and has no saved video to cut the window from` };
+ }
+ if (saved.kind === "not-covering") {
+ return { ok: false, status: 409, error: `the saved video holds ${Math.round(saved.durationSec)} s; the window ends at ${shape.to} s` };
+ }
+ const cut = await cutSavedVideoWindow({
+ paths: o.paths,
+ videoDir,
+ source: saved,
+ from: shape.from,
+ to: shape.to,
+ provenance: {
+ requestedBy: o.requestedBy ?? "live-clip",
+ ...(o.reason ? { reason: o.reason } : {}),
+ ...(o.clipId ? { clipId: o.clipId } : {}),
+ ...(o.manifest ? { manifest: o.manifest } : {}),
+ },
+ ...(o.signal ? { signal: o.signal } : {}),
+ });
+ return { ok: true, window: cut, source: "saved-video", recordedSeconds: saved.durationSec };
+}
+
+// --- the ops job ------------------------------------------------------------------------
+
+export type LiveClipRequest = {
+ slug: string;
+ id: string;
+ start?: number;
+ end?: number;
+ clip?: string;
+ project: string;
+ replace?: boolean;
+};
+
+type Check<T> = { ok: true; value: T } | { ok: false; error: string };
+
+export function parseLiveClipBody(body: Record<string, unknown>): Check<LiveClipRequest> {
+ const slug = typeof body.slug === "string" ? body.slug.trim() : "";
+ const id = typeof body.id === "string" ? body.id.trim() : "";
+ if (!slug) return { ok: false, error: '"slug" is required' };
+ if (!id || !/^[\w.-]+$/.test(id) || id === "." || id === "..") return { ok: false, error: '"id" is required: the record\'s id' };
+ const project = body.project === undefined ? liveProjectSlug(id) : body.project;
+ if (typeof project !== "string" || !PROJECT_SLUG_RE.test(project)) return { ok: false, error: '"project" is a umtool project slug' };
+ const out: LiveClipRequest = { slug, id, project };
+ if (body.clip !== undefined) {
+ if (typeof body.clip !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/.test(body.clip)) return { ok: false, error: '"clip" is a clip id of the project ("r003")' };
+ if (body.start !== undefined || body.end !== undefined) return { ok: false, error: 'give "clip" or "start" and "end", not both' };
+ out.clip = body.clip;
+ } else {
+ if (typeof body.start !== "number" || typeof body.end !== "number") return { ok: false, error: 'give "start" and "end" (seconds of the stream), or "clip"' };
+ const long = liveClipTooLong(body.start, body.end);
+ if (long) return { ok: false, error: long };
+ out.start = body.start;
+ out.end = body.end;
+ }
+ if (body.replace !== undefined) {
+ if (typeof body.replace !== "boolean") return { ok: false, error: '"replace" must be true or false' };
+ out.replace = body.replace;
+ }
+ return { ok: true, value: out };
+}
+
+export type LiveClipDeps = {
+ fetch?: typeof fetch;
+ umtoolUrl?: string | null;
+ workerToken?: string;
+ pollMs?: number;
+ sleep?: (ms: number) => Promise<void>;
+};
+
+async function json(res: Response): Promise<Record<string, unknown>> {
+ try {
+ const j = (await res.json()) as unknown;
+ return j && typeof j === "object" && !Array.isArray(j) ? (j as Record<string, unknown>) : {};
+ } catch {
+ return {};
+ }
+}
+
+export type LiveClipResult = { project: string; clip: string; short: string; url: string; bytes: number | null; window: { from: number; to: number } | null };
+
+/** umtool's live share, followed to the end. */
+export async function runLiveClip(req: LiveClipRequest, o: { onLog: (s: string) => void; signal: AbortSignal; deps?: LiveClipDeps }): Promise<LiveClipResult> {
+ const deps = o.deps ?? {};
+ const doFetch = deps.fetch ?? fetch;
+ const umtool = deps.umtoolUrl === undefined ? resolveUmtoolUrl() : deps.umtoolUrl;
+ const token = deps.workerToken ?? getWorkerToken();
+ if (!umtool) throw new Error("UMTOOL_URL is not set on the editor: a live share is made by umtool");
+ if (!token) throw new Error("WORKER_TOKEN is not set on the editor: umtool's live-share route is asked with it");
+ const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
+ const say = (s: string) => o.onLog(s.endsWith("\n") ? s : `${s}\n`);
+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+ const body = {
+ project: req.project,
+ from: `${req.slug}/${req.id}`,
+ ...(req.clip ? { clip: req.clip } : { start: req.start, end: req.end }),
+ ...(req.replace ? { replace: true } : {}),
+ };
+ say(`Share ${req.clip ? `clip ${req.clip}` : `${req.start}–${req.end} s`} of ${req.slug}/${req.id} from umtool project ${req.project}`);
+ let res: Response;
+ try {
+ res = await doFetch(`${umtool}/api/report/live-share`, { method: "POST", headers, body: JSON.stringify(body), signal: o.signal });
+ } catch (e) {
+ throw new Error(`umtool at ${umtool} did not answer (${(e as Error).message}) — is it running?`);
+ }
+ const posted = await json(res);
+ if (!res.ok) throw new Error(`umtool refused the share (HTTP ${res.status}): ${typeof posted.error === "string" ? posted.error : "no reason given"}`);
+ const job = posted.job as { id?: unknown } | undefined;
+ const jobId = typeof job?.id === "string" ? job.id : null;
+ const clip = typeof posted.clip === "string" ? posted.clip : req.clip ?? "";
+ const window = posted.window && typeof posted.window === "object" ? (posted.window as { from: number; to: number }) : null;
+ if (!jobId || !clip) throw new Error(`umtool's answer named no job or clip: ${JSON.stringify(posted).slice(0, 300)}`);
+ if (window) say(`window ${window.from}–${window.to} s cut from the ${String(posted.windowSource ?? "recording")}`);
+ say(`umtool: making the short of ${clip} (job ${jobId})`);
+ let since = 0;
+ let failures = 0;
+ for (;;) {
+ if (o.signal.aborted) {
+ await doFetch(`${umtool}/api/report/shorts?cancel=${encodeURIComponent(jobId)}`, { method: "POST", headers }).catch(() => null);
+ throw new Error(`cancelled; umtool job ${jobId} was asked to stop`);
+ }
+ let view: Record<string, unknown> | null = null;
+ try {
+ const r = await doFetch(`${umtool}/api/report/shorts?job=${encodeURIComponent(jobId)}&since=${since}`, { headers, signal: o.signal });
+ if (r.status === 404) throw new Error(`umtool no longer knows job ${jobId} (restarted?)`);
+ if (r.ok) view = await json(r);
+ } catch (e) {
+ if (/no longer knows/.test((e as Error).message)) throw e;
+ }
+ if (!view) {
+ if (++failures >= 15) throw new Error(`umtool at ${umtool} stopped answering while job ${jobId} ran`);
+ } else {
+ failures = 0;
+ const log = Array.isArray(view.log) ? view.log.filter((l): l is string => typeof l === "string") : [];
+ for (const line of log) say(`umtool: ${line.replace(/\n$/, "")}`);
+ since = typeof view.next === "number" ? view.next : since + log.length;
+ const state = typeof view.state === "string" ? view.state : "running";
+ if (state !== "running") {
+ if (state !== "done") throw new Error(`umtool job ${jobId} failed: ${typeof view.error === "string" && view.error ? view.error : `the job ended ${state}`}`);
+ break;
+ }
+ }
+ await sleep(deps.pollMs ?? 2000);
+ }
+ // The size, from the list of shorts.
+ let bytes: number | null = null;
+ try {
+ const r = await doFetch(`${umtool}/api/report/shorts?project=${encodeURIComponent(req.project)}`, { headers });
+ const j = await json(r);
+ const hit = Array.isArray(j.shorts) ? (j.shorts as { clip?: string; size?: number }[]).find((s) => s.clip === clip) : undefined;
+ bytes = typeof hit?.size === "number" ? hit.size : null;
+ } catch {
+ bytes = null;
+ }
+ const url = `${umtool}/api/report/shorts?project=${encodeURIComponent(req.project)}&clip=${encodeURIComponent(clip)}&file=1&download=1`;
+ // X takes 512 MiB at most. A 2:20 short is far under it; one over is said,
+ // not posted.
+ if (bytes !== null && bytes > LIVE_SHARE_MAX_BYTES) {
+ throw new Error(`the short of ${clip} is ${(bytes / 1024 / 1024).toFixed(0)} MiB, over X's 512 MiB — ${url}`);
+ }
+ return { project: req.project, clip, short: `shorts/${clip}.mp4`, url, bytes, window };
+}
+
+export async function runLiveClipJob(o: { paths: Paths; request: LiveClipRequest; deps?: LiveClipDeps }): Promise<StreamActionResult> {
+ const umtool = o.deps?.umtoolUrl === undefined ? resolveUmtoolUrl() : o.deps.umtoolUrl;
+ if (!umtool) return { ok: false, error: "UMTOOL_URL is not set on the editor: a live share is made by umtool (e.g. UMTOOL_URL=http://localhost:3050)" };
+ if (!(o.deps?.workerToken ?? getWorkerToken())) return { ok: false, error: "WORKER_TOKEN is not set on the editor" };
+ const busy = getRegistry()
+ .list()
+ .find((j) => j.queueKey === LIVE_CLIP_QUEUE && (j.status === "running" || j.status === "queued") && j.videoId === o.request.id);
+ if (busy) return { ok: false, info: true, error: `A share of ${o.request.slug}/${o.request.id} is already being made (job ${busy.id})` };
+ return runManagedFunction({
+ kind: LIVE_CLIP_JOB_KIND,
+ queueKey: LIVE_CLIP_QUEUE,
+ paths: o.paths,
+ channelSlug: o.request.slug,
+ videoId: o.request.id,
+ network: false,
+ fn: async (onLog, signal) => {
+ const r = await runLiveClip(o.request, { onLog, signal, ...(o.deps ? { deps: o.deps } : {}) });
+ onLog(`The short: ${r.url}${r.bytes !== null ? ` (${(r.bytes / 1024 / 1024).toFixed(1)} MiB)` : ""}\n`);
+ onLog(`${LIVE_CLIP_RESULT_MARKER}${JSON.stringify(r)}\n`);
+ },
+ });
+}
diff --git a/common/controller/livePreclip.test.ts b/common/controller/livePreclip.test.ts
@@ -0,0 +1,309 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { LiveRecordingRecord } from "../lib/liveCapture";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/livePreclip.test.ts
+//
+// Live pre-clip's loop (controller/livePreclip.ts) over a temp corpus: the
+// recording is a record and part files on disk whose LENGTH is a number the
+// test moves; the worker, the scan, umtool and the clock are stubs. Each
+// `sleep` the loop takes runs the next step of the script — the world moving
+// on while it waits.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-preclip-ctl-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+
+const { getPaths } = await import("../lib/paths");
+const { runLivePreclip, parseLivePreclipBody, memoryFloorMb, finalizeLivePreclip } = await import("./livePreclip");
+const { liveRecordingSidecar } = await import("../lib/mediaImport-server");
+const { liveTranscriptSidecar, livePreclipSidecar } = await import("../lib/livePreclip-server");
+const { PRECLIP_DEFAULTS } = await import("../lib/livePreclip");
+type Deps = NonNullable<Parameters<typeof runLivePreclip>[0]["deps"]>;
+
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-live";
+const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth", platform: "youtube", name: "Synth" } as ChannelConfig;
+const slugStore = path.join(paths.savedVideosDir, SLUG);
+await mkdir(slugStore, { recursive: true });
+
+const stemOf = (id: string, tag: string) => `.${id}.live-2026-10-27T12-00-00-000Z.${tag}`;
+
+async function setup(id: string) {
+ const videoDir = path.join(CORPUS, "channels", SLUG, "data", id);
+ await mkdir(videoDir, { recursive: true });
+ const stem = stemOf(id, "ytdlp");
+ await writeFile(path.join(slugStore, `${stem}.ts`), "growing");
+ const record: LiveRecordingRecord = {
+ status: "recording",
+ url: `https://www.youtube.com/watch?v=${id}`,
+ platform: "youtube",
+ fromStart: true,
+ startedAt: "2026-10-27T12:00:00Z",
+ parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt: "2026-10-27T12:00:00Z", stem }],
+ };
+ await liveRecordingSidecar.write(videoDir, record);
+ return { videoDir, stem, record };
+}
+
+// One cue a minute, at m·60 + 1 (and its word), inside [from, to).
+function fakeTranscript(from: number, to: number) {
+ const cues = [];
+ const words = [];
+ for (let m = Math.ceil((from - 1) / 60); m * 60 + 1 < to; m += 1) {
+ const t = m * 60 + 1;
+ if (t < from) continue;
+ cues.push({ start: t, end: t + 2, text: `minute ${m}` });
+ words.push({ w: `m${m}`, start: t, end: t + 0.4 });
+ }
+ return { cues, words };
+}
+
+// An envelope of a recording on a given clock: the same "audio" at the same
+// stream second, offset by the file's `shift` (a clock that differs).
+const pattern = (t: number, seed: number) => Math.round((-30 + 12 * Math.sin(t * 1.7 + seed) + 6 * Math.sin(t * 0.31 * (seed + 1))) * 10) / 10;
+function envelopeFor(seedOf: (file: string) => number, shiftOf: (file: string) => number = () => 0) {
+ return async (file: string, from: number, dur: number) => {
+ const out = [];
+ for (let k = 0; k < Math.round(dur / 0.1); k += 1) out.push(pattern(from + k * 0.1 + shiftOf(file), seedOf(file)));
+ return out;
+ };
+}
+
+function world(o: { recorded: Map<string, number>; script: (() => void | Promise<void>)[]; deps?: Partial<Deps> }) {
+ const calls: { from: number; to: number }[] = [];
+ const mined: Record<string, unknown>[] = [];
+ let mem = [9000];
+ const lines: string[] = [];
+ const ac = new AbortController();
+ let finalHere = false;
+ const deps: Deps = {
+ now: () => new Date("2026-10-27T12:30:00Z"),
+ sleep: async () => {
+ const step = o.script.shift();
+ if (step) await step();
+ else ac.abort();
+ },
+ memAvailableMb: async () => (mem.length > 1 ? mem.shift()! : mem[0]!),
+ memoryFloorMb: 6000,
+ freeBytes: async () => 1e12,
+ probe: async (file) => ({ seconds: o.recorded.get(path.basename(file)) ?? null, hasVideo: true, hasAudio: true }),
+ transcribe: async ({ from, to, withWav }) => {
+ calls.push({ from, to });
+ await withWav?.("span.wav", to - from);
+ return { ...fakeTranscript(from, to), worker: "gpu", ms: 1000, waitedMs: 0 };
+ },
+ scanWav: async (_wav, from, seconds) => ({ t0: from, hop: 0.5, window: 1, energy: new Array(Math.floor(seconds / 0.5)).fill(-30), laugh: null, model: null }),
+ envelope: envelopeFor(() => 1),
+ mine: async (body) => {
+ mined.push(body);
+ return { project: body.slug, created: mined.length === 1, proposals: mined.length, clips: 0 };
+ },
+ savedVideo: async () => null,
+ hasFinalTranscript: async () => finalHere,
+ recordWaitMs: 1000,
+ ...o.deps,
+ };
+ return {
+ deps,
+ calls,
+ mined,
+ lines,
+ ac,
+ setMem: (m: number[]) => (mem = m),
+ setFinal: (v: boolean) => (finalHere = v),
+ };
+}
+
+test("ticks: memory floor, a busy worker coalesced, catch-up, the landing, the supersede", async () => {
+ const id = "live001";
+ const { videoDir, stem, record } = await setup(id);
+ const file = `${stem}.ts`;
+ const recorded = new Map([[file, 600]]);
+ const script: (() => void | Promise<void>)[] = [];
+ const w = world({ recorded, script });
+ w.setMem([3000, 9000]);
+ // The first tick's worker takes 25 minutes to free up: the recording grows
+ // under it, and the next tick takes all of it (capped at 20 min, then a
+ // catch-up tick at once) — never one tick per period that passed.
+ const transcribe = w.deps.transcribe!;
+ w.deps.transcribe = async (o) => {
+ const r = await transcribe(o);
+ if (w.calls.length === 1) recorded.set(file, 600 + 25 * 60);
+ return r;
+ };
+ script.push(
+ () => {}, // the memory wait
+ () => {}, // after tick 1
+ () => {}, // after tick 2 (0 ms: catching up)
+ async () => {
+ // after tick 3: the stream ends and lands.
+ await liveRecordingSidecar.write(videoDir, { ...record, status: "landed", kept: "new", landedPart: 0, endedAt: "2026-10-27T13:00:00Z" });
+ },
+ () => void w.setFinal(true), // the wait for the final transcript
+ );
+ const summary = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS }, onLog: (l) => w.lines.push(l), signal: w.ac.signal, deps: w.deps });
+
+ assert.deepEqual(w.calls, [
+ { from: 0, to: 598 },
+ { from: 583, to: 1783 },
+ { from: 1768, to: 2098 },
+ ]);
+ const doc = (await liveTranscriptSidecar.load(videoDir))!;
+ assert.equal(doc.status, "superseded");
+ assert.equal(doc.transcribedTo, 2098);
+ const starts = doc.cues.map((c) => c.start);
+ assert.deepEqual(starts, [...new Set(starts)], "no cue twice across the overlaps");
+ assert.equal(doc.cues.length, 35, "a cue a minute, 0:01 … 34:01");
+ assert.equal(doc.words.length, 35);
+ // The scan of each span, joined by window index across the overlaps.
+ assert.equal(doc.scan?.energy.length, 2098 / 0.5);
+ assert.equal(doc.landed?.check.verdict, "same-recording");
+ const state = (await livePreclipSidecar.load(videoDir))!;
+ assert.equal(state.status, "superseded");
+ assert.equal(state.ticks, 3);
+ assert.equal(state.skipped.memory, 1);
+ assert.ok(w.lines.some((l) => /tick delayed: MemAvailable 3000 MB is under the floor of 6000 MB/.test(l)));
+ // umtool: once per tick, once at the landing (with the check), once final.
+ assert.equal(w.mined.length, 5);
+ assert.deepEqual(w.mined[3], { slug: `${id}-live`, from: `${SLUG}/${id}`, check: doc.landed!.check });
+ assert.equal(w.mined[4]!.final, true);
+ assert.equal(summary.status, "superseded");
+});
+
+test("no new data is a skipped tick; a recording that lands nothing leaves the transcript provisional", async () => {
+ const id = "live002";
+ const { videoDir, stem, record } = await setup(id);
+ const recorded = new Map([[`${stem}.ts`, 300]]);
+ const script: (() => void | Promise<void>)[] = [
+ () => {}, // after tick 1; nothing new next time
+ async () => {
+ await liveRecordingSidecar.write(videoDir, { ...record, status: "failed", error: "the stream went private" });
+ },
+ ];
+ const w = world({ recorded, script });
+ const s = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps });
+ assert.equal(w.calls.length, 1);
+ const state = (await livePreclipSidecar.load(videoDir))!;
+ assert.equal(state.skipped["no new data"], 1);
+ assert.ok(state.log.some((l) => /no new data \(0 s new/.test(l)));
+ assert.equal(s.status, "stopped");
+ assert.equal((await liveTranscriptSidecar.load(videoDir))!.status, "live");
+ assert.equal(w.mined.length, 0, "mine: false");
+});
+
+test("a recorder restart on the same clock goes on; on another clock the transcript starts again", async () => {
+ for (const sameClock of [true, false]) {
+ const id = sameClock ? "live003" : "live004";
+ const { videoDir, stem, record } = await setup(id);
+ const stem2 = stemOf(id, "browser");
+ const recorded = new Map([[`${stem}.ts`, 600]]);
+ const script: (() => void | Promise<void>)[] = [
+ async () => {
+ // The yt-dlp part ended; the browser fallback records from the DVR start.
+ await writeFile(path.join(slugStore, `${stem2}.ts`), "growing");
+ recorded.set(`${stem2}.ts`, 900);
+ await liveRecordingSidecar.write(videoDir, {
+ ...record,
+ parts: [
+ { ...record.parts[0]!, endedAt: "2026-10-27T12:10:00Z" },
+ { method: "browser", url: "u2", fromStart: true, startedAt: "2026-10-27T12:10:00Z", stem: stem2 },
+ ],
+ });
+ },
+ () => {},
+ async () => {
+ await liveRecordingSidecar.write(videoDir, { ...record, status: "cancelled", endedAt: "x" });
+ },
+ ];
+ const w = world({
+ recorded,
+ script,
+ deps: { envelope: envelopeFor((f) => (sameClock || !f.includes("browser") ? 1 : 7)) },
+ });
+ await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps });
+ const doc = (await liveTranscriptSidecar.load(videoDir))!;
+ assert.equal(doc.basis?.stem, stem2);
+ if (sameClock) {
+ assert.deepEqual(w.calls, [{ from: 0, to: 598 }, { from: 583, to: 898 }]);
+ assert.equal(doc.restarts, 0);
+ } else {
+ assert.deepEqual(w.calls, [{ from: 0, to: 598 }, { from: 0, to: 898 }]);
+ assert.equal(doc.restarts, 1);
+ assert.equal(doc.transcribedTo, 898);
+ }
+ }
+});
+
+test("a landed video not the followed part: the clock check compares the fingerprint", async () => {
+ for (const [shift, verdict] of [[0, "same"], [1.5, "shifted"]] as const) {
+ const id = `live05${shift ? "b" : "a"}`;
+ const { videoDir, stem, record } = await setup(id);
+ const recorded = new Map([[`${stem}.ts`, 600]]);
+ const script: (() => void | Promise<void>)[] = [
+ async () => {
+ await liveRecordingSidecar.write(videoDir, { ...record, status: "landed", kept: "new" });
+ },
+ ];
+ const w = world({
+ recorded,
+ script,
+ deps: {
+ savedVideo: async () => "/store/landed.mp4",
+ envelope: envelopeFor(() => 1, (f) => (f === "/store/landed.mp4" ? -shift : 0)),
+ finalWaitMs: 0,
+ },
+ });
+ const s = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps });
+ assert.equal(s.check?.verdict, verdict, JSON.stringify(s.check));
+ if (verdict === "shifted") assert.equal(s.check?.lagSeconds, 1.5);
+ assert.equal(s.status, "waiting-final", "the final wait ran out");
+ const state = (await livePreclipSidecar.load(videoDir))!;
+ assert.ok(state.log.some((l) => /finalize/.test(l)));
+ // By hand, once the final transcript is here.
+ await writeFile(path.join(videoDir, "transcript.json"), "{}");
+ const mined: Record<string, unknown>[] = [];
+ const f = await finalizeLivePreclip({
+ paths,
+ slug: SLUG,
+ id,
+ deps: { mine: async (b) => (mined.push(b), { project: b.slug, created: false, proposals: 1, clips: 1 }) },
+ });
+ assert.equal(f.ok, true);
+ assert.equal(mined[0]!.final, true);
+ assert.equal((await liveTranscriptSidecar.load(videoDir))!.status, "superseded");
+ assert.equal((await livePreclipSidecar.load(videoDir))!.status, "superseded");
+ }
+});
+
+test("stopped: the job's cancel leaves the recording alone and says how to resume", async () => {
+ const id = "live006";
+ const { videoDir, stem } = await setup(id);
+ const recorded = new Map([[`${stem}.ts`, 600]]);
+ const w = world({ recorded, script: [] });
+ const s = await runLivePreclip({ paths, slug: SLUG, id, channelConfig: CONFIG, options: { ...PRECLIP_DEFAULTS, mine: false }, onLog: () => {}, signal: w.ac.signal, deps: w.deps });
+ assert.equal(s.status, "stopped");
+ assert.equal((await liveRecordingSidecar.load(videoDir))!.status, "recording");
+ assert.ok((await livePreclipSidecar.load(videoDir))!.log.some((l) => /resumes/.test(l)));
+});
+
+test("parseLivePreclipBody and memoryFloorMb", () => {
+ assert.deepEqual(parseLivePreclipBody({ slug: "a", id: "b" }), { ok: true, value: { slug: "a", id: "b", action: "start", options: { ...PRECLIP_DEFAULTS } } });
+ const r = parseLivePreclipBody({ slug: "a", id: "b", action: "start", everyMinutes: 5 });
+ assert.equal(r.ok && r.value.options.everyMinutes, 5);
+ assert.equal(parseLivePreclipBody({ slug: "a", id: "b", action: "go" }).ok, false);
+ assert.equal(parseLivePreclipBody({ slug: "a", id: "../x" }).ok, false);
+ assert.equal(memoryFloorMb({}), 6000);
+ assert.equal(memoryFloorMb({ HEAVY_MIN_FREE_MB: "4000" }), 4000);
+ assert.equal(memoryFloorMb({ HEAVY: "0" }), 0);
+});
diff --git a/common/controller/livePreclip.ts b/common/controller/livePreclip.ts
@@ -0,0 +1,787 @@
+// LIVE PRE-CLIP — `pnpm ops live-preclip`, record-live's `preclip` knob, the
+// video page's Live pre-clip panel (plans/live-preclip.md; the arithmetic is
+// lib/livePreclip.ts, the files lib/livePreclip-server.ts).
+//
+// ONE JOB PER STREAM (`live-preclip:<slug>:<id>`), beside the recorder's own,
+// never in its way: it only reads what the recorder has written. Every
+// `everyMinutes` a TICK:
+//
+// 1. reads live-recording.json and finds the part being written and the
+// file in it that holds the sound (findLiveSource);
+// 2. is skipped — and says so — when the machine is under the heavy slot's
+// memory floor (re-checked every minute), the store's disk is short, or
+// there are fewer than 30 s new ("no new data");
+// 3. transcribes ONLY the new span (from 15 s before the end of what is
+// transcribed to 2 s short of the live edge, at most maxChunkMinutes) on a
+// worker lease (transcribeFile.ts runTranscribeFile: the cut is `ffmpeg -ss
+// <from> -i <the growing file>`, in the work dir on the store's disk), with
+// word timings; the laugh scan (lib/clips/scan.mjs) reads the same WAV;
+// 4. splices the cues, words and scan into data/<id>/live-transcript.json on
+// the recording's clock — which IS the landed video's clock;
+// 5. hands it to umtool's clip finder (`POST /api/report/clips {mode:
+// "live"}`), which grows the stream's project.
+//
+// THE JOB IS THE QUEUE. One transcription is in flight at a time: while it
+// waits for a worker (the pool's "foreground" tier) or runs, nothing else is
+// asked for, and the next tick takes everything since — so a busy worker
+// coalesces ticks and they never pile up. Behind by more than a minute after a
+// tick (a late start, a long wait), the next one starts at once.
+//
+// WHEN THE STREAM ENDS (live-recording.json says it landed): the clock check
+// (the landed part is the one followed → "same recording"; else the audio
+// envelope of the landed video against the fingerprint taken while it was live),
+// then the wait for the final transcript (a stat every 2 minutes, up to a day),
+// then the supersede — the live transcript marked superseded, umtool told to
+// read the corpus from now on. A wait that runs out leaves "waiting-final";
+// `live-preclip {action: "finalize"}` finishes it.
+//
+// NO NETWORK REQUEST: the recorder's files, the worker pool, umtool on this
+// machine.
+
+import path from "node:path";
+import { mkdir, readdir, rm } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { getSettings } from "../lib/settings";
+import { getFreeBytes } from "../lib/diskSpace";
+import { formatBytes } from "../lib/format";
+import { liveRecordingSidecar } from "../lib/mediaImport-server";
+import type { LiveRecordingRecord } from "../lib/liveCapture";
+import { savedVideoDir } from "../lib/savedVideo";
+import { loadSavedVideo } from "../lib/savedVideo-server";
+import { savedVideoPath } from "../lib/savedVideo";
+import { englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus";
+import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl";
+import { getWorkerToken } from "../lib/workerToken";
+import {
+ FINGERPRINT_HOP_SECONDS,
+ FINGERPRINT_MAX_LAG_SECONDS,
+ PRECLIP_DEFAULTS,
+ PRECLIP_DEFAULT_MIN_FREE_MB,
+ PRECLIP_MIN_FREE_DISK_BYTES,
+ appendSpan,
+ clock,
+ compareEnvelopes,
+ emptyLiveTranscript,
+ fingerprintSpan,
+ judgeClock,
+ liveProjectSlug,
+ newPreclipState,
+ nextTickDelayMs,
+ parsePreclipKnob,
+ planTick,
+ spliceScan,
+ withLogLine,
+ withSkip,
+ type ClockCheck,
+ type LivePreclipState,
+ type LiveTranscriptDoc,
+ type LiveWord,
+ type PreclipOptions,
+ type ScanPart,
+} from "../lib/livePreclip";
+import {
+ findLiveSource,
+ livePreclipSidecar,
+ liveTranscriptSidecar,
+ preclipWorkDir,
+ probeWith,
+ readEnvelope,
+ type LiveSource,
+ type ProbeSeconds,
+} from "../lib/livePreclip-server";
+import type { Cue } from "../lib/vtt";
+import { getRegistry } from "../jobs/registry";
+import { runManagedFunction, type JobRunContext, type StreamActionResult } from "../jobs/streamCommand";
+import { runTranscribeFile } from "./transcribeFile";
+import { readMemAvailableMb } from "./persistVideos";
+
+export const LIVE_PRECLIP_JOB_KIND = "live-preclip";
+export const LIVE_PRECLIP_RESULT_MARKER = "@@live-preclip ";
+export const LIVE_PRECLIP_ACTIONS = ["start", "stop", "status", "finalize"] as const;
+export type LivePreclipAction = (typeof LIVE_PRECLIP_ACTIONS)[number];
+export const LIVE_PRECLIP_BODY_KEYS = [
+ "slug",
+ "id",
+ "action",
+ "everyMinutes",
+ "maxChunkMinutes",
+ "overlapSeconds",
+ "scan",
+ "mine",
+ "project",
+] as const;
+
+// How long the job waits for live-recording.json (a pre-clip asked for at the
+// same moment as the recording), and for the final transcript after the landing.
+export const RECORD_WAIT_MS = 10 * 60_000;
+export const FINAL_WAIT_MS = 24 * 3600_000;
+export const FINAL_POLL_MS = 2 * 60_000;
+export const MEMORY_POLL_MS = 60_000;
+export const SOURCE_POLL_MS = 30_000;
+
+export function livePreclipQueueKey(slug: string, id: string): string {
+ return `live-preclip:${slug}:${id}`;
+}
+
+/** settings.livePreclip over the built-in defaults. */
+export function preclipDefaults(): Omit<PreclipOptions, "project"> {
+ return { ...PRECLIP_DEFAULTS, ...(getSettings().livePreclip ?? {}) };
+}
+
+/** HEAVY_MIN_FREE_MB when set (0 = no floor), else the slot's 6000. */
+export function memoryFloorMb(env: Readonly<Record<string, string | undefined>> = process.env): number {
+ const raw = env.HEAVY_MIN_FREE_MB;
+ const n = raw === undefined || raw === "" ? NaN : Number(raw);
+ if (env.HEAVY === "0") return 0;
+ return Number.isFinite(n) && n >= 0 ? n : PRECLIP_DEFAULT_MIN_FREE_MB;
+}
+
+export type LivePreclipRequest = { slug: string; id: string; action: LivePreclipAction; options: PreclipOptions };
+
+type Check<T> = { ok: true; value: T } | { ok: false; error: string };
+
+const ID_RE = /^[\w.-]+$/;
+
+/** The ops body, judged without touching the disk. */
+export function parseLivePreclipBody(body: Record<string, unknown>, defaults = PRECLIP_DEFAULTS): Check<LivePreclipRequest> {
+ const slug = typeof body.slug === "string" ? body.slug.trim() : "";
+ if (!slug) return { ok: false, error: '"slug" is required' };
+ const id = typeof body.id === "string" ? body.id.trim() : "";
+ if (!id || !ID_RE.test(id) || id === "." || id === "..") return { ok: false, error: '"id" is required: the record\'s id' };
+ const action = body.action === undefined ? "start" : body.action;
+ if (typeof action !== "string" || !(LIVE_PRECLIP_ACTIONS as readonly string[]).includes(action)) {
+ return { ok: false, error: `"action" is one of ${LIVE_PRECLIP_ACTIONS.join(", ")}` };
+ }
+ const knob: Record<string, unknown> = {};
+ for (const k of ["everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"]) if (body[k] !== undefined) knob[k] = body[k];
+ const options = parsePreclipKnob(Object.keys(knob).length ? knob : true, defaults);
+ if (!options || "error" in options) return { ok: false, error: options ? options.error : "no options" };
+ return { ok: true, value: { slug, id, action: action as LivePreclipAction, options } };
+}
+
+// --- the dependencies (all replaceable in a test) ----------------------------------
+
+export type TranscribeSpan = (o: {
+ file: string;
+ from: number;
+ to: number;
+ scratchParent: string;
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+ ctx?: JobRunContext;
+ withWav?: (wav: string, seconds: number) => Promise<void>;
+}) => Promise<{ cues: Cue[]; words: LiveWord[]; worker: string | null; ms: number; waitedMs: number }>;
+
+export type MineLive = (body: {
+ slug: string;
+ from: string;
+ final?: boolean;
+ check?: ClockCheck;
+}) => Promise<{ project: string; created: boolean; proposals: number; clips: number; href?: string; notes?: string[] }>;
+
+export type LivePreclipDeps = {
+ now?: () => Date;
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
+ memAvailableMb?: () => Promise<number | null>;
+ memoryFloorMb?: number;
+ freeBytes?: (dir: string) => Promise<number>;
+ probe?: ProbeSeconds;
+ transcribe?: TranscribeSpan;
+ // The laugh scan of a span's WAV, on the recording's clock (null: none).
+ scanWav?: (wav: string, from: number, seconds: number, scratch: string) => Promise<ScanPart | null>;
+ envelope?: (file: string, from: number, dur: number) => Promise<number[] | null>;
+ // Null: umtool is not configured (mining is skipped, said once).
+ mine?: MineLive | null;
+ savedVideo?: (videoDir: string) => Promise<string | null>;
+ hasFinalTranscript?: (videoDir: string) => Promise<boolean>;
+ recordWaitMs?: number;
+ finalWaitMs?: number;
+ finalPollMs?: number;
+ memoryPollMs?: number;
+ sourcePollMs?: number;
+};
+
+function sleep(ms: number, signal: AbortSignal): Promise<void> {
+ return new Promise((resolve) => {
+ if (signal.aborted || ms <= 0) return resolve();
+ const t = setTimeout(done, ms);
+ function done() {
+ clearTimeout(t);
+ signal.removeEventListener("abort", done);
+ resolve();
+ }
+ signal.addEventListener("abort", done, { once: true });
+ });
+}
+
+export function defaultTranscribe(paths: Paths): TranscribeSpan {
+ return async (o) => {
+ const r = await runTranscribeFile({
+ paths,
+ request: { path: o.file, start: o.from, end: o.to, words: true },
+ onLog: o.onLog,
+ signal: o.signal,
+ ...(o.ctx ? { ctx: o.ctx } : {}),
+ tier: "foreground",
+ scratchParent: o.scratchParent,
+ ...(o.withWav ? { withWav: o.withWav } : {}),
+ });
+ return {
+ cues: r.cues,
+ words: (r.words ?? []).map((w) => ({ w: w.w, start: w.start, end: w.end, ...(w.conf !== undefined ? { conf: w.conf } : {}) })),
+ worker: r.worker.id,
+ ms: r.durationMs,
+ waitedMs: r.waitedMs,
+ };
+ };
+}
+
+export function defaultScanWav(paths: Paths): NonNullable<LivePreclipDeps["scanWav"]> {
+ return async (wav, from, seconds, scratch) => {
+ const { resolveTagger, runAudioScan } = await import("../lib/clips/scan.mjs");
+ const tagger = resolveTagger({ repoRoot: paths.monorepoRoot, settings: getSettings() });
+ const scan = await runAudioScan({
+ file: wav,
+ duration: seconds,
+ clock: from,
+ tagger: tagger.available ? tagger : null,
+ scratch,
+ ffmpeg: paths.ffmpegBin,
+ });
+ return { t0: scan.t0, hop: scan.hop, window: scan.window, energy: scan.energy, laugh: scan.laugh, model: scan.model?.file ?? null };
+ };
+}
+
+async function umtoolBody(res: Response): Promise<Record<string, unknown>> {
+ try {
+ const j = (await res.json()) as unknown;
+ return j && typeof j === "object" && !Array.isArray(j) ? (j as Record<string, unknown>) : {};
+ } catch {
+ return {};
+ }
+}
+
+/** umtool's clips route, live mode: synchronous, a proposal pass. */
+export function umtoolMiner(umtool: string, token: string, doFetch: typeof fetch = fetch): MineLive {
+ return async (body) => {
+ let res: Response;
+ try {
+ res = await doFetch(`${umtool}/api/report/clips`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
+ body: JSON.stringify({ mode: "live", ...body }),
+ signal: AbortSignal.timeout(5 * 60_000),
+ });
+ } catch (e) {
+ throw new Error(`umtool at ${umtool} did not answer (${(e as Error).message}) — is it running?`);
+ }
+ const j = await umtoolBody(res);
+ if (!res.ok) throw new Error(`umtool refused the live clips request (HTTP ${res.status}): ${typeof j.error === "string" ? j.error : "no reason given"}`);
+ return {
+ project: String(j.project ?? body.slug),
+ created: j.created === true,
+ proposals: typeof j.proposals === "number" ? j.proposals : 0,
+ clips: typeof j.clips === "number" ? j.clips : 0,
+ ...(typeof j.href === "string" ? { href: j.href } : {}),
+ ...(Array.isArray(j.notes) ? { notes: j.notes.filter((n): n is string => typeof n === "string") } : {}),
+ };
+ };
+}
+
+export async function hasCorpusTranscript(videoDir: string): Promise<boolean> {
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ return entries.includes(WHISPER_FILENAME) || englishVttsByPreference(entries).length > 0;
+}
+
+// --- the run ---------------------------------------------------------------------------
+
+export type LivePreclipRunOpts = {
+ paths: Paths;
+ slug: string;
+ id: string;
+ channelConfig: ChannelConfig;
+ options: PreclipOptions;
+ onLog: (s: string) => void;
+ signal: AbortSignal;
+ ctx?: JobRunContext;
+ deps?: LivePreclipDeps;
+};
+
+export type LivePreclipSummary = {
+ slug: string;
+ id: string;
+ status: LivePreclipState["status"];
+ ticks: number;
+ transcribedSeconds: number;
+ cues: number;
+ project: string | null;
+ check?: ClockCheck;
+};
+
+export async function runLivePreclip(o: LivePreclipRunOpts): Promise<LivePreclipSummary> {
+ const { paths, slug, id, options, signal } = o;
+ const deps = o.deps ?? {};
+ const now = deps.now ?? (() => new Date());
+ const wait = deps.sleep ?? sleep;
+ const probe = deps.probe ?? probeWith(paths.ffprobeBin);
+ const transcribe = deps.transcribe ?? defaultTranscribe(paths);
+ const scanWav = deps.scanWav ?? defaultScanWav(paths);
+ const envelope = deps.envelope ?? ((f: string, a: number, d: number) => readEnvelope(f, a, d, paths.ffmpegBin));
+ const memory = deps.memAvailableMb ?? readMemAvailableMb;
+ const floor = deps.memoryFloorMb ?? memoryFloorMb();
+ const free = deps.freeBytes ?? getFreeBytes;
+ const hasFinal = deps.hasFinalTranscript ?? hasCorpusTranscript;
+ let mine: MineLive | null;
+ if (deps.mine !== undefined) mine = deps.mine;
+ else {
+ const umtool = resolveUmtoolUrl();
+ const token = getWorkerToken();
+ mine = umtool && token ? umtoolMiner(umtool, token) : null;
+ }
+ const say = (s: string) => o.onLog(s.endsWith("\n") ? s : `${s}\n`);
+
+ const videoDir = path.join(paths.channelsDir, slug, "data", id);
+ const slugStore = path.dirname(savedVideoDir(paths, o.channelConfig, slug, id));
+ const workDir = preclipWorkDir(slugStore, id);
+ const project = options.project ?? liveProjectSlug(id);
+
+ let state: LivePreclipState = newPreclipState(options, now(), o.ctx?.jobId);
+ const prevState = await livePreclipSidecar.load(videoDir);
+ if (prevState) state = { ...state, ticks: prevState.ticks, skipped: prevState.skipped, log: prevState.log, ...(prevState.mined ? { mined: prevState.mined } : {}) };
+ let doc: LiveTranscriptDoc = (await liveTranscriptSidecar.load(videoDir)) ?? emptyLiveTranscript(now());
+ if (doc.status !== "live") doc = { ...emptyLiveTranscript(now()), restarts: doc.restarts };
+ const note = async (line: string) => {
+ say(`pre-clip: ${line}`);
+ state = withLogLine(state, line, now());
+ await livePreclipSidecar.write(videoDir, state);
+ };
+ const saveDoc = () => liveTranscriptSidecar.write(videoDir, doc);
+ const summary = (): LivePreclipSummary => ({
+ slug,
+ id,
+ status: state.status,
+ ticks: state.ticks,
+ transcribedSeconds: doc.transcribedTo,
+ cues: doc.cues.length,
+ project: state.mined?.project ?? null,
+ ...(state.check ? { check: state.check } : {}),
+ });
+ const mineNow = async (extra: { final?: boolean; check?: ClockCheck } = {}) => {
+ if (!options.mine) return;
+ if (!mine) {
+ if (!state.log.some((l) => /umtool is not configured/.test(l))) {
+ await note("umtool is not configured on the editor (UMTOOL_URL, WORKER_TOKEN): the live transcript is kept, no windows are mined");
+ }
+ return;
+ }
+ try {
+ const r = await mine({ slug: project, from: `${slug}/${id}`, ...extra });
+ state = { ...state, mined: { project: r.project, ...(r.href ? { url: r.href } : {}), proposals: r.proposals, clips: r.clips, at: now().toISOString() } };
+ await note(`umtool: ${r.created ? "made" : "grew"} project ${r.project} — ${r.proposals} proposal(s), ${r.clips} clip(s)${extra.final ? " (final: it reads the corpus now)" : ""}`);
+ for (const n of r.notes ?? []) await note(`umtool: ${n}`);
+ } catch (e) {
+ state = { ...state, mined: { ...(state.mined ?? { project, proposals: 0, clips: 0, at: now().toISOString() }), error: (e as Error).message } };
+ await note(`umtool: not mined this tick (${(e as Error).message})`);
+ }
+ };
+
+ await note(
+ `following ${slug}/${id}: a tick every ${options.everyMinutes} min, at most ${options.maxChunkMinutes} min of audio each, ` +
+ `${options.overlapSeconds} s overlap; ${options.scan ? "laugh scan on" : "no laugh scan"}; ${options.mine ? `windows into umtool project ${project}` : "no mining"}` +
+ `${doc.transcribedTo > 0 ? `; resuming at ${clock(doc.transcribedTo)}` : ""}`,
+ );
+
+ // 0. The recording's record (record-live writes it before its recorder starts).
+ const waitedFrom = Date.now();
+ let record: LiveRecordingRecord | null = null;
+ while (!signal.aborted) {
+ record = await liveRecordingSidecar.load(videoDir);
+ if (record) break;
+ if (Date.now() - waitedFrom >= (deps.recordWaitMs ?? RECORD_WAIT_MS)) {
+ state = { ...state, status: "failed", error: `${slug}/${id} has no live-recording.json: is it being recorded (pnpm ops record-live)?` };
+ await note(state.error!);
+ throw new Error(state.error);
+ }
+ await wait(5_000, signal);
+ }
+
+ // 1. The ticks, while it records.
+ let lastWait = "";
+ let memoryHeld = false;
+ while (!signal.aborted) {
+ record = (await liveRecordingSidecar.load(videoDir)) ?? record;
+ if (!record || record.status !== "recording") break;
+ const src = await findLiveSource({ slugStore, id, record, probe });
+ if ("wait" in src) {
+ if (src.wait !== lastWait) {
+ state = withSkip(state, "unreadable");
+ await note(`waiting: ${src.wait}`);
+ lastWait = src.wait;
+ }
+ await wait(deps.sourcePollMs ?? SOURCE_POLL_MS, signal);
+ continue;
+ }
+ lastWait = "";
+
+ // The basis: the part a transcript is on.
+ if (doc.basis && doc.basis.stem !== src.stem) {
+ const moved = await rebase(src);
+ if (moved === "wait") {
+ await wait(deps.sourcePollMs ?? SOURCE_POLL_MS, signal);
+ continue;
+ }
+ }
+ if (!doc.basis) doc = { ...doc, basis: { stem: src.stem, audioFile: src.audioFile, kind: src.kind } };
+
+ // The gates.
+ const mem = floor > 0 ? await memory() : null;
+ if (mem !== null && mem < floor) {
+ if (!memoryHeld) {
+ state = withSkip(state, "memory");
+ await note(`tick delayed: MemAvailable ${mem} MB is under the floor of ${floor} MB (HEAVY_MIN_FREE_MB); re-checked every minute`);
+ memoryHeld = true;
+ }
+ await wait(deps.memoryPollMs ?? MEMORY_POLL_MS, signal);
+ continue;
+ }
+ if (memoryHeld) await note(`memory back over the floor (${mem ?? "?"} MB): ticking`);
+ memoryHeld = false;
+ const freeBytes = await free(slugStore).catch(() => Infinity);
+ if (freeBytes < PRECLIP_MIN_FREE_DISK_BYTES) {
+ state = withSkip(state, "disk");
+ await note(`tick skipped: the store's disk has ${formatBytes(freeBytes)} free (a tick needs ${formatBytes(PRECLIP_MIN_FREE_DISK_BYTES)})`);
+ await wait(options.everyMinutes * 60_000, signal);
+ continue;
+ }
+
+ const recorded = (await probe(src.audioPath))?.seconds ?? null;
+ state = { ...state, recordedSeconds: recorded };
+ // The fingerprint of the basis, once it holds enough (the landing's check).
+ if (!doc.fingerprint && recorded !== null) {
+ const span = fingerprintSpan(recorded);
+ // At 60 s in, once that is well behind the live edge.
+ if (span && span.from > 0 && recorded >= span.from + span.dur + 5) {
+ const env = await envelope(src.audioPath, span.from, span.dur);
+ if (env) doc = { ...doc, fingerprint: { from: span.from, hop: FINGERPRINT_HOP_SECONDS, env } };
+ }
+ }
+ const plan = planTick({ transcribedTo: doc.transcribedTo, recordedSeconds: recorded, opts: options });
+ if (plan.action === "wait") {
+ state = withSkip(state, "no new data");
+ await note(`tick skipped: ${plan.reason}`);
+ await saveDoc();
+ await wait(options.everyMinutes * 60_000, signal);
+ continue;
+ }
+
+ // The tick.
+ const n = state.ticks + 1;
+ await mkdir(workDir, { recursive: true });
+ const scanned: { part: ScanPart | null } = { part: null };
+ const began = Date.now();
+ try {
+ say(`pre-clip: tick ${n}: transcribing ${clock(plan.from)}–${clock(plan.to)} of ${src.audioFile}${plan.behind > 0 ? ` (${clock(plan.behind)} more behind it)` : ""}`);
+ const t = await transcribe({
+ file: src.audioPath,
+ from: plan.from,
+ to: plan.to,
+ scratchParent: workDir,
+ onLog: say,
+ signal,
+ ...(o.ctx ? { ctx: o.ctx } : {}),
+ ...(options.scan
+ ? {
+ withWav: async (wav: string, seconds: number) => {
+ try {
+ scanned.part = await scanWav(wav, plan.from, seconds, path.join(workDir, "scan"));
+ } catch (e) {
+ say(`pre-clip: the laugh scan of this span failed (${(e as Error).message}); the transcript is kept`);
+ }
+ },
+ }
+ : {}),
+ });
+ if (signal.aborted) break;
+ doc = appendSpan(doc, { from: plan.from, to: plan.to, cues: t.cues, words: t.words, worker: t.worker, ms: t.ms, waitedMs: t.waitedMs }, now());
+ const scanPart = scanned.part;
+ if (scanPart) {
+ try {
+ doc = { ...doc, scan: spliceScan(doc.scan, scanPart) };
+ } catch (e) {
+ say(`pre-clip: the scan was not joined (${(e as Error).message})`);
+ }
+ }
+ await saveDoc();
+ state = { ...state, ticks: n, transcribedSeconds: doc.transcribedTo };
+ await note(
+ `tick ${n}: ${clock(plan.from)}–${clock(plan.to)} transcribed — ${t.cues.length} cue(s), ${t.words.length} word(s)` +
+ `${t.worker ? ` on ${t.worker}` : ""} in ${Math.round(t.ms / 1000)} s${t.waitedMs >= 1000 ? ` after ${Math.round(t.waitedMs / 1000)} s waiting for the worker` : ""}` +
+ `${scanPart ? `; scanned (${scanPart.model ?? "energy only"})` : ""}`,
+ );
+ } catch (e) {
+ if (signal.aborted) break;
+ state = withSkip(state, "failed");
+ await note(`tick ${n} failed after ${Math.round((Date.now() - began) / 1000)} s: ${(e as Error).message}`);
+ await wait(options.everyMinutes * 60_000, signal);
+ continue;
+ } finally {
+ await rm(workDir, { recursive: true, force: true }).catch(() => {});
+ }
+ await mineNow();
+ await livePreclipSidecar.write(videoDir, state);
+ await wait(nextTickDelayMs(plan.behind, options), signal);
+ }
+ await rm(workDir, { recursive: true, force: true }).catch(() => {});
+
+ if (signal.aborted) {
+ state = { ...state, status: "stopped" };
+ await note(`stopped at ${clock(doc.transcribedTo)} transcribed (the recording goes on; live-preclip {action: "start"} resumes)`);
+ await saveDoc();
+ say(`${LIVE_PRECLIP_RESULT_MARKER}${JSON.stringify(summary())}`);
+ return summary();
+ }
+
+ // 2. The stream is over.
+ if (!record || record.kept === undefined) {
+ state = { ...state, status: "stopped" };
+ await note(`the recording ended ${record?.status ?? "?"} with nothing landed${record?.error ? ` (${record.error})` : ""}: the live transcript stays provisional`);
+ say(`${LIVE_PRECLIP_RESULT_MARKER}${JSON.stringify(summary())}`);
+ return summary();
+ }
+ const landedPart = record.landedPart !== undefined ? record.parts[record.landedPart] : undefined;
+ const check = await clockCheck(landedPart?.stem ?? null);
+ doc = { ...doc, status: "landed", landed: { at: now().toISOString(), check } };
+ await saveDoc();
+ state = { ...state, status: "waiting-final", check };
+ await note(`landed: ${check.why}${check.verdict === "same" || check.verdict === "same-recording" ? "" : " — the project's windows are flagged"}`);
+ await mineNow({ check });
+
+ // 3. The final transcript supersedes the live one.
+ const until = Date.now() + (deps.finalWaitMs ?? FINAL_WAIT_MS);
+ let said = false;
+ while (!signal.aborted && !(await hasFinal(videoDir))) {
+ if (!said) {
+ await note("waiting for the final transcript (the landing handed the recording to the transcription lane)");
+ said = true;
+ }
+ if (Date.now() >= until) {
+ await note('no final transcript yet: once there is one, pnpm ops live-preclip {"action": "finalize"} finishes the supersede');
+ say(`${LIVE_PRECLIP_RESULT_MARKER}${JSON.stringify(summary())}`);
+ return summary();
+ }
+ await wait(deps.finalPollMs ?? FINAL_POLL_MS, signal);
+ }
+ if (signal.aborted) {
+ await note('stopped while waiting for the final transcript: pnpm ops live-preclip {"action": "finalize"} finishes it');
+ say(`${LIVE_PRECLIP_RESULT_MARKER}${JSON.stringify(summary())}`);
+ return summary();
+ }
+ await supersede();
+ say(`${LIVE_PRECLIP_RESULT_MARKER}${JSON.stringify(summary())}`);
+ return summary();
+
+ // --- the pieces ---
+
+ // A new part is being written (a restart, a fallback): its clock is the
+ // old one when its audio at the fingerprint's span matches; else the live
+ // transcript starts again on it.
+ async function rebase(src: LiveSource): Promise<"same" | "restarted" | "wait"> {
+ const fp = doc.fingerprint;
+ if (fp) {
+ const have = (await probe(src.audioPath))?.seconds ?? 0;
+ const pad = FINGERPRINT_MAX_LAG_SECONDS;
+ if (have < fp.from + fp.env.length * fp.hop + pad) {
+ if (lastWait !== `rebase ${src.stem}`) {
+ await note(`the recording moved to ${src.stem}; comparing its clock once it holds ${clock(fp.from + fp.env.length * fp.hop + pad)}`);
+ lastWait = `rebase ${src.stem}`;
+ }
+ return "wait";
+ }
+ const env = await envelope(src.audioPath, Math.max(0, fp.from - pad), fp.env.length * fp.hop + 2 * pad);
+ const padFrames = Math.round(Math.min(pad, fp.from) / fp.hop);
+ const verdict = env ? judgeClock(compareEnvelopes(fp.env, env, padFrames), fp.hop, now()) : null;
+ if (verdict?.verdict === "same") {
+ doc = { ...doc, basis: { stem: src.stem, audioFile: src.audioFile, kind: src.kind } };
+ await note(`the recording moved to ${src.stem}: the same clock (${verdict.why}); the live transcript goes on`);
+ return "same";
+ }
+ await note(`the recording moved to ${src.stem} on another clock (${verdict ? verdict.why : "its audio could not be read"}): the live transcript starts again on it`);
+ } else {
+ await note(`the recording moved to ${src.stem} before a fingerprint was taken: the live transcript starts again on it`);
+ }
+ doc = { ...emptyLiveTranscript(now()), restarts: doc.restarts + 1, basis: { stem: src.stem, audioFile: src.audioFile, kind: src.kind } };
+ await saveDoc();
+ return "restarted";
+ }
+
+ async function clockCheck(landedStem: string | null): Promise<ClockCheck> {
+ const at = now().toISOString();
+ if (doc.basis && landedStem && landedStem === doc.basis.stem) {
+ return { verdict: "same-recording", why: `the landed video is the recording the live transcript followed (${landedStem})`, at };
+ }
+ const fp = doc.fingerprint;
+ if (!fp) return { verdict: "unverified", why: "no fingerprint was taken while it was live", at };
+ const saved = await (deps.savedVideo ?? defaultSavedVideo)(videoDir);
+ if (!saved) return { verdict: "unverified", why: "the landed video's saved container is not readable", at };
+ const pad = Math.min(FINGERPRINT_MAX_LAG_SECONDS, fp.from);
+ const env = await envelope(saved, fp.from - pad, fp.env.length * fp.hop + 2 * pad);
+ if (!env) return { verdict: "unverified", why: "the landed video's audio could not be read at the fingerprint", at };
+ return judgeClock(compareEnvelopes(fp.env, env, Math.round(pad / fp.hop)), fp.hop, now());
+ }
+
+ async function supersede() {
+ doc = { ...doc, status: "superseded", supersededAt: now().toISOString() };
+ await saveDoc();
+ state = { ...state, status: "superseded" };
+ await note("the final transcript is here: the live transcript is superseded");
+ await mineNow({ final: true, ...(state.check ? { check: state.check } : {}) });
+ await livePreclipSidecar.write(videoDir, state);
+ }
+}
+
+async function defaultSavedVideo(videoDir: string): Promise<string | null> {
+ const pointer = await loadSavedVideo(videoDir).catch(() => null);
+ return pointer ? savedVideoPath(pointer) : null;
+}
+
+// --- the ops actions -----------------------------------------------------------------
+
+function runningJobOf(slug: string, id: string) {
+ const key = livePreclipQueueKey(slug, id);
+ return getRegistry()
+ .list()
+ .find((j) => j.queueKey === key && (j.status === "running" || j.status === "queued"));
+}
+
+export async function startLivePreclipJob(o: {
+ paths: Paths;
+ slug: string;
+ id: string;
+ channelConfig: ChannelConfig;
+ options: PreclipOptions;
+ // Refuse unless the recording is in progress (an ops start); record-live
+ // starts it before its record says so.
+ requireRecording?: boolean;
+ deps?: LivePreclipDeps;
+}): Promise<StreamActionResult> {
+ const videoDir = path.join(o.paths.channelsDir, o.slug, "data", o.id);
+ if (o.requireRecording !== false) {
+ const rec = await liveRecordingSidecar.load(videoDir);
+ if (!rec) return { ok: false, error: `${o.slug}/${o.id} is not being recorded (no live-recording.json): start it with record-live {"preclip": true}` };
+ if (rec.status !== "recording") {
+ return { ok: false, error: `${o.slug}/${o.id}'s recording is ${rec.status}, not in progress${rec.status === "landed" || rec.status === "cancelled" ? ' — "finalize" supersedes a live transcript once the final one is here' : ""}` };
+ }
+ }
+ const busy = runningJobOf(o.slug, o.id);
+ if (busy) return { ok: false, info: true, error: `Pre-clip is already running for ${o.slug}/${o.id} (job ${busy.id})` };
+ return runManagedFunction({
+ kind: LIVE_PRECLIP_JOB_KIND,
+ queueKey: livePreclipQueueKey(o.slug, o.id),
+ paths: o.paths,
+ channelSlug: o.slug,
+ videoId: o.id,
+ network: false,
+ fn: async (onLog, signal, _p, ctx) => {
+ await runLivePreclip({ paths: o.paths, slug: o.slug, id: o.id, channelConfig: o.channelConfig, options: o.options, onLog, signal, ctx, ...(o.deps ? { deps: o.deps } : {}) });
+ },
+ });
+}
+
+/** Stop a running pre-clip (the recording is not touched). */
+export function stopLivePreclip(slug: string, id: string): { ok: true; jobId: string } | { ok: false; error: string } {
+ const job = runningJobOf(slug, id);
+ if (!job) return { ok: false, error: `no pre-clip is running for ${slug}/${id}` };
+ getRegistry().cancel(job.id);
+ return { ok: true, jobId: job.id };
+}
+
+export type LivePreclipStatusView = {
+ slug: string;
+ id: string;
+ job: { id: string; status: string } | null;
+ state: LivePreclipState | null;
+ transcript: {
+ status: LiveTranscriptDoc["status"];
+ transcribedTo: number;
+ cues: number;
+ words: number;
+ chunks: number;
+ restarts: number;
+ basis: LiveTranscriptDoc["basis"];
+ landed?: LiveTranscriptDoc["landed"];
+ lastCues: Cue[];
+ } | null;
+ recording: { status: string; parts: number } | null;
+};
+
+export async function livePreclipStatus(paths: Paths, slug: string, id: string): Promise<LivePreclipStatusView> {
+ const videoDir = path.join(paths.channelsDir, slug, "data", id);
+ const [state, doc, rec] = await Promise.all([livePreclipSidecar.load(videoDir), liveTranscriptSidecar.load(videoDir), liveRecordingSidecar.load(videoDir)]);
+ const job = runningJobOf(slug, id);
+ return {
+ slug,
+ id,
+ job: job ? { id: job.id, status: job.status } : null,
+ state,
+ transcript: doc
+ ? {
+ status: doc.status,
+ transcribedTo: doc.transcribedTo,
+ cues: doc.cues.length,
+ words: doc.words.length,
+ chunks: doc.chunks.length,
+ restarts: doc.restarts,
+ basis: doc.basis,
+ ...(doc.landed ? { landed: doc.landed } : {}),
+ lastCues: doc.cues.slice(-8),
+ }
+ : null,
+ recording: rec ? { status: rec.status, parts: rec.parts.length } : null,
+ };
+}
+
+/** The supersede by hand (`action: "finalize"`), once the final transcript is here. */
+export async function finalizeLivePreclip(o: {
+ paths: Paths;
+ slug: string;
+ id: string;
+ options?: Pick<PreclipOptions, "project">;
+ deps?: Pick<LivePreclipDeps, "mine" | "hasFinalTranscript" | "now">;
+}): Promise<{ ok: true; project: string | null; check: ClockCheck | null } | { ok: false; error: string }> {
+ const videoDir = path.join(o.paths.channelsDir, o.slug, "data", o.id);
+ const now = o.deps?.now ?? (() => new Date());
+ if (runningJobOf(o.slug, o.id)) return { ok: false, error: `pre-clip is still running for ${o.slug}/${o.id}: it supersedes by itself, or stop it first` };
+ const doc = await liveTranscriptSidecar.load(videoDir);
+ if (!doc) return { ok: false, error: `${o.slug}/${o.id} has no live transcript` };
+ if (!(await (o.deps?.hasFinalTranscript ?? hasCorpusTranscript)(videoDir))) {
+ return { ok: false, error: `${o.slug}/${o.id} has no final transcript yet (transcript.json or an English caption track)` };
+ }
+ const state = await livePreclipSidecar.load(videoDir);
+ const check = doc.landed?.check ?? state?.check ?? null;
+ await liveTranscriptSidecar.write(videoDir, { ...doc, status: "superseded", supersededAt: now().toISOString() });
+ let mine = o.deps?.mine;
+ if (mine === undefined) {
+ const umtool = resolveUmtoolUrl();
+ const token = getWorkerToken();
+ mine = umtool && token ? umtoolMiner(umtool, token) : null;
+ }
+ const project = o.options?.project ?? state?.mined?.project ?? liveProjectSlug(o.id);
+ let mined: Awaited<ReturnType<MineLive>> | null = null;
+ if (mine) mined = await mine({ slug: project, from: `${o.slug}/${o.id}`, final: true, ...(check ? { check } : {}) });
+ if (state) {
+ await livePreclipSidecar.write(
+ videoDir,
+ withLogLine(
+ {
+ ...state,
+ status: "superseded",
+ ...(mined ? { mined: { project: mined.project, proposals: mined.proposals, clips: mined.clips, at: now().toISOString() } } : {}),
+ },
+ `finalized by hand: the live transcript is superseded${mined ? `; umtool project ${mined.project} reads the corpus now` : ""}`,
+ now(),
+ ),
+ );
+ }
+ return { ok: true, project: mined?.project ?? null, check };
+}
diff --git a/common/controller/livePreclipMedia.test.ts b/common/controller/livePreclipMedia.test.ts
@@ -0,0 +1,195 @@
+// The snapshot and the clock of a recording IN PROGRESS, on real files: an
+// MPEG-TS (the muxed recorders) and a separate fMP4 video + audio pair
+// (YouTube's), each written in increments at arbitrary byte boundaries the way
+// a recorder appends, with a 1 kHz burst at a known second of the stream.
+// Tiny (160x90, 90 s), and skipped where ffmpeg has no libx264.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { appendFile, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { execa } from "execa";
+import { windowWavArgs } from "./transcribeFile";
+import type { LiveRecordingRecord } from "../lib/liveCapture";
+import { cutLiveWindow, findLiveSource, liveWindowCutArgs, probeWith, readEnvelope } from "../lib/livePreclip-server";
+import { compareEnvelopes, envelopeOf, judgeClock, planTick } from "../lib/livePreclip";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-preclip-"));
+const FF = process.env.FFMPEG_BIN ?? "ffmpeg";
+const FP = process.env.FFPROBE_BIN ?? "ffprobe";
+const probe = probeWith(FP);
+const BURST_AT = 47;
+const AUDIO = `aevalsrc='if(between(t,${BURST_AT},${BURST_AT}.5),0.8*sin(2*PI*1000*t),0.05*sin(2*PI*220*t)*(1+sin(2*PI*0.7*t)))':s=16000:d=90`;
+
+let haveX264 = true;
+const ts = path.join(ROOT, "src.ts");
+const fv = path.join(ROOT, "src-video.mp4");
+const fa = path.join(ROOT, "src-audio.m4a");
+try {
+ // A stream whose clock does not start at 0 (a TS's first PTS is wherever
+ // the broadcast's was): -output_ts_offset.
+ await execa(FF, [
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", "testsrc2=s=160x90:r=10:d=90", "-f", "lavfi", "-i", AUDIO,
+ "-c:v", "libx264", "-preset", "ultrafast", "-g", "20", "-c:a", "aac", "-b:a", "48k",
+ "-output_ts_offset", "1000", "-f", "mpegts", ts,
+ ]);
+ await execa(FF, ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=160x90:r=10:d=90", "-c:v", "libx264", "-preset", "ultrafast", "-g", "20", "-movflags", "+frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", fv]);
+ await execa(FF, ["-v", "error", "-y", "-f", "lavfi", "-i", AUDIO, "-c:a", "aac", "-b:a", "48k", "-movflags", "+frag_keyframe+empty_moov+default_base_moof", "-frag_duration", "2000000", "-f", "mp4", fa]);
+} catch {
+ haveX264 = false;
+}
+
+/** A recorder, appending `src` to `dst` in pieces cut at arbitrary bytes. */
+async function grower(src: string, dst: string) {
+ const bytes = await readFile(src);
+ let at = 0;
+ await writeFile(dst, Buffer.alloc(0));
+ return async (share: number) => {
+ const to = Math.min(bytes.length, Math.floor(bytes.length * share) + 37);
+ if (to > at) await appendFile(dst, bytes.subarray(at, to));
+ at = to;
+ };
+}
+
+const peakAt = (env: number[], hop = 0.1) => env.indexOf(Math.max(...env)) * hop;
+
+function recording(stem: string): LiveRecordingRecord {
+ return {
+ status: "recording",
+ url: "https://example.com/live",
+ platform: "youtube",
+ fromStart: true,
+ startedAt: "2026-10-27T12:00:00Z",
+ parts: [{ method: "ytdlp", url: "https://example.com/live", fromStart: true, startedAt: "2026-10-27T12:00:00Z", stem }],
+ };
+}
+
+test("a growing MPEG-TS: its length grows, a span is read by time on the landed clock", async (t) => {
+ if (!haveX264) return t.skip("no ffmpeg with libx264 here");
+ const store = path.join(ROOT, "ts-store");
+ await mkdir(store, { recursive: true });
+ const stem = ".vid1.live-2026-10-27T12-00-00-000Z.ytdlp";
+ const part = path.join(store, `${stem}.ts`);
+ const grow = await grower(ts, part);
+ await grow(0.4);
+ const src = await findLiveSource({ slugStore: store, id: "vid1", record: recording(stem), probe });
+ assert.ok(!("wait" in src), JSON.stringify(src));
+ if ("wait" in src) return;
+ assert.equal(src.kind, "muxed");
+ assert.equal(src.audioPath, part);
+ const early = (await probe(part))!.seconds!;
+ assert.ok(early > 25 && early < 45, `40% of 90 s reads as ${early}`);
+
+ await grow(1);
+ const full = (await probe(part))!.seconds!;
+ assert.ok(full > 88, `the whole stream reads as ${full}`);
+ // The tick after the first: from 15 s before what was transcribed.
+ const plan = planTick({ transcribedTo: 40, recordedSeconds: full, opts: { maxChunkMinutes: 20, overlapSeconds: 15 } });
+ assert.equal(plan.action, "transcribe");
+ if (plan.action !== "transcribe") return;
+ assert.equal(plan.from, 25);
+ const wav = path.join(ROOT, "ts-span.wav");
+ await execa(FF, windowWavArgs(part, wav, { start: plan.from, end: plan.to }));
+ const env = envelopeOf(await decodeWav(wav), 16000);
+ // The burst at 47 s of the stream is 22 s into a span from 25 s — so second
+ // S of the growing file is second S of the stream, whatever its first PTS.
+ assert.ok(Math.abs(peakAt(env) + plan.from - BURST_AT) < 0.25, `burst at ${peakAt(env) + plan.from}`);
+
+ // The landing remuxes `-c copy` to mp4 (no -copyts): the burst is at 47 s there too.
+ const landed = path.join(ROOT, "landed.mp4");
+ await execa(FF, ["-v", "error", "-y", "-i", part, "-map", "0:v?", "-map", "0:a?", "-c", "copy", "-movflags", "+faststart", "-f", "mp4", landed]);
+ const landedEnv = (await readEnvelope(landed, 40, 15, FF))!;
+ assert.ok(Math.abs(peakAt(landedEnv) + 40 - BURST_AT) < 0.25, `landed burst at ${peakAt(landedEnv) + 40}`);
+ // And the clock check says so: the same span, fingerprinted on the growing
+ // file and on the landed one.
+ const ref = (await readEnvelope(part, 40, 15, FF))!;
+ const probed = (await readEnvelope(landed, 38, 19, FF))!;
+ assert.equal(judgeClock(compareEnvelopes(ref, probed, 20), 0.1, new Date()).verdict, "same");
+
+ // A window cut now from the growing file: picture and sound, the burst 2 s in.
+ const videoDir = path.join(ROOT, "ts-video-dir");
+ const win = await cutLiveWindow({ ffmpegBin: FF, videoDir, source: src, from: 45, to: 52, requestedBy: "test" });
+ assert.equal(win.file, "45.00-52.00.mp4");
+ const p = await probe(win.path);
+ assert.ok(p?.hasVideo && p.hasAudio);
+ assert.ok(Math.abs(p!.seconds! - 7) < 0.3, `window of ${p!.seconds} s`);
+ const wenv = (await readEnvelope(win.path, 0, 7, FF))!;
+ assert.ok(Math.abs(peakAt(wenv) - 2) < 0.25, `window burst at ${peakAt(wenv)}`);
+ // The picture from the window's first second (a TS seeks by timestamp, not
+ // to a keyframe: the cut's run-up is what keeps the first GOP).
+ const starts = await execa(FP, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=start_time", "-of", "csv=p=0", win.path]);
+ assert.ok(Number(String(starts.stdout).trim()) < 0.2, `picture starts at ${starts.stdout}`);
+ const side =JSON.parse(await readFile(path.join(videoDir, "clips", "45.00-52.00.json"), "utf8"));
+ assert.equal(side.source, "live-recording");
+});
+
+test("a growing separate pair: the audio stream is read, the window takes both", async (t) => {
+ if (!haveX264) return t.skip("no ffmpeg with libx264 here");
+ const store = path.join(ROOT, "pair-store");
+ await mkdir(store, { recursive: true });
+ const stem = ".vid2.live-2026-10-27T12-00-00-000Z.ytdlp";
+ const video = path.join(store, `${stem}.f270.mp4`);
+ const audio = path.join(store, `${stem}.f234.mp4`);
+ const gv = await grower(fv, video);
+ const ga = await grower(fa, audio);
+ for (const share of [0.2, 0.55, 1]) {
+ await gv(share);
+ await ga(share);
+ const src = await findLiveSource({ slugStore: store, id: "vid2", record: recording(stem), probe });
+ assert.ok(!("wait" in src), JSON.stringify(src));
+ if ("wait" in src) return;
+ assert.equal(src.kind, "separate");
+ assert.equal(src.audioPath, audio);
+ assert.equal(src.videoPath, video);
+ }
+ const seconds = (await probe(audio))!.seconds!;
+ assert.ok(seconds > 85, `audio reads ${seconds}`);
+ const wav = path.join(ROOT, "pair-span.wav");
+ await execa(FF, windowWavArgs(audio, wav, { start: 40, end: 60 }));
+ const env = envelopeOf(await decodeWav(wav), 16000);
+ assert.ok(Math.abs(peakAt(env) + 40 - BURST_AT) < 0.25, `burst at ${peakAt(env) + 40}`);
+
+ const args = liveWindowCutArgs(video, audio, 45, 52, "out.mp4");
+ assert.deepEqual(args.filter((a) => a === "-i").length, 2);
+ assert.ok(args.includes("1:a:0"));
+ const videoDir = path.join(ROOT, "pair-video-dir");
+ const src = await findLiveSource({ slugStore: store, id: "vid2", record: recording(stem), probe });
+ if ("wait" in src) return;
+ const win = await cutLiveWindow({ ffmpegBin: FF, videoDir, source: src, from: 45, to: 52, requestedBy: "test" });
+ const p = await probe(win.path);
+ assert.ok(p?.hasVideo && p.hasAudio, JSON.stringify(p));
+ const wenv = (await readEnvelope(win.path, 0, 7, FF))!;
+ assert.ok(Math.abs(peakAt(wenv) - 2) < 0.25, `window burst at ${peakAt(wenv)}`);
+});
+
+test("findLiveSource: an ended part is not followed; nothing written yet is a wait", async () => {
+ const store = path.join(ROOT, "wait-store");
+ await mkdir(store, { recursive: true });
+ const stem = ".vid3.live-2026-10-27T12-00-00-000Z.ytdlp";
+ const rec = recording(stem);
+ assert.deepEqual(await findLiveSource({ slugStore: store, id: "vid3", record: rec, probe }), { wait: "the recorder has written nothing yet" });
+ await writeFile(path.join(store, `${stem}.ts`), "not media");
+ const unreadable = await findLiveSource({ slugStore: store, id: "vid3", record: rec, probe });
+ assert.ok("wait" in unreadable && /no audio ffprobe can read/.test(unreadable.wait));
+ const ended = { ...rec, parts: [{ ...rec.parts[0]!, endedAt: "2026-10-27T13:00:00Z" }] };
+ assert.deepEqual(await findLiveSource({ slugStore: store, id: "vid3", record: ended, probe }), { wait: "no part is being recorded" });
+});
+
+/** A 16 kHz mono s16le WAV's samples. */
+async function decodeWav(file: string): Promise<Float32Array> {
+ const buf = await readFile(file);
+ // The data chunk: after the 44-byte header ffmpeg writes (plus a LIST chunk, sometimes).
+ const data = buf.indexOf(Buffer.from("data"));
+ const start = data + 8;
+ const n = Math.floor((buf.length - start) / 2);
+ const out = new Float32Array(n);
+ for (let i = 0; i < n; i += 1) out[i] = buf.readInt16LE(start + i * 2) / 32768;
+ return out;
+}
+
+test.after(async () => {
+ await rm(ROOT, { recursive: true, force: true });
+ void stat;
+});
diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts
@@ -163,6 +163,51 @@ test("Rumble path A: yt-dlp --live-from-start into a staging part, then landed;
assert.deepEqual((await readdir(slugStore)).filter((n) => n.startsWith(".")), [], "no staging left");
});
+test("preclip: the knob parsed (implies transcribe), the pre-clip asked for once the first part begins, each part's stem recorded", async () => {
+ const p = parseRecordLiveRequest({ slug: "s", url: "https://rumble.com/v1x-y.html", preclip: { everyMinutes: 5 } });
+ assert.ok(!("error" in p));
+ if ("error" in p) return;
+ assert.equal(p.preclip?.everyMinutes, 5);
+ assert.equal(p.preclip?.maxChunkMinutes, 20);
+ assert.equal(p.transcribe, true, "preclip implies the landing's transcription");
+ const off = parseRecordLiveRequest({ slug: "s", url: "https://rumble.com/v1x-y.html", preclip: true, transcribe: false });
+ assert.ok(!("error" in off) && off.transcribe === false && off.preclip?.everyMinutes === 10);
+ assert.match((parseRecordLiveRequest({ slug: "s", url: "https://rumble.com/v1x-y.html", preclip: { every: 1 } }) as { error: string }).error, /preclip/);
+
+ const asked: { slug: string; id: string; every: number }[] = [];
+ const log: string[] = [];
+ await recordLiveRun({
+ paths,
+ request: { slug: SLUG, url: "https://rumble.com/v3ccccc-show.html", preclip: p.preclip },
+ plan: { url: "https://rumble.com/v3ccccc-show.html", platform: "rumble", id: "v3ccccc" },
+ channelConfig: CONFIG,
+ cookiePolicy: NO_COOKIES,
+ onLog: (l) => void log.push(l),
+ signal: new AbortController().signal,
+ startPreclip: async (slug, id, options) => {
+ asked.push({ slug, id, every: options.everyMinutes });
+ return { ok: true, jobId: "job-pre" };
+ },
+ deps: {
+ refresh: refreshWith(RUMBLE_META),
+ fetchText: async () => DVR,
+ spawn: async ({ args }) => {
+ // The pre-clip is asked for while the recorder runs.
+ await new Promise((r) => setImmediate(r));
+ await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=60;");
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ land,
+ freeBytes: async () => 1e15,
+ handoff,
+ },
+ });
+ assert.deepEqual(asked, [{ slug: SLUG, id: "v3ccccc", every: 5 }]);
+ assert.ok(log.some((l) => /Live pre-clip: job job-pre/.test(l)));
+ const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", SLUG, "data", "v3ccccc"));
+ assert.match(rec?.parts[0]?.stem ?? "", /^\.v3ccccc\.live-.+\.ytdlp$/);
+});
+
test("yt-dlp cannot start at the start: --no-live-from-start with ffmpeg at index 0; the longest part lands", async () => {
const calls: string[][] = [];
const s = await recordLiveRun({
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -101,6 +101,7 @@ import {
import { refreshVideoMetadata, type RefreshRunner } from "./refreshVideoMetadata";
import { findVideoSourceUrl } from "./undownloadedVideos";
import { jitterYtdlpSleeps } from "../lib/jitter";
+import { parsePreclipKnob, type PreclipOptions } from "../lib/livePreclip";
import { jitterMs } from "../lib/jitter";
export const RECORD_LIVE_JOB_KIND = "record-live";
@@ -117,6 +118,7 @@ export const RECORD_LIVE_BODY_KEYS = [
"doNotClean",
"note",
"dryRun",
+ "preclip",
] as const;
// The user agent path B's ffmpeg and the playlist reads present (the pinned
@@ -151,9 +153,16 @@ export type RecordLiveRequest = {
doNotClean?: boolean;
note?: string;
dryRun?: boolean;
+ // LIVE PRE-CLIP (plans/live-preclip.md): transcribe and mine the recording
+ // while it records — its own job (controller/livePreclip.ts), started once
+ // the first part begins. Implies `transcribe` unless that is false.
+ preclip?: PreclipOptions;
};
-export function parseRecordLiveRequest(body: Record<string, unknown>): RecordLiveRequest | { error: string } {
+export function parseRecordLiveRequest(
+ body: Record<string, unknown>,
+ preclipDefaults?: Omit<PreclipOptions, "project">,
+): RecordLiveRequest | { error: string } {
const str = (k: string) => (typeof body[k] === "string" ? (body[k] as string).trim() : undefined);
const slug = str("slug");
if (!slug) return { error: '"slug" is required' };
@@ -181,6 +190,12 @@ export function parseRecordLiveRequest(body: Record<string, unknown>): RecordLiv
}
const note = str("note");
if (note) out.note = note;
+ const preclip = parsePreclipKnob(body.preclip, preclipDefaults);
+ if (preclip && "error" in preclip) return preclip;
+ if (preclip) {
+ out.preclip = preclip;
+ if (out.transcribe === undefined) out.transcribe = true;
+ }
return out;
}
@@ -518,6 +533,9 @@ export type RecordLiveJobOpts = {
channelConfig: ChannelConfig;
cookiePolicy: ResolvedCookiePolicy;
requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>;
+ // The pre-clip job for this stream (request.preclip), asked for once the
+ // first part begins.
+ startPreclip?: (slug: string, id: string, options: PreclipOptions) => Promise<{ ok: boolean; jobId?: string; error?: string }>;
afterRun?: () => void | Promise<void>;
deps?: RecordLiveDeps;
};
@@ -695,6 +713,12 @@ export async function recordLiveRun(
: `Would record with yt-dlp ${fromStart ? "--live-from-start" : ""}${BROWSER_FALLBACK_PLATFORMS.has(plan.platform) ? ", the page's own playlist by ffmpeg if yt-dlp is refused" : ""}.`,
);
say("Then the longest part is landed as the video's source (the store, audio, the archive line) and handed to the transcription lane.");
+ if (req.preclip) {
+ say(
+ `Live pre-clip: every ${req.preclip.everyMinutes} min the new span is transcribed (at most ${req.preclip.maxChunkMinutes} min a tick)` +
+ `${req.preclip.mine ? " and mined into a umtool project" : ""}, while it records.`,
+ );
+ }
summary.status = "landed";
say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`);
return summary;
@@ -811,10 +835,22 @@ export async function recordLiveRun(
// Each part by its stem's name (the files on disk are read back by it).
const parts: { part: LivePart; stem: string }[] = [];
+ let preclipAsked = false;
const begin = (method: LivePartMethod, url: string, file: string, fs: boolean) => {
- const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString() };
+ const stem = path.basename(file).replace(/\.ts$/, "");
+ const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString(), stem };
record.parts.push(part);
- parts.push({ part, stem: path.basename(file).replace(/\.ts$/, "") });
+ parts.push({ part, stem });
+ if (req.preclip && !preclipAsked && opts.startPreclip) {
+ preclipAsked = true;
+ // After the save that lists this part (the pre-clip reads the record).
+ setImmediate(() => {
+ void opts.startPreclip!(req.slug, id, req.preclip!).then(
+ (r) => say(r.ok ? `Live pre-clip: job ${r.jobId} (every ${req.preclip!.everyMinutes} min)` : `Live pre-clip was not started: ${r.error ?? "no job"}`),
+ (e: Error) => say(`Live pre-clip was not started: ${e.message}`),
+ );
+ });
+ }
return part;
};
const finish = (part: LivePart, note: string) => {
diff --git a/common/controller/transcribeFile.ts b/common/controller/transcribeFile.ts
@@ -475,13 +475,21 @@ export type RunTranscribeFileOpts = {
onLog: (line: string) => void;
signal?: AbortSignal;
ctx?: Pick<JobRunContext, "jobId" | "addTask" | "updateTask" | "removeTask" | "recordTaskDone">;
+ // The pool tier asked for (default: transcribeFileTier of the cut's length).
+ tier?: SchedulerTier;
+ // Where the scratch dir is made (default the OS temp dir). Live pre-clip
+ // passes its work dir on the store's disk: /tmp may be a RAM tmpfs.
+ scratchParent?: string;
+ // Called with the cut WAV once it is transcribed, before the scratch goes:
+ // what live pre-clip's laugh scan reads, so the span is decoded once.
+ withWav?: (wav: string, seconds: number) => Promise<void>;
};
export async function runTranscribeFile(
opts: RunTranscribeFileOpts,
): Promise<TranscribeFileResult> {
const { request: req, onLog, paths } = opts;
- const scratch = await mkdtemp(path.join(os.tmpdir(), "archilyzer-transcribe-"));
+ const scratch = await mkdtemp(path.join(opts.scratchParent ?? os.tmpdir(), "archilyzer-transcribe-"));
try {
const wav = path.join(scratch, AUDIO_NAME);
onLog(`Cutting ${describeRequest(req)} to 16 kHz mono WAV…`);
@@ -508,7 +516,7 @@ export async function runTranscribeFile(
// there (the last attempt's, when a transport failure moved it).
const used: { worker?: Worker; startedAt?: number } = {};
const audioSec = wavSeconds(wavStat.size);
- const tier = transcribeFileTier(audioSec);
+ const tier = opts.tier ?? transcribeFileTier(audioSec);
onLog(
`${req.workerId ? `Waiting for worker ${req.workerId}` : "Waiting for a free local worker"}` +
(tier === "urgent"
@@ -550,6 +558,7 @@ export async function runTranscribeFile(
const raw = await readFile(path.join(scratch, "transcript.json"), "utf8");
const transcriptFormat = detectTranscriptFormat(raw) ?? "whisper-json";
const cues = offsetCues(parseTranscriptJson(raw, transcriptFormat), req.start ?? 0);
+ if (opts.withWav) await opts.withWav(wav, audioSec);
return {
version: 1,
path: req.path,
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -905,6 +905,38 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
network: true,
needsMedia: true,
},
+ // LIVE PRE-CLIP (plans/live-preclip.md, controller/livePreclip.ts — `pnpm
+ // ops live-preclip`, record-live's `preclip`): a recording in progress
+ // transcribed and mined while it records — a tick every few minutes reads
+ // only the new span of the growing file (never writing it), transcribes it
+ // on a worker lease, splices it into live-transcript.json and grows the
+ // stream's umtool project. One per stream on its own queue
+ // (`live-preclip:<slug>:<id>`), beside the recorder's: a stop never touches
+ // the recording. No network: the recorder's files, the pool, umtool here.
+ // `needsText`: its sidecars are beside the record. Not replayable: the ops
+ // start resumes from the live transcript.
+ "live-preclip": {
+ kind: "live-preclip",
+ label: "Live pre-clip",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ network: false,
+ needsText: true,
+ },
+ // A SHAREABLE CLIP OF A STREAM STILL LIVE (controller/liveClip.ts — `pnpm
+ // ops live-clip`): the window cut now from the growing recording (no
+ // network), then umtool's short of it with the live transcript's captions,
+ // followed to the end. Its own queue (`live-clip`), one at a time.
+ "live-clip": {
+ kind: "live-clip",
+ label: "Live clip",
+ drainable: false,
+ replayable: false,
+ queueKeyStrategy: "custom",
+ network: false,
+ needsText: true,
+ },
// FIND CLIPS (release 36 lane A, controller/findClips.ts — the video page's
// Find clips, `pnpm ops find-clips`): the clip finder's chain for one video,
// each step skipped when its output exists — persist the source, the corpus
diff --git a/common/lib/clipWindow.ts b/common/lib/clipWindow.ts
@@ -201,7 +201,9 @@ export type ClipProvenance = {
// "saved-video" for a window cut from the video's saved container (release 21
// D2, lib/savedVideoWindow-server.ts); "stored-media-url" for one fetched from
// the media URL its metadata.info.json stores (release 32 R5,
- // lib/storedMediaUrl.ts), with that URL's host in `sourceHost`. Absent on a
+ // lib/storedMediaUrl.ts), with that URL's host in `sourceHost`;
+ // "live-recording" for one cut from a live recording still in progress (live
+ // pre-clip's share, lib/livePreclip-server.ts cutLiveWindow). Absent on a
// window fetched through the page.
source?: ClipWindowSource;
sourceHost?: string;
@@ -241,7 +243,7 @@ export function coerceClipCopy(v: unknown): ClipCopy | undefined {
return { from: r.from as ClipCopy["from"], url: r.url };
}
-export const CLIP_WINDOW_SOURCES = ["saved-video", "stored-media-url"] as const;
+export const CLIP_WINDOW_SOURCES = ["saved-video", "stored-media-url", "live-recording"] as const;
export type ClipWindowSource = (typeof CLIP_WINDOW_SOURCES)[number];
const str = (v: unknown): string | undefined =>
diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts
@@ -420,6 +420,9 @@ export type LivePartMethod = "ytdlp" | "browser" | "vod-poll";
export type LivePart = {
method: LivePartMethod;
+ // The part's stem in the store's slug dir (livePartFiles): which files on
+ // disk are this part's — what live pre-clip follows while it records.
+ stem?: string;
url: string;
fromStart: boolean;
startedAt: string;
diff --git a/common/lib/livePreclip-server.ts b/common/lib/livePreclip-server.ts
@@ -0,0 +1,209 @@
+// LIVE PRE-CLIP — the files (plans/live-preclip.md): its two sidecars, which
+// file of a recording in progress a tick reads, how long it is, its audio's
+// envelope, and a window cut out of it.
+//
+// EVERY READ HERE IS OF BYTES ALREADY WRITTEN. A recorder appends (MPEG-TS
+// packets, fMP4 fragments, Kick's segments); nothing here writes, renames or
+// truncates a part, so the recorder is never disturbed. ffmpeg reading a growing
+// file stops at what is there (a partial last packet or fragment is dropped,
+// measured 2026-10-27), and every span asked for ends PRECLIP_EDGE_SECONDS short
+// of the live edge.
+//
+// SERVER-ONLY (node:fs, ffmpeg).
+
+import path from "node:path";
+import { mkdir, readdir, rename, rm, stat } from "node:fs/promises";
+import { execa } from "execa";
+import { sidecar, sidecarField } from "./sidecar-server";
+import {
+ LIVE_PRECLIP_FILENAME,
+ LIVE_TRANSCRIPT_FILENAME,
+ coerceLivePreclipState,
+ coerceLiveTranscript,
+ envelopeOf,
+ FINGERPRINT_HOP_SECONDS,
+ type LiveBasis,
+} from "./livePreclip";
+import { livePartFiles, type LivePart, type LiveRecordingRecord } from "./liveCapture";
+import { EVIDENCE_AUDIO_BITRATE, EVIDENCE_CRF, EVIDENCE_MAX_HEIGHT, EVIDENCE_MAX_WIDTH, probeMedia } from "./evidenceClip-server";
+import { clipWindowFile, type ClipProvenance } from "./clipWindow";
+import { clipWindowPath, writeClipProvenance, type ClipWindow } from "./clipWindow-server";
+import { tmpPathFor } from "./jsonFile-server";
+import { decodeSpan } from "./montage/voiceMatch.mjs";
+
+export const liveTranscriptSidecar = sidecar(LIVE_TRANSCRIPT_FILENAME, sidecarField(coerceLiveTranscript), { indent: 0 });
+export const livePreclipSidecar = sidecar(LIVE_PRECLIP_FILENAME, sidecarField(coerceLivePreclipState));
+
+// The pre-clip's scratch (each tick's WAV, the scan's chunks): beside the
+// recording's parts, on the store's disk — never /tmp, a RAM tmpfs here.
+export function preclipWorkDir(slugStore: string, id: string): string {
+ return path.join(slugStore, `.${id}.preclip`);
+}
+
+export type ProbeSeconds = (file: string) => Promise<{ seconds: number | null; hasVideo: boolean; hasAudio: boolean } | null>;
+
+export function probeWith(ffprobeBin: string): ProbeSeconds {
+ return async (file) => {
+ const p = await probeMedia(file, ffprobeBin);
+ return p ? { seconds: p.durationSec, hasVideo: p.hasVideo, hasAudio: p.hasAudio } : null;
+ };
+}
+
+export type LiveSource = LiveBasis & {
+ // Absolute paths: the file a tick reads (audio), and the picture's file when
+ // it is another one (a separate pair).
+ audioPath: string;
+ videoPath: string | null;
+ part: LivePart | null;
+};
+
+const sizeOf = (f: string) => stat(f).then((s) => s.size, () => 0);
+
+/**
+ * THE FILE A TICK READS: of the parts the recording lists without an end (the
+ * ones being written), a from-start one before one from now (Kick's VOD before
+ * its channel), then the one with the most bytes; in it, the muxed file, or of
+ * a separate pair the stream ffprobe hears audio in. A reason instead when
+ * there is nothing readable yet.
+ */
+export async function findLiveSource(o: {
+ slugStore: string;
+ id: string;
+ record: LiveRecordingRecord;
+ probe: ProbeSeconds;
+}): Promise<LiveSource | { wait: string }> {
+ const names = await readdir(o.slugStore).catch(() => [] as string[]);
+ const groups = livePartFiles(o.id, names);
+ const open = o.record.parts.filter((p) => !p.endedAt);
+ const ranked: { part: LivePart | null; stem: string; bytes: number }[] = [];
+ for (const g of groups) {
+ const part = o.record.parts.find((p) => p.stem === g.stem) ?? null;
+ // A part the record says has ended is not the one being written.
+ if (part?.endedAt) continue;
+ // With the record listing open parts, an unlisted group is an earlier run's.
+ if (open.length && !part) continue;
+ let bytes = 0;
+ for (const f of [...g.finished, ...g.streams]) bytes += await sizeOf(path.join(o.slugStore, f));
+ if (bytes > 0) ranked.push({ part, stem: g.stem, bytes });
+ }
+ if (!ranked.length) return { wait: open.length ? "the recorder has written nothing yet" : "no part is being recorded" };
+ ranked.sort((a, b) => Number(b.part?.fromStart ?? false) - Number(a.part?.fromStart ?? false) || b.bytes - a.bytes);
+ const best = ranked[0]!;
+ const g = groups.find((x) => x.stem === best.stem)!;
+ const at = (n: string) => path.join(o.slugStore, n);
+ // Muxed (or yt-dlp's finished merge): one file with the sound.
+ for (const f of g.finished) {
+ const p = await o.probe(at(f));
+ if (p?.hasAudio) return { stem: g.stem, audioFile: f, kind: "muxed", audioPath: at(f), videoPath: p.hasVideo ? at(f) : null, part: best.part };
+ }
+ let audio: string | null = null;
+ let video: string | null = null;
+ for (const f of g.streams) {
+ const p = await o.probe(at(f));
+ if (!p) continue;
+ if (p.hasAudio && p.hasVideo) return { stem: g.stem, audioFile: f, kind: "muxed", audioPath: at(f), videoPath: at(f), part: best.part };
+ if (p.hasAudio && !audio) audio = f;
+ else if (p.hasVideo && !video) video = f;
+ }
+ if (audio) return { stem: g.stem, audioFile: audio, kind: "separate", audioPath: at(audio), videoPath: video ? at(video) : null, part: best.part };
+ return { wait: `${g.stem} holds no audio ffprobe can read yet` };
+}
+
+/** The RMS envelope (FINGERPRINT_HOP_SECONDS frames) of [from, from + dur) of a file's audio; null when ffmpeg reads nothing. */
+export async function readEnvelope(file: string, from: number, dur: number, ffmpegBin: string): Promise<number[] | null> {
+ try {
+ const rate = 8000;
+ const samples = await decodeSpan(file, Math.max(0, from), dur, { ffmpeg: ffmpegBin, rate });
+ if (samples.length < rate) return null;
+ return envelopeOf(samples, rate, FINGERPRINT_HOP_SECONDS);
+ } catch {
+ return null;
+ }
+}
+
+// Seconds a cut seeks BEFORE the window, then decodes and drops: an MPEG-TS
+// seeks by timestamp, not to a keyframe (measured 2026-10-27: an input `-ss`
+// into a TS with a 2 s GOP lost the first 1.1 s of picture), so the picture
+// needs a GOP of run-up. The sound is exact either way.
+export const LIVE_CUT_PREROLL_SECONDS = 10;
+
+/**
+ * ffmpeg's cut of [a, b] seconds from a recording into a window, in the
+ * clip-window cache's format (evidenceClip-server's: H.264 inside 1280×720 +
+ * AAC in an mp4, the first frame the asked-for second): seeked on the input
+ * LIVE_CUT_PREROLL_SECONDS early and trimmed on the output, with the sound from
+ * a second input for a separate pair.
+ */
+export function liveWindowCutArgs(video: string | null, audio: string, a: number, b: number, out: string): string[] {
+ const seek = Math.max(0, a - LIVE_CUT_PREROLL_SECONDS);
+ const input = (f: string) => ["-ss", seek.toFixed(3), "-i", f];
+ const trim = ["-ss", (a - seek).toFixed(3), "-t", (b - a).toFixed(3)];
+ const sound = ["-c:a", "aac", "-b:a", EVIDENCE_AUDIO_BITRATE, "-ac", "2"];
+ const tail = ["-map_metadata", "-1", "-sn", "-dn", "-movflags", "+faststart", "-f", "mp4", out];
+ const head = ["-nostdin", "-v", "error", "-y"];
+ if (!video) return [...head, ...input(audio), ...trim, "-map", "0:a:0", "-vn", ...sound, ...tail];
+ const pair = video !== audio;
+ return [
+ ...head,
+ ...input(video),
+ ...(pair ? input(audio) : []),
+ ...trim,
+ "-map", "0:v:0",
+ "-map", pair ? "1:a:0" : "0:a:0?",
+ "-vf", `scale='min(${EVIDENCE_MAX_WIDTH},iw)':'min(${EVIDENCE_MAX_HEIGHT},ih)':force_original_aspect_ratio=decrease:force_divisible_by=2,format=yuv420p`,
+ "-c:v", "libx264", "-preset", "medium", "-profile:v", "high", "-crf", String(EVIDENCE_CRF),
+ ...sound,
+ ...tail,
+ ];
+}
+
+/**
+ * A window of the recording in progress, cut NOW (the snapshot on demand):
+ * into data/<id>/clips/<from>-<to>.mp4 with its provenance (`source:
+ * "live-recording"`), through a temp name no window parser accepts, so a
+ * reader never sees half of one.
+ */
+export async function cutLiveWindow(opts: {
+ ffmpegBin: string;
+ videoDir: string;
+ source: Pick<LiveSource, "audioPath" | "videoPath" | "stem">;
+ from: number;
+ to: number;
+ requestedBy: string;
+ reason?: string;
+ clipId?: string;
+ manifest?: string;
+ signal?: AbortSignal;
+}): Promise<ClipWindow> {
+ const dest = clipWindowPath(opts.videoDir, opts.from, opts.to);
+ await mkdir(path.dirname(dest), { recursive: true });
+ const tmp = tmpPathFor(dest);
+ try {
+ const r = await execa(opts.ffmpegBin, liveWindowCutArgs(opts.source.videoPath, opts.source.audioPath, opts.from, opts.to, tmp), {
+ reject: false,
+ timeout: 10 * 60_000,
+ ...(opts.signal ? { cancelSignal: opts.signal } : {}),
+ });
+ if (r.exitCode !== 0) {
+ const err = String(r.stderr ?? "").trim().split("\n").slice(-3).join(" | ");
+ throw new Error(`ffmpeg could not cut ${opts.from}–${opts.to} s from the recording (${opts.source.stem})${err ? `: ${err}` : ""}`);
+ }
+ const bytes = (await stat(tmp)).size;
+ await rename(tmp, dest);
+ const now = new Date().toISOString();
+ const provenance: ClipProvenance = {
+ requestedBy: opts.requestedBy,
+ ...(opts.manifest ? { manifest: opts.manifest } : {}),
+ ...(opts.clipId ? { clipId: opts.clipId } : {}),
+ ...(opts.reason ? { reason: opts.reason } : {}),
+ requestedAt: now,
+ bytes,
+ fetchedAt: now,
+ source: "live-recording",
+ };
+ await writeClipProvenance(opts.videoDir, opts.from, opts.to, provenance);
+ return { file: clipWindowFile(opts.from, opts.to), path: dest, from: opts.from, to: opts.to, bytes, provenance };
+ } finally {
+ await rm(tmp, { force: true }).catch(() => {});
+ }
+}
diff --git a/common/lib/livePreclip.test.ts b/common/lib/livePreclip.test.ts
@@ -0,0 +1,205 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ LIVE_CLIP_MAX_SECONDS,
+ PRECLIP_DEFAULTS,
+ PRECLIP_EDGE_SECONDS,
+ appendSpan,
+ coerceLivePreclipState,
+ coerceLiveTranscript,
+ compareEnvelopes,
+ emptyLiveTranscript,
+ envelopeOf,
+ fingerprintSpan,
+ judgeClock,
+ liveClipTooLong,
+ checkLiveWindow,
+ liveProjectSlug,
+ newPreclipState,
+ nextTickDelayMs,
+ parsePreclipKnob,
+ planTick,
+ spliceAt,
+ spliceCut,
+ spliceScan,
+ withLogLine,
+ withSkip,
+} from "./livePreclip";
+
+const now = new Date("2026-10-27T12:00:00Z");
+
+test("parsePreclipKnob: off, defaults, keys over the defaults, refusals", () => {
+ assert.equal(parsePreclipKnob(undefined), null);
+ assert.equal(parsePreclipKnob(false), null);
+ assert.deepEqual(parsePreclipKnob(true), { ...PRECLIP_DEFAULTS });
+ assert.deepEqual(parsePreclipKnob(true, { ...PRECLIP_DEFAULTS, everyMinutes: 5 }), { ...PRECLIP_DEFAULTS, everyMinutes: 5 });
+ assert.deepEqual(parsePreclipKnob({ everyMinutes: 3, scan: false, project: "demo-live" }), {
+ ...PRECLIP_DEFAULTS,
+ everyMinutes: 3,
+ scan: false,
+ project: "demo-live",
+ });
+ assert.match((parsePreclipKnob({ everyMinutes: 0 }) as { error: string }).error, /everyMinutes/);
+ assert.match((parsePreclipKnob({ every: 3 }) as { error: string }).error, /does not take "every"/);
+ assert.match((parsePreclipKnob({ project: "Not A Slug" }) as { error: string }).error, /project/);
+ assert.match((parsePreclipKnob("yes") as { error: string }).error, /preclip/);
+ assert.match((parsePreclipKnob({ maxChunkMinutes: 2, overlapSeconds: 60 }) as { error: string }).error, /overlap/);
+});
+
+test("liveProjectSlug: the id, lowercased, -live", () => {
+ assert.equal(liveProjectSlug("5-XlMxKT494"), "5-xlmxkt494-live");
+ assert.equal(liveProjectSlug("v7h8pxg"), "v7h8pxg-live");
+ assert.ok(liveProjectSlug("x".repeat(200)).length <= 80);
+});
+
+test("planTick: no new data, the first tick from 0, the overlap, the cap, behind", () => {
+ const opts = { maxChunkMinutes: 20, overlapSeconds: 15 };
+ assert.deepEqual(planTick({ transcribedTo: 0, recordedSeconds: null, opts }).action, "wait");
+ const idle = planTick({ transcribedTo: 600, recordedSeconds: 620, opts });
+ assert.equal(idle.action, "wait");
+ assert.match((idle as { reason: string }).reason, /no new data \(18 s new/);
+ assert.deepEqual(planTick({ transcribedTo: 0, recordedSeconds: 600, opts }), { action: "transcribe", from: 0, to: 598, behind: 0 });
+ assert.deepEqual(planTick({ transcribedTo: 598, recordedSeconds: 1200, opts }), { action: "transcribe", from: 583, to: 1198, behind: 0 });
+ // Two hours behind (the worker was busy, or pre-clip started late): one chunk, the rest behind.
+ const behind = planTick({ transcribedTo: 0, recordedSeconds: 7200, opts });
+ assert.deepEqual(behind, { action: "transcribe", from: 0, to: 1200, behind: 7200 - PRECLIP_EDGE_SECONDS - 1200 });
+ assert.equal(nextTickDelayMs(5998, { everyMinutes: 10 }), 0);
+ assert.equal(nextTickDelayMs(0, { everyMinutes: 10 }), 600_000);
+});
+
+test("planTick coalesces: however many periods passed, one tick covers what is new (up to the cap)", () => {
+ // The worker was busy for 25 minutes; five 5-minute ticks came due. One
+ // tick, from the overlap to the edge — never five.
+ const p = planTick({ transcribedTo: 300, recordedSeconds: 300 + 25 * 60, opts: { maxChunkMinutes: 30, overlapSeconds: 15 } });
+ assert.deepEqual(p, { action: "transcribe", from: 285, to: 300 + 25 * 60 - PRECLIP_EDGE_SECONDS, behind: 0 });
+});
+
+test("spliceAt / spliceCut: the old before the overlap's middle, the new from it, no duplicate", () => {
+ assert.equal(spliceCut(600, 585), 592.5);
+ assert.equal(spliceCut(600, 600), 600);
+ const old = [
+ { start: 580, end: 588, text: "a" },
+ { start: 588, end: 596, text: "b (cut short by the boundary)" },
+ ];
+ const incoming = [
+ { start: 586, end: 590, text: "a-tail" },
+ { start: 588.1, end: 597, text: "b whole" },
+ { start: 597, end: 603, text: "c" },
+ ];
+ const got = spliceAt(old, incoming, spliceCut(596, 585));
+ assert.deepEqual(got.map((c) => c.text), ["a", "b (cut short by the boundary)", "c"]);
+ const got2 = spliceAt(old, incoming, 588.05);
+ assert.deepEqual(got2.map((c) => c.text), ["a", "b (cut short by the boundary)", "b whole", "c"]);
+});
+
+test("appendSpan: transcribedTo, chunks, words spliced the same way", () => {
+ let doc = emptyLiveTranscript(now);
+ doc = appendSpan(
+ doc,
+ { from: 0, to: 598, cues: [{ start: 1, end: 3, text: "hi" }, { start: 590, end: 597, text: "cut" }], words: [{ w: "hi", start: 1, end: 1.4 }, { w: "cut", start: 590, end: 590.5 }], worker: "gpu", ms: 4000, waitedMs: 10 },
+ now,
+ );
+ doc = appendSpan(
+ doc,
+ { from: 583, to: 1198, cues: [{ start: 589.9, end: 597.5, text: "cut whole" }, { start: 700, end: 702, text: "later" }], words: [{ w: "cut", start: 589.9, end: 590.4 }, { w: "later", start: 700, end: 700.4 }], worker: "gpu", ms: 4000, waitedMs: 0 },
+ now,
+ );
+ assert.equal(doc.transcribedTo, 1198);
+ assert.deepEqual(doc.cues.map((c) => c.text), ["hi", "cut", "later"]);
+ assert.equal(doc.words.length, 3);
+ assert.equal(doc.chunks.length, 2);
+ assert.equal(coerceLiveTranscript(JSON.parse(JSON.stringify(doc)))?.cues.length, 3);
+ assert.equal(coerceLiveTranscript({ version: 2 }), null);
+});
+
+test("spliceScan: by window index, gaps silent, laugh kept when a span had no tagger", () => {
+ let s = spliceScan(null, { t0: 0, hop: 0.5, window: 1, energy: [-20, -21, -22, -23], laugh: [0.1, 0.2, 0.3, 0.4], model: "ced" });
+ assert.deepEqual(s.energy, [-20, -21, -22, -23]);
+ // Overlap from window 2 (t0 1.0): rewritten, extended.
+ s = spliceScan(s, { t0: 1, hop: 0.5, window: 1, energy: [-30, -31, -32], laugh: [0.9, 0.8, 0.7], model: "ced" });
+ assert.deepEqual(s.energy, [-20, -21, -30, -31, -32]);
+ assert.deepEqual(s.laugh, [0.1, 0.2, 0.9, 0.8, 0.7]);
+ // A gap (t0 4.0 = window 8), no tagger on this span.
+ s = spliceScan(s, { t0: 4, hop: 0.5, window: 1, energy: [-10], laugh: null, model: null });
+ assert.deepEqual(s.energy, [-20, -21, -30, -31, -32, -120, -120, -120, -10]);
+ assert.deepEqual(s.laugh, [0.1, 0.2, 0.9, 0.8, 0.7, 0, 0, 0, 0]);
+ assert.equal(s.model, "ced");
+ assert.throws(() => spliceScan(s, { t0: 5, hop: 0.25, window: 1, energy: [1], laugh: null, model: null }), /cannot join/);
+});
+
+function speechLike(seconds: number, rate: number, seed: number, offsetSamples = 0): Float32Array {
+ // Bursts of noise at pseudo-random lengths: an envelope with a shape.
+ const out = new Float32Array(Math.round(seconds * rate));
+ let x = seed;
+ const rnd = () => ((x = (x * 1103515245 + 12345) % 2 ** 31) / 2 ** 31);
+ let on = true;
+ let left = 0;
+ // Warm the generator so offsetSamples shifts the same signal.
+ const total = out.length + offsetSamples;
+ const all = new Float32Array(total);
+ for (let i = 0; i < total; i += 1) {
+ if (left <= 0) {
+ on = !on;
+ left = Math.round((0.15 + rnd() * 0.6) * rate);
+ }
+ left -= 1;
+ all[i] = on ? (rnd() - 0.5) * 0.6 : (rnd() - 0.5) * 0.01;
+ }
+ out.set(all.subarray(offsetSamples, offsetSamples + out.length));
+ return out;
+}
+
+test("envelopeOf + compareEnvelopes + judgeClock: same, shifted, mismatch, flat", () => {
+ const rate = 8000;
+ const pad = 20; // 2 s at 0.1 s
+ const base = speechLike(34, rate, 7);
+ // ref = 30 s from 2 s in; probe = 34 s (2 s either side).
+ const ref = envelopeOf(base.subarray(2 * rate, 32 * rate), rate);
+ const probeSame = envelopeOf(base, rate);
+ const same = judgeClock(compareEnvelopes(ref, probeSame, pad), 0.1, now);
+ assert.equal(same.verdict, "same");
+ // The same audio, 1.2 s later in the probed file.
+ const later = new Float32Array(base.length);
+ later.set(base.subarray(0, base.length - Math.round(1.2 * rate)), Math.round(1.2 * rate));
+ const shifted = judgeClock(compareEnvelopes(ref, envelopeOf(later, rate), pad), 0.1, now);
+ assert.equal(shifted.verdict, "shifted");
+ assert.equal(shifted.lagSeconds, 1.2);
+ const other = judgeClock(compareEnvelopes(ref, envelopeOf(speechLike(34, rate, 99), rate), pad), 0.1, now);
+ assert.equal(other.verdict, "mismatch");
+ const silent = new Float32Array(34 * rate);
+ const flat = judgeClock(compareEnvelopes(ref, envelopeOf(silent, rate), pad), 0.1, now);
+ assert.equal(flat.verdict, "unverified");
+});
+
+test("fingerprintSpan: 60 s in, else the start, else none", () => {
+ assert.deepEqual(fingerprintSpan(4000), { from: 60, dur: 30 });
+ assert.deepEqual(fingerprintSpan(50), { from: 0, dur: 30 });
+ assert.equal(fingerprintSpan(20), null);
+});
+
+test("the state: log lines kept to the last twelve, skips counted, coerced back", () => {
+ let s = newPreclipState({ ...PRECLIP_DEFAULTS }, now, "job1");
+ for (let i = 0; i < 20; i += 1) s = withLogLine(s, `tick ${i}`, now);
+ s = withSkip(withSkip(s, "memory"), "memory");
+ assert.equal(s.log.length, 12);
+ assert.match(s.log.at(-1)!, /tick 19$/);
+ assert.deepEqual(s.skipped, { memory: 2 });
+ const back = coerceLivePreclipState(JSON.parse(JSON.stringify(s)));
+ assert.equal(back?.jobId, "job1");
+ assert.equal(coerceLivePreclipState({ version: 1, status: "nope" }), null);
+});
+
+test("liveClipTooLong / checkLiveWindow: X's 2:20, inside what is recorded", () => {
+ assert.equal(liveClipTooLong(100, 160), null);
+ assert.equal(liveClipTooLong(0, LIVE_CLIP_MAX_SECONDS), null);
+ assert.match(liveClipTooLong(0, LIVE_CLIP_MAX_SECONDS + 1)!, /2:20/);
+ assert.match(liveClipTooLong(10, 5)!, /start before end/);
+ assert.deepEqual(checkLiveWindow(95.5, 164.5, 3600), { from: 95.5, to: 164.5 });
+ assert.deepEqual(checkLiveWindow(3500, 3598, 3600), { from: 3500, to: 3598 });
+ assert.match(
+ (checkLiveWindow(3590, 3610, 3600) as { error: string }).error,
+ /holds 1:00:00 so far; the window ends at 1:00:10 — ask again in 12 s/,
+ );
+ assert.match((checkLiveWindow(0, 1000, 3600) as { error: string }).error, /at most 3:20/);
+ assert.deepEqual(checkLiveWindow(0, 30, null), { from: 0, to: 30 });
+});
diff --git a/common/lib/livePreclip.ts b/common/lib/livePreclip.ts
@@ -0,0 +1,608 @@
+// LIVE PRE-CLIP — the pure half (plans/live-preclip.md): a live recording
+// transcribed and mined WHILE it records.
+//
+// A recording is append-only: what a recorder has written never changes, so a
+// tick reads the prefix already written (by time: `ffmpeg -ss <from> -i <the
+// growing file>`), never a copy. Second S of the growing file is second S of the
+// landed video (the landing's `-c copy` remux and the separate streams' merge
+// both subtract the input's start time, as `-ss` counts from it), so every time
+// here is on the landed video's clock.
+//
+// Everything here is pure: numbers and documents in, numbers and documents out.
+// The I/O — the files, ffmpeg, the worker lease, umtool — is
+// controller/livePreclip.ts.
+
+import type { Cue } from "./vtt";
+
+// --- the two sidecars -------------------------------------------------------------
+
+// The provisional transcript, beside the record. Never `transcript.json` (the
+// index, find-clips and the transcription lane read that one as THE transcript)
+// and never `transcript.<x>.<y>` (a caption track).
+export const LIVE_TRANSCRIPT_FILENAME = "live-transcript.json";
+// The pre-clip job's state: what it did, what it skipped and why.
+export const LIVE_PRECLIP_FILENAME = "live-preclip.json";
+
+// --- the knob ------------------------------------------------------------------------
+
+export type PreclipOptions = {
+ // Minutes between two ticks.
+ everyMinutes: number;
+ // The most one tick transcribes; a recording further behind is caught up in
+ // several ticks, back to back.
+ maxChunkMinutes: number;
+ // Seconds a tick re-reads before the end of what is transcribed, so a word
+ // the boundary cut is heard whole once.
+ overlapSeconds: number;
+ // The laugh scan (CED when its model is there, energy always) of each span.
+ scan: boolean;
+ // Hand the transcript to umtool's clip finder after each tick.
+ mine: boolean;
+ // The umtool project's slug (default `<id>-live`).
+ project?: string;
+};
+
+export const PRECLIP_DEFAULTS: Readonly<Omit<PreclipOptions, "project">> = Object.freeze({
+ everyMinutes: 10,
+ maxChunkMinutes: 20,
+ overlapSeconds: 15,
+ scan: true,
+ mine: true,
+});
+
+export const PRECLIP_BOUNDS = Object.freeze({
+ everyMinutes: [1, 120] as const,
+ maxChunkMinutes: [2, 60] as const,
+ overlapSeconds: [0, 60] as const,
+});
+
+// A tick with less than this new is not run ("no new data").
+export const PRECLIP_MIN_NEW_SECONDS = 30;
+// The live edge is not read: the last seconds may be a fragment mid-write.
+export const PRECLIP_EDGE_SECONDS = 2;
+// A tick behind by more than this after it ran starts the next at once.
+export const PRECLIP_CATCH_UP_SECONDS = 60;
+// The store's disk must have this much free for a tick (its WAV is ~2 MB a
+// minute of audio, removed after the tick).
+export const PRECLIP_MIN_FREE_DISK_BYTES = 2 * 1024 ** 3;
+// The heavy slot's memory floor (scripts/queue-lock.mjs HEAVY_MIN_FREE_MB).
+export const PRECLIP_DEFAULT_MIN_FREE_MB = 6000;
+// The mining reads the transcript up to this far before its end: a proposal
+// near the live edge would be cut mid-thought (its tail is the next silence).
+export const PRECLIP_MINE_EDGE_SECONDS = 20;
+
+// A SHAREABLE CLIP OF A PARTIAL (the operator's second ask): sized for X.
+export const LIVE_CLIP_MAX_SECONDS = 140;
+export const LIVE_SHARE_MAX_BYTES = 512 * 1024 * 1024;
+
+export const PROJECT_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;
+
+/** The umtool project a stream's pre-clip writes, when none is named. */
+export function liveProjectSlug(id: string): string {
+ const base = id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "stream";
+ return `${base.slice(0, 74)}-live`;
+}
+
+function bounded(v: unknown, key: keyof typeof PRECLIP_BOUNDS): number | { error: string } {
+ const [lo, hi] = PRECLIP_BOUNDS[key];
+ if (typeof v !== "number" || !Number.isFinite(v) || v < lo || v > hi) {
+ return { error: `"preclip.${key}" is a number from ${lo} to ${hi}` };
+ }
+ return v;
+}
+
+/**
+ * The `preclip` knob of record-live (and the options of `live-preclip start`):
+ * absent or false = no pre-clip; true = the defaults (settings.livePreclip over
+ * PRECLIP_DEFAULTS); an object = those keys over the defaults.
+ */
+export function parsePreclipKnob(
+ v: unknown,
+ defaults: Omit<PreclipOptions, "project"> = PRECLIP_DEFAULTS,
+): PreclipOptions | null | { error: string } {
+ if (v === undefined || v === null || v === false) return null;
+ if (v === true) return { ...defaults };
+ if (typeof v !== "object" || Array.isArray(v)) return { error: '"preclip" is true, or {"everyMinutes"?, "maxChunkMinutes"?, "overlapSeconds"?, "scan"?, "mine"?, "project"?}' };
+ const r = v as Record<string, unknown>;
+ const known = new Set(["everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"]);
+ const unknown = Object.keys(r).filter((k) => !known.has(k));
+ if (unknown.length) return { error: `"preclip" does not take ${unknown.map((k) => `"${k}"`).join(", ")}` };
+ const out: PreclipOptions = { ...defaults };
+ for (const k of ["everyMinutes", "maxChunkMinutes", "overlapSeconds"] as const) {
+ if (r[k] === undefined) continue;
+ const n = bounded(r[k], k);
+ if (typeof n !== "number") return n;
+ out[k] = n;
+ }
+ for (const k of ["scan", "mine"] as const) {
+ if (r[k] === undefined) continue;
+ if (typeof r[k] !== "boolean") return { error: `"preclip.${k}" must be true or false` };
+ out[k] = r[k] as boolean;
+ }
+ if (r.project !== undefined) {
+ if (typeof r.project !== "string" || !PROJECT_SLUG_RE.test(r.project)) {
+ return { error: '"preclip.project" is a umtool project slug (lowercase letters, digits and dashes)' };
+ }
+ out.project = r.project;
+ }
+ if (out.overlapSeconds * 2 >= out.maxChunkMinutes * 60) return { error: '"preclip.overlapSeconds" must be well under the chunk' };
+ return out;
+}
+
+// --- the live transcript ----------------------------------------------------------
+
+export type LiveWord = { w: string; start: number; end: number; conf?: number };
+
+// The laugh scan of the recording so far, on its clock (t0 0): window i covers
+// [i·hop, i·hop + window). `laugh` null when no tagger ran on any span.
+export type LiveScan = {
+ hop: number;
+ window: number;
+ energy: number[];
+ laugh: number[] | null;
+ model: string | null;
+};
+
+// The part of the recording a transcript is on. A recorder restart or a
+// fallback writes a new part; its clock is the old one only when its opening
+// audio says so (compareEnvelopes).
+export type LiveBasis = {
+ stem: string;
+ // The file read: the muxed part, or the audio stream of a separate pair.
+ audioFile: string;
+ kind: "muxed" | "separate";
+};
+
+export type LiveChunk = {
+ from: number;
+ to: number;
+ cues: number;
+ words: number;
+ worker: string | null;
+ at: string;
+ // The engine's time and the wait for a worker, ms.
+ ms: number;
+ waitedMs: number;
+};
+
+export type LiveFingerprint = { from: number; hop: number; env: number[] };
+
+export type ClockVerdict = "same-recording" | "same" | "shifted" | "mismatch" | "unverified";
+
+export type ClockCheck = {
+ verdict: ClockVerdict;
+ // Seconds the landed video's audio lags the live transcript's (shifted).
+ lagSeconds?: number;
+ corr?: number;
+ why: string;
+ at: string;
+};
+
+export type LiveTranscriptStatus = "live" | "landed" | "superseded";
+
+export type LiveTranscriptDoc = {
+ version: 1;
+ provisional: true;
+ status: LiveTranscriptStatus;
+ basis: LiveBasis | null;
+ // How many times the basis changed to a part on another clock.
+ restarts: number;
+ // Seconds of the recording transcribed, from 0.
+ transcribedTo: number;
+ cues: Cue[];
+ words: LiveWord[];
+ scan: LiveScan | null;
+ chunks: LiveChunk[];
+ fingerprint: LiveFingerprint | null;
+ updatedAt: string;
+ landed?: { at: string; check: ClockCheck };
+ supersededAt?: string;
+};
+
+export function emptyLiveTranscript(now: Date): LiveTranscriptDoc {
+ return {
+ version: 1,
+ provisional: true,
+ status: "live",
+ basis: null,
+ restarts: 0,
+ transcribedTo: 0,
+ cues: [],
+ words: [],
+ scan: null,
+ chunks: [],
+ fingerprint: null,
+ updatedAt: now.toISOString(),
+ };
+}
+
+const isNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
+const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
+
+export function coerceLiveTranscript(raw: unknown): LiveTranscriptDoc | null {
+ if (!isObj(raw) || raw.version !== 1) return null;
+ const status = raw.status === "landed" || raw.status === "superseded" ? raw.status : "live";
+ const cues = Array.isArray(raw.cues)
+ ? (raw.cues as unknown[]).filter((c): c is Cue => isObj(c) && isNum(c.start) && isNum(c.end) && typeof c.text === "string")
+ : [];
+ const words = Array.isArray(raw.words)
+ ? (raw.words as unknown[]).filter((w): w is LiveWord => isObj(w) && isNum(w.start) && isNum(w.end) && typeof w.w === "string")
+ : [];
+ const b = raw.basis;
+ const basis: LiveBasis | null =
+ isObj(b) && typeof b.stem === "string" && typeof b.audioFile === "string"
+ ? { stem: b.stem, audioFile: b.audioFile, kind: b.kind === "separate" ? "separate" : "muxed" }
+ : null;
+ const s = raw.scan;
+ const scan: LiveScan | null =
+ isObj(s) && isNum(s.hop) && isNum(s.window) && Array.isArray(s.energy)
+ ? {
+ hop: s.hop,
+ window: s.window,
+ energy: (s.energy as unknown[]).map((x) => (isNum(x) ? x : -120)),
+ laugh: Array.isArray(s.laugh) ? (s.laugh as unknown[]).map((x) => (isNum(x) ? x : 0)) : null,
+ model: typeof s.model === "string" ? s.model : null,
+ }
+ : null;
+ const f = raw.fingerprint;
+ const fingerprint: LiveFingerprint | null =
+ isObj(f) && isNum(f.from) && isNum(f.hop) && Array.isArray(f.env)
+ ? { from: f.from, hop: f.hop, env: (f.env as unknown[]).map((x) => (isNum(x) ? x : -120)) }
+ : null;
+ return {
+ version: 1,
+ provisional: true,
+ status,
+ basis,
+ restarts: isNum(raw.restarts) ? raw.restarts : 0,
+ transcribedTo: isNum(raw.transcribedTo) ? raw.transcribedTo : 0,
+ cues,
+ words,
+ scan,
+ chunks: Array.isArray(raw.chunks) ? (raw.chunks as LiveChunk[]).filter((c) => isObj(c) && isNum(c.from) && isNum(c.to)) : [],
+ fingerprint,
+ updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : new Date(0).toISOString(),
+ ...(isObj(raw.landed) ? { landed: raw.landed as LiveTranscriptDoc["landed"] } : {}),
+ ...(typeof raw.supersededAt === "string" ? { supersededAt: raw.supersededAt } : {}),
+ };
+}
+
+/**
+ * Two transcriptions of one recording, the old up to `cut` and the new from it.
+ * Both lists sorted by start; an entry is kept by where it STARTS, so a cue that
+ * straddles the cut is taken once — from the side it starts on.
+ */
+export function spliceAt<T extends { start: number }>(old: readonly T[], incoming: readonly T[], cut: number): T[] {
+ return [...old.filter((x) => x.start < cut), ...incoming.filter((x) => x.start >= cut)].sort((a, b) => a.start - b.start);
+}
+
+// Where a chunk takes over from what is transcribed: the middle of the overlap
+// (each side heard its half with the context of the other), or the chunk's
+// start when it does not overlap.
+export function spliceCut(transcribedTo: number, chunkFrom: number): number {
+ return chunkFrom < transcribedTo ? Math.round(((chunkFrom + transcribedTo) / 2) * 1000) / 1000 : chunkFrom;
+}
+
+export type TranscribedSpan = {
+ from: number;
+ to: number;
+ cues: readonly Cue[];
+ words: readonly LiveWord[];
+ worker: string | null;
+ ms: number;
+ waitedMs: number;
+};
+
+/** The doc with one transcribed span spliced in (its cues and words already on the recording's clock). */
+export function appendSpan(doc: LiveTranscriptDoc, span: TranscribedSpan, now: Date): LiveTranscriptDoc {
+ const cut = spliceCut(doc.transcribedTo, span.from);
+ const cues = spliceAt(doc.cues, span.cues, cut);
+ const words = spliceAt(doc.words, span.words, cut);
+ return {
+ ...doc,
+ cues,
+ words,
+ transcribedTo: Math.max(doc.transcribedTo, span.to),
+ chunks: [
+ ...doc.chunks,
+ {
+ from: span.from,
+ to: span.to,
+ cues: span.cues.length,
+ words: span.words.length,
+ worker: span.worker,
+ at: now.toISOString(),
+ ms: span.ms,
+ waitedMs: span.waitedMs,
+ },
+ ],
+ updatedAt: now.toISOString(),
+ };
+}
+
+// One span's scan (runAudioScan's shape: windows from t0, every hop).
+export type ScanPart = { t0: number; hop: number; window: number; energy: readonly number[]; laugh: readonly number[] | null; model: string | null };
+
+/**
+ * A span's scan written into the scan so far, by window index (t0 / hop). The
+ * windows between the end of the scan and the span (a gap the scan did not
+ * see) are silence (-120 dB) and no laugh. A span scanned with no tagger leaves
+ * the laugh scores already there.
+ */
+export function spliceScan(acc: LiveScan | null, part: ScanPart): LiveScan {
+ const hop = acc?.hop ?? part.hop;
+ const window = acc?.window ?? part.window;
+ if (Math.abs(hop - part.hop) > 1e-9 || Math.abs(window - part.window) > 1e-9) {
+ throw new Error(`a scan of hop ${part.hop}/window ${part.window} cannot join one of ${hop}/${window}`);
+ }
+ const i0 = Math.max(0, Math.round(part.t0 / hop));
+ const n = i0 + part.energy.length;
+ const energy = [...(acc?.energy ?? [])];
+ while (energy.length < n) energy.push(-120);
+ part.energy.forEach((e, k) => (energy[i0 + k] = e));
+ let laugh = acc?.laugh ? [...acc.laugh] : null;
+ if (part.laugh) {
+ laugh = laugh ?? new Array(energy.length).fill(0);
+ while (laugh.length < n) laugh.push(0);
+ part.laugh.forEach((s, k) => ((laugh as number[])[i0 + k] = s));
+ } else if (laugh) while (laugh.length < energy.length) laugh.push(0);
+ return { hop, window, energy, laugh, model: part.model ?? acc?.model ?? null };
+}
+
+// --- the tick ---------------------------------------------------------------------
+
+export type TickPlan =
+ | { action: "transcribe"; from: number; to: number; behind: number }
+ | { action: "wait"; reason: string };
+
+/**
+ * What a tick does, given what is transcribed and what the file holds now:
+ * transcribe `[from, to)` — from `overlapSeconds` before the end of the
+ * transcript, to the live edge less PRECLIP_EDGE_SECONDS, at most
+ * `maxChunkMinutes` — or wait, and why. `behind` is what is left after it.
+ */
+export function planTick(o: {
+ transcribedTo: number;
+ recordedSeconds: number | null;
+ opts: Pick<PreclipOptions, "maxChunkMinutes" | "overlapSeconds">;
+}): TickPlan {
+ if (o.recordedSeconds === null) return { action: "wait", reason: "the recording's length cannot be read yet" };
+ const edge = Math.max(0, o.recordedSeconds - PRECLIP_EDGE_SECONDS);
+ const fresh = edge - o.transcribedTo;
+ if (fresh < PRECLIP_MIN_NEW_SECONDS) {
+ return { action: "wait", reason: `no new data (${Math.max(0, Math.round(fresh))} s new, a tick needs ${PRECLIP_MIN_NEW_SECONDS})` };
+ }
+ const from = o.transcribedTo > 0 ? Math.max(0, o.transcribedTo - o.opts.overlapSeconds) : 0;
+ const to = Math.min(edge, from + o.opts.maxChunkMinutes * 60);
+ const r = (x: number) => Math.round(x * 1000) / 1000;
+ return { action: "transcribe", from: r(from), to: r(to), behind: r(Math.max(0, edge - to)) };
+}
+
+/** Milliseconds to the next tick: at once when still behind, else the period. */
+export function nextTickDelayMs(behind: number, opts: Pick<PreclipOptions, "everyMinutes">): number {
+ return behind > PRECLIP_CATCH_UP_SECONDS ? 0 : opts.everyMinutes * 60_000;
+}
+
+// --- the clock check: an RMS envelope ----------------------------------------------
+
+export const FINGERPRINT_FROM_SECONDS = 60;
+export const FINGERPRINT_SECONDS = 30;
+export const FINGERPRINT_HOP_SECONDS = 0.1;
+// The lag searched either way, seconds.
+export const FINGERPRINT_MAX_LAG_SECONDS = 10;
+export const CLOCK_MIN_CORR = 0.75;
+export const CLOCK_SAME_LAG_SECONDS = 0.3;
+// An envelope whose spread is under this (dB) is silence or a steady tone: it
+// cannot say where it is.
+export const FINGERPRINT_MIN_SPREAD_DB = 1.5;
+
+/** Where a fingerprint is taken in a recording of `seconds`: 60 s in, else the start; null when too short. */
+export function fingerprintSpan(seconds: number): { from: number; dur: number } | null {
+ if (seconds >= FINGERPRINT_FROM_SECONDS + FINGERPRINT_SECONDS) return { from: FINGERPRINT_FROM_SECONDS, dur: FINGERPRINT_SECONDS };
+ if (seconds >= FINGERPRINT_SECONDS + PRECLIP_EDGE_SECONDS) return { from: 0, dur: FINGERPRINT_SECONDS };
+ return null;
+}
+
+/** Each `hop`'s RMS level in dB (1 dp) of mono samples. */
+export function envelopeOf(samples: Float32Array, rate: number, hop = FINGERPRINT_HOP_SECONDS): number[] {
+ const n = Math.max(1, Math.round(rate * hop));
+ const out: number[] = [];
+ for (let a = 0; a + n <= samples.length; a += n) {
+ let s = 0;
+ for (let i = a; i < a + n; i += 1) s += samples[i]! * samples[i]!;
+ const rms = Math.sqrt(s / n);
+ out.push(Math.round((rms > 1e-6 ? 20 * Math.log10(rms) : -120) * 10) / 10);
+ }
+ return out;
+}
+
+function spread(v: readonly number[]): number {
+ if (v.length < 2) return 0;
+ const m = v.reduce((a, b) => a + b, 0) / v.length;
+ return Math.sqrt(v.reduce((a, b) => a + (b - m) ** 2, 0) / v.length);
+}
+
+function pearson(a: readonly number[], b: readonly number[]): number {
+ const n = Math.min(a.length, b.length);
+ if (n < 10) return 0;
+ let ma = 0;
+ let mb = 0;
+ for (let i = 0; i < n; i += 1) {
+ ma += a[i]!;
+ mb += b[i]!;
+ }
+ ma /= n;
+ mb /= n;
+ let num = 0;
+ let da = 0;
+ let db = 0;
+ for (let i = 0; i < n; i += 1) {
+ const x = a[i]! - ma;
+ const y = b[i]! - mb;
+ num += x * y;
+ da += x * x;
+ db += y * y;
+ }
+ return da > 0 && db > 0 ? num / Math.sqrt(da * db) : 0;
+}
+
+/**
+ * Where `probe` (the same span, read from another file — `pad` frames longer
+ * on either side) best matches `ref`: the correlation, and the lag in frames
+ * (positive: the probe's copy of the span is later). `probe[pad + k]` is the
+ * frame `ref[k]` should be at when the clocks agree.
+ */
+export function compareEnvelopes(
+ ref: readonly number[],
+ probe: readonly number[],
+ pad: number,
+): { corr: number; lag: number; flat: boolean } {
+ const flat = spread(ref) < FINGERPRINT_MIN_SPREAD_DB || spread(probe) < FINGERPRINT_MIN_SPREAD_DB;
+ let best = { corr: -1, lag: 0 };
+ for (let lag = -pad; lag <= pad; lag += 1) {
+ const start = pad + lag;
+ if (start < 0) continue;
+ const seg = probe.slice(start, start + ref.length);
+ if (seg.length < ref.length * 0.8) continue;
+ const c = pearson(ref, seg);
+ if (c > best.corr + 1e-9 || (Math.abs(c - best.corr) <= 1e-9 && Math.abs(lag) < Math.abs(best.lag))) best = { corr: c, lag };
+ }
+ return { corr: Math.round(best.corr * 1000) / 1000, lag: best.lag, flat };
+}
+
+/** The verdict on two clocks, from compareEnvelopes. */
+export function judgeClock(
+ cmp: { corr: number; lag: number; flat: boolean },
+ hop: number,
+ now: Date,
+): ClockCheck {
+ const at = now.toISOString();
+ const lagSeconds = Math.round(cmp.lag * hop * 1000) / 1000;
+ if (cmp.flat) return { verdict: "unverified", corr: cmp.corr, why: "the compared audio is silence or a steady tone: it cannot say where it is", at };
+ if (cmp.corr < CLOCK_MIN_CORR) {
+ return { verdict: "mismatch", corr: cmp.corr, why: `the landed video's audio does not match the live transcript's (best correlation ${cmp.corr})`, at };
+ }
+ if (Math.abs(lagSeconds) <= CLOCK_SAME_LAG_SECONDS) {
+ return { verdict: "same", corr: cmp.corr, lagSeconds, why: `the landed video starts where the live recording did (correlation ${cmp.corr}, ${lagSeconds} s)`, at };
+ }
+ return {
+ verdict: "shifted",
+ corr: cmp.corr,
+ lagSeconds,
+ why: `the landed video is ${Math.abs(lagSeconds)} s ${lagSeconds > 0 ? "later" : "earlier"} than the live transcript's clock (correlation ${cmp.corr})`,
+ at,
+ };
+}
+
+// --- the job's state -----------------------------------------------------------------
+
+export type LivePreclipStatus = "running" | "waiting-final" | "superseded" | "stopped" | "failed";
+
+export type LivePreclipState = {
+ version: 1;
+ status: LivePreclipStatus;
+ jobId?: string;
+ options: PreclipOptions;
+ startedAt: string;
+ updatedAt: string;
+ ticks: number;
+ recordedSeconds: number | null;
+ transcribedSeconds: number;
+ // Ticks not run, by reason ("no new data", "memory", "disk", "unreadable",
+ // "failed").
+ skipped: Record<string, number>;
+ // The last lines of the job's log about ticks, newest last.
+ log: string[];
+ mined?: { project: string; url?: string; proposals: number; clips: number; at: string; error?: string };
+ check?: ClockCheck;
+ error?: string;
+};
+
+export const PRECLIP_LOG_LINES = 12;
+
+export function newPreclipState(options: PreclipOptions, now: Date, jobId?: string): LivePreclipState {
+ return {
+ version: 1,
+ status: "running",
+ ...(jobId ? { jobId } : {}),
+ options,
+ startedAt: now.toISOString(),
+ updatedAt: now.toISOString(),
+ ticks: 0,
+ recordedSeconds: null,
+ transcribedSeconds: 0,
+ skipped: {},
+ log: [],
+ };
+}
+
+const STATES: ReadonlySet<string> = new Set(["running", "waiting-final", "superseded", "stopped", "failed"]);
+
+export function coerceLivePreclipState(raw: unknown): LivePreclipState | null {
+ if (!isObj(raw) || raw.version !== 1 || typeof raw.status !== "string" || !STATES.has(raw.status)) return null;
+ const opts = parsePreclipKnob(isObj(raw.options) ? raw.options : true);
+ return {
+ ...(raw as LivePreclipState),
+ options: opts && !("error" in opts) ? opts : { ...PRECLIP_DEFAULTS },
+ ticks: isNum(raw.ticks) ? raw.ticks : 0,
+ recordedSeconds: isNum(raw.recordedSeconds) ? raw.recordedSeconds : null,
+ transcribedSeconds: isNum(raw.transcribedSeconds) ? raw.transcribedSeconds : 0,
+ skipped: isObj(raw.skipped) ? (raw.skipped as Record<string, number>) : {},
+ log: Array.isArray(raw.log) ? (raw.log as unknown[]).filter((l): l is string => typeof l === "string") : [],
+ };
+}
+
+/** The state with one more log line (the last PRECLIP_LOG_LINES kept). */
+export function withLogLine(s: LivePreclipState, line: string, now: Date): LivePreclipState {
+ return { ...s, log: [...s.log, `${now.toISOString().slice(11, 19)} ${line}`].slice(-PRECLIP_LOG_LINES), updatedAt: now.toISOString() };
+}
+
+export function withSkip(s: LivePreclipState, reason: string): LivePreclipState {
+ return { ...s, skipped: { ...s.skipped, [reason]: (s.skipped[reason] ?? 0) + 1 } };
+}
+
+/** "1:02:03" / "4:05". */
+export function clock(seconds: number): string {
+ const t = Math.max(0, Math.round(seconds));
+ const h = Math.floor(t / 3600);
+ const m = Math.floor((t % 3600) / 60);
+ const s = t % 60;
+ return h ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` : `${m}:${String(s).padStart(2, "0")}`;
+}
+
+// --- a shareable clip's window -----------------------------------------------------
+
+/** A share's clip (its cut) is at most X's 2:20. Null when it fits; else the sentence. */
+export function liveClipTooLong(start: number, end: number): string | null {
+ if (!isNum(start) || !isNum(end) || start < 0 || end <= start) return '"start" and "end" are seconds, start before end';
+ if (end - start > LIVE_CLIP_MAX_SECONDS + 1e-6) {
+ return `a share is at most ${clock(LIVE_CLIP_MAX_SECONDS)} (X's limit); this clip is ${clock(end - start)}`;
+ }
+ return null;
+}
+
+// The source window a share's render reads is its clip's extent plus the
+// build's fetch pad (report-to-video/build-video.mjs fetchSpan): at most this.
+export const LIVE_WINDOW_MAX_SECONDS = LIVE_CLIP_MAX_SECONDS + 60;
+
+/**
+ * A window cut from a recording in progress: inside what is recorded (short of
+ * the live edge), at most LIVE_WINDOW_MAX_SECONDS. Refusals are sentences —
+ * a window past the edge says how long to wait.
+ */
+export function checkLiveWindow(
+ from: number,
+ to: number,
+ recordedSeconds: number | null,
+): { from: number; to: number } | { error: string } {
+ if (!isNum(from) || !isNum(to) || from < 0 || to <= from) return { error: '"from" and "to" are seconds, from before to' };
+ if (to - from > LIVE_WINDOW_MAX_SECONDS + 1e-6) {
+ return { error: `a live window is at most ${clock(LIVE_WINDOW_MAX_SECONDS)}; this one is ${clock(to - from)}` };
+ }
+ if (recordedSeconds !== null && to > recordedSeconds - PRECLIP_EDGE_SECONDS) {
+ const wait = Math.ceil(to - (recordedSeconds - PRECLIP_EDGE_SECONDS));
+ return { error: `the recording holds ${clock(recordedSeconds)} so far; the window ends at ${clock(to)} — ask again in ${wait} s` };
+ }
+ const r = (x: number) => Math.round(x * 100) / 100;
+ return { from: r(from), to: r(to) };
+}
diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts
@@ -21,6 +21,7 @@ import {
BUILD_PIPELINE_SETTINGS_FIELD_DOCS,
DIARIZATION_SETTINGS_FIELD_DOCS,
PACING_SETTINGS_FIELD_DOCS,
+ LIVE_PRECLIP_SETTINGS_FIELD_DOCS,
PUBLISH_SETTINGS_FIELD_DOCS,
REPORT_SCHEDULE_SETTINGS_FIELD_DOCS,
DIGEST_SETTINGS_FIELD_DOCS,
@@ -149,6 +150,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings,
{ path: "workers[].remote", docs: REMOTE_WORKER_CONFIG_FIELD_DOCS },
{ path: "workers[].llm", docs: LLM_WORKER_CONFIG_FIELD_DOCS },
],
+ livePreclip: [
+ {
+ path: "livePreclip",
+ docs: LIVE_PRECLIP_SETTINGS_FIELD_DOCS,
+ defaults: fromObject(d.livePreclip),
+ },
+ ],
pacing: [
{
path: "pacing",
diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts
@@ -43,6 +43,7 @@ import type {
DiarizationSettings,
DigestSettings,
PacingSettingsBlock,
+ LivePreclipSettingsBlock,
PublishSettings,
ReportScheduleSettings,
ReportDebouncePreset,
@@ -79,6 +80,8 @@ type PreSchemaSiteSettings = {
// Release 16 slice XL — the one key it adds.
social: SocialSettings;
sleepBetweenDownloadsSeconds: number;
+ // Live pre-clip (plans/live-preclip.md) — its defaults.
+ livePreclip: LivePreclipSettingsBlock;
// Release 17 slice RL — the adaptive pace and the hold.
pacing: PacingSettingsBlock;
downloadFormat: DownloadFormatPreset;
@@ -129,7 +132,7 @@ type PreSchemaSiteSettings = {
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true;
-test("SiteSettings keeps its 43 fields, in file order", () => {
+test("SiteSettings keeps its 44 fields, in file order", () => {
assert.equal(shapeUnchanged, true);
assert.deepEqual(Object.keys(siteSettingsSchema.shape), [
"adminTitle",
@@ -141,6 +144,7 @@ test("SiteSettings keeps its 43 fields, in file order", () => {
"cookieMode",
"social",
"sleepBetweenDownloadsSeconds",
+ "livePreclip",
"pacing",
"downloadFormat",
"sourceVideoQuality",
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -874,6 +874,45 @@ export function sanitizePacing(v: unknown): PacingSettingsBlock {
};
}
+// LIVE PRE-CLIP (plans/live-preclip.md): the defaults a `preclip: true` on
+// record-live (and `pnpm ops live-preclip`) takes. Each field is documented in
+// LIVE_PRECLIP_SETTINGS_FIELD_DOCS (rendered into SETTINGS.md).
+export type LivePreclipSettingsBlock = {
+ everyMinutes: number;
+ maxChunkMinutes: number;
+ overlapSeconds: number;
+ scan: boolean;
+ mine: boolean;
+};
+
+export const LIVE_PRECLIP_SETTINGS_FIELD_DOCS: FieldDocs<LivePreclipSettingsBlock> = {
+ everyMinutes:
+ "Minutes between two pre-clip ticks of a live recording. A tick transcribes only what was recorded since the last " +
+ "one; a tick with under 30 s new is skipped. Clamped 1–120; default 10.",
+ maxChunkMinutes:
+ "The most one tick transcribes, minutes of audio. A recording further behind (pre-clip started late, the worker was " +
+ "busy) is caught up in ticks of this size, back to back. Clamped 2–60; default 20.",
+ overlapSeconds:
+ "Seconds each tick re-reads before the end of what is transcribed, so a word the boundary cut is heard whole once; " +
+ "the splice keeps each side's half. Clamped 0–60; default 15.",
+ scan:
+ "Run the clip finder's laugh scan (CED when its model is installed, the energy always) on each tick's span. Default true.",
+ mine:
+ "Hand the live transcript to umtool's clip finder after each tick (`POST /api/report/clips {mode: \"live\"}`), growing the " +
+ "stream's project. Default true.",
+};
+
+export function sanitizeLivePreclip(v: unknown): LivePreclipSettingsBlock {
+ const r = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;
+ return {
+ everyMinutes: clampInt(r.everyMinutes, 1, 120, 10),
+ maxChunkMinutes: clampInt(r.maxChunkMinutes, 2, 60, 20),
+ overlapSeconds: clampInt(r.overlapSeconds, 0, 60, 15),
+ scan: r.scan !== false,
+ mine: r.mine !== false,
+ };
+}
+
export const SLEEP_BETWEEN_DOWNLOADS_MAX_SECONDS = 600;
export const SLEEP_BETWEEN_DOWNLOADS_DEFAULT_SECONDS = 10;
@@ -1846,6 +1885,9 @@ export const siteSettingsSchema = z.object({
sleepBetweenDownloadsSeconds: settingsField((v): number => clampSleepBetweenDownloadsSeconds(v)).describe(
"Pause (seconds) inserted between per-video yt-dlp invocations in managed batch downloads, and between two auto-download units on one platform (release 17; the lane ignored it before). yt-dlp's own `-t sleep` only paces requests within one invocation, so without this the managed loop hammers the source IP back-to-back. The adaptive pace above its base (see `pacing`) is added to it. 0 disables. Per-channel override available for batch downloads.",
),
+ livePreclip: settingsField((v): LivePreclipSettingsBlock => sanitizeLivePreclip(v)).describe(
+ "The defaults of LIVE PRE-CLIP (plans/live-preclip.md): a live recording transcribed and mined while it records — record-live's `\"preclip\": true`, `pnpm ops live-preclip`. A request's own `preclip` keys override these. See common/controller/livePreclip.ts.",
+ ),
pacing: settingsField((v): PacingSettingsBlock => sanitizePacing(v)).describe(
"How the download pace adapts to rate limits, per platform (release 17). Every yt-dlp spawn against a platform paces its requests (`--sleep-requests`) at the platform's adaptive pace, and the download lane waits sleepBetweenDownloadsSeconds plus the pace above its fixed value between units. A rate limit doubles the pace; clean units ease it back; a rate limit that outlasts the cooldown cap holds the platform to one probe at a time. The live pace, cooldowns and holds are in `.auto-queue/state.json`, shown on /operations/download. See common/jobs/platformBackoff.ts.",
),
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **A live stream can be transcribed and clipped while it is still recording.** Until now a recording was transcribed only once the stream ended and the file landed, so on a long stream nothing could be found or shared until hours later. `pnpm ops record-live` takes `"preclip": true` (or `{"everyMinutes": 10, "maxChunkMinutes": 20, "overlapSeconds": 15, "scan": true, "mine": true, "project": "<slug>"}`, defaults in `settings.livePreclip`). `pnpm ops live-preclip {"slug", "id"}` starts the same thing on a recording already running, and the video page's **Live pre-clip** panel has a Start button. Every few minutes a tick transcribes only what was recorded since the last one. It reads the growing file in place and never copies it or touches the recorder, whatever the recording is: one MPEG-TS, YouTube's separate video and audio, or Kick's polled VOD. The new span is transcribed on the transcription worker, with word timings, and added to `data/<id>/live-transcript.json`, marked provisional, on the clock the landed video will have. The clip finder then grows a umtool project for the stream (`<id>-live`), so its windows can be walked in the clip editor while the stream goes on. A busy worker never piles ticks up: the next tick takes everything since, and a tick that is far behind is followed by the next one at once. A tick is skipped, and the log says why, when there is under 30 s new, when the machine is under the 6 GB memory floor (checked again every minute), or when the store's disk has under 2 GB free. A recorder that restarts or falls back (Rumble) is followed. If its audio matches, the transcript goes on; if not, it starts again on the new recording and the project's windows are flagged. When the stream lands, the landed video is checked against what was transcribed live, and the windows stay where they are when it matches (flagged when it does not). Once the final transcript is there it replaces the live one, and the project reads the corpus from then on. `"action": "stop"`, `"status"` and `"finalize"` stop it (the recording goes on), print its state, and finish that hand-over by hand. **A clip of a stream still live can be shared at once:** `pnpm ops live-clip {"slug", "id", "start", "end"}`, the panel's **Share this clip**, or the clip editor's **Share now (live)** cuts the window from what is recorded so far and makes the clip's short with the live captions. A share is at most 2:20 and 512 MiB, for X, and nothing is fetched from the network. Needs a restart of the editor and umtool.
- **A reply can be captured with the post it answers above it.** `capture-posts` with `"thread": true` (X; or a channel's new `postCaptureThread`, or the Thread shot box under Capture posts on an X channel's page) also writes `shot-thread.png` beside the post's `shot.png`: the post it replies to over the reply, in the same page load — only the immediate parent, a longer chain cut to it. The parent is the post the archive says it answers; with no archive word, the post directly above it on the page; a post the archive says is no reply is not opened for it, and a post shot before gets only its thread shot. **The replied-to author is blurred** — avatar, name and handle, and any link to them in the reply — unless they carry an organisation's gold or a government's grey check, or are the reply's own author. X Premium's blue check is bought, so a blue-checked person is blurred like anyone else (the first live proof's parent was one). `"threadRedact": false` (or `{"<id>": false}`) takes it unblurred; a parent whose name cannot be found to blur gets no thread shot. capture.json records the parent, its badge and every blurred box. Proved on TheQuartering's reply 2114214000653414579. Needs a restart of the editor.
- **A report video can draw a reply with the post it answers.** A manifest post's `thread: true` draws its capture's `shot-thread.png` in place of its shot (its own shot while there is none) — set with `umtool posts set <project> <post> thread=on`, `umtool posts add … --thread`, or the **thread** box in the On-screen Posts table. In the feed a thread shot is drawn whole: the card under it leaves rather than the reply being squeezed, and one taller than the column is scaled to fit, never cut. A cut with no thread shot renders byte for byte as before.
- **A site build can now run beside a report-video render when there is memory for both.** A render declared nothing to the machine's heavy slot, so it always ran alone: a site build started while a take rendered waited out the whole render (an hour or more for a full cut). A render now says how much memory it will need — measured on the Huck cut: about 6 GB for a whole cut (its widest step, a crossfade over 23 clips at once, peaked at 4.9 GB), about 2.4 GB for a short take of part of a cut, more with more `UMTOOL_CHROME_WORKERS` — and the encode ladder (`umtool variants`) about 1 GB. A capped site build (one run under `systemd-run … -p MemoryMax=5G`) is let in beside it while the memory left after the render's share stays at or above the 6000 MB floor, and waits for it otherwise. On this 16 GB machine that is often for a short take and rare for a whole cut. A publish stage's own build is not capped, so it still waits for the render as before. `UMTOOL_RENDER_ESTIMATE_MB` / `UMTOOL_LADDER_ESTIMATE_MB` set the share by hand, and `0` makes a render run alone again. Start a take or a build-video run as it is, not under `pnpm heavy --`, which makes it run alone. Needs a restart of umtool for takes made from the app (the `umtool take` command has it now).
diff --git a/editor/app/api/media/live-window/route.ts b/editor/app/api/media/live-window/route.ts
@@ -0,0 +1,54 @@
+import { NextResponse } from "next/server";
+import { authorizeWorkerRequest } from "yt-dlp-transcript-common/lib/workerToken";
+import { liveWindowAction } from "../../../channels/[slug]/liveMediaActions";
+
+export const dynamic = "force-dynamic";
+
+// A WINDOW OF A RECORDING IN PROGRESS, cut now (controller/liveClip.ts
+// liveWindow) — what umtool's live share (`/api/report/live-share`) asks
+// before it makes the short. The same door as /api/media/fetch-window (the
+// WORKER_TOKEN), but it never reaches the network: the window is read from the
+// part being recorded (or the saved video, once landed) into
+// data/<id>/clips/<from>-<to>.mp4, or found there already.
+//
+// POST { slug, id, from, to, requestedBy?, manifest?, clipId?, reason? }
+// -> 200 { path, file, from, to, bytes, source, recordedSeconds }
+// -> 409 { error } past what is recorded ("ask again in N s"), or the
+// recording not readable yet
+// -> 400/404/503 { error }
+const ID_RE = /^[\w.-]+$/;
+const num = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
+const str = (v: unknown): string | undefined => (typeof v === "string" && v.trim() ? v.trim() : undefined);
+
+export async function POST(request: Request) {
+ const auth = authorizeWorkerRequest(request.headers.get("authorization"));
+ if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status });
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return NextResponse.json({ error: "body must be a JSON object" }, { status: 400 });
+ const slug = str(body.slug);
+ const id = str(body.id);
+ if (!slug || !id || !ID_RE.test(id) || id === "." || id === "..") {
+ return NextResponse.json({ error: '"slug" and "id" are required' }, { status: 400 });
+ }
+ if (!num(body.from) || !num(body.to)) return NextResponse.json({ error: '"from" and "to" are seconds' }, { status: 400 });
+ const r = await liveWindowAction({
+ slug,
+ id,
+ from: body.from,
+ to: body.to,
+ ...(str(body.requestedBy) ? { requestedBy: str(body.requestedBy)! } : {}),
+ ...(str(body.manifest) ? { manifest: str(body.manifest)! } : {}),
+ ...(str(body.clipId) ? { clipId: str(body.clipId)! } : {}),
+ ...(str(body.reason) ? { reason: str(body.reason)! } : {}),
+ });
+ if (!r.ok) return NextResponse.json({ error: r.error }, { status: r.status });
+ return NextResponse.json({
+ path: r.window.path,
+ file: r.window.file,
+ from: r.window.from,
+ to: r.window.to,
+ bytes: r.window.bytes,
+ source: r.source,
+ recordedSeconds: r.recordedSeconds,
+ });
+}
diff --git a/editor/app/api/ops/_door.test.ts b/editor/app/api/ops/_door.test.ts
@@ -112,6 +112,8 @@ test("a traversing slug is refused at the door, on every route that takes one",
["find-clips", { slug: "../../escape", id: "abc123" }],
["import-media", { slug: "../../escape", path: "/tmp/ops-api-never.mp4", id: "abc123" }],
["record-live", { slug: "../../escape", url: "https://rumble.com/v1abcde-x.html" }],
+ ["live-preclip", { slug: "../../escape", id: "abc123", action: "status" }],
+ ["live-clip", { slug: "../../escape", id: "abc123", start: 1, end: 20 }],
["keep-videos", { slug: "../../escape", ids: ["abc123"] }],
["check-windows", { slug: "../../escape", dryRun: true }],
];
diff --git a/editor/app/api/ops/live-clip/route.ts b/editor/app/api/ops/live-clip/route.ts
@@ -0,0 +1,20 @@
+import { LIVE_CLIP_BODY_KEYS } from "yt-dlp-transcript-common/controller/liveClip";
+import { liveClipAction } from "../../../channels/[slug]/liveMediaActions";
+import { jobResponse, ops, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, id, start, end | clip, project?, replace? } -> { ok: true, jobId }
+//
+// A SHAREABLE CLIP OF A STREAM STILL LIVE (controller/liveClip.ts): umtool's
+// live share — the window cut now from the recording in progress (no network),
+// the clip added to the stream's project when given by seconds, its short made
+// with the live transcript's captions — followed to the end as a `live-clip`
+// job. A clip is at most 2:20 (X's limit). `project` defaults to `<id>-live`,
+// the project live pre-clip grows.
+export async function POST(request: Request) {
+ return ops(request, LIVE_CLIP_BODY_KEYS, async (body) => {
+ reqSlug(body, "slug");
+ return jobResponse(await liveClipAction(body));
+ });
+}
diff --git a/editor/app/api/ops/live-preclip/route.ts b/editor/app/api/ops/live-preclip/route.ts
@@ -0,0 +1,31 @@
+import { NextResponse } from "next/server";
+import { LIVE_PRECLIP_BODY_KEYS } from "yt-dlp-transcript-common/controller/livePreclip";
+import { livePreclipAction } from "../../../channels/[slug]/liveMediaActions";
+import { opsFail, ops, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, id, action?: "start" (default) | "stop" | "status" | "finalize",
+// everyMinutes?, maxChunkMinutes?, overlapSeconds?, scan?, mine?,
+// project? }
+// start -> { ok: true, jobId } the live-preclip job for a recording in
+// progress (record-live's `preclip` starts
+// it by itself)
+// stop -> { ok: true, jobId } that job cancelled; the recording goes on
+// status -> { ok: true, status } live-preclip.json, the live transcript's
+// summary and last cues, the job
+// finalize -> { ok: true, project } the supersede by hand, once the final
+// transcript is here
+//
+// LIVE PRE-CLIP (controller/livePreclip.ts; plans/live-preclip.md): every few
+// minutes the new span of the growing recording is transcribed on a worker
+// lease and spliced into data/<id>/live-transcript.json, and umtool's clip
+// finder grows the stream's project — no network request.
+export async function POST(request: Request) {
+ return ops(request, LIVE_PRECLIP_BODY_KEYS, async (body) => {
+ reqSlug(body, "slug");
+ const r = await livePreclipAction(body);
+ if (!r.ok) return opsFail(r.error, 400, r.info ? { info: true } : undefined);
+ return NextResponse.json(r);
+ });
+}
diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts
@@ -8,6 +8,13 @@
// instead (attachMediaAction).
// recordLiveAction `pnpm ops record-live`, "Record live" — controller/
// recordLive.ts.
+// livePreclipAction `pnpm ops live-preclip`, the video page's Live pre-clip
+// panel — controller/livePreclip.ts (start, stop,
+// status, finalize).
+// liveClipAction `pnpm ops live-clip` — controller/liveClip.ts: a share
+// of a stream still live, made by umtool.
+// liveWindowAction `POST /api/media/live-window` (umtool's share asks it):
+// a window cut now from the recording in progress.
//
// Both land through controller/landMedia.ts, and with `transcribe: true` ask
// for a transcribe-one job (whisperVideoAction) once the audio is in place —
@@ -23,6 +30,17 @@ import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/
import { parseImportRequest } from "yt-dlp-transcript-common/lib/mediaImport";
import { isArchivePath, runImportMediaJob } from "yt-dlp-transcript-common/controller/importMedia";
import { parseRecordLiveRequest, runRecordLiveJob } from "yt-dlp-transcript-common/controller/recordLive";
+import {
+ finalizeLivePreclip,
+ livePreclipStatus,
+ parseLivePreclipBody,
+ preclipDefaults,
+ startLivePreclipJob,
+ stopLivePreclip,
+ type LivePreclipStatusView,
+} from "yt-dlp-transcript-common/controller/livePreclip";
+import { liveWindow, parseLiveClipBody, runLiveClipJob, type LiveWindowOutcome } from "yt-dlp-transcript-common/controller/liveClip";
+import type { PreclipOptions } from "yt-dlp-transcript-common/lib/livePreclip";
import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
import { safeRevalidate } from "../../lib/safeRevalidate";
import { attachMediaAction } from "./attachMediaActions";
@@ -74,7 +92,7 @@ export async function importMediaAction(body: Record<string, unknown>): Promise<
}
export async function recordLiveAction(body: Record<string, unknown>): Promise<StreamActionResult> {
- const req = parseRecordLiveRequest(body);
+ const req = parseRecordLiveRequest(body, preclipDefaults());
if ("error" in req) return { ok: false, error: req.error };
if (!isValidChannelSlug(req.slug)) return { ok: false, error: `"${req.slug}" is not a channel slug` };
const paths = getPaths();
@@ -86,6 +104,73 @@ export async function recordLiveAction(body: Record<string, unknown>): Promise<S
channelConfig: config,
cookiePolicy: resolveCookiePolicy(getSettings(), config),
requestTranscription,
+ startPreclip: async (slug: string, id: string, options: PreclipOptions) => {
+ const r = await startLivePreclipJob({ paths, slug, id, channelConfig: config, options, requireRecording: false });
+ if (!r.ok) return { ok: false, error: r.error };
+ void r.stream.cancel();
+ return { ok: true, jobId: r.jobId };
+ },
afterRun: () => safeRevalidate([`/channels/${req.slug}`]),
});
}
+
+export type LivePreclipActionResult =
+ | { ok: true; action: "start"; jobId: string }
+ | { ok: true; action: "stop"; jobId: string }
+ | { ok: true; action: "status"; status: LivePreclipStatusView }
+ | { ok: true; action: "finalize"; project: string | null }
+ | { ok: false; error: string; info?: boolean };
+
+export async function livePreclipAction(body: Record<string, unknown>): Promise<LivePreclipActionResult> {
+ const parsed = parseLivePreclipBody(body, preclipDefaults());
+ if (!parsed.ok) return parsed;
+ const { slug, id, action, options } = parsed.value;
+ if (!isValidChannelSlug(slug)) return { ok: false, error: `"${slug}" is not a channel slug` };
+ const paths = getPaths();
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `Channel "${slug}" not found` };
+ if (action === "status") return { ok: true, action, status: await livePreclipStatus(paths, slug, id) };
+ if (action === "stop") {
+ const r = stopLivePreclip(slug, id);
+ return r.ok ? { ok: true, action, jobId: r.jobId } : r;
+ }
+ if (action === "finalize") {
+ const r = await finalizeLivePreclip({ paths, slug, id, ...(options.project ? { options: { project: options.project } } : {}) });
+ return r.ok ? { ok: true, action, project: r.project } : r;
+ }
+ const r = await startLivePreclipJob({ paths, slug, id, channelConfig: config, options });
+ if (!r.ok) return { ok: false, error: r.error, ...(r.info ? { info: true } : {}) };
+ void r.stream.cancel();
+ safeRevalidate([`/channels/${slug}/videos/${id}`]);
+ return { ok: true, action, jobId: r.jobId };
+}
+
+export async function liveClipAction(body: Record<string, unknown>): Promise<StreamActionResult> {
+ const parsed = parseLiveClipBody(body);
+ if (!parsed.ok) return parsed;
+ if (!isValidChannelSlug(parsed.value.slug)) return { ok: false, error: `"${parsed.value.slug}" is not a channel slug` };
+ const paths = getPaths();
+ if (!(await readChannelConfig(paths, parsed.value.slug))) return { ok: false, error: `Channel "${parsed.value.slug}" not found` };
+ return runLiveClipJob({ paths, request: parsed.value });
+}
+
+export async function liveWindowAction(body: {
+ slug: string;
+ id: string;
+ from: number;
+ to: number;
+ requestedBy?: string;
+ manifest?: string;
+ clipId?: string;
+ reason?: string;
+}): Promise<LiveWindowOutcome> {
+ if (!isValidChannelSlug(body.slug)) return { ok: false, status: 400, error: `"${body.slug}" is not a channel slug` };
+ const paths = getPaths();
+ const config = await readChannelConfig(paths, body.slug);
+ if (!config) return { ok: false, status: 404, error: `Channel "${body.slug}" not found` };
+ try {
+ return await liveWindow({ paths, channelConfig: config, ...body });
+ } catch (e) {
+ return { ok: false, status: 500, error: (e as Error).message };
+ }
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/LivePreclipPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/LivePreclipPanel.tsx
@@ -0,0 +1,208 @@
+"use client";
+
+// LIVE PRE-CLIP (plans/live-preclip.md): a recording in progress transcribed
+// and mined while it records — the same job as `pnpm ops live-preclip`
+// (controller/livePreclip.ts). Drawn when the video has a live recording or a
+// live transcript: the job's state (ticks, what was skipped and why, the last
+// lines), the umtool project it grows, the PROVISIONAL transcript so far, and
+// a share of a few seconds of it while it is still live (`pnpm ops live-clip`).
+//
+// TYPE-ONLY from the controller (it reaches node:fs): the state arrives as
+// props, read by the page.
+
+import { useState } from "react";
+import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog";
+import type { LivePreclipStatusView } from "yt-dlp-transcript-common/controller/livePreclip";
+import type { Cue } from "yt-dlp-transcript-common/lib/vtt";
+import { cancelJobAction } from "../../../../../jobs/actions";
+import { shareLiveClipAction, startLivePreclipAction, stopLivePreclipAction } from "../livePreclipActions";
+
+const input = "rounded border border-border bg-card px-2 py-1 text-sm";
+
+function clock(seconds: number): string {
+ const s = Math.max(0, Math.round(seconds));
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ const sec = s % 60;
+ return h > 0 ? `${h}:${String(m).padStart(2, "0")}:${String(sec).padStart(2, "0")}` : `${m}:${String(sec).padStart(2, "0")}`;
+}
+
+// "1:02:03", "62:03" or "3723" → seconds.
+function parseClock(v: string): number | null {
+ const t = v.trim();
+ if (!t) return null;
+ if (/^\d+(\.\d+)?$/.test(t)) return Number(t);
+ const parts = t.split(":").map(Number);
+ if (parts.some((p) => !Number.isFinite(p))) return null;
+ return parts.reduce((a, p) => a * 60 + p, 0);
+}
+
+export function LivePreclipPanel({
+ slug,
+ videoId,
+ umtoolUrl,
+ view,
+ cues,
+}: {
+ slug: string;
+ videoId: string;
+ umtoolUrl: string | null;
+ view: LivePreclipStatusView;
+ // The live transcript's cues (all of them, while it is not superseded).
+ cues: Cue[];
+}) {
+ const [every, setEvery] = useState("");
+ const [from, setFrom] = useState("");
+ const [to, setTo] = useState("");
+ const [stopNote, setStopNote] = useState<string | null>(null);
+ const state = view.state;
+ const t = view.transcript;
+ const recording = view.recording?.status === "recording";
+ const running = view.job !== null;
+ const start = parseClock(from);
+ const end = parseClock(to);
+ const shareOk = start !== null && end !== null && end > start && end - start <= 140;
+ const status = running
+ ? `running — ${state?.ticks ?? 0} tick(s), ${clock(t?.transcribedTo ?? 0)} transcribed${state?.recordedSeconds ? ` of ${clock(state.recordedSeconds)}` : ""}`
+ : state
+ ? `${state.status}${t ? ` — ${clock(t.transcribedTo)} transcribed` : ""}`
+ : recording
+ ? "not running"
+ : "—";
+ return (
+ <section aria-label="live pre-clip panel" className="flex flex-col gap-3 rounded border border-border p-3">
+ <div className="flex flex-wrap items-baseline justify-between gap-2">
+ <h2 className="text-lg font-semibold">Live pre-clip</h2>
+ <span aria-label="live pre-clip status" className="text-xs text-muted-foreground">
+ {status}
+ </span>
+ </div>
+ {!umtoolUrl && (
+ <p role="status" className="text-sm text-muted-foreground">
+ UMTOOL_URL is not set on the editor: the live transcript is kept, no clip windows are mined.
+ </p>
+ )}
+ {recording && !running && (
+ <div className="flex flex-wrap items-end gap-3 text-sm">
+ <label className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground">Every (minutes; empty = {state?.options.everyMinutes ?? 10})</span>
+ <input type="number" min={1} max={120} value={every} onChange={(e) => setEvery(e.target.value)} aria-label="pre-clip every (minutes)" className={`${input} w-24`} />
+ </label>
+ </div>
+ )}
+ {recording && !running && (
+ <StreamActionLog
+ trigger={() => startLivePreclipAction(slug, videoId, Number(every) > 0 ? Number(every) : undefined)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Start pre-clip"
+ runningLabel="Pre-clipping…"
+ label={`Live pre-clip of ${videoId}`}
+ />
+ )}
+ {running && (
+ <div className="flex flex-wrap items-center gap-3 text-sm">
+ <button
+ type="button"
+ className="rounded border border-border px-2 py-1"
+ aria-label="stop pre-clip"
+ onClick={async () => {
+ const r = await stopLivePreclipAction(slug, videoId);
+ setStopNote(r.ok ? "Stopped (the recording goes on)." : (r.error ?? "not stopped"));
+ }}
+ >
+ Stop pre-clip
+ </button>
+ <a href={`/jobs/${view.job!.id}`} className="underline">
+ its job
+ </a>
+ {stopNote && <span className="text-muted-foreground">{stopNote}</span>}
+ </div>
+ )}
+ {state && (
+ <div className="flex flex-col gap-1 text-sm">
+ {state.mined && (
+ <p>
+ Clips:{" "}
+ {umtoolUrl ? (
+ <a href={`${umtoolUrl}/projects/${encodeURIComponent(state.mined.project)}/clips`} className="font-mono underline" data-live-project>
+ {state.mined.project}
+ </a>
+ ) : (
+ <span className="font-mono">{state.mined.project}</span>
+ )}{" "}
+ <span className="text-muted-foreground">
+ — {state.mined.proposals} proposal(s), {state.mined.clips} clip(s)
+ {state.mined.error ? `; last mining failed: ${state.mined.error}` : ""}
+ </span>
+ </p>
+ )}
+ {state.check && (
+ <p aria-label="live pre-clip check" className={state.check.verdict === "same" || state.check.verdict === "same-recording" ? "text-muted-foreground" : "text-amber-600"}>
+ Landing check: {state.check.verdict} — {state.check.why}
+ </p>
+ )}
+ {Object.keys(state.skipped).length > 0 && (
+ <p className="text-xs text-muted-foreground">
+ Skipped ticks: {Object.entries(state.skipped).map(([k, n]) => `${k} ${n}`).join(", ")}
+ </p>
+ )}
+ {state.log.length > 0 && (
+ <pre aria-label="live pre-clip log" className="max-h-40 overflow-auto whitespace-pre-wrap rounded bg-muted p-2 text-xs">
+ {state.log.join("\n")}
+ </pre>
+ )}
+ </div>
+ )}
+ {t && (
+ <details className="text-sm" open={recording}>
+ <summary>
+ Live transcript ({t.status === "superseded" ? "superseded by the final transcript" : "provisional"}): {t.cues} cue(s) to {clock(t.transcribedTo)}
+ {t.restarts ? `, restarted ${t.restarts}×` : ""}
+ </summary>
+ {t.status !== "superseded" && (
+ <ol aria-label="live transcript" className="mt-2 flex max-h-96 flex-col gap-0.5 overflow-auto font-mono text-xs">
+ {cues.map((c, i) => (
+ <li key={`${c.start}-${i}`}>
+ <button
+ type="button"
+ className="text-muted-foreground underline-offset-2 hover:underline"
+ title="share from here"
+ onClick={() => {
+ setFrom(clock(c.start));
+ if (!to) setTo(clock(c.start + 30));
+ }}
+ >
+ {clock(c.start)}
+ </button>{" "}
+ {c.text}
+ </li>
+ ))}
+ </ol>
+ )}
+ </details>
+ )}
+ {(recording || (t && t.status !== "superseded")) && (
+ <div className="flex flex-col gap-2 text-sm">
+ <div className="flex flex-wrap items-end gap-3">
+ <label className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground">Share from</span>
+ <input value={from} onChange={(e) => setFrom(e.target.value)} placeholder="1:02:03" aria-label="share from" className={`${input} w-28`} />
+ </label>
+ <label className="flex flex-col gap-0.5">
+ <span className="text-xs text-muted-foreground">to (at most 2:20 later)</span>
+ <input value={to} onChange={(e) => setTo(e.target.value)} placeholder="1:03:00" aria-label="share to" className={`${input} w-28`} />
+ </label>
+ </div>
+ <StreamActionLog
+ trigger={() => shareLiveClipAction(slug, videoId, start ?? 0, end ?? 0)}
+ cancelAction={cancelJobAction}
+ buttonLabel="Share this clip"
+ runningLabel="Making the short…"
+ label={`Live share of ${videoId}`}
+ disabled={!umtoolUrl || !shareOk}
+ />
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/livePreclipActions.ts b/editor/app/channels/[slug]/videos/[id]/livePreclipActions.ts
@@ -0,0 +1,35 @@
+"use server";
+
+// The video page's Live pre-clip panel: the same jobs as `pnpm ops
+// live-preclip` and `pnpm ops live-clip` (controller/livePreclip.ts,
+// controller/liveClip.ts). NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use
+// server" file).
+
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
+import { preclipDefaults, startLivePreclipJob, stopLivePreclip } from "yt-dlp-transcript-common/controller/livePreclip";
+import { parseLiveClipBody, runLiveClipJob } from "yt-dlp-transcript-common/controller/liveClip";
+import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand";
+import { safeRevalidate } from "../../../../lib/safeRevalidate";
+
+export async function startLivePreclipAction(slug: string, videoId: string, everyMinutes?: number): Promise<StreamActionResult> {
+ const paths = getPaths();
+ const config = await readChannelConfig(paths, slug);
+ if (!config) return { ok: false, error: `Channel "${slug}" not found` };
+ const options = { ...preclipDefaults(), ...(everyMinutes && everyMinutes >= 1 && everyMinutes <= 120 ? { everyMinutes: Math.round(everyMinutes) } : {}) };
+ const r = await startLivePreclipJob({ paths, slug, id: videoId, channelConfig: config, options });
+ safeRevalidate([`/channels/${slug}/videos/${videoId}`]);
+ return r;
+}
+
+export async function stopLivePreclipAction(slug: string, videoId: string): Promise<{ ok: boolean; error?: string }> {
+ const r = stopLivePreclip(slug, videoId);
+ safeRevalidate([`/channels/${slug}/videos/${videoId}`]);
+ return r.ok ? { ok: true } : { ok: false, error: r.error };
+}
+
+export async function shareLiveClipAction(slug: string, videoId: string, start: number, end: number): Promise<StreamActionResult> {
+ const parsed = parseLiveClipBody({ slug, id: videoId, start, end });
+ if (!parsed.ok) return parsed;
+ return runLiveClipJob({ paths: getPaths(), request: parsed.value });
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -49,6 +49,9 @@ import { TagsPanel } from "./components/TagsPanel";
import { FrameScanPanel } from "./components/FrameScanPanel";
import { FindClipsPanel } from "./components/FindClipsPanel";
import { loadFindClipsRecord } from "yt-dlp-transcript-common/lib/findClipsRecord-server";
+import { LivePreclipPanel } from "./components/LivePreclipPanel";
+import { livePreclipStatus } from "yt-dlp-transcript-common/controller/livePreclip";
+import { liveTranscriptSidecar } from "yt-dlp-transcript-common/lib/livePreclip-server";
import { umtoolUrl as resolveUmtoolUrl } from "yt-dlp-transcript-common/lib/umtoolUrl";
import { frameScanView } from "./lib/frameScanView";
import { loadFrameScans } from "yt-dlp-transcript-common/lib/frameScan-server";
@@ -228,6 +231,21 @@ export default async function VideoDetailPage({
// What the last Find clips found (release 36 lane A): one small sidecar.
const findClips = await loadFindClipsRecord(videoDir);
+ // Live pre-clip (plans/live-preclip.md): only for a video with a live
+ // recording or a live transcript — two small sidecars, then the
+ // transcript's cues while it is not superseded.
+ const livePreclipView = await livePreclipStatus(getPaths(), slug, id);
+ const livePreclip =
+ livePreclipView.recording || livePreclipView.transcript
+ ? {
+ view: livePreclipView,
+ cues:
+ livePreclipView.transcript && livePreclipView.transcript.status !== "superseded"
+ ? ((await liveTranscriptSidecar.load(videoDir))?.cues ?? [])
+ : [],
+ }
+ : null;
+
// The curated tags on this video, with each one's provenance. Reads tags.json
// plus (for rule hits) ONE key out of the transcript index — not a scan.
const tagsView = await loadVideoTags(slug, id);
@@ -254,6 +272,7 @@ export default async function VideoDetailPage({
tagsView,
frameScans,
findClips,
+ livePreclip,
};
};
const drive = config.dataDir?.trim();
@@ -289,6 +308,7 @@ export default async function VideoDetailPage({
tagsView,
frameScans,
findClips,
+ livePreclip,
} = loaded;
const registry = getRegistry();
@@ -451,6 +471,11 @@ export default async function VideoDetailPage({
readingT={readingT}
/>
+ {/* A recording in progress, transcribed and mined while it records. */}
+ {livePreclip && (
+ <LivePreclipPanel slug={slug} videoId={id} umtoolUrl={resolveUmtoolUrl()} view={livePreclip.view} cues={livePreclip.cues} />
+ )}
+
{/* The clip finder's chain for this video (release 36 lane A). */}
<FindClipsPanel
slug={slug}
diff --git a/plans/live-preclip.md b/plans/live-preclip.md
@@ -0,0 +1,158 @@
+# Live pre-clip — transcribe and mine a live stream while it records (lane `lane/live-preclip`)
+
+Asked by the operator on 2026-10-27: "I want to add the ability to start pre-clipping a live stream by
+periodically copying the partial file, transcribing it, and mining clip windows." Two additions the same day:
+"since streams download first-to-last naturally the partial mined clips will still be relevant on the full
+video" (the partial's clock IS the final video's clock: no re-anchoring, a cheap check, a flag when it fails),
+and "it'd also be cool to get shareable clips from a partial in case something really interesting happens on a
+long stream" (a captioned, X-sized clip of a window while the stream is still live).
+
+## What was measured (ffmpeg n9.0.2, 2026-10-27)
+
+- A growing MPEG-TS (a 20-minute TS cut at an arbitrary byte, mid-packet): `ffprobe` reads its duration from the
+ last PTS it finds (234.76 s for 7 MB of 35.8 MB — exact); `ffmpeg -ss 200 -i grow.ts -vn …wav` takes 0.18 s
+ and gives the 34.6 s from 200 s to the end of what is written. The trailing partial packet is dropped.
+- A growing fragmented MP4 (audio, 1-hour, 2 s fragments, cut mid-fragment at 10 MB of 14.9 MB): `ffprobe` gives
+ 2420.7 s; `ffmpeg -ss 2300 -i grow.m4a` takes 0.34 s. The partial last fragment logs a decoder error and the
+ exit is still 0.
+- `-ss` on an input is relative to the input's start time, and the landing's remux (`-c copy`, no `-copyts`)
+ subtracts the same start time: a TS whose audio starts at PTS 1001.336 lands as an mp4 whose audio starts at
+ 0. So **second S of the growing file, read with `-ss S`, is second S of the landed video**, for the muxed
+ recordings; for separate streams the merge subtracts each input's own start, so second S of the growing
+ audio stream is second S of the landed video's audio.
+
+## Design
+
+### The per-tick snapshot: a byte prefix, read by time
+
+A recording is append-only. The bytes a recorder has written never change, so the "stable, readable copy" of a
+tick is the prefix of the file already written — nothing is copied. Each tick:
+
+1. finds the part being recorded (`live-recording.json`'s parts — each now records its `stem` — and the files
+ named for it, `lib/liveCapture.ts livePartFiles`) and the AUDIO-BEARING file in it:
+ - muxed (`<stem>.ts`: yt-dlp `--hls-use-mpegts`, the browser path's ffmpeg, Kick's VOD poller): the file;
+ - separate (`<stem>.f<id>.<ext>`, YouTube): the stream ffprobe says holds audio (cached per file); the video
+ stream is never read by a tick;
+ - Kick records two parts at once (the VOD from segment 0, the channel from now): the from-start part wins.
+2. probes how many seconds it holds (`ffprobe` format duration — the TS tail's last PTS, the fMP4's fragments;
+ cheap, never proportional to the stream) and keeps a 2 s margin from the live edge;
+3. cuts ONLY the new span's audio — `ffmpeg -ss <from> -i <file> -t <span> -vn -ac 1 -ar 16000` — into a 16 kHz
+ WAV in the pre-clip's work dir on the store's disk (`<store>/<slug>/.<id>.preclip/`, never /tmp, removed
+ after each tick and at the end). The cost of a tick is the new span: ffmpeg seeks a TS by its timestamps and
+ an fMP4 by its fragments.
+
+The span starts `overlapSeconds` (15) before the end of what is transcribed, so a word cut by the boundary is
+heard whole once; the splice keeps the old cues before the overlap's middle and the new ones from it.
+
+### The job: `live-preclip`, one per stream
+
+Its own job kind and queue (`live-preclip:<slug>:<id>`), separate from the recorder's: starting or stopping
+pre-clip never touches the recording. `record-live {"preclip": true | {everyMinutes, maxChunkMinutes, scan}}`
+starts it once the first part begins (and implies `transcribe: true` for the landing); `pnpm ops live-preclip
+{slug, id, action: "start"}` starts it on a recording already running; `"stop"` cancels it; `"status"` prints
+its state; `"finalize"` runs the supersede by hand. The default period and caps are settings
+(`settings.livePreclip`).
+
+Ticks never pile up: the job IS the queue. One transcription is in flight at a time, on a worker lease from the
+pool (`transcribeFile.ts runTranscribeFile`, the path `pnpm ops transcribe` and find-clips' word timings take —
+the "foreground" tier: ahead of the lane's background units, behind a manual batch queued first). While it waits
+for a worker or runs, no further tick is asked for; when it returns, the next tick covers everything since,
+capped at `maxChunkMinutes` (20) — and a tick that leaves the transcript behind by more than a period starts
+the next at once (catch-up) instead of sleeping.
+
+Skipped, and said in the log, never silently: a tick with less than 30 s new ("no new data"); MemAvailable
+under the heavy slot's floor (`HEAVY_MIN_FREE_MB`, 6000 — re-checked every minute, one line per due tick); the
+store's disk under 2 GB free; a part that is not readable yet. A recorder restart or fallback (a new part) is a
+new BASIS: when the new part's opening audio matches the old one's (the fingerprint below) the transcript goes
+on; else it starts again on the new part's clock, and umtool is told (the project's windows are flagged).
+
+### The live transcript: `data/<id>/live-transcript.json`
+
+A per-video sidecar (`sidecar()`; not `transcript.<x>.<y>`, so it is never a caption track, and not
+`transcript.json`, so the index, find-clips and the transcription lane never read it as THE transcript):
+`{version, provisional: true, status: "live" | "landed" | "superseded", basis {stem, file, audioFile},
+transcribedTo, cues [{start, end, text}], words [{w, start, end}], scan {hop, window, energy[], laugh[] | null,
+model}, chunks [{from, to, cues, words, worker, at}], fingerprint {from, hop, env[]}, updatedAt}`, every time on
+the stream's (= the landed video's) clock. `live-preclip.json` beside it is the job's state: status, options,
+ticks, skips by reason, the last ten tick lines, transcribed seconds, what was mined, the landing check.
+
+The laugh scan runs on each tick's WAV (`lib/clips/scan.mjs runAudioScan`, the same CED tagger umtool's
+`clips analyze` uses, energy only when no model) and is spliced into the doc by window index: the scan is
+incremental too.
+
+### Mining: umtool `POST /api/report/clips {mode: "live"}`
+
+Synchronous (a proposal pass is arithmetic; it does not wait behind a render on umtool's one-job runner). umtool
+reads the editor's `live-transcript.json` from the corpus and keeps the project's own copy of the recording in
+its `.shadow-channels/<slug>/data/<id>/` (a project with a shadow dir reads its recording from there —
+`report-to-video/sources.mjs channelsDirFor`): `transcript.cues.json` (the live cues), a synthetic
+`diarization.json` (one speaker, turns from the cues — the clip finder needs turns; the real diarization comes
+with the landing), `metadata.info.json` (the record's), `clips -> <corpus>/data/<id>/clips` (the editor's clip
+cache, where a live share's window lands), plus `<project>/words.json` (the live words) and the scan cache
+`scans/<slug>--<id>.audio.json` (the live scan). The first call scaffolds the project with the reactions seed
+(`<id>-live` unless named); every call runs `proposeProject` over `[0, transcribedTo − 20 s]` (the live edge is
+left for the next tick, so a proposal is never cut mid-thought). Ids are stable (`stableIds`: a proposal that
+overlaps an earlier one keeps its id), ruled and edited clips are protected (`rulingsGuard`), so the windows
+grow without re-proposing what was proposed. No model step: when the CED model is missing the laughs are the
+transcript's markers and the energy bursts (the clip finder's own fallback), and the phrase finder and the clip
+editor's strip work over the shadow cues as over any recording.
+
+### When the stream ends: the supersede
+
+The recording lands as before (the longest part). The pre-clip job then:
+
+1. **checks the clock**: the landed part is the basis part → "same recording" (append-only, nothing to check);
+ else the RMS envelope of 30 s of audio (100 ms frames, from 60 s in) of the landed video is compared with
+ the one taken from the basis when it was recorded: correlation ≥ 0.75 at a lag ≤ 0.3 s → "same"; a
+ correlation at a larger lag → "shifted by N s" (flagged, not moved); none → "mismatch"; silence → "unverified";
+2. marks the live transcript `landed`, then waits (a stat every 2 minutes, up to 24 h) for the final
+ `transcript.json`; then marks it `superseded` and tells umtool `{mode: "live", final: true, check}`: the
+ shadow dir goes (the project now reads the corpus — the final cues and, once diarized, the speakers), the
+ project's `words.json` becomes the final words (data/<id>/words.json when find-clips made it, else it is
+ removed so captions come from transcript.json), and the windows stay as they are, by source second — flagged
+ in the clip editor when the check was not "same". A wait that times out leaves `landed` and `pnpm ops
+ live-preclip {action: "finalize"}` does the rest.
+
+The provisional and the final transcripts are never mixed: different files, and every reader that prefers the
+live one does so only while `transcript.json` is absent.
+
+### Shareable clips from a partial
+
+`pnpm ops live-clip {slug, id, start, end | clip, project?}` and the clip editor's **Share now** (a live
+project): umtool `POST /api/report/live-share {project, clip | start, end}`:
+
+1. adds the clip to the project when given by seconds (the clip editor's `add`, the clip finder's 1.5 s pad);
+2. asks the editor `POST /api/media/live-window {slug, id, from, to}` (WORKER_TOKEN) for the build's own span of
+ the clip (build-video.mjs `fetchSpan`: its extent plus `render.fetchPad`), cut from the growing recording NOW
+ into the clip cache, `data/<id>/clips/<from>-<to>.mp4` with its provenance (`source: "live-recording"`), in the
+ cache's format (H.264 ≤720p + AAC, the first frame the asked-for second — re-encoded, as every cut window is;
+ seeked 10 s early and trimmed on the output, because an MPEG-TS seeks by timestamp, not to a keyframe:
+ measured, an input `-ss` lost the first 1.1 s of picture). This is the snapshot-on-demand: it reads the bytes
+ written so far, so it is never older than the request; a window past what is recorded is refused with how
+ many seconds to wait. After the landing the same call cuts from the saved video. No network request, and the
+ recorder is only read;
+3. makes its short (`build-video.mjs --short`, `--skip-fetch --no-network`: the window above is the source, the
+ live words the captions), refusing a clip over 2:20; a short over 512 MiB (it is not, at 2:20) is refused
+ with the size rather than posted.
+
+## What is incremental, and what is not
+
+| Step | Per tick | Notes |
+|---|---|---|
+| audio cut | the new span | ffmpeg seeks by time; nothing is copied |
+| transcription | the new span (+15 s overlap) | one lease at a time, coalesced, capped |
+| laugh / energy scan | the new span | spliced by window index |
+| proposal pass | the whole transcript | arithmetic over cues/words/scan, milliseconds to seconds |
+| shadow files | rewritten whole | JSON of the transcript so far (MBs at 4 h) |
+
+## Owed / not built
+
+- Speakers during the stream (a live diarization): one synthetic speaker until the landing.
+- Chat during the stream: the replay is fetched after (fetch-chat), not live.
+- MPEG-TS PTS wrap (26.5 h) and a discontinuity inside one part are not handled: a part that resets its clock is
+ read as ffmpeg reads it.
+- The phrase finder reads the corpus's transcript.cues.json, so during the stream it does not see the live
+ transcript; the clip editor's strip (the project's shadow cues and words) and the video page's live transcript
+ (click a time to share from it) are the manual paths until the landing.
+- Not tried on a real stream yet (no stream was live while it was built, and the heavy gates were held for the
+ operator's renders): the tests write synthetic TS and fMP4 recordings in increments.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -50,6 +50,9 @@
// pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait
// pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'
// pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'
+// pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'
+// pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'
+// pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait
// pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'
// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'
// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait
@@ -394,6 +397,14 @@ const ACTIONS = [
// job; both land through the same code.
"import-media",
"record-live",
+ // LIVE PRE-CLIP (plans/live-preclip.md): a recording in progress transcribed
+ // and mined while it records ({slug, id, action?: start | stop | status |
+ // finalize, everyMinutes?, maxChunkMinutes?, overlapSeconds?, scan?, mine?,
+ // project?}) — record-live's "preclip" starts it by itself — and a
+ // shareable clip of it cut now and made by umtool ({slug, id, start, end |
+ // clip, project?, replace?}).
+ "live-preclip",
+ "live-clip",
// A channel's saved containers remuxed losslessly into browser-playable
// copies, one torrent each ({slug, ids?, trackers?, root?, dryRun?}).
"prepare-playable",
@@ -634,6 +645,9 @@ export const REMOTE_LISTING_RESULT_MARKER = "@@remote-listing ";
// The same for Find clips (FIND_CLIPS_RESULT_MARKER in
// common/controller/findClips.ts).
export const FIND_CLIPS_RESULT_MARKER = "@@find-clips ";
+// The same for a live share (LIVE_CLIP_RESULT_MARKER in
+// common/controller/liveClip.ts).
+export const LIVE_CLIP_RESULT_MARKER = "@@live-clip ";
// The provenance a tag write from this CLI carries. Everything else ignores it.
function agentSource() {
@@ -883,6 +897,7 @@ export function parseArgs(argv) {
...(action === "frame-scan" ? { resultMarker: FRAME_SCAN_RESULT_MARKER } : {}),
...(action === "mirror-scan" ? { resultMarker: MIRROR_SCAN_RESULT_MARKER } : {}),
...(action === "find-clips" ? { resultMarker: FIND_CLIPS_RESULT_MARKER } : {}),
+ ...(action === "live-clip" ? { resultMarker: LIVE_CLIP_RESULT_MARKER } : {}),
...(action === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}),
wait,
quiet,
@@ -1530,7 +1545,33 @@ export function usage() {
" polled from its first segment beside the channel's live stream. One job",
" per stream; job cancel stops it with SIGINT and lands what it has (video",
" and audio left unmerged are merged, -c copy); the longest part wins.",
- " Refused for a stream that is not live.",
+ " Refused for a stream that is not live. \"preclip\": true (or",
+ ' {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine",',
+ ' "project"}, over settings.livePreclip) starts live-preclip once the first',
+ ' part begins, and implies "transcribe".',
+ "",
+ 'live-preclip transcribes and mines a recording WHILE it records: {"slug",',
+ ' "id", "action"?: "start" (default) | "stop" | "status" | "finalize"}, and',
+ ' for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"?',
+ ' (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the',
+ " umtool project, <id>-live). One job per stream beside the recorder's: each",
+ " tick reads only the new span of the growing file (never writing it),",
+ " transcribes it on a worker lease (one at a time — a busy worker coalesces",
+ " ticks), splices it into data/<id>/live-transcript.json (provisional) and",
+ " grows the umtool project. Skipped and said: under 30 s new, MemAvailable",
+ " under HEAVY_MIN_FREE_MB (6000), the store's disk under 2 GB. When the",
+ " stream lands: the clock check (flagged when the landed video's start",
+ " differs), then the final transcript supersedes the live one. stop cancels",
+ " the job, never the recording; status prints the state; finalize does the",
+ " supersede by hand. No network request.",
+ "",
+ 'live-clip makes a shareable clip of a stream still live: {"slug", "id",',
+ ' "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id',
+ ' of the project), "project"? (<id>-live), "replace"?. umtool cuts the',
+ " window from the recording now (the editor's /api/media/live-window: the",
+ " part being written, or the saved video once landed; no network), adds",
+ " the clip, and makes its short with the live transcript's captions. With",
+ " --wait the result (the short's URL) is stdout.",
"",
'prepare-playable remuxes each of a channel\'s saved containers, losslessly',
' (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes',
diff --git a/settings.json.example b/settings.json.example
@@ -9,6 +9,13 @@
"x": {}
},
"sleepBetweenDownloadsSeconds": 10,
+ "livePreclip": {
+ "everyMinutes": 10,
+ "maxChunkMinutes": 20,
+ "overlapSeconds": 15,
+ "scan": true,
+ "mine": true
+ },
"pacing": {
"sleepRequestsCapSeconds": 16,
"decayAfterCleanUnits": 5,
diff --git a/umtool/app/api/report/clips/route.ts b/umtool/app/api/report/clips/route.ts
@@ -2,6 +2,7 @@ import { getJob, jobView, runningJob, startJob } from "@/lib/jobs";
import { invalidateProjects, projectRef } from "@/lib/projects";
import { agentToken, routeCaller } from "@/lib/annotations/agentAuth.mjs";
import { ClipsNewError, planClipsNew } from "@/lib/report/clipsNew.mjs";
+import { liveClips } from "@/lib/report/clipsLive.mjs";
import { clipEditorHref } from "@/lib/hrefs";
import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
@@ -25,6 +26,10 @@ export const dynamic = "force-dynamic";
// segment?, wordsPath? } (release 36: the editor's Find clips) → { jobId, job, project, created, segments,
// segment, scope, href, notes } — a reactions project for the same recording whose scope covers the
// chosen one is analyzed again (`created: false`), else `slug` is scaffolded (lib/report/clipsNew.mjs)
+// POST { mode: "live", slug, from: "<channel>/<id>", final?, check? } (live pre-clip, the editor's
+// live-preclip job after each tick) → { project, created, proposals, clips, minedTo, flags, notes, href }
+// — synchronous, no job: the stream's project grown from data/<id>/live-transcript.json
+// (lib/report/clipsLive.mjs); `final` hands it to the corpus
// ?cancel=<job> stop it
// A POST with no Authorization header is the app's page; `Bearer <WORKER_TOKEN>` the editor; any other: 401.
export async function GET(request: Request) {
@@ -78,6 +83,7 @@ export async function POST(request: Request) {
const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 });
if (body.mode === "new") return startNew(body);
+ if (body.mode === "live") return liveMode(body);
const project = await projectRef(String(body.project ?? ""));
if (!project) return Response.json({ error: "no such project" }, { status: 404 });
if (!kindMakesTakes(project.kind)) return Response.json({ error: "clips are found for a report video" }, { status: 400 });
@@ -101,6 +107,23 @@ export async function POST(request: Request) {
}
}
+/**
+ * `mode: "live"` (plans/live-preclip.md): the stream's project made or grown
+ * from the editor's live transcript — one proposal pass, answered here, never
+ * a job (it must not wait behind a render). `final: true` hands it to the
+ * corpus (lib/report/clipsLive.mjs).
+ */
+async function liveMode(body: Record<string, unknown>) {
+ try {
+ const r = await liveClips(body);
+ invalidateProjects();
+ return Response.json({ ok: true, ...r }, { headers: { "cache-control": "no-store" } });
+ } catch (e) {
+ const status = e instanceof ClipsNewError ? e.status : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status });
+ }
+}
+
/** `mode: "new"`: the project found or scaffolded, then `clips analyze` as one job. */
async function startNew(body: Record<string, unknown>) {
const running = runningJob();
diff --git a/umtool/app/api/report/live-share/route.ts b/umtool/app/api/report/live-share/route.ts
@@ -0,0 +1,55 @@
+import { jobView, runningJob, startJob } from "@/lib/jobs";
+import { invalidateProjects, projectRef } from "@/lib/projects";
+import { agentToken, routeCaller } from "@/lib/annotations/agentAuth.mjs";
+import { kindMakesTakes } from "@/lib/projects/kinds.mjs";
+import { LiveShareError, editorWindowAsker, prepareLiveShare } from "@/lib/report/liveShare.mjs";
+import { setShortAside, shortSteps } from "@/lib/report/shorts.mjs";
+
+export const dynamic = "force-dynamic";
+
+// A SHAREABLE CLIP OF A STREAM STILL LIVE (plans/live-preclip.md;
+// lib/report/liveShare.mjs): the clip (added at [start, end] when given by
+// seconds), its window cut NOW by the editor from the recording in progress
+// (`/api/media/live-window`), then its short (`build-video --short`, no
+// network) as ONE job on the app's runner — followed on /api/report/shorts
+// (`?job=`), listed there like any short. The clip editor's Share now; `pnpm
+// ops live-clip` asks it with the WORKER_TOKEN.
+//
+// POST { project, clip | start, end, from?: "<channel>/<id>", replace? }
+// → { ok, clip, added, window, windowSource, job }
+// → 409 { error } past what is recorded ("ask again in N s"), a job running,
+// or a short already there (needsReplace)
+const headers = { "cache-control": "no-store" };
+
+export async function POST(request: Request) {
+ const who = routeCaller(request.headers.get("authorization"), agentToken(), "/api/report/live-share");
+ if (!who.ok) return Response.json({ error: who.error }, { status: who.status, headers });
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers });
+ const project = await projectRef(String(body.project ?? ""));
+ if (!project) return Response.json({ error: `no project ${String(body.project ?? "")}` }, { status: 404, headers });
+ if (!kindMakesTakes(project.kind)) return Response.json({ error: "a share is made of a report video's clip" }, { status: 400, headers });
+ const running = runningJob();
+ if (running) return Response.json({ error: `a job is already running (${running.kind})`, running: jobView(running) }, { status: 409, headers });
+ let prepared: Awaited<ReturnType<typeof prepareLiveShare>>;
+ try {
+ prepared = await prepareLiveShare(project, body, { askWindow: editorWindowAsker() });
+ } catch (e) {
+ const status = e instanceof LiveShareError ? e.status : 500;
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers });
+ }
+ invalidateProjects();
+ let aside: string | null = null;
+ try {
+ aside = await setShortAside(project.dir, prepared.clip, { replace: body.replace === true || prepared.added });
+ } catch (e) {
+ const needsReplace = !!(e as { needsReplace?: boolean })?.needsReplace;
+ return Response.json({ error: e instanceof Error ? e.message : String(e), needsReplace, clip: prepared.clip }, { status: 409, headers });
+ }
+ try {
+ const job = startJob(`short ${project.id} ${prepared.clip}`, shortSteps(project, prepared.clip, { offline: true }), { project: project.id });
+ return Response.json({ ok: true, ...prepared, aside, job: jobView(job) }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e), clip: prepared.clip }, { status: 409, headers });
+ }
+}
diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx
@@ -480,6 +480,20 @@ export default function ClipEditor({
return (
<div data-clip-editor={clip.id} data-clip-editor-busy={busy ? "" : undefined} className="flex min-h-0 flex-1 flex-col lg:grid lg:grid-cols-[minmax(0,1fr)_minmax(300px,26%)]">
<main data-bench-work="" className="deck-main min-h-0 space-y-3 overflow-auto p-4">
+ {view.live && (
+ <div data-live-project={view.live.status} className="space-y-0.5 text-[12px] text-text-2">
+ <p className="m-0">
+ {view.live.status === "live"
+ ? `Live: the stream is transcribed to ${edgeClock(view.live.transcribedTo)}, mined to ${edgeClock(view.live.minedTo)} (${view.live.passes} pass${view.live.passes === 1 ? "" : "es"}) — the words are provisional; more windows come as it records.`
+ : "Was live: the project reads the final transcript now; its windows stayed where they were."}
+ </p>
+ {view.live.flags.map((f) => (
+ <p key={f.why} role="alert" className="m-0 text-reject-text">
+ {f.why}
+ </p>
+ ))}
+ </div>
+ )}
{/* ---- the clip ---------------------------------------------------- */}
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
<h1 className="m-0 font-mono text-[15px] font-semibold text-text" data-editor-clip-id="">
@@ -833,7 +847,7 @@ export default function ClipEditor({
{view.reactionsError && <p className="m-0 text-[12px] text-reject-text">{view.reactionsError}</p>}
{view.rulingsError && <p className="m-0 text-[12px] text-reject-text">{view.rulingsError}</p>}
- <ShortMaker project={project} clipId={clip.id} short={view.shorts?.[clip.id] ?? null} framed={!!clip.vertical} framing={framing} onFraming={setFraming} onCentre={() => setCrop(null)} onMade={() => void reload().catch(() => {})} busy={busy} />
+ <ShortMaker project={project} clipId={clip.id} short={view.shorts?.[clip.id] ?? null} framed={!!clip.vertical} framing={framing} onFraming={setFraming} onCentre={() => setCrop(null)} onMade={() => void reload().catch(() => {})} busy={busy} live={view.live?.status === "live"} />
<RenderTake project={project} render={render} takes={takes} takesHref={takesHref} />
</aside>
</div>
@@ -1537,7 +1551,7 @@ function SpeakerLabel({ speaker, busy, onSave }: { speaker: Speaker; busy: boole
}
/** Make a short: the clip at 1080x1920 from its box, a job; the one there is set aside, never overwritten. */
-function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCentre, onMade, busy }: {
+function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCentre, onMade, busy, live = false }: {
project: string;
clipId: string;
short: { mtimeMs: number; size: number; stale: boolean } | null;
@@ -1547,6 +1561,9 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
onCentre: () => void;
onMade: () => void;
busy: boolean;
+ // A live pre-clip project (plans/live-preclip.md): Share now cuts the window
+ // from the recording in progress first (/api/report/live-share).
+ live?: boolean;
}) {
const [job, setJob] = useState<{ id: string; state: string; error: string | null } | null>(null);
const [err, setErr] = useState<string | null>(null);
@@ -1572,6 +1589,15 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
if (!r.ok || !j.job) setErr(j.error ?? `HTTP ${r.status}`);
else setJob({ id: j.job.id, state: j.job.state, error: j.job.error });
};
+ // Share now (a stream still live): the window is cut from the recording
+ // first, then the same short; nothing is fetched.
+ const shareNow = async () => {
+ setErr(null);
+ const r = await fetch("/api/report/live-share", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ project, clip: clipId, replace: !!short }) });
+ const j = (await r.json().catch(() => ({}))) as { job?: { id: string; state: string; error: string | null }; error?: string };
+ if (!r.ok || !j.job) setErr(j.error ?? `HTTP ${r.status}`);
+ else setJob({ id: j.job.id, state: j.job.state, error: j.job.error });
+ };
const running = job?.state === "running";
return (
<section data-short-maker={clipId} data-short-made={short ? "" : undefined} className="space-y-1.5">
@@ -1592,6 +1618,11 @@ function ShortMaker({ project, clipId, short, framed, framing, onFraming, onCent
<button type="button" data-make-short={clipId} disabled={running || busy} onClick={() => void make()} className={buttonVariants({ variant: "go", size: "sm" })}>
{running ? "Making the short…" : short ? "Make the short again" : "Make a short"}
</button>
+ {live && (
+ <button type="button" data-live-share={clipId} disabled={running || busy} onClick={() => void shareNow()} className={buttonVariants({ variant: "outline", size: "sm" })} title="cut this clip's seconds from the recording in progress, then make its short (at most 2:20)">
+ Share now (live)
+ </button>
+ )}
{short && (
<a href={`/api/report/shorts?project=${encodeURIComponent(project)}&clip=${encodeURIComponent(clipId)}&file=1&v=${short.mtimeMs}`} target="_blank" rel="noreferrer" data-short-open={clipId} className={buttonVariants({ variant: "quiet", size: "sm" })}>
Play it
diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs
@@ -45,6 +45,7 @@ import { resolveFactcheck } from "umtool-report-to-video/factcheck";
import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs";
import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerLabel, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs";
import { readShorts } from "./shorts.mjs";
+import { readLiveProject } from "./liveProject.mjs";
import { quoteBetween, unusedProposals, wordsOf } from "./clipEditorModel.mjs";
import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
import { clipRoom } from "umtool-report-to-video/room";
@@ -146,7 +147,18 @@ export async function clipEditorView(project) {
});
const shorts = await readShorts(project.dir, manifest);
const doc = reactions.doc;
+ const live = await readLiveProject(project.dir);
return {
+ live: live
+ ? {
+ status: live.status === "final" ? "final" : "live",
+ transcribedTo: fin(live.transcribedTo) ? live.transcribedTo : 0,
+ minedTo: fin(live.minedTo) ? live.minedTo : 0,
+ passes: fin(live.passes) ? live.passes : 0,
+ lastPass: typeof live.lastPass === "string" ? live.lastPass : null,
+ flags: Array.isArray(live.flags) ? live.flags.filter(isObj) : [],
+ }
+ : null,
clips,
token,
rulingsError: rulings.error,
diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts
@@ -82,6 +82,19 @@ export type EditorView = {
repropose: { available: boolean; why: string | null };
/** The shorts on disk, by clip id (release 36). */
shorts: Record<string, { mtimeMs: number; size: number; stale: boolean }>;
+ /**
+ * A live pre-clip project's record (lib/report/clipsLive.mjs, plans/live-preclip.md):
+ * the stream it grows from, how far it is transcribed and mined, and its flags
+ * (a restart on another clock, a landing check that did not match). Null: not live.
+ */
+ live?: {
+ status: "live" | "final";
+ transcribedTo: number;
+ minedTo: number;
+ passes: number;
+ lastPass: string | null;
+ flags: { at: string; why: string }[];
+ } | null;
/** The cut's render.room and its join's length (release 36 lane E). */
room?: { tail: boolean; head: boolean; minGap: number | null; maxS: number | null; join: number };
/** The claim knobs' defaults (video knobs). */
diff --git a/umtool/lib/report/clipsLive.mjs b/umtool/lib/report/clipsLive.mjs
@@ -0,0 +1,269 @@
+// LIVE PRE-CLIP's project (plans/live-preclip.md): `POST /api/report/clips
+// {mode: "live", slug, from: "<channel>/<id>", final?, check?}` — the editor's
+// live-preclip job asks it after each tick. SYNCHRONOUS: a proposal pass is
+// arithmetic, and it must not wait behind a render on the app's one-job runner.
+//
+// THE RECORDING IS THE PROJECT'S OWN COPY while the stream is live: a project
+// with a `.shadow-channels/` reads its recording from there
+// (report-to-video/sources.mjs channelsDirFor), and this keeps it current from
+// the editor's data/<id>/live-transcript.json:
+//
+// .shadow-channels/<ch>/data/<id>/transcript.cues.json the live cues
+// .shadow-channels/<ch>/data/<id>/diarization.json one speaker, turns from
+// the cues (the clip finder
+// needs turns; the real
+// speakers come with the
+// landing)
+// .shadow-channels/<ch>/data/<id>/metadata.info.json the record's
+// .shadow-channels/<ch>/data/<id>/clips -> <corpus>/data/<id>/clips
+// the editor's clip cache,
+// where a live share's
+// window lands
+// words.json the live words
+// scans/<ch>--<id>.audio.json the live laugh scan
+// live-preclip.json this module's record:
+// the source, the passes,
+// the flags
+//
+// Each pass proposes over [0, transcribedTo − 20 s] (the live edge waits for the
+// next tick: a proposal there would be cut mid-thought). Ids are stable across
+// passes (clips.mjs stableIds), ruled and edited clips are protected
+// (rulingsGuard), so the windows grow without re-proposing what was proposed.
+//
+// FINAL (`final: true`, the live transcript superseded by the corpus's): the
+// shadow goes — the project reads the corpus from now on, the final cues and,
+// once diarized, the speakers — and words.json becomes the corpus's words.json
+// (or goes, so the captions come from transcript.json). The windows stay where
+// they are, by source second: the recording is append-only from its start, so
+// the partial's clock is the landed video's. A landing check that was not
+// "same" flags them (live-preclip.json `flags`, the clip editor's banner).
+//
+// Plain ESM: the route calls it; its tests run with bare node.
+import { copyFile, lstat, mkdir, readFile, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { LAUGH_CLASSES } from "yt-dlp-transcript-common/lib/clips/clips.mjs";
+import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
+import { REPORTS_ROOT } from "../projects/core.mjs";
+import { GLOBAL_CHANNELS_DIR, readManifest, clipsOf } from "../projects/report.mjs";
+import { CHANNEL_SLUG_RE, SLUG_RE, scaffoldReportVideo } from "../projects/scaffold.mjs";
+import { walkProjects } from "../projects/walk.mjs";
+import { SHADOW_CHANNELS } from "umtool-report-to-video/sources";
+import { ClipsNewError } from "./clipsNew.mjs";
+import { WORDS_FILE, proposeProject } from "./reactions.mjs";
+import { LIVE_PROJECT_FILE, readLiveProject } from "./liveProject.mjs";
+
+export const LIVE_TRANSCRIPT_FILENAME = "live-transcript.json";
+export { LIVE_PROJECT_FILE, readLiveProject };
+/** The live edge a pass leaves for the next tick (lib/livePreclip.ts PRECLIP_MINE_EDGE_SECONDS). */
+export const LIVE_MINE_EDGE_S = 20;
+/** Two cues closer than this are one turn. */
+export const LIVE_TURN_GAP_S = 1.5;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const num = (v) => typeof v === "number" && Number.isFinite(v);
+const readJson = (f) => readFile(f, "utf8").then(JSON.parse, () => null);
+
+async function writeWhole(file, doc) {
+ await mkdir(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, `${JSON.stringify(doc)}\n`);
+ await rename(tmp, file);
+}
+
+/**
+ * The turns of a one-speaker recording from its cues: consecutive cues with
+ * gaps under `gap` are one turn, speaker 0.
+ * @param {{ start: number, end: number }[]} cues
+ */
+export function liveTurns(cues, gap = LIVE_TURN_GAP_S) {
+ const out = [];
+ for (const c of [...cues].filter((x) => num(x?.start) && num(x?.end) && x.end > x.start).sort((a, b) => a.start - b.start)) {
+ const last = out.at(-1);
+ if (last && c.start - last.end < gap) last.end = Math.max(last.end, c.end);
+ else out.push({ start: c.start, end: c.end, speaker: 0 });
+ }
+ return out.map((t) => ({ start: Math.round(t.start * 1000) / 1000, end: Math.round(t.end * 1000) / 1000, speaker: 0 }));
+}
+
+/** The request's fields, checked. */
+export function parseLiveBody(body) {
+ const b = isObj(body) ? body : {};
+ const slug = String(b.slug ?? "").trim().toLowerCase();
+ if (!SLUG_RE.test(slug)) throw new ClipsNewError(`slug "${b.slug ?? ""}": lower-case letters, digits and dashes`);
+ const m = /^([^/]+)\/([^/]+)$/.exec(String(b.from ?? ""));
+ if (!m || !CHANNEL_SLUG_RE.test(m[1]) || !CHANNEL_SLUG_RE.test(m[2])) throw new ClipsNewError(`from "${b.from ?? ""}": <channel>/<videoId>`);
+ const check = isObj(b.check) && typeof b.check.verdict === "string" ? { verdict: String(b.check.verdict), why: String(b.check.why ?? ""), ...(num(b.check.lagSeconds) ? { lagSeconds: b.check.lagSeconds } : {}) } : null;
+ return { slug, channel: m[1], video: m[2], final: b.final === true, check };
+}
+
+/** The editor's live transcript of a recording, or null. */
+export async function readLiveTranscript(channelsDir, channel, video) {
+ const doc = await readJson(path.join(channelsDir, channel, "data", video, LIVE_TRANSCRIPT_FILENAME));
+ return isObj(doc) && doc.version === 1 && Array.isArray(doc.cues) ? doc : null;
+}
+
+
+/**
+ * The project's copy of the recording, written from the live transcript.
+ * `shadowRoot` is the `.shadow-channels` dir (the project's, or a staging one).
+ */
+export async function writeShadow({ shadowRoot, channelsDir, channel, video, doc }) {
+ const dir = path.join(shadowRoot, channel, "data", video);
+ await mkdir(dir, { recursive: true });
+ const duration = num(doc.transcribedTo) ? doc.transcribedTo : 0;
+ const turns = liveTurns(doc.cues);
+ // The clip finder refuses a recording with no turns; a live one with no words yet has one silent turn.
+ if (!turns.length) turns.push({ start: 0, end: Math.max(1, duration), speaker: 0 });
+ await writeWhole(path.join(dir, "transcript.cues.json"), { version: 1, source: "live-preclip", provisional: true, duration, cues: doc.cues });
+ await writeWhole(path.join(dir, "diarization.json"), {
+ turns,
+ audioSeconds: duration,
+ generatedAt: String(doc.updatedAt ?? new Date().toISOString()),
+ engine: { engine: "live-preclip (one speaker until the landing)" },
+ });
+ const meta = await readJson(path.join(channelsDir, channel, "data", video, "metadata.info.json"));
+ if (meta) await writeWhole(path.join(dir, "metadata.info.json"), meta);
+ const clips = path.join(dir, "clips");
+ const there = await lstat(clips).catch(() => null);
+ if (!there) await symlink(path.join(channelsDir, channel, "data", video, "clips"), clips).catch(() => {});
+ return { dir, turns: turns.length, duration };
+}
+
+/** The live laugh scan as the clip finder's scan cache (reactions.mjs readScans). */
+export function liveScanDoc(doc, now = new Date()) {
+ const s = doc.scan;
+ if (!isObj(s) || !Array.isArray(s.energy)) return null;
+ return {
+ version: 1,
+ window: s.window,
+ hop: s.hop,
+ t0: 0,
+ windows: s.energy.length,
+ energy: s.energy,
+ laugh: Array.isArray(s.laugh) ? s.laugh : null,
+ model: typeof s.model === "string" ? { file: s.model, sherpaOnnx: null, classes: [...LAUGH_CLASSES] } : null,
+ classes: [...LAUGH_CLASSES],
+ source: { path: LIVE_TRANSCRIPT_FILENAME, size: s.energy.length, mtimeMs: 0 },
+ clock: 0,
+ kind: "live",
+ madeAt: now.toISOString(),
+ };
+}
+
+async function findProject(reportsRoot, slug) {
+ for (const p of await walkProjects(reportsRoot)) if (p.id === slug) return p;
+ return null;
+}
+
+const countOf = async (dir) => {
+ const [reactions, manifest] = await Promise.all([readReactions(dir), readManifest(dir)]);
+ return { proposals: reactions?.proposals?.length ?? 0, clips: manifest ? clipsOf(manifest).length : 0 };
+};
+
+/**
+ * One `mode: "live"` request: the project made or grown, or finalized.
+ * @param {unknown} body
+ * @param {{ reportsRoot?: string, channelsDir?: string, sitesDir?: string, now?: Date }} [o]
+ */
+export async function liveClips(body, { reportsRoot = REPORTS_ROOT, channelsDir = GLOBAL_CHANNELS_DIR(), sitesDir = undefined, now = new Date() } = {}) {
+ const req = parseLiveBody(body);
+ if (!channelsDir) throw new ClipsNewError("no channels directory (CHANNELS_DIR)", 500);
+ const doc = await readLiveTranscript(channelsDir, req.channel, req.video);
+ if (!doc) throw new ClipsNewError(`${req.channel}/${req.video} has no live transcript (${LIVE_TRANSCRIPT_FILENAME})`, 404);
+ const notes = [];
+ let found = await findProject(reportsRoot, req.slug);
+ let live = found ? await readLiveProject(found.dir) : null;
+ if (found && (!live || live.source?.channel !== req.channel || live.source?.video !== req.video)) {
+ throw new ClipsNewError(`project ${req.slug} exists and is not the live project of ${req.channel}/${req.video}: name another ("project")`, 409);
+ }
+ const flags = [...(Array.isArray(live?.flags) ? live.flags : [])];
+ const flag = (why) => {
+ if (!flags.some((f) => f.why === why)) flags.push({ at: now.toISOString(), why });
+ };
+ if (live && num(live.restarts) && num(doc.restarts) && doc.restarts > live.restarts) {
+ flag(`the recording restarted on another clock (${doc.restarts}×): windows proposed before ${now.toISOString().slice(11, 16)} may not sit on the landed video's seconds`);
+ }
+ if (req.check && req.check.verdict !== "same" && req.check.verdict !== "same-recording") {
+ flag(`landing check: ${req.check.verdict} — ${req.check.why}`);
+ }
+
+ // FINAL: the corpus from now on.
+ if (req.final) {
+ if (!found) throw new ClipsNewError(`no live project ${req.slug} to finalize`, 404);
+ await rm(path.join(found.dir, SHADOW_CHANNELS), { recursive: true, force: true });
+ const corpusWords = path.join(channelsDir, req.channel, "data", req.video, WORDS_FILE);
+ if (await stat(corpusWords).then((s) => s.isFile(), () => false)) {
+ await copyFile(corpusWords, path.join(found.dir, WORDS_FILE));
+ notes.push("words.json: the final word timings");
+ } else {
+ await rm(path.join(found.dir, WORDS_FILE), { force: true });
+ notes.push("words.json removed: the captions come from the final transcript");
+ }
+ await rm(path.join(found.dir, "scans", `${req.channel}--${req.video}.audio.json`), { force: true });
+ await writeWhole(path.join(found.dir, LIVE_PROJECT_FILE), { ...live, status: "final", finalAt: now.toISOString(), check: req.check ?? live?.check ?? null, flags });
+ notes.push(`the shadow recording is gone: ${req.slug} reads ${req.channel}/${req.video} from the corpus (Find clips on the landed video re-analyzes it with the speakers and the sound)`);
+ const c = await countOf(found.dir);
+ return { project: req.slug, created: false, final: true, ...c, flags, notes, href: `/projects/${encodeURIComponent(req.slug)}/clips` };
+ }
+
+ // A pass over the live transcript.
+ let created = false;
+ if (!found) {
+ const staging = path.join(reportsRoot, `.live-staging-${req.slug}-${process.pid}`);
+ await rm(staging, { recursive: true, force: true });
+ try {
+ await writeShadow({ shadowRoot: staging, channelsDir, channel: req.channel, video: req.video, doc });
+ let r;
+ try {
+ r = await scaffoldReportVideo({ root: reportsRoot, slug: req.slug, from: `${req.channel}/${req.video}`, seed: "reactions", channelsDir: staging, ...(sitesDir ? { sitesDir } : {}) });
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ throw new ClipsNewError(msg, /already exists/.test(msg) ? 409 : 400);
+ }
+ await rename(staging, path.join(r.dir, SHADOW_CHANNELS));
+ found = { id: r.id, dir: r.dir, kind: r.kind };
+ created = true;
+ notes.push(...(r.notes ?? []).filter((n) => !/umtool clips analyze|pnpm ops transcribe/.test(n)));
+ } finally {
+ await rm(staging, { recursive: true, force: true });
+ }
+ } else {
+ await writeShadow({ shadowRoot: path.join(found.dir, SHADOW_CHANNELS), channelsDir, channel: req.channel, video: req.video, doc });
+ }
+ if (Array.isArray(doc.words) && doc.words.length) await writeWhole(path.join(found.dir, WORDS_FILE), { words: doc.words, provisional: true });
+ const scan = liveScanDoc(doc, now);
+ if (scan) await writeWhole(path.join(found.dir, "scans", `${req.channel}--${req.video}.audio.json`), scan);
+ const upTo = Math.max(0, (num(doc.transcribedTo) ? doc.transcribedTo : 0) - LIVE_MINE_EDGE_S);
+ const pass = await proposeProject({
+ project: { id: found.id, dir: found.dir },
+ from: { channel: req.channel, video: req.video },
+ params: { scopeFrom: 0, scopeTo: Math.round(upTo * 1000) / 1000 },
+ now,
+ });
+ const passes = (num(live?.passes) ? live.passes : 0) + 1;
+ await writeWhole(path.join(found.dir, LIVE_PROJECT_FILE), {
+ version: 1,
+ status: "live",
+ source: { channel: req.channel, video: req.video },
+ madeAt: live?.madeAt ?? now.toISOString(),
+ passes,
+ lastPass: now.toISOString(),
+ transcribedTo: doc.transcribedTo ?? 0,
+ minedTo: upTo,
+ restarts: num(doc.restarts) ? doc.restarts : 0,
+ ...(req.check ? { check: req.check } : live?.check ? { check: live.check } : {}),
+ flags,
+ });
+ live = { passes };
+ return {
+ project: found.id,
+ created,
+ final: false,
+ proposals: pass.doc.proposals.length,
+ clips: clipsOf({ timeline: pass.timeline }).length,
+ minedTo: upTo,
+ flags,
+ notes,
+ href: `/projects/${encodeURIComponent(found.id)}/clips`,
+ };
+}
diff --git a/umtool/lib/report/clipsLive.test.mjs b/umtool/lib/report/clipsLive.test.mjs
@@ -0,0 +1,185 @@
+// Live pre-clip's project (lib/report/clipsLive.mjs): a stream's clip-finder
+// project made from the editor's live transcript, grown as the transcript
+// grows (ids kept), flagged by a landing check, then handed to the corpus.
+// Synthetic: no audio, no model, no network.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { lstat, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import { readReactions } from "yt-dlp-transcript-common/lib/clips/reactions.mjs";
+import { scaffoldReportVideo } from "../projects/scaffold.mjs";
+import { LIVE_PROJECT_FILE, liveClips, liveScanDoc, liveTurns, parseLiveBody } from "./clipsLive.mjs";
+
+const CH = "synth-live";
+const VID = "stream001";
+
+/** A host talking, a line every 4 s, laughing ("hahaha") at the seconds given. */
+function liveDoc(transcribedTo, laughsAt, restarts = 0) {
+ const cues = [];
+ const words = [];
+ for (let t = 1; t + 3 < transcribedTo; t += 4) {
+ const laugh = laughsAt.some((l) => l >= t && l < t + 4);
+ const text = laugh ? "that is the funniest thing hahaha" : "and so the thing is we keep talking";
+ cues.push({ start: t, end: t + 3, text });
+ const ws = text.split(" ");
+ ws.forEach((w, i) => words.push({ w, start: Math.round((t + (i * 3) / ws.length) * 1000) / 1000, end: Math.round((t + ((i + 0.8) * 3) / ws.length) * 1000) / 1000 }));
+ }
+ const n = Math.floor(transcribedTo / 0.5);
+ return {
+ version: 1,
+ provisional: true,
+ status: "live",
+ basis: { stem: ".stream001.live-x.ytdlp", audioFile: ".stream001.live-x.ytdlp.ts", kind: "muxed" },
+ restarts,
+ transcribedTo,
+ cues,
+ words,
+ scan: { hop: 0.5, window: 1, energy: new Array(n).fill(-30), laugh: null, model: null },
+ chunks: [],
+ fingerprint: null,
+ updatedAt: "2026-10-27T12:00:00Z",
+ };
+}
+
+async function fixture() {
+ const root = await mkdtemp(path.join(tmpdir(), "clips-live-"));
+ const channelsDir = path.join(root, "channels");
+ const reportsRoot = path.join(root, "reports");
+ const sitesDir = path.join(root, "sites");
+ const videoDir = path.join(channelsDir, CH, "data", VID);
+ await mkdir(videoDir, { recursive: true });
+ await mkdir(reportsRoot, { recursive: true });
+ await mkdir(sitesDir, { recursive: true });
+ await writeFile(path.join(channelsDir, CH, "config.json"), JSON.stringify({ name: "Synth", platform: "youtube" }));
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id: VID, title: "A live show", webpage_url: `https://www.youtube.com/watch?v=${VID}`, extractor_key: "Youtube", channel: "Synth", live_status: "is_live" }));
+ const put = (doc) => writeFile(path.join(videoDir, "live-transcript.json"), JSON.stringify(doc));
+ return { root, channelsDir, reportsRoot, sitesDir, videoDir, put };
+}
+
+test("liveTurns: cues joined across short gaps, one speaker", () => {
+ assert.deepEqual(
+ liveTurns([{ start: 0, end: 2 }, { start: 2.5, end: 4 }, { start: 9, end: 10 }]),
+ [{ start: 0, end: 4, speaker: 0 }, { start: 9, end: 10, speaker: 0 }],
+ );
+ assert.deepEqual(liveTurns([]), []);
+});
+
+test("parseLiveBody: slug, from, final, check", () => {
+ assert.deepEqual(parseLiveBody({ slug: "a-live", from: "ch/vid", final: true, check: { verdict: "shifted", why: "w", lagSeconds: 1.5 } }), {
+ slug: "a-live", channel: "ch", video: "vid", final: true, check: { verdict: "shifted", why: "w", lagSeconds: 1.5 },
+ });
+ assert.throws(() => parseLiveBody({ slug: "A B", from: "ch/vid" }), /slug/);
+ assert.throws(() => parseLiveBody({ slug: "ok", from: "nope" }), /from/);
+});
+
+test("liveScanDoc: the scan cache reactions.mjs reads", () => {
+ const s = liveScanDoc(liveDoc(10, []));
+ assert.equal(s.version, 1);
+ assert.equal(s.t0, 0);
+ assert.equal(s.windows, 20);
+ assert.equal(s.laugh, null);
+ assert.equal(liveScanDoc({ scan: null }), null);
+});
+
+test("a live project: made, grown with its ids kept, flagged, then handed to the corpus", async () => {
+ const f = await fixture();
+ const opts = { reportsRoot: f.reportsRoot, channelsDir: f.channelsDir, sitesDir: f.sitesDir, now: new Date("2026-10-27T12:10:00Z") };
+ try {
+ await assert.rejects(liveClips({ slug: "stream001-live", from: `${CH}/${VID}` }, opts), (e) => e.status === 404);
+ await f.put(liveDoc(600, [200, 400]));
+ const a = await liveClips({ slug: "stream001-live", from: `${CH}/${VID}` }, opts);
+ assert.equal(a.created, true);
+ assert.equal(a.minedTo, 580);
+ assert.ok(a.proposals > 0, "the laughs and the comments make proposals");
+ const dir = path.join(f.reportsRoot, "stream001-live");
+ const shadow = path.join(dir, ".shadow-channels", CH, "data", VID);
+ const diar = JSON.parse(await readFile(path.join(shadow, "diarization.json"), "utf8"));
+ assert.equal(diar.audioSeconds, 600);
+ assert.ok(diar.turns.every((t) => t.speaker === 0));
+ assert.ok((await lstat(path.join(shadow, "clips"))).isSymbolicLink(), "the editor's clip cache, linked");
+ assert.equal(JSON.parse(await readFile(path.join(dir, "words.json"), "utf8")).provisional, true);
+ let doc = await readReactions(dir);
+ assert.deepEqual(doc.params.scope, [0, 580]);
+ assert.ok(doc.proposals.every((p) => p.end <= 580));
+ const first = doc.proposals.map((p) => [p.id, p.start, p.end]);
+ assert.ok(doc.laughs.length >= 2, "laughs from the transcript's markers (no model)");
+
+ // The transcript grows: a laugh at 900 s. The earlier proposals keep their ids.
+ await f.put(liveDoc(1200, [200, 400, 900]));
+ const b = await liveClips({ slug: "stream001-live", from: `${CH}/${VID}` }, { ...opts, now: new Date("2026-10-27T12:20:00Z") });
+ assert.equal(b.created, false);
+ assert.ok(b.proposals >= a.proposals);
+ doc = await readReactions(dir);
+ assert.deepEqual(doc.params.scope, [0, 1180]);
+ for (const [id, start, end] of first) {
+ const same = doc.proposals.find((p) => p.id === id);
+ assert.ok(same && Math.abs(same.start - start) < 0.01 && Math.abs(same.end - end) < 0.01, `${id} kept`);
+ }
+ assert.ok(doc.proposals.some((p) => p.start > 800 && p.start < 960), "a window near the new span");
+ const live = JSON.parse(await readFile(path.join(dir, LIVE_PROJECT_FILE), "utf8"));
+ assert.equal(live.passes, 2);
+ assert.deepEqual(live.flags, []);
+
+ // Another project's slug is not taken over.
+ await scaffoldReportVideo({ root: f.reportsRoot, slug: "someone-else", title: "x" });
+ await assert.rejects(liveClips({ slug: "someone-else", from: `${CH}/${VID}` }, opts), (e) => e.status === 409);
+
+ // A restart on another clock, then a landing check that did not match: flagged.
+ await f.put(liveDoc(1300, [200, 400, 900], 1));
+ const c = await liveClips({ slug: "stream001-live", from: `${CH}/${VID}`, check: { verdict: "shifted", why: "1.5 s later", lagSeconds: 1.5 } }, opts);
+ assert.equal(c.flags.length, 2, JSON.stringify(c.flags));
+ assert.ok(c.flags.some((x) => /restarted on another clock/.test(x.why)));
+ assert.ok(c.flags.some((x) => /landing check: shifted/.test(x.why)));
+
+ // Final: the shadow goes, words.json becomes the corpus's, the windows stay.
+ const clipsBefore = c.clips;
+ await writeFile(path.join(f.videoDir, "words.json"), JSON.stringify({ words: [{ w: "final", start: 1, end: 1.3 }] }));
+ const d = await liveClips({ slug: "stream001-live", from: `${CH}/${VID}`, final: true }, opts);
+ assert.equal(d.final, true);
+ assert.equal(d.clips, clipsBefore, "every window kept, by source second");
+ assert.equal(await stat(path.join(dir, ".shadow-channels")).then(() => true, () => false), false);
+ assert.equal(JSON.parse(await readFile(path.join(dir, "words.json"), "utf8")).words[0].w, "final");
+ assert.equal(await stat(path.join(f.videoDir, "words.json")).then(() => true, () => false), true, "the corpus's file is untouched");
+ const fin = JSON.parse(await readFile(path.join(dir, LIVE_PROJECT_FILE), "utf8"));
+ assert.equal(fin.status, "final");
+ assert.equal(fin.flags.length, 2);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
+
+test("a live share: the clip added at its seconds, the build's window asked of the editor, 2:20 at most", async () => {
+ const { prepareLiveShare, shareSpan } = await import("./liveShare.mjs");
+ const f = await fixture();
+ const opts = { reportsRoot: f.reportsRoot, channelsDir: f.channelsDir, sitesDir: f.sitesDir };
+ try {
+ await f.put(liveDoc(600, [200]));
+ await liveClips({ slug: "stream001-live", from: `${CH}/${VID}` }, opts);
+ const project = { id: "stream001-live", dir: path.join(f.reportsRoot, "stream001-live") };
+ const asked = [];
+ const askWindow = async (req) => (asked.push(req), { ok: true, status: 200, body: { from: req.from, to: req.to, source: "live-recording" } });
+ const r = await prepareLiveShare(project, { start: 300, end: 345 }, { askWindow });
+ assert.equal(r.added, true);
+ assert.equal(r.windowSource, "live-recording");
+ assert.equal(asked[0].slug, CH);
+ assert.equal(asked[0].id, VID);
+ // The clip's extent (the cut ± 1.5 s) plus the build's fetch pad.
+ const m = JSON.parse(await readFile(path.join(project.dir, "video.manifest.json"), "utf8"));
+ const clip = m.timeline.find((e) => e.id === r.clip);
+ assert.deepEqual([clip.cutStart, clip.cutEnd, clip.start, clip.end], [300, 345, 298.5, 346.5]);
+ assert.deepEqual({ from: asked[0].from, to: asked[0].to }, shareSpan(clip, m.render));
+ assert.ok(asked[0].from <= 298.5 && asked[0].to >= 346.5);
+
+ // By id; the editor's "not yet recorded" passes through as a 409.
+ const late = async () => ({ ok: false, status: 409, body: { error: "the recording holds 10:00 so far; the window ends at 10:03 — ask again in 5 s" } });
+ await assert.rejects(prepareLiveShare(project, { clip: r.clip }, { askWindow: late }), (e) => e.status === 409 && /ask again in 5 s/.test(e.message));
+ await assert.rejects(prepareLiveShare(project, { start: 0, end: 200 }, { askWindow }), /2:20/);
+ await assert.rejects(prepareLiveShare(project, { clip: "nope" }, { askWindow }), (e) => e.status === 404);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/liveProject.mjs b/umtool/lib/report/liveProject.mjs
@@ -0,0 +1,17 @@
+// A live pre-clip project's record, `<project>/live-preclip.json`
+// (lib/report/clipsLive.mjs writes it; plans/live-preclip.md). Its own small
+// module so the clip editor's view reads it without the scaffold behind it.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+
+export const LIVE_PROJECT_FILE = "live-preclip.json";
+
+/** The project's live record, or null (not a live project). */
+export async function readLiveProject(dir) {
+ try {
+ const d = JSON.parse(await readFile(path.join(dir, LIVE_PROJECT_FILE), "utf8"));
+ return d && typeof d === "object" && !Array.isArray(d) && d.version === 1 ? d : null;
+ } catch {
+ return null;
+ }
+}
diff --git a/umtool/lib/report/liveShare.mjs b/umtool/lib/report/liveShare.mjs
@@ -0,0 +1,121 @@
+// A SHAREABLE CLIP OF A STREAM STILL LIVE (plans/live-preclip.md) — the clip
+// editor's Share now and `pnpm ops live-clip`: `POST /api/report/live-share
+// {project, clip | start, end, from?, replace?}`.
+//
+// 1. the clip: one of the project's, or a new one added at [start, end] (the
+// clip editor's `add`, with the clip finder's WINDOW_PAD_S either side);
+// at most 2:20 (X's limit);
+// 2. its source window — the build's own span (report-to-video/build-video.mjs
+// fetchSpan: the clip's extent plus render.fetchPad) — asked of the editor
+// (`POST /api/media/live-window`, WORKER_TOKEN): cut NOW from the part being
+// recorded, or from the saved video once it has landed, into the clip
+// cache the project's shadow recording links. Past the live edge the editor
+// answers 409 with how long to wait;
+// 3. its short (lib/report/shorts.mjs, `--skip-fetch --no-network`: the window
+// above is the source, the project's words.json — the live words — the
+// captions), as one job on the app's runner.
+//
+// No request leaves this machine.
+import path from "node:path";
+import { WINDOW_PAD_S } from "yt-dlp-transcript-common/lib/clips/assist.mjs";
+import { clipsOf, readManifest } from "../projects/report.mjs";
+import { addClip } from "./manifest.mjs";
+import { readLiveProject } from "./liveProject.mjs";
+
+/** X's limit on a video's length, seconds (common/lib/livePreclip.ts LIVE_CLIP_MAX_SECONDS). */
+export const LIVE_SHARE_MAX_SECONDS = 140;
+
+export class LiveShareError extends Error {
+ /** @param {string} message @param {number} [status] */
+ constructor(message, status = 400) {
+ super(message);
+ this.status = status;
+ }
+}
+
+const fin = (v) => typeof v === "number" && Number.isFinite(v);
+const r2 = (x) => Math.round(x * 100) / 100;
+
+/** The span the build reads for a clip (build-video.mjs fetchSpan, its default pad). */
+export function shareSpan(entry, render) {
+ const pad = fin(render?.fetchPad) ? render.fetchPad : 3;
+ return { from: r2(Math.max(0, entry.start - pad)), to: r2(entry.end + pad) };
+}
+
+/**
+ * Steps 1 and 2: the clip (added when given by seconds) and its window, asked
+ * of the editor through `askWindow({slug, id, from, to, clipId, manifest})`,
+ * which resolves `{ ok, status, body }`.
+ * @param {{ id: string, dir: string }} project
+ * @param {Record<string, unknown>} body
+ * @param {{ askWindow: (req: Record<string, unknown>) => Promise<{ ok: boolean, status: number, body: any }> }} o
+ */
+export async function prepareLiveShare(project, body, { askWindow }) {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new LiveShareError("no manifest", 404);
+ const live = await readLiveProject(project.dir);
+ let entry;
+ let added = false;
+ if (typeof body.clip === "string" && body.clip) {
+ entry = clipsOf(manifest).find((e) => e.id === body.clip);
+ if (!entry) throw new LiveShareError(`no clip ${body.clip} in ${project.id}`, 404);
+ } else {
+ if (!fin(body.start) || !fin(body.end) || body.end <= body.start) throw new LiveShareError('give "clip", or "start" and "end" (seconds of the stream)');
+ const from = typeof body.from === "string" ? /^([^/]+)\/([^/]+)$/.exec(body.from) : null;
+ const channel = from?.[1] ?? live?.source?.channel ?? null;
+ const video = from?.[2] ?? live?.source?.video ?? null;
+ if (!video) throw new LiveShareError(`${project.id} is not a live project: say which recording ("from": "<channel>/<id>")`);
+ if (body.end - body.start > LIVE_SHARE_MAX_SECONDS + 1e-6) throw new LiveShareError(`a share is at most 2:20 (X's limit); this clip is ${Math.round(body.end - body.start)} s`);
+ const res = await addClip(project.dir, {
+ video,
+ ...(channel && channel !== manifest.provenance?.channelSlug ? { channel } : {}),
+ cutStart: body.start,
+ cutEnd: body.end,
+ start: Math.max(0, body.start - WINDOW_PAD_S),
+ end: body.end + WINDOW_PAD_S,
+ title: "live share",
+ });
+ entry = res.entry;
+ added = true;
+ }
+ const cutStart = fin(entry.cutStart) ? entry.cutStart : entry.start;
+ const cutEnd = fin(entry.cutEnd) ? entry.cutEnd : entry.end;
+ if (cutEnd - cutStart > LIVE_SHARE_MAX_SECONDS + 1e-6) {
+ throw new LiveShareError(`${entry.id} is ${Math.round(cutEnd - cutStart)} s: a share is at most 2:20 (X's limit) — trim it first`);
+ }
+ const slug = entry.channel ?? manifest.provenance?.channelSlug ?? live?.source?.channel ?? null;
+ if (!slug) throw new LiveShareError(`${entry.id} names no channel`);
+ const span = shareSpan(entry, manifest.render);
+ const w = await askWindow({
+ slug,
+ id: entry.video,
+ from: span.from,
+ to: span.to,
+ requestedBy: "umtool live-share",
+ manifest: path.join(project.dir, "video.manifest.json"),
+ clipId: entry.id,
+ reason: `a live share of ${entry.id}`,
+ });
+ if (!w.ok) throw new LiveShareError(`the editor did not cut the window: ${w.body?.error ?? `HTTP ${w.status}`}`, w.status === 409 ? 409 : 502);
+ return { clip: entry.id, added, window: { from: w.body.from, to: w.body.to }, windowSource: w.body.source ?? null };
+}
+
+/** The editor's live-window route (ARCHILYZER_EDITOR_URL, WORKER_TOKEN — fetch-via-editor.mjs's). */
+export function editorWindowAsker({ editorUrl = process.env.ARCHILYZER_EDITOR_URL ?? "http://localhost:3001", token = process.env.WORKER_TOKEN ?? "", doFetch = fetch } = {}) {
+ return async (req) => {
+ if (!token) return { ok: false, status: 503, body: { error: "WORKER_TOKEN is not set on umtool: the editor cannot be asked for the window" } };
+ let res;
+ try {
+ res = await doFetch(`${editorUrl.replace(/\/+$/, "")}/api/media/live-window`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
+ body: JSON.stringify(req),
+ signal: AbortSignal.timeout(10 * 60_000),
+ });
+ } catch (e) {
+ return { ok: false, status: 502, body: { error: `the editor at ${editorUrl} did not answer (${e instanceof Error ? e.message : String(e)})` } };
+ }
+ const body = await res.json().catch(() => ({}));
+ return { ok: res.ok, status: res.status, body };
+ };
+}
diff --git a/umtool/lib/report/shorts.mjs b/umtool/lib/report/shorts.mjs
@@ -29,10 +29,14 @@ export function shortFile(dir, clipId) {
* The job's one step: build-video `--short`, NDJSON progress, beside the
* build's own steps (lib/report/driver.mjs). No path or argv from a client.
*
+ * `offline` (a live share, lib/report/liveShare.mjs): `--skip-fetch
+ * --no-network` — the window is already cut, and nothing may be fetched.
+ *
* @param {{ dir: string }} project
* @param {string} clipId
+ * @param {{ offline?: boolean }} [o]
*/
-export function shortSteps(project, clipId) {
+export function shortSteps(project, clipId, { offline = false } = {}) {
if (!safeClipId(clipId)) throw new Error(`not a clip id: ${clipId}`);
return [
{
@@ -44,6 +48,7 @@ export function shortSteps(project, clipId) {
path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"),
"--out", path.join(/* turbopackIgnore: true */ project.dir, "out"),
"--short", clipId, "--progress", "ndjson",
+ ...(offline ? ["--skip-fetch", "--no-network"] : []),
],
ndjson: true,
timeoutMs: SHORT_TIMEOUT_MS,