// THE CHAIN'S EXECUTOR (release 27 S7): one step of ./chain.mjs, run as its // own process — // // node --import tsx umtool/lib/report/chain-run.mjs step
// [--projects-root ] [--site-origin ] [--final] [--model ] // [--mode draft-all] [--allow-whole-recording] // // — under tsx, because the article registry, the iterations store and the // reports CLIs it calls are common's TypeScript. The Next app never imports // this file (it imports ./chain.mjs, which plans). Each step records itself in // the iteration's `steps` as `chain:` (running → done | failed | // cancelled, minutes, one line) and exits 0 when it is done. // // Every fetch, capture and voice is the EDITOR's (no yt-dlp, gallery-dl or // TTS here): `pnpm ops fetch-windows` / `capture-posts` and // narrate-via-editor.mjs, with the editor's URL and token read from the // environment or the editor's env files at run time — never put in a step. // // A generation step (`draft-`, release 28 M9) is a `report-draft` job // the editor runs: POST /api/ops/report-draft, then GET /api/ops/job/ // until it ends (its progress and log lines printed), and a cancel of the // chain cancels the job. The step is OPTIONAL: refused or failed, it is // recorded failed and the process exits 0 so the chain goes on; with nothing // to draft (every field already written) it is recorded skipped. // // The deck step (`deck`, release 29 G1, Draft everything's option) asks no // model: it adds the minimal on-screen deck through umtool's manifest writer // (manifest.mjs addDeckChrome: a snapshot first) when the cut has none. import { spawn } from "node:child_process"; import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; import { articleDir, articleFile } from "yt-dlp-transcript-common/lib/report/registry"; import { lineage, lineageSource, makeCurrent, projectOf, readIteration, readIterationFile, recordIterationStep, setCurrentVideo, updateIteration, } from "yt-dlp-transcript-common/lib/report/iterations"; import { articleReportStore } from "yt-dlp-transcript-common/lib/report/store"; import { readStoreMediaIndex } from "yt-dlp-transcript-common/publish/reportMedia"; import { isArticleProblem } from "yt-dlp-transcript-common/publish/reportHost"; import { main as prepareMain } from "yt-dlp-transcript-common/bin/reports-prepare"; import { toManifestMain } from "yt-dlp-transcript-common/bin/reports-convert"; import { attachVideoMain } from "yt-dlp-transcript-common/bin/reports-attach-video"; import { checkMain } from "yt-dlp-transcript-common/bin/reports-check"; import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, cutWindows, originFromSweep } from "./chain.mjs"; import { deckChrome, deckRefusedDetail, deckStepDetail, draftFileOf, draftOutcome, draftPrecheck } from "./chain-draft.mjs"; import { ChromeRefused, addDeckChrome } from "./manifest.mjs"; import { socialTexts } from "umtool-report-to-video/social"; import { PIPELINE_DIR } from "./driver.mjs"; import { resolveLocalSource } from "umtool-report-to-video/sources"; import { dedupeMedia, seedFromParent } from "./iterations.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; import { WHOLE_RECORDING_REFUSED, connectedArchives, disconnectedArchiveRefusal, originOfHandle } from "yt-dlp-transcript-common/lib/remoteArchives"; import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs"; import { archiveRecordPageHref } from "yt-dlp-transcript-common/controller/remoteOnlyChannel"; import { cachedArchiveGetJson } from "yt-dlp-transcript-common/lib/archiveCache-server"; const OPS = path.join(REPO_ROOT, "scripts", "archilyzer-ops.mjs"); const SCREENSHOT_MISSING = /no captured screenshot/; const CLIP_MISSING = /fetch the window or persist the video in the editor/; /** A step that ends early with a reason: failed, with that line. */ class StepFailed extends Error {} /** A step with nothing to do: skipped, with that line (an optional step's). */ class StepSkipped extends Error {} const exists = async (p) => !!(await stat(p).catch(() => null)); /** Run a command, its output into this process's, its exit code back. */ function run(argv, { cwd = REPO_ROOT, env = process.env } = {}) { return new Promise((resolve, reject) => { const child = spawn(argv[0], argv.slice(1), { cwd, env, stdio: "inherit" }); child.on("error", reject); child.on("exit", (code, signal) => resolve(signal ? 128 + 15 : (code ?? 1))); }); } /** * This process's environment with the editor's URL and token filled in, as * `pnpm ops` fills its own (scripts/archilyzer-ops.mjs loadEditorEnv: the * environment, else the editor's env files). The values are never printed. * Imported at run time by path: the ops client is a CLI, not a module the * app's scan set should follow. */ async function editorEnv() { const { loadEditorEnv } = await import(pathToFileURL(OPS).href); const env = { ...process.env }; loadEditorEnv(env); return env; } // The ops client fills the editor's URL and token itself. const ops = (action, args) => run([process.execPath, OPS, action, ...args, "--wait"]); /** The article's own problems in the prepared media index, and the post screenshots among them. */ async function ownProblems(paths, article) { const index = await readStoreMediaIndex(articleReportStore(paths)); const own = (index?.problems ?? []).filter((p) => isArticleProblem(p, article)); const shots = own.filter((p) => p.kind === "missing-media" && SCREENSHOT_MISSING.test(p.message) && p.moment); // An evidence clip whose window is not on disk (publish/reportMedia.ts). const clips = own.filter((p) => p.kind === "missing-media" && CLIP_MISSING.test(p.message) && !shots.includes(p)); return { own, shots, clips, rest: own.filter((p) => !shots.includes(p) && !clips.includes(p)) }; } /** * Ask the editor for a step's windows (demo epic D1 adds the archive): when * the lineage read a connected archive (`scope.source`), the body names it and * each item carries its page URL from the archive's record, so the editor * registers a channel it does not hold as remote-only. Then a DRY RUN first: * a remote-only channel's whole recording (Rumble) refused with its size fails * the step with every such refusal — nothing fetched — until the chain runs * again with `allowWholeRecording` (umtool's one press). Then the run, waited on. */ async function fetchWindowsStep(ctx, body, what) { const origin = originOfHandle(await lineageSource(ctx.article, ctx.n, ctx.paths).catch(() => null)); if (origin) { // An archive removed from settings is not read any more (the editor // refuses its channels' windows too): nothing is asked of it, and the step // says to connect it again. The connected ones are settings.json's and // TRANSCRIPT_SITE_URL's, as the source picker lists them (lib/research/sources.ts). const settingsFile = process.env.SETTINGS_FILE?.trim() || path.join(REPO_ROOT, "settings.json"); const stored = await readFile(settingsFile, "utf8").then((t) => JSON.parse(t)?.remoteArchives, () => null); const gone = disconnectedArchiveRefusal(origin, connectedArchives(stored)); if (gone) throw new StepFailed(`this article was swept over a published archive, and ${gone}`); const getJson = cachedArchiveGetJson(); body.archive = origin; for (const item of body.items) { if (item.webpageUrl) continue; // Only a video platform's page (the editor refuses any other, too), and // as the URL the check parsed — never the record's own string. const href = await archiveRecordPageHref(origin, item.slug, item.id, detectPlatform, { getJson }); if (href) item.webpageUrl = href; } if (ctx.allowWholeRecording) body.allowWholeRecording = true; const dry = await editorCall(await editorEnv(), "POST", "/api/ops/fetch-windows", { ...body, dryRun: true }); if (!dry.ok) throw new StepFailed(`the editor refused the windows: ${dry.error}`); const whole = (dry.body?.unresolved ?? []).filter((u) => String(u?.error ?? "").startsWith(WHOLE_RECORDING_REFUSED)); if (whole.length > 0) { const sizes = whole.map((u) => /: (\S+ is [^.]+|\S+'s length is not known to its archive)\./.exec(String(u.error))?.[1] ?? `${u.item?.slug}/${u.item?.id}`); throw new StepFailed( `${WHOLE_RECORDING_REFUSED} ${whole.length} window(s) need their whole recording downloaded — ${[...new Set(sizes)].join("; ")}. ` + "Allow the whole recordings to fetch them (the chain again, allowWholeRecording).", ); } } await mkdir(ctx.project, { recursive: true }); const file = path.join(ctx.project, "windows.json"); await writeJson(file, body); const code = await ops("fetch-windows", ["--file", file]); if (code !== 0) throw new StepFailed(`the editor's fetch-windows ended ${code} (a re-run fetches only what is missing)`); return `${body.items.length} window(s) ${what} on disk${origin ? ` (archive ${origin})` : ""}`; } const describe = (problems) => problems .slice(0, 3) .map((p) => `${p.kind}: ${p.moment ?? p.report ?? ""} ${p.message}`.trim()) .join("; ") + (problems.length > 3 ? `; and ${problems.length - 3} more` : ""); // ─── The steps: each answers its one line, or throws StepFailed ─── const STEPS = { async current(ctx) { const { report, current } = await makeCurrent(ctx.article, ctx.n, ctx.paths); await mkdir(ctx.project, { recursive: true }); if (ctx.iteration.projectDir !== ctx.project) await updateIteration(ctx.article, ctx.n, { projectDir: ctx.project }, ctx.paths); return `the article is i${ctx.n}${current.reportFrom !== ctx.n ? ` (the report of i${current.reportFrom})` : ""}: “${report.title}”`; }, async windows(ctx) { const report = JSON.parse(await readFile(articleFile(ctx.paths, ctx.article), "utf8")); const body = chainWindows(report, { pad: CHAIN_WINDOW_PAD, requestedBy: `umtool chain ${ctx.article} i${ctx.n}` }); if (body.items.length === 0) return "no clip windows cited"; return fetchWindowsStep(ctx, body, "cited"); }, // Draft everything's (demo epic D1): the windows of the clips the cut kept. async ["cut-windows"](ctx) { const file = path.join(ctx.project, "video.manifest.json"); const manifest = await readJsonOr(file); if (!manifest) throw new StepFailed(`no video manifest at ${file}: run the chain's manifest step first`); const body = cutWindows(manifest, { pad: CHAIN_WINDOW_PAD, requestedBy: `umtool chain ${ctx.article} i${ctx.n} cut` }); if (body.items.length === 0) return "the cut has no clip"; // What the build would find on disk is not asked for: the project's own // out/clips-raw, the corpus's windows, a saved recording (sources.mjs, the // build's lookup order). const rawDir = path.join(ctx.project, "out", "clips-raw"); const missing = []; for (const item of body.items) { const hit = await resolveLocalSource({ video: item.id, slug: item.slug, from: item.from, to: item.to }, { rawDir, channelsDir: ctx.paths.channelsDir, render: manifest.render ?? null }).catch(() => null); if (!hit) missing.push(item); } if (missing.length === 0) return `the cut's ${body.items.length} window(s) are on disk already`; const held = body.items.length - missing.length; const said = await fetchWindowsStep(ctx, { ...body, items: missing }, "of the cut's"); return held ? `${said}; ${held} on disk already` : said; }, async prepare(ctx) { const code = await prepareMain({ article: ctx.article, only: true }); if (code === 0) return "the evidence media is complete; the article is exported"; const { own, shots, clips, rest } = await ownProblems(ctx.paths, ctx.article); // Draft everything fetches the CUT's windows later (cut-windows): an // evidence clip not fetched yet does not stop it. const later = ctx.mode === "draft-all" ? clips : []; const blocking = ctx.mode === "draft-all" ? rest : [...clips, ...rest]; if (own.length > 0 && blocking.length === 0) { return [ shots.length ? `${shots.length} post screenshot(s) to capture (the next step)` : "", later.length ? `${later.length} evidence clip(s) not fetched: the cut's are fetched after the cut is drafted; the rest by Fetch missing evidence` : "", ].filter(Boolean).join("; "); } throw new StepFailed(blocking.length ? describe(blocking) : `reports prepare ended ${code}`); }, async posts(ctx) { const { shots, clips, rest: others } = await ownProblems(ctx.paths, ctx.article); const rest = ctx.mode === "draft-all" ? others : [...clips, ...others]; if (rest.length > 0) throw new StepFailed(`prepare has this article's other problems first: ${describe(rest)}`); if (shots.length === 0) return "no post screenshot to capture"; const bySlug = new Map(); for (const p of shots) { const [slug, id] = String(p.moment).split("/"); if (!slug || !id) continue; bySlug.set(slug, [...new Set([...(bySlug.get(slug) ?? []), id])]); } for (const [slug, ids] of bySlug) { console.log(`chain: capturing ${ids.length} post screenshot(s) of ${slug} (the editor, paced)`); const code = await ops("capture-posts", ["--json", JSON.stringify({ slug, ids, media: false })]); if (code !== 0) throw new StepFailed(`the editor's capture-posts for ${slug} ended ${code}`); } const code = await prepareMain({ article: ctx.article, only: true }); if (code !== 0) { const again = await ownProblems(ctx.paths, ctx.article); const left = ctx.mode === "draft-all" ? [...again.shots, ...again.rest] : again.own; if (left.length === 0) return `${shots.length} post screenshot(s) captured; ${again.clips.length} evidence clip(s) not fetched yet`; throw new StepFailed(left.length ? describe(left) : `reports prepare ended ${code}`); } return `${shots.length} post screenshot(s) captured; the evidence media is complete`; }, async manifest(ctx) { const file = path.join(ctx.project, "video.manifest.json"); await mkdir(ctx.project, { recursive: true }); if (await exists(file)) return "the project's manifest is kept (delete it to start the cut over)"; const input = articleFile(ctx.paths, ctx.article); const siteOrigin = ctx.siteOrigin ?? (await sweepOrigin(ctx)); const code = await toManifestMain({ input, out: file, channelsDir: ctx.paths.channelsDir, ...(siteOrigin ? { siteOrigin } : {}), }); if (code !== 0) throw new StepFailed(`reports to-manifest ended ${code}`); // What the cut reads beside its manifest: the report, and any still it shows. await copyFile(input, path.join(ctx.project, "report.json")); const manifest = JSON.parse(await readFile(file, "utf8")); let stills = 0; for (const e of manifest.timeline ?? []) { if (e?.type !== "image" || typeof e.src !== "string" || path.isAbsolute(e.src) || e.src.split(/[\\/]/).includes("..")) continue; const src = path.join(articleDir(ctx.paths, ctx.article), e.src); if (!(await exists(src))) continue; await mkdir(path.dirname(path.join(ctx.project, e.src)), { recursive: true }); await copyFile(src, path.join(ctx.project, e.src)); stills += 1; } let seeded = ""; const parentN = ctx.iteration.parent; if (parentN !== null) { const parent = await readIteration(ctx.article, parentN, ctx.paths); const parentProject = parent?.projectDir ?? projectOf(ctx.projectsRoot, ctx.article, parentN); if (await exists(path.join(parentProject, "video.manifest.json"))) { const r = await seedFromParent(parentProject, ctx.project); seeded = `; from i${parentN}: ${r.carried} narration(s) carried, ${r.linked} voice file(s) linked`; } } return `${(manifest.timeline ?? []).length} timeline entries${stills ? `, ${stills} still(s)` : ""}${siteOrigin ? "" : " — no site origin: set provenance.siteOrigin before the QR codes render"}${seeded}`; }, async voices(ctx) { const file = path.join(ctx.project, "video.manifest.json"); const manifest = JSON.parse(await readFile(file, "utf8")); const narrated = (manifest.timeline ?? []).filter((e) => e?.type === "card" && e.narration?.text).length; if (narrated === 0) return "no narration to voice"; const code = await run( [process.execPath, path.join(PIPELINE_DIR, "narrate-via-editor.mjs"), file, "--out", path.join(ctx.project, "out"), "--progress", "ndjson"], { cwd: PIPELINE_DIR, env: await editorEnv() }, ); if (code !== 0) throw new StepFailed(`narrate-via-editor ended ${code}`); return `${narrated} card(s) voiced`; }, async video(ctx) { const file = path.join(ctx.project, "video.manifest.json"); const out = path.join(ctx.project, "out"); const argv = [process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), file, "--out", out, "--progress", "ndjson", "--continue-on-error", "--skip-fetch"]; if (!ctx.final) argv.push("--no-xfade"); const code = await run(argv, { cwd: PIPELINE_DIR }); if (code !== 0) throw new StepFailed(`build-video ended ${code}`); const verify = [process.execPath, path.join(PIPELINE_DIR, "verify-build.mjs"), file, "--out", out]; if (!ctx.final) verify.push("--no-xfade"); const v = await run(verify, { cwd: PIPELINE_DIR }); if (v !== 0) throw new StepFailed(`verify-build ended ${v}: the cut is not what the manifest says`); return `${ctx.final ? "final (crossfaded)" : "fast (hard cuts)"} cut built and verified`; }, async podcast(ctx) { const file = path.join(ctx.project, "video.manifest.json"); const code = await run( [process.execPath, path.join(PIPELINE_DIR, "build-podcast.mjs"), file, "--out", path.join(ctx.project, "out"), "--progress", "ndjson"], { cwd: PIPELINE_DIR }, ); if (code !== 0) throw new StepFailed(`build-podcast ended ${code}`); return "podcast built"; }, async attach(ctx) { const manifest = JSON.parse(await readFile(path.join(ctx.project, "video.manifest.json"), "utf8")); const video = path.join(ctx.project, "out", `${manifest.slug ?? ctx.article}.mp4`); if (!(await exists(video))) throw new StepFailed(`no cut at ${video}: build the video first`); const code = await attachVideoMain({ article: ctx.article, video }); if (code !== 0) throw new StepFailed(`reports attach-video ended ${code}`); await setCurrentVideo(ctx.article, ctx.n, ctx.paths); const check = await checkMain({ article: ctx.article, paths: ctx.paths }); await updateIteration( ctx.article, ctx.n, (cur) => ({ checks: [...(cur.checks ?? []).filter((c) => c.name !== "reports check"), { name: "reports check", ok: check === 0, ...(check === 0 ? {} : { detail: `exit ${check}` }) }], }), ctx.paths, ); if (check !== 0) throw new StepFailed(`attached, but reports check --article ${ctx.article} ended ${check}`); return `the article's video is i${ctx.n}'s; reports check passes`; }, async dedupe(ctx) { const r = await dedupeMedia(path.join(ctx.projectsRoot, ctx.article)); return `${r.links} file(s) linked, ${(r.freedBytes / 1e6).toFixed(1)} MB freed`; }, }; // ─── The generation steps (release 28 M9): one report-draft job each ─── // How often a draft step asks the editor about its job. const DRAFT_POLL_MS = Number(process.env.CHAIN_DRAFT_POLL_MS) > 0 ? Number(process.env.CHAIN_DRAFT_POLL_MS) : 2000; // A run of failed polls this long ends the step (the job keeps running in the editor). const DRAFT_POLL_GIVE_UP = 60; const RESULT_MARKER = "@@report-draft "; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** One call to the editor's ops API: `{ ok, status, body }` or `{ ok: false, error }`. Never throws. */ async function editorCall(env, method, route, body) { const base = (env.ARCHILYZER_EDITOR_URL || "http://localhost:3001").replace(/\/+$/, ""); try { const res = await fetch(`${base}${route}`, { method, headers: { ...(env.WORKER_TOKEN ? { authorization: `Bearer ${env.WORKER_TOKEN}` } : {}), "content-type": "application/json" }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), }); const json = await res.json().catch(() => ({})); if (!res.ok || json?.ok === false) return { ok: false, status: res.status, error: String(json?.error ?? `HTTP ${res.status}`) }; return { ok: true, status: res.status, body: json }; } catch (err) { return { ok: false, status: 0, error: `the editor at ${base} did not answer: ${err?.message ?? err}` }; } } /** The task's report-draft marker in a job's log tail, or null. */ function markerOf(tail) { for (let i = tail.length - 1; i >= 0; i--) { const at = String(tail[i]).indexOf(RESULT_MARKER); if (at < 0) continue; try { return JSON.parse(String(tail[i]).slice(at + RESULT_MARKER.length)); } catch { return null; } } return null; } const readJsonOr = async (file) => { try { return JSON.parse(await readFile(file, "utf8")); } catch { return null; } }; async function draftStep(ctx, task) { const file = path.join(ctx.project, "video.manifest.json"); const manifest = await readJsonOr(file); if (!manifest) throw new StepFailed(`no video manifest at ${file}: run the chain's manifest step first`); const why = draftPrecheck(task, manifest); if (why) throw new StepSkipped(why); const env = await editorEnv(); const body = { task, article: ctx.article, iteration: ctx.n, ...(ctx.model ? { model: ctx.model } : {}) }; const started = await editorCall(env, "POST", "/api/ops/report-draft", body); if (!started.ok) throw new StepFailed(`the editor refused the ${task} draft: ${started.error}`); const jobId = String(started.body.jobId ?? ""); if (!jobId) throw new StepFailed(`the editor started no job for the ${task} draft`); console.log(`chain: ${task} draft — job ${jobId}${ctx.model ? ` on ${ctx.model}` : " on the route's model"}`); ctx.onCancel(() => editorCall(env, "POST", "/api/ops/job", { verb: "cancel", ids: [jobId] })); let job = null; let tail = []; let misses = 0; let said = ""; for (;;) { const r = await editorCall(env, "GET", `/api/ops/job/${encodeURIComponent(jobId)}?tail=200`); if (!r.ok) { if (++misses >= DRAFT_POLL_GIVE_UP) throw new StepFailed(`lost the ${task} draft's job ${jobId}: ${r.error} (it may still be running in the editor)`); } else { misses = 0; job = r.body.job ?? {}; tail = Array.isArray(r.body.tail) ? r.body.tail.map(String) : []; const p = job.progress; const now = `${job.status}${p && typeof p.current === "number" ? ` — ${p.metric ?? "progress"} ${p.current}/${p.target ?? "?"}` : ""}`; if (now !== said) { console.log(`chain: ${task} draft ${now}`); said = now; } if (["done", "failed", "cancelled"].includes(job.status)) break; } await sleep(DRAFT_POLL_MS); } for (const line of tail.filter((l) => !l.includes(RESULT_MARKER)).slice(-8)) console.log(` ${line}`); const marker = markerOf(tail); const it = await readIteration(ctx.article, ctx.n, ctx.paths).catch(() => null); const step = [...(it?.steps ?? [])].reverse().find((s) => s.task === task && s.jobId === jobId); const words = marker?.summary ?? step?.detail ?? null; if (job.status === "done") return words ?? `${task} drafted`; if (job.status === "cancelled") throw new StepFailed(`the ${task} draft's job ${jobId} was cancelled in the editor`); const outcome = draftOutcome(await readJsonOr(path.join(ctx.project, draftFileOf(task)))); if (outcome.status === "skipped") throw new StepSkipped(outcome.detail); throw new StepFailed(`${words ?? `the ${task} draft failed`} (job ${jobId})`); } // After the YouTube draft, a built cut re-muxes its chapters, which writes // out/youtube.txt (build-video --chapters-only; Draft everything's build is // the fast one). Not built yet: the next build writes it. async function youtubeText(ctx) { const file = path.join(ctx.project, "video.manifest.json"); const manifest = await readJsonOr(file); const out = path.join(ctx.project, "out"); if (!manifest || !(await exists(path.join(out, `${manifest.slug ?? ctx.article}.mp4`)))) return "; the next build writes out/youtube.txt"; const code = await run( [process.execPath, path.join(PIPELINE_DIR, "build-video.mjs"), file, "--out", out, "--chapters-only", "--no-xfade", "--skip-fetch"], { cwd: PIPELINE_DIR }, ); return code === 0 ? "; out/youtube.txt written" : `; out/youtube.txt not written (build-video --chapters-only ended ${code})`; } // The deck option (release 29 G1): the minimal deck on a cut with none, so // flips and threads have a panel to draw on; a cut with a deck is untouched. STEPS.deck = async (ctx) => { const file = path.join(ctx.project, "video.manifest.json"); if (!(await exists(file))) throw new StepFailed(`no video manifest at ${file}: run the chain's manifest step first`); let r; try { r = await addDeckChrome(ctx.project, deckChrome()); } catch (err) { // The deck's defaults need a frame tall enough for the footage beside it: // a sub-HD cut refuses it, and the step says so (the flips and threads are // then skipped for want of a deck). if (err instanceof ChromeRefused) throw new StepFailed(deckRefusedDetail(err.errors, JSON.parse(await readFile(file, "utf8")).render)); throw err; } return deckStepDetail(r.added); }; for (const name of ["cut", "onscreen", "teaser", "flips", "threads", "narrate"]) { STEPS[`draft-${name}`] = (ctx) => draftStep(ctx, name); } STEPS["draft-youtube"] = async (ctx) => { const said = await draftStep(ctx, "youtube"); return `${said}${await youtubeText(ctx)}`; }; // After the social draft (release 29 G2), its posts as files to copy: // out/x.txt and out/bluesky.txt (report-to-video/social.mjs; the build writes // them too). They need no build: the posts are the manifest's. async function writeSocialFiles(ctx) { const manifest = await readJsonOr(path.join(ctx.project, "video.manifest.json")); const out = path.join(ctx.project, "out"); await mkdir(out, { recursive: true }); const written = []; for (const { name, text } of socialTexts(manifest)) { // A platform with no post loses its old file, as the build's writer does. if (text === null) { await rm(path.join(out, name), { force: true }); continue; } await writeFile(path.join(out, name), text, "utf8"); written.push(`out/${name}`); } return written.length ? `${written.join(" and ")} written` : "no post to write"; } STEPS["draft-social"] = async (ctx) => { let said; try { said = await draftStep(ctx, "social"); } catch (err) { // Nothing to draft (both posts written already): their files still are. if (err instanceof StepSkipped) throw new StepSkipped(`${err.message}; ${await writeSocialFiles(ctx)}`); throw err; } return `${said}; ${await writeSocialFiles(ctx)}`; }; async function writeJson(file, value) { const tmp = tmpPathFor(file); await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); await rename(tmp, file); } // The archive the sweep's moment links name — the QR codes' origin: the // newest sweep.md in the iteration's lineage that names one. // When none does (a hand-made iteration, a sweep.md without moment links), // the published archive the lineage read (demo epic D1: `scope.source`, // remote:) — the editor cited it there. async function sweepOrigin(ctx) { const line = await lineage(ctx.article, ctx.n, ctx.paths).catch(() => [ctx.n]); for (const n of [...line].reverse()) { const origin = originFromSweep(await readIterationFile(ctx.article, n, "sweep.md", ctx.paths)); if (origin) return origin; } const source = await lineageSource(ctx.article, ctx.n, ctx.paths).catch(() => null); return originOfHandle(source) ?? undefined; } /** * Run one step of an iteration's chain, recorded in its `steps`. * @returns {Promise} the exit code: 0 done, 1 failed, 2 refused */ export async function runChainStep(article, n, name, opts = {}) { if (!ALL_CHAIN_STEP_NAMES.includes(name)) { console.error(`chain: no step "${name}" (${ALL_CHAIN_STEP_NAMES.join(", ")})`); return 2; } const optional = chainStepDef(name)?.optional === true; const paths = opts.paths ?? getPaths(); const iteration = await readIteration(article, n, paths).catch((err) => { console.error(`chain: ${err.message}`); return undefined; }); if (iteration === undefined) return 2; if (!iteration) { console.error(`chain: "${article}" has no iteration i${n}`); return 2; } if (iteration.status !== "done") { console.error(`chain: "${article}" i${n} is ${iteration.status} — the chain runs over a done iteration`); return 2; } const projectsRoot = opts.projectsRoot ?? configuredProjectsRoot(); const ctx = { article, n, paths, iteration, projectsRoot, project: projectOf(projectsRoot, article, n), siteOrigin: opts.siteOrigin, final: opts.final === true, model: opts.model, mode: opts.mode === "draft-all" ? "draft-all" : "video", allowWholeRecording: opts.allowWholeRecording === true, cancels: [], onCancel(fn) { this.cancels.push(fn); }, }; const task = chainTask(name); const startedAt = new Date(); const record = (status, detail) => recordIterationStep( article, n, { task, status, startedAt: startedAt.toISOString(), ...(status === "running" ? {} : { endedAt: new Date().toISOString(), minutes: Number(((Date.now() - startedAt.getTime()) / 60_000).toFixed(2)) }), ...(detail ? { detail } : {}), }, paths, ); await record("running"); // A cancel (the job runner's SIGTERM to the step's process group) is recorded, best effort. const onTerm = () => { // What the step started elsewhere (a draft's editor job) is cancelled first. const hooks = Promise.allSettled(ctx.cancels.map((f) => f())); Promise.race([hooks, sleep(5000)]) .then(() => record("cancelled", "cancelled")) .finally(() => process.exit(143)); }; process.once("SIGTERM", onTerm); console.log(`chain: ${article} i${n} — ${name}`); try { const detail = await STEPS[name](ctx); await record("done", detail); console.log(`chain: ${name} done — ${detail}`); return 0; } catch (err) { if (err instanceof StepSkipped) { await record("skipped", err.message).catch(() => {}); console.log(`chain: ${name} skipped — ${err.message}`); return 0; } const detail = err instanceof StepFailed ? err.message : `${err?.name ?? "Error"}: ${err?.message ?? String(err)}`; await record("failed", detail).catch(() => {}); if (optional) { // A missing draft never blocks the chain. console.error(`chain: ${name} failed — ${detail}; the chain goes on without it`); return 0; } console.error(`chain: ${name} failed — ${detail}`); return 1; } finally { process.removeListener("SIGTERM", onTerm); } } function parseArgs(argv) { const [cmd, article, n, name, ...rest] = argv; const flag = (k) => { const i = rest.indexOf(k); return i >= 0 ? rest[i + 1] : undefined; }; return { cmd, article, n: Number(n), name, projectsRoot: flag("--projects-root"), siteOrigin: flag("--site-origin"), final: rest.includes("--final"), model: flag("--model"), mode: flag("--mode"), allowWholeRecording: rest.includes("--allow-whole-recording"), }; } const isMain = !!process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url); if (isMain) { const a = parseArgs(process.argv.slice(2)); if (a.cmd !== "step" || !a.article || !Number.isInteger(a.n) || !a.name) { console.error("usage: node --import tsx chain-run.mjs step
[--projects-root ] [--site-origin ] [--final] [--model ] [--mode draft-all] [--allow-whole-recording]"); process.exit(2); } runChainStep(a.article, a.n, a.name, a).then( (code) => process.exit(code), (err) => { console.error(`chain: ${err?.message ?? err}`); process.exit(1); }, ); }