// 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//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=` 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//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 { logicalEntries } from "../lib/storedText"; 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 = { 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 = { 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): Check { 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 { 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); // LOGICAL for the transcript (lib/storedText.ts): a stored caption counts. const transcript = entries.includes(WHISPER_FILENAME) ? WHISPER_FILENAME : (englishVttsByPreference(logicalEntries(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): 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) — its WORK's: a job // that handed its work on (a whisper-video's transcription, queued as its own // transcribe-one job) answers with that job's state, `via` naming it. jobOf: (id: string) => Promise<{ status: string; via?: string } | null>; umtoolUrl?: string | null; workerToken?: string; fetch?: typeof fetch; settings?: () => SiteSettings; pool?: Pick; transcribeWords?: ( request: TranscribeFileRequest, o: { onLog: (line: string) => void; signal: AbortSignal; ctx?: JobRunContext }, ) => Promise; diarize?: (o: BackfillChannelJobOptions) => Promise; // 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; pollMs?: number; // The pause before asking a busy umtool again (default 30 s). busyWaitMs?: number; sleep?: (ms: number) => Promise; now?: () => Date; // Called inside the job after the record is written (the editor revalidates // the video page here). onDone?: () => void | Promise; }; const TERMINAL = new Set(["done", "failed", "cancelled"]); // How many times a busy umtool (409 naming its running job) is asked again, // `busyWaitMs` (30 s) apart: an hour. const UMTOOL_BUSY_TRIES = 120; class StepError extends Error { constructor(step: FindClipsStepId, message: string) { super(`step ${FIND_CLIPS_STEP_LABELS[step]}: ${message}`); } } function sleeper(deps: FindClipsDeps): (ms: number) => Promise { 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 { const sleep = sleeper(deps); const pollMs = deps.pollMs ?? 2000; let misses = 0; let last = ""; let via = ""; 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?.via && j.via !== via) { via = j.via; onLog(` job ${jobId} handed off to job ${via}`); } 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[] { 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, signal: AbortSignal, onLog: (line: string) => void, ): Promise { let body: Record; 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[]; // The segment umtool chose (the one asked, else auto-scope's), and the // clip editor's path ("/projects//clips"). segment?: string; href?: string; }; function segmentsOf(v: unknown): FindClipsSegment[] { if (!Array.isArray(v)) return []; return v .filter((s): s is Record => !!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> { try { const j = (await res.json()) as unknown; return j && typeof j === "object" && !Array.isArray(j) ? (j as Record) : {}; } catch { return {}; } } async function runUmtool( deps: FindClipsDeps, o: { umtool: string; token: string; body: Record; signal: AbortSignal; onLog: (line: string) => void }, ): Promise { const doFetch = deps.fetch ?? fetch; const endpoint = `${o.umtool}/api/report/clips`; const headers = { authorization: `Bearer ${o.token}`, "content-type": "application/json" }; const sleep = sleeper(deps); let res!: Response; let posted: Record = {}; // umtool runs one job at a time: a 409 that names the running job is a // wait, not a refusal (the run is retried until umtool is free); any other // 409 (the project's slug exists) is a refusal. for (let tries = 0; ; tries++) { 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?`); } posted = await umtoolJson(res); if (res.status !== 409 || !posted.running || tries >= UMTOOL_BUSY_TRIES) break; if (tries === 0) o.onLog(`umtool is busy (${typeof posted.error === "string" ? posted.error : "a job is running"}); waiting for it`); await sleep(deps.busyWaitMs ?? 30_000); if (o.signal.aborted) throw new StepError("umtool", "cancelled while waiting for umtool"); } 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); const segment = typeof posted.segment === "string" && posted.segment ? posted.segment : undefined; const href = typeof posted.href === "string" && posted.href.startsWith("/") ? posted.href : undefined; o.onLog(`umtool: ${created ? "made" : "re-analyzing"} project ${project}${segment ? ` (segment ${segment})` : ""} (job ${jobId})`); if (Array.isArray(posted.notes)) { for (const n of posted.notes) if (typeof n === "string" && n.trim()) o.onLog(`umtool: note: ${n}`); } if (segments.length) o.onLog(`umtool: segments ${segments.map((s) => `${s.id} ${Math.round(s.from)}–${Math.round(s.to)} s`).join(", ")}`); 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 | 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, ...(segment ? { segment } : {}), ...(href ? { href } : {}) }; } } await sleep(pollMs); } } // ─── the chain ─── export type FindClipsResult = Omit & { umtoolJob: string }; export async function runFindClips( req: FindClipsRequest, deps: FindClipsDeps, o: { config: ChannelConfig; onLog: (line: string) => void; signal: AbortSignal; ctx?: JobRunContext }, ): Promise { 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: u.href ? `${umtool}${u.href}` : umtoolProjectUrl(umtool, u.project), created: u.created, ...(req.segment ?? u.segment ? { segment: req.segment ?? u.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, deps: FindClipsDeps): Promise { 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?.(); }, }), }; }