Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit ff5a245e52e9c757e7127e2b803f08eeb1e2cfab
parent ea50edfe47e36370b599d4a86b0ba1778221e224
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 19 Oct 2026 12:19:55 -0400

clips: Find clips — the clip finder's chain for one video, one button and `pnpm ops find-clips`

A find-clips job (controller/findClips.ts) on its own queue runs, each step
skipped when its output exists and named in the log: persist the source video
(persist-videos), the corpus transcript (transcribe-one), word timings
(transcribe with words, in the job, into data/<id>/words.json — a declared
sidecar), the chat replay (fetch-chat, YouTube; a refusal or failure is logged
and the chain goes on), diarization (the backfill lane's one-video run; past a
held lane, in the job, only when the run is whilePaused), then umtool's
`POST /api/report/clips {mode: "new", slug, from, target?, scope: "auto" |
segment, wordsPath}` with the worker token, followed to the end with its log
relayed. A paused pool, diarization off or a held lane fails the step at once
with where to fix it rather than parking. The log ends `@@find-clips {json}`;
data/<id>/find-clips.json keeps the project, its clip editor URL and the
segments for the video page.

The video page's Find clips panel: a target length, "Run while paused" when
something holds a step, the button (disabled with a status line when
UMTOOL_URL is unset), and after a run the project linked and each segment with
its own "Find clips in this part". The editor e2e server names a stub umtool
through E2E_UMTOOL_ORIGIN_FILE (lib/umtoolUrl.ts).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Acommon/controller/findClips.test.ts | 390+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/findClips.ts | 689+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 3++-
Acommon/lib/findClipsRecord-server.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/sidecar-server.test.ts | 6+++++-
Acommon/lib/umtoolUrl.ts | 31+++++++++++++++++++++++++++++++
Acommon/lib/wordTimings-server.ts | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/_door.test.ts | 2++
Aeditor/app/api/ops/_findClips.ts | 20++++++++++++++++++++
Meditor/app/api/ops/_researchEditor.ts | 13+++++++++++++
Aeditor/app/api/ops/find-clips/route.ts | 34++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/videos/[id]/components/FindClipsPanel.tsx | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/videos/[id]/findClipsActions.ts | 29+++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/page.tsx | 21+++++++++++++++++++++
Meditor/e2e/servers.ts | 7+++++++
Meditor/playwright.config.ts | 4++++
Mscripts/archilyzer-ops.mjs | 28+++++++++++++++++++++++++++-
Mscripts/archilyzer-ops.test.mjs | 16++++++++++++++++
18 files changed, 1552 insertions(+), 3 deletions(-)

diff --git a/common/controller/findClips.test.ts b/common/controller/findClips.test.ts @@ -0,0 +1,390 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { TranscribeFileRequest, TranscribeFileResult } from "./transcribeFile"; +import type { FindClipsDeps } from "./findClips"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/findClips.test.ts +// +// THE CHAIN END TO END WITH STUBS (release 36, lane A): the editor's ops +// actions (a door that writes what each job would leave), the job registry +// (every job done), the word timings (a fake engine result), diarization (a +// started job that writes diarization.json) and umtool (a fetch that answers +// the clips route's contract). No yt-dlp, no engine, no network. Every case +// is its own video in one temp corpus. + +const ROOT = await mkdtemp(path.join(tmpdir(), "find-clips-")); +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 { getSettings } = await import("../lib/settings"); +const { + FIND_CLIPS_RESULT_MARKER, + enqueueFindClips, + parseFindClipsBody, + planFindClipsSteps, + inspectFindClips, + projectSlugFor, + runFindClips, +} = await import("./findClips"); +const { loadFindClipsRecord } = await import("../lib/findClipsRecord-server"); + +const paths = getPaths(); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +const SLUG = "synth-react"; +const CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig; +await mkdir(path.join(CORPUS, "channels", SLUG), { recursive: true }); +await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG)); + +const SETTINGS_ON = () => { + const s = getSettings(); + return { + ...s, + diarization: { ...s.diarization, enabled: true, segModel: "/m/seg.onnx", embModel: "/m/emb.onnx" }, + autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, held: false } }, + }; +}; +const SEGMENTS = [ + { id: "s1", from: 290, to: 6300, subject: 4, host: 1, why: "subject 4 holds 81% of long-turn time" }, + { id: "s2", from: 6500, to: 9278, subject: 16, host: 1, why: "subject 16 holds 77% of long-turn time" }, +]; + +async function video(id: string, platformUrl = `https://www.youtube.com/watch?v=${id}`): Promise<string> { + const dir = path.join(CORPUS, "channels", SLUG, "data", id); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id, title: "Synth stream", webpage_url: platformUrl, was_live: true })); + return dir; +} + +// Everything a finished chain leaves on disk, so every step is skipped. +async function complete(dir: string) { + await writeFile(path.join(dir, "source-media.mp4"), "container"); + await writeFile(path.join(dir, "audio.mp3"), "audio"); + await writeFile(path.join(dir, "transcript.json"), JSON.stringify({ transcription: [] })); + await writeFile(path.join(dir, "words.json"), JSON.stringify({ version: 1, words: [{ w: "hello", start: 1, end: 1.4 }] })); + await writeFile(path.join(dir, "transcript.live_chat.json"), "\n"); + await writeFile(path.join(dir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [] })); + await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] })); +} + +type Harness = { + deps: FindClipsDeps; + actions: { action: string; args: Record<string, unknown> }[]; + umtoolCalls: { method: string; url: string; body?: unknown; auth?: string | null }[]; + words: TranscribeFileRequest[]; + diarized: number; + log: string[]; +}; + +function harness(dir: string, o: { umtool?: "ok" | "down" | "refuses" | "fails"; paused?: boolean; pauseHeld?: string[]; chatFails?: boolean } = {}): Harness { + const h: Harness = { actions: [], umtoolCalls: [], words: [], diarized: 0, log: [], deps: null as unknown as FindClipsDeps }; + let n = 0; + const editor = { + async run(action: string, args: Record<string, unknown>) { + h.actions.push({ action, args }); + if (action === "persist-videos") await writeFile(path.join(dir, "source-media.mp4"), "container"); + if (action === "transcribe-one") await writeFile(path.join(dir, "transcript.json"), JSON.stringify({ transcription: [] })); + if (action === "fetch-chat") { + if (o.chatFails) throw new Error("youtube is in a rate-limit cooldown (300s remaining)"); + await writeFile(path.join(dir, "transcript.live_chat.json"), "\n"); + await writeFile(path.join(dir, "live_chat.cues.json"), JSON.stringify({ version: 1, source: "live_chat", cues: [] })); + } + return { ok: true, jobId: `j${++n}` }; + }, + }; + let polls = 0; + const fetchStub = (async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input); + const method = init?.method ?? "GET"; + const auth = new Headers(init?.headers).get("authorization"); + h.umtoolCalls.push({ method, url, ...(init?.body ? { body: JSON.parse(String(init.body)) } : {}), auth }); + if (o.umtool === "down") throw new TypeError("fetch failed (ECONNREFUSED)"); + if (method === "POST") { + if (o.umtool === "refuses") return Response.json({ error: "no diarization.json for synth-react/v" }, { status: 400 }); + return Response.json({ jobId: "u1", project: "v-clips", created: true, segments: SEGMENTS }); + } + polls++; + if (polls === 1) return Response.json({ state: "running", log: ["analyze: laughs 12"], next: 1 }); + if (o.umtool === "fails") return Response.json({ state: "failed", error: "CED-mini exited 1", log: [], next: 1 }); + return Response.json({ state: "done", log: ["propose: 18 clips, 612 s"], next: 2 }); + }) as typeof fetch; + h.deps = { + paths, + editor, + jobOf: async () => ({ status: "done" }), + umtoolUrl: "http://127.0.0.1:9", + workerToken: "tok", + fetch: fetchStub, + settings: SETTINGS_ON, + pool: { + isPaused: () => o.paused === true, + enabledIds: () => (o.paused ? [] : ["gpu"]), + pauseHeldIds: () => o.pauseHeld ?? (o.paused ? ["gpu"] : []), + }, + transcribeWords: async (req) => { + h.words.push(req); + return { + version: 1, + path: req.path, + window: null, + worker: { id: "gpu", name: "GPU", appId: "parakeet", model: "m.gguf", device: null }, + transcriptFormat: "chough-json", + transcribedAt: "2026-10-19T00:00:00.000Z", + durationMs: 10, + waitedMs: 0, + cues: [{ start: 1, end: 2, text: "hello world" }], + text: "hello world", + words: [ + { w: "hello", start: 1, end: 1.4 }, + { w: "world", start: 1.5, end: 2 }, + ], + } satisfies TranscribeFileResult; + }, + diarize: async () => { + h.diarized++; + await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] })); + return { ok: true, jobId: "d1", stream: new ReadableStream<string>(), done: Promise.resolve({ status: "done" as const, jobId: "d1" }) }; + }, + pollMs: 1, + sleep: async () => {}, + }; + return h; +} + +const run = (h: Harness, id: string, extra: Record<string, unknown> = {}) => + runFindClips({ slug: SLUG, id, ...extra }, h.deps, { + config: CONFIG, + onLog: (l) => h.log.push(l), + signal: new AbortController().signal, + }); + +test("the body: slug and id required; target, segment, project and the flags checked", () => { + assert.match((parseFindClipsBody({}) as { error: string }).error, /"slug" is required/); + assert.match((parseFindClipsBody({ slug: SLUG }) as { error: string }).error, /"id" is required/); + assert.match((parseFindClipsBody({ slug: SLUG, id: "v", target: 3 }) as { error: string }).error, /"target"/); + assert.match((parseFindClipsBody({ slug: SLUG, id: "v", segment: "s 2" }) as { error: string }).error, /"segment"/); + assert.match((parseFindClipsBody({ slug: SLUG, id: "v", project: "Bad_Slug" }) as { error: string }).error, /"project"/); + assert.match((parseFindClipsBody({ slug: SLUG, id: "v", whilePaused: "yes" }) as { error: string }).error, /"whilePaused"/); + assert.deepEqual(parseFindClipsBody({ slug: SLUG, id: "v", target: 600.4, segment: "s2", whilePaused: true, dryRun: false }), { + ok: true, + value: { slug: SLUG, id: "v", target: 600, segment: "s2", whilePaused: true }, + }); + assert.equal(projectSlugFor("fGSRhEWc9M4"), "fgsrhewc9m4-clips"); + assert.equal(projectSlugFor("fGSRhEWc9M4", "s2"), "fgsrhewc9m4-clips-s2"); +}); + +test("every step run: each in order, named in the log, outputs written, umtool followed", async () => { + const id = "runAll00001"; + const dir = await video(id); + const h = harness(dir); + const r = await run(h, id, { target: 600, whilePaused: true }); + assert.deepEqual( + h.actions.map((a) => a.action), + ["persist-videos", "transcribe-one", "fetch-chat"], + ); + assert.deepEqual(h.actions[0].args, { items: [{ slug: SLUG, id }] }); + assert.deepEqual(h.actions[1].args, { slug: SLUG, id, whilePaused: true }); + assert.equal(h.words.length, 1); + assert.equal(h.words[0].words, true); + assert.equal(h.words[0].whilePaused, true); + assert.equal(h.words[0].path, path.join(dir, "source-media.mp4"), "the container when no audio file is here"); + assert.equal(h.diarized, 1); + // words.json: the result without cues and text. + const words = JSON.parse(await readFile(path.join(dir, "words.json"), "utf8")); + assert.equal(words.words.length, 2); + assert.ok(!("cues" in words) && !("text" in words)); + // umtool: the contract's body, the worker token, then the job followed. + const post = h.umtoolCalls[0]; + assert.equal(post.method, "POST"); + assert.equal(post.url, "http://127.0.0.1:9/api/report/clips"); + assert.equal(post.auth, "Bearer tok"); + assert.deepEqual(post.body, { + mode: "new", + slug: "runall00001-clips", + from: `${SLUG}/${id}`, + target: 600, + scope: "auto", + wordsPath: path.join(dir, "words.json"), + }); + assert.match(h.umtoolCalls[1].url, /\?job=u1&since=0$/); + assert.match(h.umtoolCalls[2].url, /\?job=u1&since=1$/); + const text = h.log.join("\n"); + for (const line of [ + /running: saved video — no saved video/, + /running: corpus transcript — no corpus transcript/, + /running: word timings — transcribing source-media\.mp4 with word timings/, + /running: chat replay — fetching the chat replay/, + /running: diarization — no diarization\.json/, + /running: umtool — finding the segments and the clips/, + /umtool: analyze: laughs 12/, + /umtool: propose: 18 clips, 612 s/, + ]) { + assert.match(text, line); + } + assert.equal(r.project, "v-clips"); + assert.equal(r.url, "http://127.0.0.1:9/projects/v-clips/clips"); + assert.equal(r.created, true); + assert.deepEqual(r.segments.map((s) => s.id), ["s1", "s2"]); + assert.deepEqual(r.steps.map((s) => s.action), ["ran", "ran", "ran", "ran", "ran", "ran"]); +}); + +test("every step skipped: nothing asked of the editor or an engine; umtool still asked", async () => { + const id = "skipAll0001"; + const dir = await video(id); + await complete(dir); + const h = harness(dir); + const r = await run(h, id, { segment: "s2" }); + assert.deepEqual(h.actions, []); + assert.equal(h.words.length, 0); + assert.equal(h.diarized, 0); + const text = h.log.join("\n"); + for (const line of [ + /skipped: saved video — saved video present/, + /skipped: corpus transcript — transcript\.json present/, + /skipped: word timings — words\.json present \(1 words\)/, + /skipped: chat replay — live_chat\.cues\.json present/, + /skipped: diarization — diarization\.json present/, + /running: umtool — finding clips in segment s2/, + ]) { + assert.match(text, line); + } + assert.deepEqual(h.umtoolCalls[0].body, { + mode: "new", + slug: "skipall0001-clips-s2", + from: `${SLUG}/${id}`, + segment: "s2", + wordsPath: path.join(dir, "words.json"), + }); + assert.equal(r.segment, "s2"); + assert.deepEqual(r.steps.map((s) => s.action), ["skipped", "skipped", "skipped", "skipped", "skipped", "ran"]); +}); + +test("umtool down, refusing, or failing: a clear failure naming the step", async () => { + for (const [mode, re] of [ + ["down", /^step umtool: umtool at http:\/\/127\.0\.0\.1:9 did not answer \(fetch failed \(ECONNREFUSED\)\) — is it running\?$/], + ["refuses", /^step umtool: umtool refused the clips request \(HTTP 400\): no diarization\.json/], + ["fails", /^step umtool: umtool job u1 failed: CED-mini exited 1$/], + ] as const) { + const id = `um${mode}`.padEnd(11, "0"); + const dir = await video(id); + await complete(dir); + await assert.rejects(run(harness(dir, { umtool: mode }), id), { message: re }); + } +}); + +test("a twitch video skips the chat with the sentence; a refused chat fetch is logged and the chain goes on", async () => { + const tw = await video("twitch00001", "https://www.twitch.tv/videos/123"); + await complete(tw); + await rm(path.join(tw, "live_chat.cues.json")); + await rm(path.join(tw, "transcript.live_chat.json")); + const h = harness(tw); + await run(h, "twitch00001"); + assert.match(h.log.join("\n"), /skipped: chat replay — no chat fetcher for twitch: only YouTube's chat replay is fetched/); + assert.deepEqual(h.actions, []); + + const yt = await video("chatfail001"); + await complete(yt); + await rm(path.join(yt, "live_chat.cues.json")); + await rm(path.join(yt, "transcript.live_chat.json")); + const h2 = harness(yt, { chatFails: true }); + const r = await run(h2, "chatfail001"); + assert.match(h2.log.join("\n"), /the chat was not fetched \(step chat replay: fetch-chat refused: youtube is in a rate-limit cooldown/); + assert.equal(r.project, "v-clips", "the chain finished without the chat"); +}); + +test("a paused pool fails the transcription step at once unless the run is whilePaused", async () => { + const id = "paused00001"; + const dir = await video(id); + await writeFile(path.join(dir, "source-media.mp4"), "container"); + await assert.rejects(run(harness(dir, { paused: true }), id), { message: /^step corpus transcript: the transcription workers are paused — run it with "while paused"/ }); + // Paused, flagged, but no worker the pause alone switched off. + await assert.rejects( + run(harness(dir, { paused: true, pauseHeld: [] }), id, { whilePaused: true }), + { message: /^step corpus transcript: the workers are paused and none was switched off by the pause alone/ }, + ); + const h = harness(dir, { paused: true }); + await run(h, id, { whilePaused: true }); + assert.equal(h.actions.find((a) => a.action === "transcribe-one")?.args.whilePaused, true); + assert.equal(h.words[0].whilePaused, true); +}); + +test("diarization off or the backfill lane held fails the step with where to fix it", async () => { + const id = "diar0000001"; + const dir = await video(id); + await complete(dir); + await rm(path.join(dir, "diarization.json")); + const off = harness(dir); + off.deps.settings = () => getSettings(); + await assert.rejects(run(off, id), { message: /^step diarization: diarization is switched off, or its models are not set — set it up on \/operations\/diarization$/ }); + const held = harness(dir); + held.deps.settings = () => { + const s = SETTINGS_ON(); + return { ...s, autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, held: true } } }; + }; + await assert.rejects(run(held, id), { message: /^step diarization: the backfill lane is held, and it holds a diarization run too — run Find clips "while paused"/ }); + + // whilePaused: the one-video diarization in this job, the lane left held. + let inline = 0; + held.deps.diarizeInline = async () => { + inline++; + await writeFile(path.join(dir, "diarization.json"), JSON.stringify({ speakers: [] })); + return "diarized"; + }; + await run(held, id, { whilePaused: true }); + assert.equal(inline, 1); + assert.equal(held.diarized, 0, "the lane job was not asked"); + assert.match(held.log.join("\n"), /running: diarization — no diarization\.json: diarizing this one video in this job \(the backfill lane stays held\)/); + // An engine that fails names its outcome. + await rm(path.join(dir, "diarization.json")); + held.deps.diarizeInline = async () => "failed"; + await assert.rejects(run(held, id, { whilePaused: true }), { message: /^step diarization: the one-video diarization ended "failed"$/ }); +}); + +test("the dry run plans every step from the disk; the job writes find-clips.json and ends with the marker", async () => { + const id = "dryrun00001"; + const dir = await video(id); + await writeFile(path.join(dir, "transcript.json"), "{}"); + const state = await inspectFindClips(paths, SLUG, id, CONFIG); + assert.deepEqual( + planFindClipsSteps(state, {}).map((s) => [s.id, s.run]), + [["persist", true], ["transcript", false], ["words", true], ["chat", true], ["diarization", true], ["umtool", true]], + ); + const h = harness(dir); + const dry = await enqueueFindClips({ slug: SLUG, id, dryRun: true }, h.deps); + assert.ok(dry.dryRun); + assert.equal(dry.plan.steps.length, 6); + assert.deepEqual(h.actions, [], "a dry run asks nothing"); + + // Refusals before a job. + const noUmtool = await enqueueFindClips({ slug: SLUG, id }, { ...h.deps, umtoolUrl: null }); + assert.ok(!noUmtool.dryRun && !noUmtool.result.ok && /UMTOOL_URL is not set/.test(noUmtool.result.error)); + const noVideo = await enqueueFindClips({ slug: SLUG, id: "nope" }, h.deps); + assert.ok(!noVideo.dryRun && !noVideo.result.ok && /not a video of synth-react/.test(noVideo.result.error)); + const noChannel = await enqueueFindClips({ slug: "no-such-channel", id }, h.deps); + assert.ok(!noChannel.dryRun && !noChannel.result.ok && /not found/.test(noChannel.result.error)); + + const out = await enqueueFindClips({ slug: SLUG, id }, h.deps); + assert.ok(!out.dryRun && out.result.ok, JSON.stringify(out)); + void out.result.stream.cancel(); + const done = await out.result.done; + assert.equal(done.status, "done"); + const record = await loadFindClipsRecord(dir); + assert.ok(record); + assert.equal(record.project, "v-clips"); + assert.equal(record.url, "http://127.0.0.1:9/projects/v-clips/clips"); + assert.equal(record.jobId, out.result.jobId); + assert.deepEqual(record.segments.map((s) => s.id), ["s1", "s2"]); + const log = await readFile(path.join(paths.jobsDir, `${out.result.jobId}.log`), "utf8"); + const line = log.split("\n").find((l) => l.startsWith(FIND_CLIPS_RESULT_MARKER)); + assert.ok(line, log); + assert.equal(JSON.parse(line.slice(FIND_CLIPS_RESULT_MARKER.length)).umtoolJob, "u1"); +}); diff --git a/common/controller/findClips.ts b/common/controller/findClips.ts @@ -0,0 +1,689 @@ +// FIND CLIPS — the clip finder's whole chain for ONE video, as one job +// (release 36, lane A): the video page's Find clips, `pnpm ops find-clips`. +// +// Release 35 ran this from a shell, step by step: persist the source video, +// the corpus transcript, word timings (`pnpm ops transcribe {words:true}`), +// diarization, then `umtool new --seed reactions` and `umtool clips +// analyze`. Each of those is already an editor operation; what was missing +// is the chain. This job runs it, in order, and SKIPS EVERY STEP WHOSE OUTPUT +// IS ALREADY ON DISK, naming each in its log ("skipped: saved video — …", +// "running: word timings — …"): +// +// persist no saved video (and no source container in the dir) → +// `persist-videos {items: [{slug, id}]}`, waited on +// transcript no corpus transcript (transcript.json or an English +// caption track) → `transcribe-one {slug, id}`, waited on +// words no words.json beside it → the file transcription with word +// timestamps (transcribeFile.ts runTranscribeFile, words) IN +// THIS JOB on a worker lease, written to data/<id>/words.json +// (lib/wordTimings-server.ts) — reusable, so skippable +// chat a YouTube video whose chat replay is not here and fresh → +// `fetch-chat {slug, id}` (fetchLiveChat.ts), waited on; any +// other platform is skipped with "no chat fetcher for …". The +// chat is a signal, not a requirement: a refused or failed +// fetch is logged and the chain goes on without it +// diarization no diarization.json → the backfill lane's one-video run +// (operationJobs.ts runBackfillChannelJob, the panel's Run), +// waited on; with the lane HELD and a `whilePaused` run, the +// one-video diarization in this job instead (diarizeOne.ts), +// the hold left on +// umtool `POST ${UMTOOL_URL}/api/report/clips {mode: "new", slug, +// from, target?, scope: "auto" | segment, wordsPath}` with +// `Authorization: Bearer WORKER_TOKEN` → {jobId, project, +// created, segments}; then `GET ?job=<id>` followed to the end, +// its log relayed here line by line +// +// The editor-side steps go through THE EDITOR'S OWN OPS ACTIONS IN PROCESS +// (deps.editor — editor/app/api/ops/_researchEditor.ts findClipsEditor, the +// research run's door): the same body checks, refusals and queues a `pnpm +// ops` caller meets. Each is its own job on its own queue (the platform's +// download queue, the transcription pool, the backfill queue), and this job +// waits on it from the `find-clips` queue — never on a queue a step needs. +// +// WHAT HOLDS IT IS SAID, NOT WAITED ON FOREVER. A paused transcription pool +// would park a transcription step until someone resumed it: unless the run +// asked `whilePaused` (then the two transcriptions run on a worker the pause +// alone switched off — workerPool.ts pauseHeld — and the pause stays on), +// the step fails at once with the sentence. Diarization switched off fails +// the same way, and so does a held backfill lane unless the run is +// `whilePaused` ("this one video, past the holds"). umtool not answering +// fails the umtool step with its URL. +// +// THE RESULT: the log ends with `@@find-clips {json}` (how `pnpm ops +// find-clips --wait` prints it), and data/<id>/find-clips.json records it for +// the video page — the project, its clip editor's URL, the segments umtool +// found, and what each step did. + +import path from "node:path"; +import { readdir, stat } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { SiteSettings } from "../lib/settings"; +import { getSettings } from "../lib/settings"; +import { assertChannelTextReadable } from "../lib/channelMedia"; +import { findSourceMedia, isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles"; +import { DIARIZATION_FILENAME, englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus"; +import { loadSavedVideo, resolveSavedVideo } from "../lib/savedVideo-server"; +import { backfillLaneOperations, DIARIZATION_OPERATION_ID } from "../lib/operations"; +import { isGateHeld } from "../lib/pauseGates"; +import { getWorkerToken } from "../lib/workerToken"; +import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl"; +import { loadWordTimings, writeWordTimings, wordTimingsSidecar, type WordTimingsRecord } from "../lib/wordTimings-server"; +import { + writeFindClipsRecord, + type FindClipsRecord, + type FindClipsSegment, + type FindClipsStepRecord, +} from "../lib/findClipsRecord-server"; +import type { ResearchEditor } from "../lib/report/draft/research/tools"; +import { getWorkerPool, type WorkerPool } from "../jobs/workerPool"; +import { runManagedFunction, type JobRunContext, type StreamActionResult } from "../jobs/streamCommand"; +import { readChannelConfig, isValidChannelSlug } from "./channels"; +import { isVideoIdSegment } from "./refreshVideoMetadata"; +import { liveChatPlan, noChatFetcherSentence, type LiveChatPlan } from "./fetchLiveChat"; +import { runBackfillChannelJob, type BackfillChannelJobOptions } from "./operationJobs"; +import { diarizeOneVideo, type DiarizeOneOutcome } from "./diarizeOne"; +import { runTranscribeFile, type TranscribeFileRequest, type TranscribeFileResult } from "./transcribeFile"; + +export const FIND_CLIPS_JOB_KIND = "find-clips"; +// Its own queue, one at a time: two chains over one machine would contend for +// the same worker and the same umtool runner (which runs one job at a time). +export const FIND_CLIPS_QUEUE = "find-clips"; +export const FIND_CLIPS_RESULT_MARKER = "@@find-clips "; +export const FIND_CLIPS_BODY_KEYS = ["slug", "id", "target", "segment", "project", "whilePaused", "dryRun"] as const; +// The editor actions the chain asks its door for. +export const FIND_CLIPS_EDITOR_ACTIONS = ["persist-videos", "transcribe-one", "fetch-chat"] as const; + +export type FindClipsStepId = "persist" | "transcript" | "words" | "chat" | "diarization" | "umtool"; + +export const FIND_CLIPS_STEP_LABELS: Record<FindClipsStepId, string> = { + persist: "saved video", + transcript: "corpus transcript", + words: "word timings", + chat: "chat replay", + diarization: "diarization", + umtool: "umtool", +}; + +export type FindClipsRequest = { + slug: string; + id: string; + // The cut's target length, seconds (umtool's default when absent). + target?: number; + // A segment umtool found ("s2"): find clips in that part only. + segment?: string; + // The umtool project's slug when one is made (default: from the id). + project?: string; + // Run the two transcriptions during a pause-all (workerPool.ts pauseHeld). + whilePaused?: boolean; + dryRun?: boolean; +}; + +type Check<T> = { ok: true; value: T } | { ok: false; error: string }; + +const SEGMENT_RE = /^[a-z0-9][a-z0-9-]{0,31}$/i; +const PROJECT_RE = /^[a-z0-9][a-z0-9-]{0,79}$/; + +/** The body's shape, judged without touching the disk. */ +export function parseFindClipsBody(body: Record<string, unknown>): Check<FindClipsRequest> { + const slug = body.slug; + if (typeof slug !== "string" || !isValidChannelSlug(slug)) { + return { ok: false, error: '"slug" is required: a channel slug' }; + } + const id = body.id; + if (typeof id !== "string" || !isVideoIdSegment(id)) { + return { ok: false, error: '"id" is required: a video id (one path segment)' }; + } + const out: FindClipsRequest = { slug, id }; + if (body.target !== undefined) { + if (typeof body.target !== "number" || !Number.isFinite(body.target) || body.target < 10 || body.target > 6 * 3600) { + return { ok: false, error: '"target" is the cut\'s length in seconds (10 to 21600)' }; + } + out.target = Math.round(body.target); + } + if (body.segment !== undefined) { + if (typeof body.segment !== "string" || !SEGMENT_RE.test(body.segment)) { + return { ok: false, error: '"segment" is a segment id umtool found ("s2")' }; + } + out.segment = body.segment; + } + if (body.project !== undefined) { + if (typeof body.project !== "string" || !PROJECT_RE.test(body.project)) { + return { ok: false, error: '"project" is a umtool project slug (lowercase letters, digits and dashes)' }; + } + out.project = body.project; + } + for (const key of ["whilePaused", "dryRun"] as const) { + const v = body[key]; + if (v !== undefined && typeof v !== "boolean") return { ok: false, error: `"${key}" must be true or false` }; + if (v === true) out[key] = true; + } + return { ok: true, value: out }; +} + +/** The umtool project slug a run makes when none is named: the id, lowercased, and the segment. */ +export function projectSlugFor(id: string, segment?: string): string { + const base = id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "video"; + return `${base}-clips${segment ? `-${segment.toLowerCase()}` : ""}`.slice(0, 80); +} + +/** The umtool clip editor of `project`. */ +export function umtoolProjectUrl(umtool: string, project: string): string { + return `${umtool}/projects/${encodeURIComponent(project)}/clips`; +} + +// ─── what is on disk ─── + +export type FindClipsState = { + // A saved-video pointer, or a source container in the video dir. + saved: boolean; + // What the word timings read: the preferred audio file, else the source + // container, else the saved video. Null when there is nothing to read. + audioPath: string | null; + // The corpus transcript's file name, or null. + transcript: string | null; + // Words in words.json, or null when it is absent. + words: number | null; + chat: LiveChatPlan; + diarization: boolean; +}; + +export async function inspectFindClips( + paths: Paths, + slug: string, + id: string, + config: ChannelConfig, +): Promise<FindClipsState> { + const videoDir = path.join(paths.channelsDir, slug, "data", id); + const entries = await readdir(videoDir).catch(() => [] as string[]); + const pointer = await loadSavedVideo(videoDir).catch(() => null); + const container = findSourceMedia(entries); + const audio = pickPreferredAudio(entries.filter(isRealAudioFile)); + let audioPath: string | null = audio ? path.join(videoDir, audio) : container ? path.join(videoDir, container) : null; + if (!audioPath && pointer) audioPath = await resolveSavedVideo(videoDir).catch(() => null); + const transcript = entries.includes(WHISPER_FILENAME) ? WHISPER_FILENAME : (englishVttsByPreference(entries)[0] ?? null); + const words = await loadWordTimings(videoDir).catch(() => null); + return { + saved: pointer !== null || container !== null, + audioPath, + transcript, + words: words ? words.words.length : null, + chat: await liveChatPlan(paths, slug, id, config), + diarization: entries.includes(DIARIZATION_FILENAME), + }; +} + +export type FindClipsPlanStep = { id: FindClipsStepId; label: string; run: boolean; why: string }; + +/** What each step would do over `state` — the dry run, and the log's first lines. */ +export function planFindClipsSteps(state: FindClipsState, req: Pick<FindClipsRequest, "segment" | "target">): FindClipsPlanStep[] { + const step = (id: FindClipsStepId, run: boolean, why: string): FindClipsPlanStep => ({ id, label: FIND_CLIPS_STEP_LABELS[id], run, why }); + const chat = state.chat; + return [ + step("persist", !state.saved, state.saved ? "saved video present" : "no saved video: persist the source"), + step("transcript", state.transcript === null, state.transcript ? `${state.transcript} present` : "no corpus transcript: transcribe it"), + step("words", state.words === null, state.words !== null ? `words.json present (${state.words} words)` : "no words.json: transcribe with word timings"), + chat.kind === "fetch" || chat.kind === "normalize" + ? step("chat", true, chat.kind === "fetch" ? "no chat replay here: fetch it (YouTube)" : "the chat replay is here: normalize it") + : step( + "chat", + false, + chat.kind === "fresh" + ? "live_chat.cues.json present" + : chat.kind === "no-fetcher" + ? noChatFetcherSentence(chat.platform) + : chat.kind === "not-live" + ? "never live: no chat replay" + : chat.error, + ), + step("diarization", !state.diarization, state.diarization ? "diarization.json present" : "no diarization.json: diarize it"), + step("umtool", true, req.segment ? `find clips in segment ${req.segment}` : "find the segments and the clips"), + ]; +} + +// ─── the deps ─── + +export type FindClipsDeps = { + paths: Paths; + // The editor's ops actions, in process (editor: _researchEditor.ts + // findClipsEditor). A refusal throws with the action's sentence. + editor: ResearchEditor; + // An editor job's state (researchRuns.ts jobOfPaths). + jobOf: (id: string) => Promise<{ status: string } | null>; + umtoolUrl?: string | null; + workerToken?: string; + fetch?: typeof fetch; + settings?: () => SiteSettings; + pool?: Pick<WorkerPool, "isPaused" | "enabledIds" | "pauseHeldIds">; + transcribeWords?: ( + request: TranscribeFileRequest, + o: { onLog: (line: string) => void; signal: AbortSignal; ctx?: JobRunContext }, + ) => Promise<TranscribeFileResult>; + diarize?: (o: BackfillChannelJobOptions) => Promise<StreamActionResult>; + // The one-video diarization in this job, for a held backfill lane and a + // whilePaused run (diarizeOne.ts diarizeOneVideo). + diarizeInline?: (o: { onLog: (line: string) => void; signal: AbortSignal }) => Promise<DiarizeOneOutcome>; + pollMs?: number; + sleep?: (ms: number) => Promise<void>; + now?: () => Date; + // Called inside the job after the record is written (the editor revalidates + // the video page here). + onDone?: () => void | Promise<void>; +}; + +const TERMINAL = new Set(["done", "failed", "cancelled"]); + +class StepError extends Error { + constructor(step: FindClipsStepId, message: string) { + super(`step ${FIND_CLIPS_STEP_LABELS[step]}: ${message}`); + } +} + +function sleeper(deps: FindClipsDeps): (ms: number) => Promise<void> { + return deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))); +} + +async function waitForJob( + deps: FindClipsDeps, + step: FindClipsStepId, + jobId: string, + signal: AbortSignal, + onLog: (line: string) => void, +): Promise<string> { + const sleep = sleeper(deps); + const pollMs = deps.pollMs ?? 2000; + let misses = 0; + let last = ""; + for (;;) { + if (signal.aborted) throw new StepError(step, `cancelled while job ${jobId} ran (it keeps running)`); + const j = await deps.jobOf(jobId).catch(() => null); + if (j && TERMINAL.has(j.status)) return j.status; + if (!j && ++misses > 30) throw new StepError(step, `job ${jobId} is not in the registry`); + if (j && j.status !== last) { + last = j.status; + if (j.status === "queued") onLog(` job ${jobId} is queued behind other work on its queue`); + } + await sleep(pollMs); + } +} + +// Why a transcription step would park forever right now; null when it runs. +function transcriptionBlocked(deps: FindClipsDeps, whilePaused: boolean): string | null { + const pool = deps.pool ?? getWorkerPool(); + if (pool.isPaused()) { + if (!whilePaused) { + return "the transcription workers are paused — run it with \"while paused\" (whilePaused: true), or resume them on /workers"; + } + if (pool.pauseHeldIds().length === 0) { + return "the workers are paused and none was switched off by the pause alone (a worker drained, degraded or disabled by hand is never used) — enable one on /workers"; + } + return null; + } + if (pool.enabledIds().length === 0) return "no transcription worker is enabled — enable one on /workers"; + return null; +} + +function jobIdsOf(body: Record<string, unknown>): string[] { + if (Array.isArray(body.jobIds)) return body.jobIds.filter((x): x is string => typeof x === "string"); + return typeof body.jobId === "string" ? [body.jobId] : []; +} + +// One ops action through the door, then every job it started, waited on. +async function runAction( + deps: FindClipsDeps, + step: FindClipsStepId, + action: (typeof FIND_CLIPS_EDITOR_ACTIONS)[number], + args: Record<string, unknown>, + signal: AbortSignal, + onLog: (line: string) => void, +): Promise<void> { + let body: Record<string, unknown>; + try { + body = await deps.editor.run(action, args); + } catch (e) { + throw new StepError(step, `${action} refused: ${(e as Error).message}`); + } + for (const jobId of jobIdsOf(body)) { + onLog(` ${action}: job ${jobId}`); + const status = await waitForJob(deps, step, jobId, signal, onLog); + if (status !== "done") throw new StepError(step, `${action} job ${jobId} ended ${status} — its log on /jobs says why`); + onLog(` ${action}: job ${jobId} done`); + } +} + +// ─── umtool ─── + +type UmtoolNew = { jobId: string; project: string; created: boolean; segments: FindClipsSegment[] }; + +function segmentsOf(v: unknown): FindClipsSegment[] { + if (!Array.isArray(v)) return []; + return v + .filter((s): s is Record<string, unknown> => !!s && typeof s === "object") + .filter((s) => typeof s.id === "string" && typeof s.from === "number" && typeof s.to === "number") + .map((s) => ({ + id: s.id as string, + from: s.from as number, + to: s.to as number, + ...(typeof s.subject === "number" || typeof s.subject === "string" ? { subject: s.subject } : {}), + ...(typeof s.host === "number" || typeof s.host === "string" ? { host: s.host } : {}), + ...(typeof s.why === "string" ? { why: s.why } : {}), + })); +} + +async function umtoolJson(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 {}; + } +} + +async function runUmtool( + deps: FindClipsDeps, + o: { umtool: string; token: string; body: Record<string, unknown>; signal: AbortSignal; onLog: (line: string) => void }, +): Promise<UmtoolNew & { state: string }> { + const doFetch = deps.fetch ?? fetch; + const endpoint = `${o.umtool}/api/report/clips`; + const headers = { authorization: `Bearer ${o.token}`, "content-type": "application/json" }; + let res: Response; + try { + res = await doFetch(endpoint, { method: "POST", headers, body: JSON.stringify(o.body), signal: o.signal }); + } catch (e) { + if (o.signal.aborted) throw new StepError("umtool", "cancelled"); + throw new StepError("umtool", `umtool at ${o.umtool} did not answer (${(e as Error).message}) — is it running?`); + } + const posted = await umtoolJson(res); + if (!res.ok) { + const why = typeof posted.error === "string" ? posted.error : `HTTP ${res.status}`; + throw new StepError("umtool", `umtool refused the clips request (HTTP ${res.status}): ${why}`); + } + const job = posted.job as { id?: unknown } | undefined; + const jobId = typeof posted.jobId === "string" ? posted.jobId : typeof job?.id === "string" ? job.id : null; + const project = typeof posted.project === "string" ? posted.project : null; + if (!jobId || !project) throw new StepError("umtool", `umtool's answer named no job or project: ${JSON.stringify(posted).slice(0, 300)}`); + const created = posted.created !== false; + let segments = segmentsOf(posted.segments); + o.onLog(`umtool: ${created ? "made" : "re-analyzing"} project ${project} (job ${jobId})`); + if (segments.length) o.onLog(`umtool: segments ${segments.map((s) => `${s.id} ${Math.round(s.from)}–${Math.round(s.to)} s`).join(", ")}`); + + const sleep = sleeper(deps); + const pollMs = deps.pollMs ?? 2000; + let since = 0; + let failures = 0; + for (;;) { + if (o.signal.aborted) { + await doFetch(`${endpoint}?cancel=${encodeURIComponent(jobId)}`, { method: "POST", headers }).catch(() => null); + throw new StepError("umtool", `cancelled; umtool job ${jobId} was asked to stop`); + } + let view: Record<string, unknown> | null = null; + try { + const r = await doFetch(`${endpoint}?job=${encodeURIComponent(jobId)}&since=${since}`, { headers, signal: o.signal }); + if (r.status === 404) throw new StepError("umtool", `umtool no longer knows job ${jobId} (restarted?)`); + if (r.ok) view = await umtoolJson(r); + } catch (e) { + if (e instanceof StepError) throw e; + } + if (!view) { + if (++failures >= 15) throw new StepError("umtool", `umtool at ${o.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) o.onLog(`umtool: ${line.replace(/\n$/, "")}`); + if (typeof view.next === "number") since = view.next; + else since += log.length; + if (Array.isArray(view.segments)) segments = segmentsOf(view.segments); + const state = typeof view.state === "string" ? view.state : "running"; + if (state !== "running") { + if (state !== "done") { + const why = typeof view.error === "string" && view.error ? view.error : `the job ended ${state}`; + throw new StepError("umtool", `umtool job ${jobId} failed: ${why}`); + } + return { jobId, project, created, segments, state }; + } + } + await sleep(pollMs); + } +} + +// ─── the chain ─── + +export type FindClipsResult = Omit<FindClipsRecord, "version" | "at" | "jobId"> & { umtoolJob: string }; + +export async function runFindClips( + req: FindClipsRequest, + deps: FindClipsDeps, + o: { config: ChannelConfig; onLog: (line: string) => void; signal: AbortSignal; ctx?: JobRunContext }, +): Promise<FindClipsResult> { + const { paths } = deps; + const { onLog, signal } = o; + const { slug, id } = req; + const videoDir = path.join(paths.channelsDir, slug, "data", id); + const whilePaused = req.whilePaused === true; + const settings = (deps.settings ?? getSettings)(); + const umtool = deps.umtoolUrl === undefined ? resolveUmtoolUrl() : deps.umtoolUrl; + const token = deps.workerToken ?? getWorkerToken(); + if (!umtool) throw new StepError("umtool", "UMTOOL_URL is not set on the editor"); + if (!token) throw new StepError("umtool", "WORKER_TOKEN is not set on the editor"); + const steps: FindClipsStepRecord[] = []; + const skip = (s: FindClipsStepId, why: string) => { + steps.push({ id: s, label: FIND_CLIPS_STEP_LABELS[s], action: "skipped", why }); + onLog(`skipped: ${FIND_CLIPS_STEP_LABELS[s]} — ${why}`); + }; + const running = (s: FindClipsStepId, why: string) => { + steps.push({ id: s, label: FIND_CLIPS_STEP_LABELS[s], action: "ran", why }); + onLog(`running: ${FIND_CLIPS_STEP_LABELS[s]} — ${why}`); + }; + const inspect = () => inspectFindClips(paths, slug, id, o.config); + onLog(`Find clips in ${slug}/${id}${req.segment ? ` (segment ${req.segment})` : ""}${whilePaused ? " — while paused" : ""}`); + + // 1. the saved video + let state = await inspect(); + if (state.saved) skip("persist", "saved video present"); + else { + running("persist", "no saved video: persisting the source"); + await runAction(deps, "persist", "persist-videos", { items: [{ slug, id }] }, signal, onLog); + state = await inspect(); + if (!state.saved) throw new StepError("persist", "the source video is still not saved after persist-videos"); + } + + // 2. the corpus transcript + if (state.transcript) skip("transcript", `${state.transcript} present`); + else { + const held = transcriptionBlocked(deps, whilePaused); + if (held) throw new StepError("transcript", held); + running("transcript", "no corpus transcript: transcribing"); + await runAction(deps, "transcript", "transcribe-one", { slug, id, ...(whilePaused ? { whilePaused: true } : {}) }, signal, onLog); + state = await inspect(); + if (!state.transcript) throw new StepError("transcript", "transcribe-one ended without a transcript"); + } + + // 3. word timings + let wordsPath: string | null = null; + if (state.words !== null) { + skip("words", `words.json present (${state.words} words)`); + wordsPath = wordTimingsSidecar.path(videoDir); + } else { + if (!state.audioPath) throw new StepError("words", "no audio, source container or saved video to read"); + const held = transcriptionBlocked(deps, whilePaused); + if (held) throw new StepError("words", held); + running("words", `transcribing ${path.basename(state.audioPath)} with word timings`); + const transcribe = + deps.transcribeWords ?? + ((request, t) => runTranscribeFile({ paths, request, onLog: t.onLog, signal: t.signal, ...(t.ctx ? { ctx: t.ctx } : {}) })); + let r: TranscribeFileResult; + try { + r = await transcribe( + { path: state.audioPath, words: true, ...(whilePaused ? { whilePaused: true } : {}) }, + { onLog, signal, ...(o.ctx ? { ctx: o.ctx } : {}) }, + ); + } catch (e) { + throw new StepError("words", (e as Error).message); + } + const words = r.words ?? []; + if (words.length === 0) { + onLog(` ${r.worker.appId} [${r.worker.id}] keeps no word timestamps: the clips' edges sit on the transcript's cues`); + } else { + const { cues: _cues, text: _text, ...rest } = r; + const record: WordTimingsRecord = { ...rest, words } as WordTimingsRecord; + await writeWordTimings(videoDir, record); + wordsPath = wordTimingsSidecar.path(videoDir); + onLog(` ${words.length} words → words.json (${r.worker.appId} [${r.worker.id}])`); + } + } + + // 4. the chat replay (a signal, never a requirement) + const chat = state.chat; + if (chat.kind === "fetch" || chat.kind === "normalize") { + running("chat", chat.kind === "fetch" ? "fetching the chat replay (YouTube, paced)" : "normalizing the chat replay on disk"); + try { + await runAction(deps, "chat", "fetch-chat", { slug, id }, signal, onLog); + } catch (e) { + if (signal.aborted) throw e; + onLog(` the chat was not fetched (${(e as Error).message}) — going on without it`); + } + } else { + skip( + "chat", + chat.kind === "fresh" + ? "live_chat.cues.json present" + : chat.kind === "no-fetcher" + ? noChatFetcherSentence(chat.platform) + : chat.kind === "not-live" + ? "never live: no chat replay" + : chat.error, + ); + } + + // 5. diarization + if (state.diarization) skip("diarization", "diarization.json present"); + else { + if (!backfillLaneOperations(settings).some((op) => op.id === DIARIZATION_OPERATION_ID)) { + throw new StepError("diarization", "diarization is switched off, or its models are not set — set it up on /operations/diarization"); + } + const laneHeld = isGateHeld(settings, "backfill"); + if (laneHeld && !whilePaused) { + throw new StepError( + "diarization", + "the backfill lane is held, and it holds a diarization run too — run Find clips \"while paused\" (whilePaused: true) to diarize this one video in this job, or lift the hold", + ); + } + if (laneHeld) { + // PAST THE HOLD, for this one video: the one-video diarization in this + // job (diarizeOne.ts — what a transcription's inline pass runs), the + // lane's hold left on. + running("diarization", "no diarization.json: diarizing this one video in this job (the backfill lane stays held)"); + const diarizeInline = + deps.diarizeInline ?? + ((d: { onLog: (l: string) => void; signal: AbortSignal }) => + diarizeOneVideo({ paths, videoDir, videoId: id, settings: settings.diarization, onLog: d.onLog, signal: d.signal })); + const outcome = await diarizeInline({ onLog, signal }); + if (outcome !== "diarized" && outcome !== "already-exists") { + throw new StepError("diarization", `the one-video diarization ended "${outcome}"`); + } + } else { + running("diarization", "no diarization.json: diarizing (the backfill lane's one-video run)"); + const diarize = deps.diarize ?? runBackfillChannelJob; + const started = await diarize({ paths, channelSlug: slug, kindIds: [DIARIZATION_OPERATION_ID], ids: [id] }); + if (!started.ok) throw new StepError("diarization", started.error); + void started.stream.cancel(); + onLog(` backfill-channel: job ${started.jobId}`); + const done = await started.done; + if (done.status !== "done") throw new StepError("diarization", `job ${started.jobId} ended ${done.status}`); + } + state = await inspect(); + if (!state.diarization) throw new StepError("diarization", "no diarization.json was written — the log above says why"); + } + + // 6. umtool + const project = req.project ?? projectSlugFor(id, req.segment); + running("umtool", req.segment ? `finding clips in segment ${req.segment}` : "finding the segments and the clips"); + const u = await runUmtool(deps, { + umtool, + token, + signal, + onLog, + body: { + mode: "new", + slug: project, + from: `${slug}/${id}`, + ...(req.target !== undefined ? { target: req.target } : {}), + ...(req.segment ? { segment: req.segment } : { scope: "auto" }), + ...(wordsPath ? { wordsPath } : {}), + }, + }); + return { + project: u.project, + url: umtoolProjectUrl(umtool, u.project), + created: u.created, + ...(req.segment ? { segment: req.segment } : {}), + segments: u.segments, + steps, + umtoolJob: u.jobId, + }; +} + +// ─── the job ─── + +export type FindClipsPlan = { + slug: string; + id: string; + umtoolUrl: string | null; + workersPaused: boolean; + steps: FindClipsPlanStep[]; +}; + +export type FindClipsEnqueued = + | { dryRun: true; plan: FindClipsPlan } + | { dryRun: false; result: StreamActionResult }; + +/** Validate; a dry run's plan; else the job. Every refusal is `{ok: false}` before a job exists. */ +export async function enqueueFindClips(body: Record<string, unknown>, deps: FindClipsDeps): Promise<FindClipsEnqueued> { + const refuse = (error: string): FindClipsEnqueued => ({ dryRun: false, result: { ok: false, error } }); + const parsed = parseFindClipsBody(body); + if (!parsed.ok) return refuse(parsed.error); + const req = parsed.value; + const { paths } = deps; + const config = await readChannelConfig(paths, req.slug); + if (!config) return refuse(`Channel "${req.slug}" not found`); + try { + await assertChannelTextReadable(paths, req.slug, config); + } catch (e) { + return refuse((e as Error).message); + } + const videoDir = path.join(paths.channelsDir, req.slug, "data", req.id); + if (!(await stat(videoDir).then((s) => s.isDirectory(), () => false))) { + return refuse(`"${req.id}" is not a video of ${req.slug} (no data/${req.id}/): import or sync it first`); + } + const state = await inspectFindClips(paths, req.slug, req.id, config); + const umtool = deps.umtoolUrl === undefined ? resolveUmtoolUrl() : deps.umtoolUrl; + const pool = deps.pool ?? getWorkerPool(); + if (req.dryRun) { + return { + dryRun: true, + plan: { slug: req.slug, id: req.id, umtoolUrl: umtool, workersPaused: pool.isPaused(), steps: planFindClipsSteps(state, req) }, + }; + } + if (!umtool) return refuse("UMTOOL_URL is not set on the editor: Find clips hands the recording to umtool's clip finder (e.g. UMTOOL_URL=http://localhost:3050)"); + if (!(deps.workerToken ?? getWorkerToken())) return refuse("WORKER_TOKEN is not set on the editor: umtool's clips route is asked with it"); + const now = deps.now ?? (() => new Date()); + return { + dryRun: false, + result: await runManagedFunction({ + kind: FIND_CLIPS_JOB_KIND, + queueKey: FIND_CLIPS_QUEUE, + paths, + channelSlug: req.slug, + videoId: req.id, + fn: async (onLog, signal, _setProgress, ctx) => { + const r = await runFindClips(req, { ...deps, umtoolUrl: umtool }, { config, onLog, signal, ctx }); + const { umtoolJob: _u, ...kept } = r; + const record: FindClipsRecord = { version: 1, at: now().toISOString(), jobId: ctx.jobId, ...kept }; + await writeFindClipsRecord(path.join(paths.channelsDir, req.slug, "data", req.id), record); + onLog(`Done: ${r.segments.length} segment(s); the clips are in ${r.url}`); + onLog(`${FIND_CLIPS_RESULT_MARKER}${JSON.stringify({ ...record, umtoolJob: r.umtoolJob })}`); + await deps.onDone?.(); + }, + }), + }; +} diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -126,7 +126,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "UMTOOL_MEDIA_DIR", audience: "runtime", default: "unset (no media root: a project link's target is kept)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's media root, where a tiered project's `out/` (and its deliverables) are linked to. Read by `archilyzer reports delete` and the editor's `delete-article` / `delete-iteration` too: an iteration project's link that is exactly its mirror there is removed with its target. Its other uses are documented in [umtool/docs](umtool/docs/README.md)." }, { name: "REPORTS_DIR", audience: "runtime", default: "`~/reports` (or the parent of `SONG_REPORTS_DIR`)", readBy: "common/lib/report/delete.ts, umtool (lib/paths.mjs)", doc: "umtool's reports root, the tree its projects hang off; with `UMTOOL_MEDIA_DIR`, it says where a project's media mirror is (`<media>/<path relative to it>`) for a delete." }, { name: "SONG_REPORTS_DIR", audience: "runtime", default: "unset", readBy: "common/lib/report/delete.ts, umtool (song/paths.mjs)", doc: "umtool's um-song deliverables tree; when `REPORTS_DIR` is unset, its parent is the reports root a delete reads (as umtool does)." }, - { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`)." }, + { name: "UMTOOL_URL", audience: "runtime", default: "unset (no link; the MCP's `notes` off)", readBy: "editor/app/channels/[slug]/videos/[id]/page.tsx, common/lib/umtoolUrl.ts, mcp/src/archivalTools.ts", doc: "umtool's front door; when set, the video page links to it, its Find clips hands the recording to umtool's clip finder (the `find-clips` job posts to `/api/report/clips` with WORKER_TOKEN), and the MCP's `notes` tool reads the operator's notes there and writes a reply as the agent's (e.g. `http://localhost:3050`). Unset: Find clips is disabled." }, { name: "TRANSCRIPT_SITE_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: one published archive to read over HTTP." }, { name: "TRANSCRIPT_HUB_URL", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a hub, federating every archive it lists." }, { name: "TRANSCRIPT_LOCAL_DIR", audience: "runtime", default: "—", readBy: "mcp/src/sources.ts", doc: "MCP server: a composed public dir on disk." }, @@ -230,6 +230,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." }, { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, { name: "E2E_ODYSEE_PAGE_FIXTURE", audience: "test", default: "unset (a headless browser)", readBy: "common/ytdlp/odyseePageReader.ts, common/ytdlp/storedUrlPageOpen.ts, common/ytdlp/odyseeBrowserLookup.ts", doc: "A JSON file of recorded Odysee page reads keyed by page URL (`\"*\"` for any): while set, the browser lookup answers from it instead of opening a browser (with no gap between lookups), and the player-page opener opens nothing. The editor's e2e server names a file in each slot's test data (`browser-lookup.spec`)." }, + { name: "E2E_UMTOOL_ORIGIN_FILE", audience: "test", default: "unset (UMTOOL_URL)", readBy: "common/lib/umtoolUrl.ts", doc: "A file holding one loopback origin; while it exists, umtool is that origin for the editor's Find clips — the stub umtool `find-clips.spec` starts. The editor's e2e server names a file in each slot's test data; anything but a loopback origin in it is ignored." }, { name: "E2E_BLUESKY_ORIGIN_FILE", audience: "test", default: "unset (the real Bluesky)", readBy: "common/social/blueskyEndpoints.ts", doc: "A file holding one loopback origin; while it exists, the Bluesky AppView, bsky.app and its image CDN are that origin — the fake Bluesky a spec starts (`common/testing/social/fakeBluesky.mjs`). The editor's e2e server names a file in each slot's test data (`capture-posts.spec`); anything but a loopback origin in it is ignored." }, { name: "E2E_AUDIO_CHECK_DEBUG_PAUSE_MS", audience: "test", default: "off", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "A debugging pause inside the audio check." }, { name: "E2E_FAKE_YTDLP_AUDIO_CHECK_MODE", audience: "test", default: "—", readBy: "editor/e2e/fixtures/bin/fake-ytdlp.mjs", doc: "Fake yt-dlp: which audio-check scenario to act out." }, diff --git a/common/lib/findClipsRecord-server.ts b/common/lib/findClipsRecord-server.ts @@ -0,0 +1,55 @@ +// WHAT THE LAST "FIND CLIPS" FOUND — `data/<id>/find-clips.json` (release 36, +// lane A). Written by the find-clips job when umtool's clip finder finished +// (controller/findClips.ts); read by the video page's Find clips panel, which +// links the umtool project and lists the narrated-video segments umtool found, +// each with its own "Find clips in this part". Overwritten by the next run +// (the newest run is the one the panel describes; a per-segment run names its +// segment). A small text sidecar on the corpus disk; never published. + +import { sidecar, sidecarField } from "./sidecar-server"; + +export const FIND_CLIPS_FILENAME = "find-clips.json"; + +export type FindClipsSegment = { + id: string; + from: number; + to: number; + subject?: number | string; + host?: number | string; + why?: string; +}; + +export type FindClipsStepRecord = { + id: string; + label: string; + action: "ran" | "skipped"; + why: string; +}; + +export type FindClipsRecord = { + version: 1; + at: string; + jobId: string; + // The umtool project, its clip editor's URL, and whether umtool made it now + // (false: it re-analyzed the project already cut from this recording). + project: string; + url: string; + created: boolean; + // The segment this run was scoped to, when one was asked for. + segment?: string; + // Every narrated-video segment umtool found in the recording. + segments: FindClipsSegment[]; + steps: FindClipsStepRecord[]; +}; + +function coerce(value: unknown): FindClipsRecord | null { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const v = value as Record<string, unknown>; + if (v.version !== 1 || typeof v.project !== "string" || typeof v.url !== "string") return null; + if (!Array.isArray(v.segments) || !Array.isArray(v.steps)) return null; + return value as FindClipsRecord; +} + +export const findClipsSidecar = sidecar(FIND_CLIPS_FILENAME, sidecarField(coerce), { indent: 2 }); +export const loadFindClipsRecord = findClipsSidecar.load; +export const writeFindClipsRecord = findClipsSidecar.write; diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts @@ -15,6 +15,8 @@ import "./frameScan-server"; import "./metadataHistory-server"; import "./transcriptPin-server"; import "./wayback-server"; +import "./wordTimings-server"; +import "./findClipsRecord-server"; import { availabilitySidecar, loadAvailability, @@ -46,7 +48,7 @@ async function scratch(): Promise<string> { return mkdtemp(path.join(os.tmpdir(), "sidecar-")); } -test("every declared sidecar filename escapes SUB_FILE_RE, and all fifteen are declared", () => { +test("every declared sidecar filename escapes SUB_FILE_RE, and all seventeen are declared", () => { assert.deepEqual([...SIDECAR_FILENAMES].sort(), [ "ai-digest.json", "ai-digest.overrides.json", @@ -58,11 +60,13 @@ test("every declared sidecar filename escapes SUB_FILE_RE, and all fifteen are d "do-not-clean.json", "download-outcome.json", "exclude-truncated-check.json", + "find-clips.json", "frame-scan.poker.json", "metadata.history.json", "transcribe-outcome.json", "transcript-pin.json", "wayback.json", + "words.json", ]); for (const name of SIDECAR_FILENAMES) { assert.ok(!SUB_FILE_RE.test(name), name); diff --git a/common/lib/umtoolUrl.ts b/common/lib/umtoolUrl.ts @@ -0,0 +1,31 @@ +// WHERE UMTOOL IS, for the editor's side of the clip finder (release 36, lane +// A): `UMTOOL_URL`, trailing slashes dropped; null when unset. The video page +// links to it and the find-clips job posts to its `/api/report/clips`. +// +// TEST-ONLY: E2E_UMTOOL_ORIGIN_FILE names a file holding ONE loopback origin +// (`http://127.0.0.1:<port>`). While that file exists, umtool is that origin — +// the stub umtool an editor e2e spec starts (find-clips.spec) and names in the +// file after the test server booted; it is read per call. Anything but a +// loopback origin in it is ignored. Unset everywhere but the editor's e2e +// server (the Bluesky fake's pattern, social/blueskyEndpoints.ts). + +import { readFileSync } from "node:fs"; + +const LOOPBACK_ORIGIN = /^http:\/\/(?:127\.0\.0\.1|localhost)(?::\d{1,5})?$/; + +export function umtoolUrl( + env: Readonly<Record<string, string | undefined>> = process.env, +): string | null { + const file = env.E2E_UMTOOL_ORIGIN_FILE; + if (file) { + let origin = ""; + try { + origin = readFileSync(file, "utf8").trim().replace(/\/+$/, ""); + } catch { + origin = ""; + } + if (LOOPBACK_ORIGIN.test(origin)) return origin; + } + const url = env.UMTOOL_URL?.trim().replace(/\/+$/, ""); + return url ? url : null; +} diff --git a/common/lib/wordTimings-server.ts b/common/lib/wordTimings-server.ts @@ -0,0 +1,59 @@ +// A VIDEO'S WORD TIMINGS — `data/<id>/words.json` (release 36, lane A). +// +// The clip finder cuts on words: a clip's edges snap to the word the speaker +// starts or finishes on, never to a caption line's wrap. Release 35 made them +// by hand (`pnpm ops transcribe {path, words: true, out: <project>/words.json}`) +// into one umtool project. The find-clips job makes them ONCE per video, +// here, beside the transcript they belong to, so every project cut from this +// recording reads the same file (umtool copies it in as `<project>/words.json`) +// and the step is skipped the next time. +// +// THE SHAPE IS THE TRANSCRIBE RESULT'S (controller/transcribeFile.ts +// TranscribeFileResult) without its cues and text — {version, path, window, +// worker, transcriptFormat, transcribedAt, durationMs, waitedMs, words} — so a +// release-35 words.json and this file read the same (umtool reads +// `doc.words`, umtool/lib/report/reactions.mjs loadRecording). A file with no +// words array reads as absent; one with an EMPTY array is never written (an +// engine that keeps no word timestamps — the job says so and goes on). +// +// TEXT, not media: it stays in the real data/<id>/ on the corpus disk and is +// never tiered (lib/mediaTier.ts tiers by name; this name is not one). + +import { sidecar, sidecarField } from "./sidecar-server"; + +export const WORD_TIMINGS_FILENAME = "words.json"; + +export type TimedWord = { w: string; start: number; end: number; conf?: number }; + +export type WordTimingsRecord = { + version: 1; + // The file the engine read (the video's audio or saved container). + path: string; + window: { start: number; end: number | null } | null; + worker: { id: string; name: string; appId: string; model: string | null; device: string | null }; + transcriptFormat: string; + transcribedAt: string; + durationMs: number; + waitedMs: number; + words: TimedWord[]; +}; + +function isWord(w: unknown): w is TimedWord { + if (!w || typeof w !== "object") return false; + const o = w as Record<string, unknown>; + return typeof o.w === "string" && typeof o.start === "number" && typeof o.end === "number"; +} + +export function coerceWordTimings(value: unknown): WordTimingsRecord | null { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const v = value as Record<string, unknown>; + if (!Array.isArray(v.words) || v.words.length === 0 || !v.words.every(isWord)) return null; + return value as WordTimingsRecord; +} + +export const wordTimingsSidecar = sidecar(WORD_TIMINGS_FILENAME, sidecarField(coerceWordTimings), { + indent: 0, +}); + +export const loadWordTimings = wordTimingsSidecar.load; +export const writeWordTimings = wordTimingsSidecar.write; diff --git a/editor/app/api/ops/_door.test.ts b/editor/app/api/ops/_door.test.ts @@ -108,6 +108,8 @@ test("a traversing slug is refused at the door, on every route that takes one", ["fetch-posts", { slug: "../../escape", older: true }], ["capture-posts", { slug: "../../escape", ids: ["1"] }], ["persist-videos", { items: [{ slug: "../../escape", id: "abc123" }] }], + ["fetch-chat", { slug: "../../escape", id: "abc123" }], + ["find-clips", { slug: "../../escape", id: "abc123" }], ]; for (const [action, data] of cases) { const { status, body } = await callPost((await route(action)).POST!, data); diff --git a/editor/app/api/ops/_findClips.ts b/editor/app/api/ops/_findClips.ts @@ -0,0 +1,20 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { jobOfPaths } from "yt-dlp-transcript-common/controller/researchRuns"; +import type { FindClipsDeps } from "yt-dlp-transcript-common/controller/findClips"; +import { safeRevalidate } from "../../lib/safeRevalidate"; +import { findClipsEditor } from "./_researchEditor"; + +// THE EDITOR'S SIDE OF FIND CLIPS (release 36 lane A): the chain's deps — its +// steps through this editor's own ops actions in process (findClipsEditor), +// its jobs from this registry, and the video page revalidated when the record +// lands. Shared by `POST /api/ops/find-clips` and the video page's button +// (findClipsActions.ts), so the two run one chain. +export function findClipsDeps(slug: string, id: string): FindClipsDeps { + const paths = getPaths(); + return { + paths, + editor: findClipsEditor, + jobOf: jobOfPaths(paths), + onDone: () => safeRevalidate([`/channels/${slug}/videos/${id}`]), + }; +} diff --git a/editor/app/api/ops/_researchEditor.ts b/editor/app/api/ops/_researchEditor.ts @@ -86,3 +86,16 @@ export const refreshEditor: ResearchEditor = { return refreshDoor.run(action, args); }, }; + +// FIND CLIPS' EDITOR (release 36 lane A, controller/findClips.ts): the steps +// the chain hands to the editor's own ops actions — persist the source, the +// corpus transcript, the chat replay — through the same door. +const FIND_CLIPS_ROUTES: Record<string, () => Promise<{ POST: Post }>> = { + "persist-videos": () => import("./persist-videos/route"), + "transcribe-one": () => import("./transcribe-one/route"), + "fetch-chat": () => import("./fetch-chat/route"), +}; + +export const FIND_CLIPS_DOOR_ACTIONS = Object.keys(FIND_CLIPS_ROUTES); + +export const findClipsEditor: ResearchEditor = inProcessEditor(FIND_CLIPS_ROUTES, "find-clips"); diff --git a/editor/app/api/ops/find-clips/route.ts b/editor/app/api/ops/find-clips/route.ts @@ -0,0 +1,34 @@ +import { NextResponse } from "next/server"; +import { FIND_CLIPS_BODY_KEYS, enqueueFindClips } from "yt-dlp-transcript-common/controller/findClips"; +import { findClipsDeps } from "../_findClips"; +import { jobResponse, ops, reqSlug, reqVideoId } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, id, target?, segment?, project?, whilePaused?, dryRun? } +// dryRun -> { ok: true, dryRun: true, plan: { steps: [{id, label, run, why}], umtoolUrl, workersPaused } } +// else -> { ok: true, jobId } +// +// FIND CLIPS (release 36, lane A; controller/findClips.ts): the clip finder's +// chain for ONE video as one job — persist the source video, the corpus +// transcript, word timings (data/<id>/words.json), the chat replay (YouTube), +// diarization — each step skipped when its output exists and named in the +// log — then umtool's clips route (`mode: "new"`, `scope: "auto"`, or the +// `segment` asked), followed to the end. The log ends `@@find-clips {json}`: +// the project, its clip editor's URL, the segments umtool found and what each +// step did; data/<id>/find-clips.json keeps it for the video page. +// +// `target` is the cut's length in seconds; `segment` a segment id umtool +// found ("s2"); `project` names the umtool project a run makes (default from +// the id); `whilePaused` runs the two transcriptions during a pause-all on a +// worker the pause alone switched off. Refused before a job: an unknown +// channel or video, UMTOOL_URL or WORKER_TOKEN unset on the editor. +export async function POST(request: Request) { + return ops(request, FIND_CLIPS_BODY_KEYS, async (body) => { + const slug = reqSlug(body, "slug"); + const id = reqVideoId(body, "id"); + const out = await enqueueFindClips(body, findClipsDeps(slug, id)); + if (out.dryRun) return NextResponse.json({ ok: true, dryRun: true, plan: out.plan }); + return jobResponse(out.result); + }); +} diff --git a/editor/app/channels/[slug]/videos/[id]/components/FindClipsPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/FindClipsPanel.tsx @@ -0,0 +1,148 @@ +"use client"; + +// FIND CLIPS (release 36, lane A): the clip finder's whole chain for this +// video, one button — the same job as `pnpm ops find-clips` +// (controller/findClips.ts). Each step it skips or runs is in the job's log; +// what the last run found (data/<id>/find-clips.json) is drawn below it: the +// umtool project, linked, and the narrated-video segments umtool found, each +// with its own "Find clips in this part". +// +// TYPE-ONLY from lib/findClipsRecord-server (it reaches node:fs through +// sidecar-server): the record arrives as a prop, read by the page. + +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import type { FindClipsRecord } from "yt-dlp-transcript-common/lib/findClipsRecord-server"; +import { cancelJobAction } from "../../../../../jobs/actions"; +import { findClipsAction } from "../findClipsActions"; + +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")}`; +} + +export function FindClipsPanel({ + slug, + videoId, + umtoolUrl, + holds, + record, +}: { + slug: string; + videoId: string; + // UMTOOL_URL on the editor (lib/umtoolUrl.ts), read by the page. Null: the + // button is disabled and the status line says why. + umtoolUrl: string | null; + // What would hold a step right now ("the transcription workers are paused", + // "the backfill lane is held"), read by the page. Any: the "while paused" + // checkbox is offered — this one video's steps run past them. + holds: string[]; + record: FindClipsRecord | null; +}) { + const [minutes, setMinutes] = useState(""); + const [whilePaused, setWhilePaused] = useState(false); + const target = Number(minutes) > 0 ? Math.round(Number(minutes) * 60) : undefined; + const opts = (segment?: string) => ({ + ...(target !== undefined ? { target } : {}), + ...(segment ? { segment } : {}), + ...(holds.length > 0 && whilePaused ? { whilePaused: true } : {}), + }); + const status = !umtoolUrl + ? "off" + : record + ? `last run ${record.at.slice(0, 10)}: ${record.segments.length} segment${record.segments.length === 1 ? "" : "s"}` + : "not run yet"; + return ( + <section aria-label="find-clips panel" className="flex flex-col gap-4 rounded border border-border p-3"> + <div className="flex flex-wrap items-baseline justify-between gap-2"> + <h2 className="text-lg font-semibold">Find clips</h2> + <span aria-label="find-clips status" className="text-xs text-muted-foreground"> + {status} + </span> + </div> + {!umtoolUrl && ( + <p role="status" aria-label="find-clips off" className="text-sm text-muted-foreground"> + UMTOOL_URL is not set on the editor: Find clips hands the recording to umtool&apos;s clip finder. + </p> + )} + <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">Target length (minutes; empty = umtool&apos;s default)</span> + <input + type="number" + min={1} + step={1} + inputMode="numeric" + value={minutes} + onChange={(e) => setMinutes(e.target.value)} + aria-label="target length (minutes)" + className={`${input} w-28`} + /> + </label> + {holds.length > 0 && ( + <label className="flex items-center gap-2"> + <input + type="checkbox" + checked={whilePaused} + onChange={(e) => setWhilePaused(e.target.checked)} + aria-label="run while paused" + /> + Run while paused (this video only) + </label> + )} + </div> + {holds.length > 0 && ( + <p role="status" aria-label="find-clips holds" className="text-xs text-muted-foreground"> + {holds.join("; ").replace(/^./, (c) => c.toUpperCase())}. + </p> + )} + <StreamActionLog + trigger={() => findClipsAction(slug, videoId, opts())} + cancelAction={cancelJobAction} + buttonLabel="Find clips" + runningLabel="Finding clips…" + label={`Find clips in ${videoId}`} + disabled={!umtoolUrl} + /> + {record && ( + <div aria-label="find-clips result" className="flex flex-col gap-2 text-sm"> + <p> + Clips:{" "} + <a href={record.url} className="underline font-mono" data-find-clips-project> + {record.project} + </a>{" "} + <span className="text-muted-foreground"> + ({record.created ? "new project" : "re-analyzed"} + {record.segment ? `, segment ${record.segment}` : ""}) + </span> + </p> + {record.segments.length > 0 && ( + <ul aria-label="segments found" className="flex flex-col gap-2"> + {record.segments.map((s) => ( + <li key={s.id} className="flex flex-col gap-1 rounded border border-border p-2"> + <span> + <span className="font-mono">{s.id}</span> {clock(s.from)}–{clock(s.to)} + {s.why ? <span className="text-muted-foreground"> — {s.why}</span> : null} + </span> + <StreamActionLog + trigger={() => findClipsAction(slug, videoId, opts(s.id))} + cancelAction={cancelJobAction} + buttonLabel="Find clips in this part" + runningLabel="Finding clips…" + label={`Find clips in segment ${s.id}`} + disabled={!umtoolUrl} + /> + </li> + ))} + </ul> + )} + </div> + )} + </section> + ); +} diff --git a/editor/app/channels/[slug]/videos/[id]/findClipsActions.ts b/editor/app/channels/[slug]/videos/[id]/findClipsActions.ts @@ -0,0 +1,29 @@ +"use server"; + +// The video page's Find clips (release 36 lane A): the same chain as `pnpm ops +// find-clips` (controller/findClips.ts), through the same deps +// (api/ops/_findClips.ts). NOTHING BUT FUNCTIONS IS DECLARED HERE (a "use +// server" file). + +import { enqueueFindClips } from "yt-dlp-transcript-common/controller/findClips"; +import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; +import { findClipsDeps } from "../../../../api/ops/_findClips"; + +export async function findClipsAction( + slug: string, + videoId: string, + opts: { target?: number; segment?: string; whilePaused?: boolean } = {}, +): Promise<StreamActionResult> { + const out = await enqueueFindClips( + { + slug, + id: videoId, + ...(opts.target !== undefined ? { target: opts.target } : {}), + ...(opts.segment ? { segment: opts.segment } : {}), + ...(opts.whilePaused ? { whilePaused: true } : {}), + }, + findClipsDeps(slug, videoId), + ); + if (out.dryRun) return { ok: false, error: "a dry run starts no job" }; + return out.result; +} diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx @@ -38,6 +38,7 @@ import { } from "yt-dlp-transcript-common/lib/platform"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { getWorkerPool } from "yt-dlp-transcript-common/jobs/workerPool"; +import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates"; import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { resolveSourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import { liveJobRows } from "../../../../jobs/active/buildActiveJobs"; @@ -46,6 +47,9 @@ import { VideoPanel, type VideoFile } from "./components/VideoPanel"; import { OperationPanel } from "./components/OperationPanel"; 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 { 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"; import { MetadataHistoryDetails } from "./components/MetadataHistoryDetails"; @@ -221,6 +225,9 @@ export default async function VideoDetailPage({ // profile, on the corpus disk. const frameScans = await loadFrameScans(videoDir); + // What the last Find clips found (release 36 lane A): one small sidecar. + const findClips = await loadFindClipsRecord(videoDir); + // 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); @@ -246,6 +253,7 @@ export default async function VideoDetailPage({ panels, tagsView, frameScans, + findClips, }; }; const drive = config.dataDir?.trim(); @@ -280,6 +288,7 @@ export default async function VideoDetailPage({ panels, tagsView, frameScans, + findClips, } = loaded; const registry = getRegistry(); @@ -442,6 +451,18 @@ export default async function VideoDetailPage({ readingT={readingT} /> + {/* The clip finder's chain for this video (release 36 lane A). */} + <FindClipsPanel + slug={slug} + videoId={id} + umtoolUrl={resolveUmtoolUrl()} + holds={[ + ...(getWorkerPool().isPaused() ? ["the transcription workers are paused"] : []), + ...(isGateHeld(getSettings(), "backfill") ? ["the backfill lane is held"] : []), + ]} + record={findClips} + /> + {/* The external operations' per-video surface is the pipeline stage cards INSIDE VideoPanel above (download, transcode, transcription). These are the registry's — one panel per entry, and a fifth entry diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -52,6 +52,11 @@ export function blueskyOriginFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-bluesky-origin"); } +/** The file naming a slot's stub umtool (common/lib/umtoolUrl.ts; find-clips.spec). */ +export function umtoolOriginFile(transcriptsDir: string): string { + return join(transcriptsDir, ".fake-umtool-origin"); +} + /** The slot's recorded Odysee page reads (browser-lookup.spec writes it). */ export function odyseePageFixtureFile(transcriptsDir: string): string { return join(transcriptsDir, ".fake-odysee-pages.json"); @@ -205,6 +210,8 @@ export function slotServers(slot: number, mode: E2EMode, env: Env = process.env) // Where a spec names its fake Bluesky's origin (capture-posts.spec): the // slot's own test data, so two slots never share one. editorEnv.E2E_BLUESKY_ORIGIN_FILE = blueskyOriginFile(paths.transcriptsDir); + // The same for the stub umtool find-clips.spec starts (lib/umtoolUrl.ts). + editorEnv.E2E_UMTOOL_ORIGIN_FILE = umtoolOriginFile(paths.transcriptsDir); // The browser lookup's recorded page reads (browser-lookup.spec): set on // every slot, so the e2e server never opens a headless browser on the // network — the player-page opener refuses under it too. diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -34,6 +34,10 @@ import { currentSlot } from "./e2e/testPaths"; // writes its fake Bluesky's loopback origin into, // which the AppView, bsky.app and the image CDN // then are (common/social/blueskyEndpoints.ts) +// E2E_UMTOOL_ORIGIN_FILE set per slot (e2e/servers.ts): the file a spec +// writes its stub umtool's loopback origin into, +// which Find clips then posts to +// (common/lib/umtoolUrl.ts; find-clips.spec) // E2E_ODYSEE_PAGE_FIXTURE set per slot (e2e/servers.ts): the file of // recorded Odysee page reads the browser lookup // answers from (browser-lookup.spec); while it is diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -42,6 +42,9 @@ // pnpm ops metadata-scan --json '{"slug":"the-quartering"}' // pnpm ops refresh-metadata --json '{"slug":"the-quartering","id":"<videoId>"}' --wait // pnpm ops fetch-chat --json '{"slug":"demo-yt","id":"<videoId>"}' --wait +// 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 +// pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait // pnpm ops browser-lookup --json '{"slug":"demo-odysee","ids":["<claimId>"]}' --wait // pnpm ops browser-lookup --json '{"slug":"demo-odysee","listing":true,"scrolls":5}' --wait // pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait @@ -494,8 +497,13 @@ const ACTIONS = [ "audio-audit", // THE CLIP FINDER, ROUND TWO (release 36, lane A): one video's live chat // replay alone ({slug, id}), paced, into live_chat.cues.json, as a fetch-chat - // job on the platform's download queue. + // job on the platform's download queue. And the clip finder's chain for one + // video ({slug, id, target?, segment?, project?, whilePaused?, dryRun?}): + // persist, transcript, word timings, chat, diarization, umtool — each step + // skipped when its output exists — as a find-clips job. With --wait the + // result JSON (the project, its URL, the segments) is what stdout carries. "fetch-chat", + "find-clips", ]; // The log line a transcribe job ends with: this marker, then the result as @@ -523,6 +531,9 @@ export const MIRROR_SCAN_RESULT_MARKER = "@@mirror-scan "; // The same for a remote listing (REMOTE_LISTING_RESULT_MARKER in // common/controller/remoteListing.ts). 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 provenance a tag write from this CLI carries. Everything else ignores it. function agentSource() { @@ -750,6 +761,7 @@ export function parseArgs(argv) { ...(action === "bench-verdicts" ? { resultMarker: BENCH_VERDICTS_RESULT_MARKER } : {}), ...(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 === "report-schedule" ? { resultMarker: REPORT_TICK_RESULT_MARKER } : {}), wait, quiet, @@ -1143,6 +1155,20 @@ export function usage() { " job), as do a chat already here and fresh and a video never live. A pass", " that finds no replay ends done and says so.", "", + 'find-clips runs the clip finder\'s chain for ONE video as one job: {"slug",', + ' "id", "target"? (the cut\'s seconds), "segment"? (one umtool found, "s2"),', + ' "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}.', + " Persist the source video, the corpus transcript, word timings", + " (data/<id>/words.json), the chat replay (YouTube), diarization — each step", + " skipped when its output exists, named in the log — then umtool's clip", + ' finder (POST UMTOOL_URL/api/report/clips {mode: "new"}), followed to the', + " end. \"whilePaused\": true runs this one video past the holds: the two", + " transcriptions during a pause-all on a worker the pause alone switched", + " off, and its diarization in the job when the backfill lane is held.", + " \"dryRun\": true answers each step's", + " plan and starts nothing. With --wait the result — {project, url, created,", + " segments: [{id, from, to, why}], steps} — is printed on stdout.", + "", 'refresh-metadata re-reads ONE video\'s metadata.info.json from its source', ' (no subtitles, no media) on the platform\'s queue: {"slug", "id"}. The', ' job\'s log ends with what the source now says — live_status, formats,', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -6,6 +6,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { + FIND_CLIPS_RESULT_MARKER, REMOTE_LISTING_RESULT_MARKER, TRANSCRIBE_RESULT_MARKER, TTS_RESULT_MARKER, @@ -810,6 +811,21 @@ test("the archival writes are POSTs to their routes, each named in the usage", ( assert.match(usage(), /"publish", "enabled"\?, "held"\?, "action"\?/); }); +// RELEASE 36 LANE A: the clip finder's chain and one video's chat replay. +test("fetch-chat and find-clips are POSTs named in the usage; find-clips --wait carries its marker", () => { + for (const action of ["fetch-chat", "find-clips"]) { + const p = parseArgs([action, "--json", '{"slug":"x","id":"y"}']); + assert.equal(p.method, "POST", action); + assert.equal(p.path, `/api/ops/${action}`, action); + assert.match(usage(), new RegExp(`^${action} `, "m"), action); + } + const w = parseArgs(["find-clips", "--json", '{"slug":"x","id":"y"}', "--wait"]); + assert.equal(w.resultMarker, FIND_CLIPS_RESULT_MARKER); + assert.equal(FIND_CLIPS_RESULT_MARKER, "@@find-clips "); + assert.match(usage(), /"whilePaused": true runs this one video past the holds/); + assert.match(usage(), /no chat fetcher for <platform>/); +}); + test("get remote-listing posts the job, waits, and carries the result marker", () => { const r = parseArgs(["get", "remote-listing", "demo-odysee"]); assert.equal(r.method, "POST");