Archilyzer · Source

archilyzer

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

commit 859d877501235c6f5ea5a17f82ebeb40acbea370
parent 60c2da845da38acd54e33f8556a6de6b988ef98b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 23:17:02 -0400

umtool: Draft everything — the chain's optional generation steps (r28 M9)

CHAIN_STEPS gains draft-cut … draft-narrate between manifest and voices and
draft-youtube after the podcast, each optional and in the draft-all chain
only (chainStepsOf); the default chain is unchanged. A draft step is one
report-draft job through the editor, followed to its end and cancelled with
the chain; refused or failed it is recorded failed and the chain goes on, with
nothing to draft it is skipped; flips and threads are pre-checked against the
left panel. A resume passes a draft that ran. `umtool chain --draft-all
[--model M]`; the YouTube draft re-muxes a built cut's chapters so
out/youtube.txt is written.

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

Diffstat:
Mumtool/bin/umtool.mjs | 21+++++++++++++++------
Aumtool/lib/report/chain-draft.mjs | 35+++++++++++++++++++++++++++++++++++
Aumtool/lib/report/chain-draft.test.mjs | 232+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/chain-run.mjs | 162++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mumtool/lib/report/chain.mjs | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mumtool/lib/report/chain.test.mjs | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
6 files changed, 597 insertions(+), 40 deletions(-)

diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -24,8 +24,10 @@ // umtool corrections <project> what the report got wrong, as markdown for the next pass // umtool build <project> [--preset preview|fast|final] [--only ID] [--dry] // umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] +// [--draft-all [--model M]] // an iteration's pipeline: current, windows, prepare, posts, manifest, -// voices, video, podcast, attach, dedupe (resumes at the first step not done) +// voices, video, podcast, attach, dedupe (resumes at the first step not done); +// --draft-all is Draft everything: the drafts between manifest and the fast build // umtool index [--rebuild] [--prune] [--since MS] [--json] // umtool new <slug> [--kind report-video] [--from <report.md>|<share URL>|<channel>/<id>] // [--site-origin URL] [--seed chapters] [--brand archilyzer-media] @@ -69,7 +71,7 @@ import { updateClip, updateStorage } from "../lib/report/manifest.mjs"; import { withEditNotes } from "../lib/report/edit-guard.mjs"; import { hms } from "umtool-report-to-video/attribution"; import { buildSteps, checkSourcesSteps, PRESETS } from "../lib/report/driver.mjs"; -import { CHAIN_STEP_NAMES, planChain } from "../lib/report/chain.mjs"; +import { CHAIN_STEP_NAMES, chainStepsOf, planChain } from "../lib/report/chain.mjs"; import { spawn } from "node:child_process"; import { openIndex, signRecord } from "../lib/projects/index-db.mjs"; import { pipelineProcessesFor } from "../lib/report/busy.mjs"; @@ -695,9 +697,11 @@ function usage() { " an empty value (--title '') deletes the field", " umtool corrections <project> what the report got wrong + the walk's coverage", " umtool build <project> [--preset preview|fast|final] [--only ID]", - " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]", + " umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M]]", ` an article iteration's pipeline, one step a process: ${CHAIN_STEP_NAMES.join(", ")}`, " (resumes at the first step not done; --dry prints it; the project is <root>/<article>/i<n>/)", + ` --draft-all (Draft everything): ${chainStepsOf("draft-all").map((s) => s.name).join(", ")} —`, + " each draft a report-draft job on --model (else its route); a draft that fails does not stop it", " umtool index [--rebuild] [--prune] [--since MS] [--json]", " umtool new <slug> [--from <report.md>|<share URL>|<channel>/<id>] [--site-origin URL] [--seed chapters]", " [--brand archilyzer-media] render.brand: the report-to-video brand preset", @@ -944,8 +948,11 @@ async function cmdChain() { const article = positional[0]; const n = Number(positional[1]); if (!article || !Number.isInteger(n) || n < 1) { - die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL]"); + die("usage: umtool chain <article> <n> [--from <step>] [--dry] [--final] [--projects-root DIR] [--site-origin URL] [--draft-all [--model M]]"); } + const draftAll = has("--draft-all"); + if (val("--model") && !draftAll) die("--model is Draft everything's (--draft-all): the model its drafts run on"); + if (draftAll && has("--final")) die("--draft-all builds the fast cut: a final build refuses drafts nobody has reviewed"); let plan; try { plan = planChain({ @@ -956,14 +963,16 @@ async function cmdChain() { ...(val("--projects-root") ? { projectsRoot: path.resolve(val("--projects-root")) } : {}), ...(val("--site-origin") ? { siteOrigin: val("--site-origin") } : {}), final: has("--final"), + ...(draftAll ? { mode: "draft-all", ...(val("--model") ? { model: val("--model") } : {}) } : {}), }); } catch (err) { die(err.message); } const { start, steps } = plan; + const again = `umtool chain ${article} ${n}${draftAll ? " --draft-all" : ""}`; if (json && has("--dry")) return out({ article, n, start, steps }); if (steps.length === 0) { - console.log(`${article} i${n}: every step of the chain is done (--from <step> runs one again)`); + console.log(`${article} i${n}: every step of the ${draftAll ? "Draft everything chain" : "chain"} is done (--from <step> runs one again)`); return; } console.log(`# ${article} i${n} — the chain from "${start}"`); @@ -980,7 +989,7 @@ async function cmdChain() { child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1))); }); if (code !== 0) { - console.error(`chain: stopped at "${s.label}" (exit ${code}); run \`umtool chain ${article} ${n}\` again to resume there`); + console.error(`chain: stopped at "${s.label}" (exit ${code}); run \`${again}\` again to resume there`); process.exit(1); } } diff --git a/umtool/lib/report/chain-draft.mjs b/umtool/lib/report/chain-draft.mjs @@ -0,0 +1,35 @@ +// Draft everything's generation steps (release 28 M9), the pure part: what a +// draft would draw nothing on, and how a draft that did not end done is +// recorded. Plain node (common's panels.mjs is plain JS too), so the tests +// and the Next app may import it; ./chain-run.mjs executes the steps. + +import { flipsOn, threadsOn } from "yt-dlp-transcript-common/lib/report/panels.mjs"; + +/** The audit file each task writes beside the manifest (narrate's kept its old name). */ +export const draftFileOf = (task) => (task === "narrate" ? "narration-draft.json" : `${task}-draft.json`); + +/** + * Why a draft would draw nothing on this cut, before the editor is asked, or + * null: flips and threads need the on-screen deck, and share its left panel + * (the task refuses the other panel; Draft everything never forces). + */ +export function draftPrecheck(task, manifest) { + if (task !== "flips" && task !== "threads") return null; + const render = manifest?.render ?? {}; + if (!render.chrome || typeof render.chrome !== "object") return `the cut has no on-screen deck (render.chrome) to draw the ${task} on`; + if (task === "threads" && flipsOn(render)) return "the cut has flips: flips and threads share the left panel"; + if (task === "flips" && threadsOn(render)) return "the cut has threads: flips and threads share the left panel"; + return null; +} + +/** + * How a draft that did not finish done is recorded: skipped when its draft + * file says every unit was skipped (each field already written), else failed. + */ +export function draftOutcome(draftFile) { + const units = draftFile && typeof draftFile.units === "object" && draftFile.units ? Object.values(draftFile.units) : []; + if (units.length > 0 && units.every((u) => u && typeof u.skipped === "string")) { + return { status: "skipped", detail: `nothing to draft: ${units.length} field(s) already written (a re-draft of a draft is “Draft with” with force)` }; + } + return { status: "failed", detail: null }; +} diff --git a/umtool/lib/report/chain-draft.test.mjs b/umtool/lib/report/chain-draft.test.mjs @@ -0,0 +1,232 @@ +// Draft everything's generation steps (release 28 M9), run as the job runner +// runs them — one process a step under tsx — against a fake editor in this +// process (the report-draft and job routes, the way the editor answers them) +// over a temp article store: a draft done, a draft with nothing to draft +// (skipped), a draft the editor refuses and one whose job fails (failed, and +// the process exits 0 so the chain goes on), the left panel's pre-check, the +// YouTube draft with no build, and a cancel that cancels the editor's job. +// +// Run with: node --test umtool/lib/report/chain-draft.test.mjs + +import assert from "node:assert/strict"; +import test, { after, before } from "node:test"; +import { spawn } from "node:child_process"; +import http from "node:http"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { CHAIN_RUN, REPO_ROOT } from "./chain.mjs"; +import { draftOutcome, draftPrecheck, draftFileOf } from "./chain-draft.mjs"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const KIT = path.join(HERE, "..", "..", "..", "common", "testing", "draft"); +const ROOT = mkdtempSync(path.join(os.tmpdir(), "umtool-chain-draft-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const TRANSCRIPTS = path.join(ROOT, "transcripts"); +const ARTICLES = path.join(TRANSCRIPTS, "reports"); +const PROJECTS = path.join(ROOT, "projects"); +const PROJECT = path.join(PROJECTS, "synth-basic", "i1"); +const TOKEN = "chain-draft-token"; +const put = (file, data) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof data === "string" ? data : `${JSON.stringify(data, null, 2)}\n`); +}; +const json = (file) => JSON.parse(readFileSync(file, "utf8")); +const NOW = "2026-10-13T12:00:00.000Z"; +const itFile = path.join(ARTICLES, "synth-basic", "iterations", "1", "iteration.json"); +put(path.join(ROOT, "settings.json"), {}); +put(itFile, { + format: "archilyzer-iteration", + version: 1, + article: "synth-basic", + n: 1, + kind: "sweep", + model: "qwen3:8b", + parent: null, + copyOf: null, + question: "What does the baker say?", + status: "done", + usage: {}, + steps: [], + createdAt: NOW, + updatedAt: NOW, + projectDir: PROJECT, +}); +put(path.join(ARTICLES, "synth-basic", "iterations", "1", "report.json"), json(path.join(KIT, "reports", "basic.report.json"))); +const baseManifest = json(path.join(KIT, "manifests", "basic.video.manifest.json")); +put(path.join(PROJECT, "video.manifest.json"), baseManifest); + +// ─── The fake editor ─── +// What each task's job does: done (with a summary), fail (with a draft file), +// refuse (400 at the ask), slow (runs until cancelled). +const plan = { + cut: { end: "done", summary: "4 clips kept, in argument order" }, + onscreen: { end: "failed", summary: "no title(s) drafted (see onscreen-draft.json)", file: { units: { c01: { skipped: "the field has a value" }, c02: { skipped: "the field has a value" } } } }, + teaser: { refuse: "a teaser draft needs a teaser entry in the cut" }, + narrate: { end: "failed", summary: "no narration drafted", file: { units: { "the-bakery": { target: {}, attempts: [], chosen: null } } } }, + youtube: { end: "done", summary: "1 title and description drafted" }, + flips: { end: "slow" }, +}; +const requests = []; +const jobs = new Map(); +let next = 1; +const answer = (res, status, body) => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(JSON.stringify(body)); +}; +const editor = http.createServer((req, res) => { + let raw = ""; + req.on("data", (c) => (raw += c)); + req.on("end", () => { + if (req.headers.authorization !== `Bearer ${TOKEN}`) return answer(res, 401, { ok: false, error: "no token" }); + const body = raw ? JSON.parse(raw) : null; + const url = new URL(req.url, "http://x"); + if (req.method === "POST" && url.pathname === "/api/ops/report-draft") { + requests.push(body); + const p = plan[body.task]; + if (!p || p.refuse) return answer(res, 400, { ok: false, error: p?.refuse ?? "unknown task" }); + const id = `job-${next++}`; + jobs.set(id, { id, task: body.task, polls: 0, status: "queued" }); + const it = json(itFile); + it.steps.push({ task: body.task, model: body.model ?? "qwen3:8b", status: "running", jobId: id, startedAt: NOW }); + put(itFile, it); + return answer(res, 202, { ok: true, jobId: id, iteration: 1 }); + } + if (req.method === "POST" && url.pathname === "/api/ops/job") { + requests.push({ cancel: body.ids }); + for (const id of body.ids ?? []) if (jobs.has(id)) jobs.get(id).status = "cancelled"; + return answer(res, 200, { ok: true }); + } + const m = /^\/api\/ops\/job\/([^/]+)$/.exec(url.pathname); + if (req.method === "GET" && m && jobs.has(m[1])) { + const j = jobs.get(m[1]); + const p = plan[j.task]; + j.polls += 1; + if (j.status !== "cancelled" && p.end !== "slow" && j.polls >= 2) { + j.status = p.end; + if (p.file) put(path.join(PROJECT, draftFileOf(j.task)), { task: j.task, ...p.file }); + const it = json(itFile); + it.steps = it.steps.map((s) => (s.jobId === j.id ? { ...s, status: p.end, detail: p.summary } : s)); + put(itFile, it); + } else if (j.status === "queued") j.status = "running"; + const ended = ["done", "failed", "cancelled"].includes(j.status); + return answer(res, 200, { + ok: true, + job: { id: j.id, kind: "report-draft", status: j.status, ...(j.status === "running" ? { progress: { metric: "cards", initial: 0, current: 1, target: 3 } } : {}) }, + tail: ["turn 1", ...(ended && p.summary ? [`@@report-draft ${JSON.stringify({ article: "synth-basic", iteration: 1, task: j.task, status: j.status, summary: p.summary })}`] : [])], + }); + } + return answer(res, 404, { ok: false, error: "no route" }); + }); +}); +let ENV; +before(async () => { + await new Promise((r) => editor.listen(0, "127.0.0.1", r)); + ENV = { + ...process.env, + TRANSCRIPTS_DIR: TRANSCRIPTS, + SITES_DIR: path.join(TRANSCRIPTS, "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + ARCHILYZER_EDITOR_URL: `http://127.0.0.1:${editor.address().port}`, + WORKER_TOKEN: TOKEN, + CHAIN_DRAFT_POLL_MS: "50", + }; + delete ENV.ARTICLES_DIR; +}); +after(() => editor.close()); + +function step(name, ...extra) { + return new Promise((resolve) => { + const child = spawn(process.execPath, ["--import", "tsx", CHAIN_RUN, "step", "synth-basic", "1", name, "--projects-root", PROJECTS, ...extra], { cwd: REPO_ROOT, env: ENV }); + let out = ""; + child.stdout.on("data", (d) => (out += d)); + child.stderr.on("data", (d) => (out += d)); + const done = new Promise((r) => child.on("exit", (code, signal) => r({ code: signal ? 128 + 15 : code, out }))); + resolve({ child, done, out: () => out }); + }); +} +const recorded = (name) => [...json(itFile).steps].reverse().find((s) => s.task === `chain:${name}`); + +test("a draft done: one report-draft job on the model asked, followed to its end, its summary recorded", async () => { + const r = await (await step("draft-cut", "--model", "qwen3:8b")).done; + assert.equal(r.code, 0, r.out); + assert.deepEqual(requests.at(-1), { task: "cut", article: "synth-basic", iteration: 1, model: "qwen3:8b" }); + assert.match(r.out, /cut draft running — cards 1\/3/); + const s = recorded("draft-cut"); + assert.equal(s.status, "done"); + assert.equal(s.detail, "4 clips kept, in argument order"); +}); + +test("nothing to draft is skipped; a refused ask and a failed job are failed — and the chain goes on (exit 0)", async () => { + const skipped = await (await step("draft-onscreen")).done; + assert.equal(skipped.code, 0, skipped.out); + assert.equal(requests.at(-1).model, undefined, "no --model: the task's route chooses"); + assert.equal(recorded("draft-onscreen").status, "skipped"); + assert.match(recorded("draft-onscreen").detail, /nothing to draft: 2 field\(s\) already written/); + + const refused = await (await step("draft-teaser")).done; + assert.equal(refused.code, 0, refused.out); + assert.equal(recorded("draft-teaser").status, "failed"); + assert.match(recorded("draft-teaser").detail, /the editor refused the teaser draft: a teaser draft needs a teaser entry/); + assert.match(refused.out, /the chain goes on without it/); + + const failed = await (await step("draft-narrate")).done; + assert.equal(failed.code, 0, failed.out); + assert.equal(recorded("draft-narrate").status, "failed"); + assert.match(recorded("draft-narrate").detail, /^no narration drafted \(job job-\d+\)$/); +}); + +test("the left panel: no deck skips flips; flips on the cut skip threads — the editor is not asked", async () => { + const asked = requests.length; + const noDeck = await (await step("draft-flips")).done; + assert.equal(noDeck.code, 0, noDeck.out); + assert.equal(recorded("draft-flips").status, "skipped"); + assert.match(recorded("draft-flips").detail, /no on-screen deck \(render\.chrome\) to draw the flips on/); + const withFlips = { ...baseManifest, render: { ...(baseManifest.render ?? {}), chrome: { flips: { pairs: [{ id: "p" }] } } } }; + put(path.join(PROJECT, "video.manifest.json"), withFlips); + const threads = await (await step("draft-threads")).done; + assert.equal(threads.code, 0, threads.out); + assert.equal(recorded("draft-threads").status, "skipped"); + assert.match(recorded("draft-threads").detail, /the cut has flips: flips and threads share the left panel/); + assert.equal(requests.length, asked); + put(path.join(PROJECT, "video.manifest.json"), baseManifest); +}); + +test("the YouTube draft with no build yet: done, and the next build writes out/youtube.txt", async () => { + const r = await (await step("draft-youtube")).done; + assert.equal(r.code, 0, r.out); + assert.equal(recorded("draft-youtube").status, "done"); + assert.equal(recorded("draft-youtube").detail, "1 title and description drafted; the next build writes out/youtube.txt"); +}); + +test("a cancel of the chain cancels the editor's job, and the step is recorded cancelled", async () => { + put(path.join(PROJECT, "video.manifest.json"), { ...baseManifest, render: { ...(baseManifest.render ?? {}), chrome: {} } }); + const s = await step("draft-flips"); + const until = Date.now() + 60_000; + while (!/flips draft running/.test(s.out()) && Date.now() < until) await new Promise((r) => setTimeout(r, 50)); + s.child.kill("SIGTERM"); + const r = await s.done; + assert.equal(r.code, 143, r.out); + const job = requests.find((q) => q.cancel); + assert.ok(job, "the editor's job was cancelled"); + assert.equal(jobs.get(job.cancel[0]).task, "flips"); + assert.equal(recorded("draft-flips").status, "cancelled"); +}); + +test("draftPrecheck and draftOutcome, pure", () => { + assert.equal(draftPrecheck("cut", {}), null); + assert.match(draftPrecheck("threads", { render: {} }), /no on-screen deck/); + assert.equal(draftPrecheck("threads", { render: { chrome: {} } }), null); + assert.match(draftPrecheck("flips", { render: { chrome: { threads: { list: [{ id: "a" }] } } } }), /the cut has threads/); + assert.equal(draftOutcome(null).status, "failed"); + assert.equal(draftOutcome({ units: {} }).status, "failed"); + assert.equal(draftOutcome({ units: { a: { skipped: "x" }, b: { chosen: null } } }).status, "failed"); + assert.equal(draftOutcome({ units: { a: { skipped: "x" } } }).status, "skipped"); + assert.equal(draftFileOf("narrate"), "narration-draft.json"); + assert.equal(draftFileOf("cut"), "cut-draft.json"); +}); diff --git a/umtool/lib/report/chain-run.mjs b/umtool/lib/report/chain-run.mjs @@ -2,7 +2,7 @@ // own process — // // node --import tsx umtool/lib/report/chain-run.mjs step <article> <n> <step> -// [--projects-root <dir>] [--site-origin <url>] [--final] +// [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>] // // — under tsx, because the article registry, the iterations store and the // reports CLIs it calls are common's TypeScript. The Next app never imports @@ -14,6 +14,13 @@ // 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-<task>`, release 28 M9) is a `report-draft` job +// the editor runs: POST /api/ops/report-draft, then GET /api/ops/job/<id> +// 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. import { spawn } from "node:child_process"; import { copyFile, mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; @@ -38,7 +45,8 @@ import { main as prepareMain } from "yt-dlp-transcript-common/bin/reports-prepar 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 { CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs"; +import { ALL_CHAIN_STEP_NAMES, CHAIN_WINDOW_PAD, REPO_ROOT, chainStepDef, configuredProjectsRoot, chainTask, chainWindows, originFromSweep } from "./chain.mjs"; +import { draftFileOf, draftOutcome, draftPrecheck } from "./chain-draft.mjs"; import { PIPELINE_DIR } from "./driver.mjs"; import { dedupeMedia, seedFromParent } from "./iterations.mjs"; @@ -47,6 +55,8 @@ const SCREENSHOT_MISSING = /no captured screenshot/; /** 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)); @@ -244,6 +254,125 @@ const STEPS = { }, }; +// ─── 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})`; +} + +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)}`; +}; + async function writeJson(file, value) { const tmp = `${file}.tmp-${process.pid}`; await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`); @@ -266,10 +395,11 @@ async function sweepOrigin(ctx) { * @returns {Promise<number>} the exit code: 0 done, 1 failed, 2 refused */ export async function runChainStep(article, n, name, opts = {}) { - if (!CHAIN_STEP_NAMES.includes(name)) { - console.error(`chain: no step "${name}" (${CHAIN_STEP_NAMES.join(", ")})`); + 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}`); @@ -294,6 +424,11 @@ export async function runChainStep(article, n, name, opts = {}) { project: projectOf(projectsRoot, article, n), siteOrigin: opts.siteOrigin, final: opts.final === true, + model: opts.model, + cancels: [], + onCancel(fn) { + this.cancels.push(fn); + }, }; const task = chainTask(name); const startedAt = new Date(); @@ -313,7 +448,11 @@ export async function runChainStep(article, n, name, opts = {}) { await record("running"); // A cancel (the job runner's SIGTERM to the step's process group) is recorded, best effort. const onTerm = () => { - record("cancelled", "cancelled").finally(() => process.exit(143)); + // 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}`); @@ -323,8 +462,18 @@ export async function runChainStep(article, n, name, opts = {}) { 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 { @@ -346,6 +495,7 @@ function parseArgs(argv) { projectsRoot: flag("--projects-root"), siteOrigin: flag("--site-origin"), final: rest.includes("--final"), + model: flag("--model"), }; } @@ -353,7 +503,7 @@ const isMain = !!process.argv[1] && path.resolve(process.argv[1]) === fileURLToP 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 <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final]"); + console.error("usage: node --import tsx chain-run.mjs step <article> <n> <step> [--projects-root <dir>] [--site-origin <url>] [--final] [--model <m>]"); process.exit(2); } runChainStep(a.article, a.n, a.name, a).then( diff --git a/umtool/lib/report/chain.mjs b/umtool/lib/report/chain.mjs @@ -20,6 +20,25 @@ // 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-<task>` runs one `report-draft` job on +// the iteration through the editor and waits for it: +// +// current → windows → prepare → posts → manifest → draft-cut → +// draft-onscreen → draft-teaser → draft-flips → draft-threads → +// draft-narrate → voices → video (fast, never --final) → podcast → +// draft-youtube +// +// 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. 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. +// // Each step is ONE PROCESS — `node --import tsx chain-run.mjs step <id> <n> // <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 @@ -36,19 +55,53 @@ import os from "node:os"; import path from "node:path"; import { UMTOOL_DIR } from "./driver.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 }, - { name: "windows", label: "fetch the cited clip windows (editor)", timeoutMs: 6 * 60 * 60_000 }, - { name: "prepare", label: "prepare the article's evidence media", timeoutMs: 60 * 60_000 }, - { name: "posts", label: "capture the article's post screenshots (editor)", timeoutMs: 3 * 60 * 60_000 }, - { name: "manifest", label: "make the video manifest, seeded from the parent", timeoutMs: 5 * 60_000 }, - { name: "voices", label: "voice the narration (editor TTS)", timeoutMs: 3 * 60 * 60_000, ndjson: true }, - { name: "video", label: "build the video", timeoutMs: 4 * 60 * 60_000, ndjson: true }, - { name: "podcast", label: "build the podcast", timeoutMs: 30 * 60_000, ndjson: true }, - { name: "attach", label: "attach the video to the article", timeoutMs: 30 * 60_000 }, - { name: "dedupe", label: "share identical segments and voices", timeoutMs: 15 * 60_000 }, + { 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: BOTH }, + { 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: "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: "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: "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 }, ]; -export const CHAIN_STEP_NAMES = CHAIN_STEPS.map((s) => s.name); + +/** The chains: "video" (make the video, the default) and "draft-all" (Draft everything). */ +export const CHAIN_MODES = ["video", "draft-all"]; + +/** A chain's steps, in order. */ +export function chainStepsOf(mode = "video") { + if (!CHAIN_MODES.includes(mode)) throw new Error(`no chain "${mode}" (${CHAIN_MODES.join(", ")})`); + return CHAIN_STEPS.filter((s) => s.modes.includes(mode)); +} + +/** 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-<task>`). */ +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}`; @@ -94,25 +147,32 @@ export function chainProject(projectsRoot, article, n) { /** * Where a chain starts: `from` when given, else the first step the iteration - * has not recorded done (`done`: the step names recorded done), else nothing - * (the whole chain is done: null). + * 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 = [] } = {}) { +export function chainStart({ from = null, done = [], mode = "video" } = {}) { + const names = chainStepsOf(mode).map((s) => s.name); if (from !== null && from !== undefined) { - if (!CHAIN_STEP_NAMES.includes(from)) throw new Error(`--from must be one of ${CHAIN_STEP_NAMES.join(", ")}`); + if (!names.includes(from)) throw new Error(`--from must be one of ${names.join(", ")}`); return from; } const finished = new Set(done); - return CHAIN_STEP_NAMES.find((s) => !finished.has(s)) ?? null; + return names.find((s) => !finished.has(s)) ?? null; } -/** The step names an iteration.json records done, from its `steps`. */ +// 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); - if (s.status === "done") out.push(name); + const ends = chainStepDef(name)?.optional ? OPTIONAL_FINISHED : FINISHED; + if (ends.includes(s.status)) out.push(name); } return out; } @@ -132,28 +192,35 @@ export function readIterationRecord(articlesDir, article, n) { * 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). * - * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string }} o + * @param {{ article: string, n: number, projectsRoot?: string, start?: string | null, siteOrigin?: string, final?: boolean, node?: string, mode?: string, model?: string }} o * @returns {import("../trim").Step[]} */ export function chainSteps(o) { const projectsRoot = o.projectsRoot ?? configuredProjectsRoot(); chainProject(projectsRoot, o.article, o.n); - const start = o.start === undefined ? CHAIN_STEP_NAMES[0] : o.start; + const mode = o.mode ?? "video"; + const defs = chainStepsOf(mode); + const start = o.start === undefined ? defs[0].name : o.start; if (start === null) return []; - const at = CHAIN_STEP_NAMES.indexOf(start); + 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 ? ["--final"] : []), + ...(o.final && mode === "video" ? ["--final"] : []), ]; - return CHAIN_STEPS.slice(at).map((s, i) => ({ - label: `${at + i + 1}/${CHAIN_STEPS.length} ${s.label}`, + 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], + 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 } : {}), })); @@ -166,22 +233,25 @@ export function chainSteps(o) { * 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 }} o + * @param {{ articlesDir: string, article: string, n: number, from?: string | null, projectsRoot?: string, siteOrigin?: string, final?: boolean, mode?: string, model?: string }} 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 start = chainStart({ from: o.from ?? null, done: doneSteps(record) }); + const mode = o.mode ?? "video"; + const start = chainStart({ from: o.from ?? null, done: doneSteps(record), mode }); const steps = chainSteps({ article: o.article, n: o.n, start, + mode, + ...(o.model ? { model: o.model } : {}), ...(o.projectsRoot ? { projectsRoot: o.projectsRoot } : {}), ...(o.siteOrigin ? { siteOrigin: o.siteOrigin } : {}), final: o.final === true, }); - return { record, start, steps }; + return { record, start, steps, mode }; } const floor2 = (x) => Math.floor(x * 100 + 1e-6) / 100; diff --git a/umtool/lib/report/chain.test.mjs b/umtool/lib/report/chain.test.mjs @@ -21,6 +21,8 @@ import { chainStart, chainSteps, chainWindows, + chainStepsOf, + DRAFT_STEP_TASKS, doneSteps, originFromSweep, } from "./chain.mjs"; @@ -68,6 +70,57 @@ test("resume: the first step not recorded done; --from names one; all done is no assert.throws(() => chainStart({ from: "nope" }), /--from must be one of/); }); +test("Draft everything: the drafts between the manifest and the fast build, YouTube after it; the default chain unchanged", () => { + const names = chainStepsOf("draft-all").map((s) => s.name); + assert.deepEqual(names, [ + "current", "windows", "prepare", "posts", "manifest", + "draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate", + "voices", "video", "podcast", "draft-youtube", + ]); + assert.deepEqual(chainStepsOf("video").map((s) => s.name), CHAIN_STEP_NAMES); + assert.ok(chainStepsOf("video").every((s) => !s.optional), "make the video has no optional step"); + assert.deepEqual(DRAFT_STEP_TASKS, ["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube"]); + assert.throws(() => chainStepsOf("nope"), /no chain "nope"/); + + const steps = chainSteps({ article: "art", n: 2, projectsRoot: "/p", node: "node", mode: "draft-all", model: "qwen3:8b", final: true }); + assert.equal(steps.length, 15); + assert.equal(steps[5].label, "6/15 draft the cut: which clips, in what order"); + // The model rides on the draft steps only; the build is the fast one (--final is ignored). + for (const s of steps) { + const draft = s.argv[7].startsWith("draft-"); + assert.equal(s.argv.includes("--model"), draft, s.argv[7]); + assert.ok(!s.argv.includes("--final"), s.argv[7]); + } + assert.deepEqual(steps[5].argv.slice(8), ["--projects-root", "/p", "--model", "qwen3:8b"]); + // No model: each task's route chooses. + assert.ok(chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all" }).every((s) => !s.argv.includes("--model"))); + assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all", model: "a b" }), /not a model name/); + // attach is not in Draft everything. + assert.throws(() => chainSteps({ article: "art", n: 2, projectsRoot: "/p", mode: "draft-all", start: "attach" }), /no chain step "attach"/); +}); + +test("Draft everything resumes past a draft that ran — done, skipped or failed — but not past a failed code step", () => { + const it = { + steps: ["current", "windows", "prepare", "posts", "manifest"].map((s) => ({ task: `chain:${s}`, status: "done" })).concat([ + { task: "chain:draft-cut", status: "done" }, + { task: "chain:draft-onscreen", status: "failed" }, + { task: "chain:draft-teaser", status: "skipped" }, + { task: "chain:draft-flips", status: "cancelled" }, + ]), + }; + const done = doneSteps(it); + assert.deepEqual(done.slice(5), ["draft-cut", "draft-onscreen", "draft-teaser"]); + assert.equal(chainStart({ done, mode: "draft-all" }), "draft-flips"); + // The default chain never sees the drafts: it resumes at voices. + assert.equal(chainStart({ done }), "voices"); + const failedCode = { steps: [{ task: "chain:current", status: "done" }, { task: "chain:windows", status: "failed" }] }; + assert.equal(chainStart({ done: doneSteps(failedCode), mode: "draft-all" }), "windows"); + assert.equal(chainStart({ from: "draft-threads", mode: "draft-all" }), "draft-threads"); + assert.throws(() => chainStart({ from: "draft-threads" }), /--from must be one of/); + const all = chainStepsOf("draft-all").map((s) => s.name); + assert.equal(chainStart({ done: all, mode: "draft-all" }), null); +}); + test("chainWindows: each cited moment padded to the cut's fetchPad and the citation's own pad, rounded outward, once", () => { const report = { id: "art", @@ -117,6 +170,14 @@ test("umtool chain --dry: the plan, resuming where the iteration left off; refus assert.match(text, /\(cd .* && .*chain-run\.mjs step art 2 video/); assert.throws(() => run("art", "9", "--dry"), (e) => /has no iteration i9/.test(String(e.stderr))); assert.throws(() => run("art", "2", "--dry", "--from", "nope"), (e) => /--from must be one of/.test(String(e.stderr))); + // --draft-all: the same resume point, the drafts in the plan, the model on them. + const all = JSON.parse(run("art", "2", "--dry", "--json", "--draft-all", "--model", "claude-sonnet-5-5", "--projects-root", path.join(ROOT, "projects"))); + assert.equal(all.start, "prepare"); + assert.deepEqual(all.steps.map((s) => s.argv[7]).slice(3, 9), ["draft-cut", "draft-onscreen", "draft-teaser", "draft-flips", "draft-threads", "draft-narrate"]); + assert.equal(all.steps.at(-1).argv[7], "draft-youtube"); + assert.ok(all.steps.at(-1).argv.includes("claude-sonnet-5-5")); + assert.throws(() => run("art", "2", "--dry", "--model", "qwen3:8b"), (e) => /--model is Draft everything's/.test(String(e.stderr))); + assert.throws(() => run("art", "2", "--dry", "--draft-all", "--final"), (e) => /builds the fast cut/.test(String(e.stderr))); }); test("planChain: the record, the resume point and the steps; a queued iteration is refused", async () => {