// THE PIPELINE CHAIN over an article's iteration (release 27 S7; // plans/release-27.md "Shape"): the code steps that take an iteration's // report to an article with its evidence media, a video and a podcast. // // current make the iteration current (the article's report.json) // windows the editor fetches every cited clip window, padded to the // video build's fetchPad, so one fetch serves both the article's // evidence clips and the cut (in "make the video" the cut IS every // cited clip: to-manifest makes one of each) // prepare `reports prepare --article --only` // posts the editor captures THIS article's missing post screenshots, // then prepare again // manifest `reports to-manifest` into the iteration's project // (`//i/`), seeded from the parent's // project — narration carried, voices linked // voices the editor's TTS speaks the narration (narrate-via-editor) // video build-video, from the windows the editor fetched (--skip-fetch) // podcast build-podcast // attach `reports attach-video --article`, the iteration recorded as the // article's video, then `reports check --article` // dedupe hard-link identical segments and voices across the article's // projects (./iterations.mjs) // // DRAFT EVERYTHING (release 28 M9) is the same chain with the generation // steps in it, each OPTIONAL — `draft-` runs one `report-draft` job on // the iteration through the editor and waits for it: // // current → prepare → posts → manifest → draft-cut → cut-windows → // draft-onscreen → draft-teaser → draft-flips → draft-threads → // draft-narrate → voices → video (fast, never --final) → podcast → // draft-youtube → draft-social // // WINDOWS FOR THE CUT, NOT FOR EVERY CITATION (demo epic D1): Draft // everything has no early `windows`; `cut-windows` fetches the windows of the // clips the drafted cut kept (cutWindows, from the manifest), so a 37-citation // report whose cut keeps 9 asks the editor for 9. Its prepare and posts steps // go on past evidence clips not fetched yet (the article's remaining evidence // is the site's Fetch missing evidence, never the chain's). // // STOP BEFORE RENDER (demo epic D1, `stopBeforeRender`, off by default): the // chain ends before `voices` — nothing voiced, built or attached — so the cut // can be walked first; the next run resumes at `voices`. // // A connected archive's sweep (its iteration's `scope.source`, demo epic D1): // the windows steps name the archive and each clip's page URL from its record, // so the editor registers the channel remote-only; a remote-only channel's // whole recording (Rumble) is refused with its size until the chain is run // again with `allowWholeRecording` (umtool's one press). // // The drafts go after `manifest` (a media task drafts the project's manifest) // and before `voices` (narration is voiced) and the build (the drafts are in // it); YouTube's after the build, which then re-muxes its chapters so // out/youtube.txt is written; the social posts (release 29 G2) after it, // written to out/x.txt and out/bluesky.txt. No attach and no dedupe: a cut whose drafts are // not reviewed is not made the article's video. A draft step that the editor // refuses, or whose job fails, is recorded failed and the chain goes on (a // missing draft never blocks a build); one with nothing to draft is skipped. // A resume counts an optional step that ran (done, skipped or failed) as // finished. The default chain ("make the video") has no optional step. // // THE DECK OPTION (release 29 G1, off by default): Draft everything with // `deck` has one more step, `deck`, before draft-flips — no model: it writes // the minimal on-screen deck (`render.chrome`, ./chain-draft.mjs deckChrome) // through umtool's manifest writer (an `auto-before-deck` snapshot first), // ONLY when the cut has no `render.chrome`, so flips and threads have a deck // to draw on; a cut with one is left as it is. Without the option the chain // is exactly the one above (a step with `option` is in a chain only when its // option is on). // // Each step is ONE PROCESS — `node --import tsx chain-run.mjs step // ` — so lib/jobs.ts runs the chain as a job like any other (detached // process group, cancel, per-step timeout), and `umtool chain` runs the same // argv from a terminal. A step records itself in the iteration's `steps` // (`chain:`: running, then done or failed, with its minutes and a line) // through the article registry; a chain started again resumes at the first // step not done, or `--from` names one. // // This module PLANS (plain node: no TypeScript, nothing of common's), so the // Next app may import it; ./chain-run.mjs EXECUTES. import { existsSync, readFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { UMTOOL_DIR } from "./driver.mjs"; import { defaultProjectsRoot } from "yt-dlp-transcript-common/lib/projectsRoot.mjs"; // `draft`: the report-draft task an optional generation step runs. // `modes`: the chains a step is in ("video" — make the video; "draft-all"). const BOTH = ["video", "draft-all"]; const DRAFT_ONLY = ["draft-all"]; const VIDEO_ONLY = ["video"]; const DRAFT_TIMEOUT = 3 * 60 * 60_000; export const CHAIN_STEPS = [ { name: "current", label: "make the iteration current", timeoutMs: 2 * 60_000, modes: BOTH }, { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: VIDEO_ONLY }, { name: "prepare", label: "prepare the article's evidence media", timeoutMs: 60 * 60_000, modes: BOTH }, { name: "posts", label: "capture the article's post screenshots (editor)", timeoutMs: 3 * 60 * 60_000, modes: BOTH }, { name: "manifest", label: "make the video manifest, seeded from the parent", timeoutMs: 5 * 60_000, modes: BOTH }, { name: "draft-cut", label: "draft the cut: which clips, in what order", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "cut" }, { name: "cut-windows", label: "fetch the cut's clip windows (editor)", timeoutMs: 6 * 60 * 60_000, modes: DRAFT_ONLY }, { name: "draft-onscreen", label: "draft the on-screen titles", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "onscreen" }, { name: "draft-teaser", label: "draft the teaser", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "teaser" }, { name: "deck", label: "add the on-screen deck when the cut has none", timeoutMs: 5 * 60_000, modes: DRAFT_ONLY, optional: true, option: "deck" }, { name: "draft-flips", label: "draft the flips (THEN/NOW pairs)", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "flips" }, { name: "draft-threads", label: "draft the threads", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "threads" }, { name: "draft-narrate", label: "draft the narration", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "narrate" }, { name: "voices", label: "voice the narration (editor TTS)", timeoutMs: 3 * 60 * 60_000, ndjson: true, modes: BOTH }, { name: "video", label: "build the video", timeoutMs: 4 * 60 * 60_000, ndjson: true, modes: BOTH }, { name: "podcast", label: "build the podcast", timeoutMs: 30 * 60_000, ndjson: true, modes: BOTH }, { name: "draft-youtube", label: "draft the YouTube title and description", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "youtube" }, { name: "draft-social", label: "draft the posts for X and Bluesky", timeoutMs: DRAFT_TIMEOUT, modes: DRAFT_ONLY, optional: true, draft: "social" }, { name: "attach", label: "attach the video to the article", timeoutMs: 30 * 60_000, modes: VIDEO_ONLY }, { name: "dedupe", label: "share identical segments and voices", timeoutMs: 15 * 60_000, modes: VIDEO_ONLY }, ]; /** The chains: "video" (make the video, the default) and "draft-all" (Draft everything). */ export const CHAIN_MODES = ["video", "draft-all"]; /** The chains' options: `deck` (Draft everything's deck step, release 29 G1), `stopBeforeRender` (demo epic D1). Each is off by default. */ export const CHAIN_OPTIONS = ["deck", "stopBeforeRender"]; /** The step a `stopBeforeRender` chain ends before: nothing is voiced or built. */ export const RENDER_STEP = "voices"; /** * A chain's steps, in order. A step with an `option` is in it only when that * option is on (`{ deck: true }`); `stopBeforeRender` ends it before * RENDER_STEP; with none on, the chain is as it always was. * * @param {string} [mode] * @param {{ deck?: boolean, stopBeforeRender?: boolean }} [options] */ export function chainStepsOf(mode = "video", options = {}) { if (!CHAIN_MODES.includes(mode)) throw new Error(`no chain "${mode}" (${CHAIN_MODES.join(", ")})`); const steps = CHAIN_STEPS.filter((s) => s.modes.includes(mode) && (!s.option || options?.[s.option] === true)); if (options?.stopBeforeRender !== true) return steps; const at = steps.findIndex((s) => s.name === RENDER_STEP); return at < 0 ? steps : steps.slice(0, at); } /** Every step's name, either chain's (what the executor runs). */ export const ALL_CHAIN_STEP_NAMES = CHAIN_STEPS.map((s) => s.name); /** The generation steps' tasks, in Draft everything's order. */ export const DRAFT_STEP_TASKS = CHAIN_STEPS.filter((s) => s.draft).map((s) => s.draft); /** The step that drafts a task (`draft-`). */ export const draftStepName = (task) => `draft-${task}`; /** The step's definition, or undefined. */ export const chainStepDef = (name) => CHAIN_STEPS.find((s) => s.name === name); /** The default chain's step names (make the video). */ export const CHAIN_STEP_NAMES = chainStepsOf("video").map((s) => s.name); // How a step is named in the iteration's `steps`. export const chainTask = (name) => `chain:${name}`; // The video build's starter fetchPad (common/lib/report/convertManifest.ts // STARTER_RENDER): the windows are fetched this wide so the cut finds them. export const CHAIN_WINDOW_PAD = 3; // Off the corpus disk (D1): `settings.generation.projectsRoot`, blank = this — // `/articles` when REPORTS_DIR is set (a container's reports // volume), else ~/reports/articles (common/lib/projectsRoot.mjs, the one rule). export const DEFAULT_PROJECTS_ROOT = defaultProjectsRoot(); // From driver.mjs's package root, which is found from the module (or, under // the Next server, the cwd) — never this module's URL alone. /** The checkout this module is in. */ export const REPO_ROOT = path.dirname(/* turbopackIgnore: true */ UMTOOL_DIR); /** The executor every step runs. */ export const CHAIN_RUN = path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "lib", "report", "chain-run.mjs"); /** * The projects root the settings name (`settings.generation.projectsRoot`, * release 27 S6), read from the checkout's settings.json (`SETTINGS_FILE` * overrides) — `~` expanded; blank, absent or unreadable = DEFAULT_PROJECTS_ROOT. */ export function configuredProjectsRoot(settingsFile = process.env.SETTINGS_FILE ?? path.join(/* turbopackIgnore: true */ REPO_ROOT, "settings.json")) { try { const v = JSON.parse(readFileSync(/* turbopackIgnore: true */ settingsFile, "utf8"))?.generation?.projectsRoot; if (typeof v !== "string" || !v.trim()) return DEFAULT_PROJECTS_ROOT; const s = v.trim(); return s === "~" ? os.homedir() : s.startsWith("~/") ? path.join(/* turbopackIgnore: true */ os.homedir(), s.slice(2)) : s; } catch { return DEFAULT_PROJECTS_ROOT; } } const ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; /** `//i/` (common/lib/report/iterations.ts projectOf). */ export function chainProject(projectsRoot, article, n) { if (!ID_RE.test(article)) throw new Error(`"${article}" is not an article id`); if (!Number.isInteger(n) || n < 1) throw new Error(`${n} is not an iteration number`); return path.join(/* turbopackIgnore: true */ projectsRoot, article, `i${n}`); } /** * Where a chain starts: `from` when given, else the first step the iteration * has not recorded finished (`done`: the step names recorded finished, * doneSteps), else nothing (the whole chain is done: null). */ export function chainStart({ from = null, done = [], mode = "video", deck = false, stopBeforeRender = false } = {}) { const names = chainStepsOf(mode, { deck, stopBeforeRender }).map((s) => s.name); if (from !== null && from !== undefined) { if (!names.includes(from)) throw new Error(`--from must be one of ${names.join(", ")}`); return from; } const finished = new Set(done); return names.find((s) => !finished.has(s)) ?? null; } // A step that ran to an end a resume goes past: done; for an optional step // (a draft) also skipped or failed — a missing draft never blocks the chain. const FINISHED = ["done"]; const OPTIONAL_FINISHED = ["done", "skipped", "failed"]; /** The step names an iteration.json records finished, from its `steps`. */ export function doneSteps(iteration) { const out = []; for (const s of iteration?.steps ?? []) { if (typeof s?.task !== "string" || !s.task.startsWith("chain:")) continue; const name = s.task.slice("chain:".length); const ends = chainStepDef(name)?.optional ? OPTIONAL_FINISHED : FINISHED; if (ends.includes(s.status)) out.push(name); } return out; } /** An iteration's iteration.json as it is on disk, read only, or null. */ export function readIterationRecord(articlesDir, article, n) { const file = path.join(/* turbopackIgnore: true */ articlesDir, article, "iterations", String(n), "iteration.json"); if (!existsSync(/* turbopackIgnore: true */ file)) return null; try { return JSON.parse(readFileSync(/* turbopackIgnore: true */ file, "utf8")); } catch { return null; } } /** * The chain's steps for lib/jobs.ts (and `umtool chain`), from `start` * (chainStart) to the end. No secret rides in a step: the executor reads the * editor's URL and token itself (jobView shows a step's env to the browser). * `mode` "draft-all" is Draft everything: its build is the fast one whatever * `final` says, and `model` rides on the draft steps (else each task's route); * `deck` adds its deck step (G1). * * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string, deck?: boolean, stopBeforeRender?: boolean, allowWholeRecording?: boolean }} o * @returns {import("../trim").Step[]} */ export function chainSteps(o) { const projectsRoot = o.projectsRoot ?? configuredProjectsRoot(); chainProject(projectsRoot, o.article, o.n); const mode = o.mode ?? "video"; if (o.deck === true && mode !== "draft-all") throw new Error("the deck is Draft everything's option (draft-all)"); const defs = chainStepsOf(mode, { deck: o.deck === true, stopBeforeRender: o.stopBeforeRender === true }); const start = o.start === undefined ? defs[0].name : o.start; if (start === null) return []; const at = defs.findIndex((s) => s.name === start); if (at < 0) throw new Error(`no chain step "${start}"`); if (o.model !== undefined && (typeof o.model !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/.test(o.model))) { throw new Error(`"${o.model}" is not a model name`); } const extra = [ "--projects-root", projectsRoot, ...(o.siteOrigin ? ["--site-origin", o.siteOrigin] : []), ...(o.final && mode === "video" ? ["--final"] : []), ...(mode !== "video" ? ["--mode", mode] : []), ...(o.allowWholeRecording === true ? ["--allow-whole-recording"] : []), ]; return defs.slice(at).map((s, i) => ({ label: `${at + i + 1}/${defs.length} ${s.label}`, cwd: REPO_ROOT, env: {}, argv: [o.node ?? process.execPath, "--import", "tsx", CHAIN_RUN, "step", o.article, String(o.n), s.name, ...extra, ...(s.draft && o.model ? ["--model", o.model] : [])], timeoutMs: s.timeoutMs, ...(s.ndjson ? { ndjson: true } : {}), })); } /** * The chain to run for an iteration as it is on disk — what `umtool chain` * and the app's job both start from: its record (read only), where it starts * (resume, or `from`) and the steps. Throws for no such iteration, an * iteration not done, or an unknown `from`. `steps` is empty when every step * is done. * * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string, deck?: boolean, stopBeforeRender?: boolean, allowWholeRecording?: boolean }} o */ export function planChain(o) { const record = readIterationRecord(o.articlesDir, o.article, o.n); if (!record) throw new Error(`"${o.article}" has no iteration i${o.n} under ${o.articlesDir}`); if (record.status !== "done") throw new Error(`${o.article} i${o.n} is ${record.status}: the chain runs over a done iteration`); const mode = o.mode ?? "video"; const deck = o.deck === true; if (deck && mode !== "draft-all") throw new Error("the deck is Draft everything's option (draft-all)"); const stopBeforeRender = o.stopBeforeRender === true; const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode, deck, stopBeforeRender }); const steps = chainSteps({ article: o.article, n: o.n, start, mode, ...(deck ? { deck } : {}), ...(stopBeforeRender ? { stopBeforeRender } : {}), ...(o.allowWholeRecording === true ? { allowWholeRecording: true } : {}), ...(o.model ? { model: o.model } : {}), ...(o.projectsRoot ? { projectsRoot: o.projectsRoot } : {}), ...(o.siteOrigin ? { siteOrigin: o.siteOrigin } : {}), final: o.final === true, }); return { record, start, steps, mode, deck, stopBeforeRender }; } const floor2 = (x) => Math.floor(x * 100 + 1e-6) / 100; const ceil2 = (x) => Math.ceil(x * 100 - 1e-6) / 100; /** * The clip windows a report cites, as the body of the editor's fetch-windows * (one per distinct moment): each the cited span widened by `pad` (the cut's * fetchPad) and by the citation's own pad (its evidence clip's), clamped at 0 * and rounded outward to the hundredth — `from`/`to` ARE the window; `pad` * rides along as provenance. */ export function chainWindows(report, { pad = CHAIN_WINDOW_PAD, requestedBy = "umtool chain" } = {}) { const items = []; const byMoment = new Map(); for (const [cid, c] of Object.entries(report?.citations ?? {})) { if (c?.kind !== "video" && c?.kind !== "audio") continue; if (typeof c.start !== "number" || typeof c.end !== "number") continue; const before = Math.max(pad, c.pad?.before ?? 0); const after = Math.max(pad, c.pad?.after ?? 0); const from = floor2(Math.max(0, c.start - before)); const to = ceil2(c.end + after); const key = `${c.channel}/${c.id}`; const same = (byMoment.get(key) ?? []).find((w) => w.from <= from && w.to >= to); if (same) continue; const item = { slug: c.channel, id: c.id, from, to, clipId: `${report.id}#${cid}`, reason: `article ${report.id} ${cid}`, pad, }; items.push(item); byMoment.set(key, [...(byMoment.get(key) ?? []), item]); } return { items, requestedBy }; } /** * The windows of the clips a CUT keeps (demo epic D1): its manifest's clip * entries, each its span widened by `pad` and rounded outward to the * hundredth, one per distinct moment — the same body chainWindows makes from * a report, for the cut a draft (or a person) narrowed. */ export function cutWindows(manifest, { pad = CHAIN_WINDOW_PAD, requestedBy = "umtool chain" } = {}) { const items = []; const byMoment = new Map(); const fallbackChannel = manifest?.provenance?.channelSlug; for (const e of manifest?.timeline ?? []) { if (e?.type !== "clip") continue; const slug = e.channel ?? fallbackChannel; if (!slug || !e.video || typeof e.start !== "number" || typeof e.end !== "number") continue; const from = floor2(Math.max(0, e.start - pad)); const to = ceil2(e.end + pad); const key = `${slug}/${e.video}`; if ((byMoment.get(key) ?? []).some((w) => w.from <= from && w.to >= to)) continue; const item = { slug, id: e.video, from, to, clipId: `${manifest.slug ?? "cut"}#${e.id}`, reason: `cut ${manifest.slug ?? ""} ${e.id}`.trim(), pad, }; items.push(item); byMoment.set(key, [...(byMoment.get(key) ?? []), item]); } return { items, requestedBy }; } /** The archive origin a sweep's moment links name (`https://host/?v=…`), or null. */ export function originFromSweep(text) { const m = /(https?:\/\/[^/\s)"']+)\/?\?v=/.exec(String(text ?? "")); return m ? m[1] : null; }