commit d141168fbb94bc2eaada3b0f61f8c00debc4883d
parent b1dcf528b2ea2e3d2de56d0692eb910558015a57
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 00:58:30 -0400
Merge r28/surfaces: release 28 M9 — Draft with, Draft everything, MCP and /gen, plan-first site delete
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
# Conflicts:
# plans/release-28.md
Diffstat:
46 files changed, 2604 insertions(+), 142 deletions(-)
diff --git a/.claude/commands/gen.md b/.claude/commands/gen.md
@@ -8,20 +8,33 @@ each task. Use the archilyzer MCP tools only; run no script for it.
1. Call `mcp__archilyzer__generation_policy` with no arguments and read the routes, the models and the day's spend.
2. Map the request below to tasks: `sweep` (a new cited report), `revise-report` (a new iteration of an article's
- report from feedback), `revise-video` (a new iteration of its video cut: cards, narration, title), `narrate`
- (card narration drafts for a done iteration's cut), `research` (find what the corpus lacks and propose
- acquisitions — archive.org imports, channels, posts — under an autonomy: propose, limits or auto; a sweep with
- the research run's iteration continues it over the widened scope). The clip fetches, voices, render and podcast are the
- pipeline's code, not generation: the operator runs that chain from umtool (the article's Iterations tab).
+ report from feedback), `revise-video` (a new iteration of its video cut from feedback), `research` (find what the
+ corpus lacks and propose acquisitions — archive.org imports, channels, posts — under an autonomy: propose, limits
+ or auto; a sweep with the research run's iteration continues it over the widened scope). A request to draft part
+ of a done iteration's video cut is a media draft, a step on that iteration (`iteration`; `entries` to limit it):
+ - `cut` — "pick the clips", "reorder the cut", "cut it down";
+ - `onscreen` — "draft the on-screen titles", "titles and subtitles";
+ - `teaser` — "make a teaser", "the teaser lines";
+ - `flips` — "then and now", "the flip-flops", "THEN/NOW pairs";
+ - `threads` — "group the clips into threads", "the threads panel";
+ - `narrate` — "narrate it", "the card narration";
+ - `youtube` — "YouTube title", "YouTube description", "the upload text".
+ "Draft everything" (every media draft in order, then voices, a fast build and the podcast) is the operator's button
+ on umtool's Iterations tab, or `umtool chain <article> <n> --draft-all`; it is not a `generate` task. The clip
+ fetches, voices, render and podcast are the pipeline's code, not generation: the operator runs that chain from umtool.
3. For each task routed to `api` or `local`, call `mcp__archilyzer__generate` with the task, the article, its
inputs (question and channels for a sweep or research run; iteration and concrete feedback for a revision;
- iteration for a narration) and `wait: true`, and do not redo its work yourself. If it answers still running, call it again with
+ iteration, and `entries` when the operator named some, for a media draft) and `wait: true`, and do not redo its
+ work yourself. If it answers still running, call it again with
the job, article and iteration it names — never start the same task twice. Then REVIEW what it made, as its
answer says: read the iteration's files, spot-check its quotes with `mcp__archilyzer__get_transcript`, read the
ops it refused and its checks, and tell the operator what is good and what is not. Recommend making it current
(the operator does that in umtool) or a revision; for a revision, call `generate` again with that feedback.
A research run's proposals are the operator's to approve (umtool's research queue); say which you would approve
- and why. Edit an iteration's files by hand only if the operator asks.
+ and why. A media draft's review is as its answer says: its `<task>-draft.json` and the drafted fields; the
+ operator approves or rejects each field in umtool (the project page's Review drafts) — never write
+ `drafts.review.json` yourself. `force: true` re-drafts only what a model drafted; a field the operator wrote is
+ never replaced. Edit an iteration's files by hand only if the operator asks.
4. For each task routed to `code`, do it yourself as usual: `/sweep` for a report (its plan reads the same
policy).
5. `via: "api"` or `"local"` on `generate` (or `via=` in a `/sweep` request) overrides one run when the operator asks
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -40,8 +40,8 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer reports import-local-runs` | `[--apply] [--runs <dir>] [--only <run,…>] [--move-projects] [--generation <file>]` | ONE-OFF (release 27): the stopgap's kept runs (--runs: its directory, default ~/reports/local-reports; --only: those runs, default piratesoftware-ai-friends and api-shondo-recent) become i1 of their article through the iterations store — made current only when the run's report.json is the article's; a run with no article becomes an article in the making — and each video project is copied (--move-projects: moved) to the generation projects root; ~/.config/archilyzer/generation.json, when there is one, becomes settings.generation's routes and models. Lists the stopgap's test runs, projects and drafts to delete after the operator's OK (deletes nothing). A dry run printing the plan unless --apply (exit 1 when a run is refused) |
| `archilyzer gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers |
| `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) |
-| `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, narrate, research) |
-| `archilyzer gen run` | `<task> [<question\|feedback>] --article <id> [--via api\|local\|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--force] [--autonomy propose\|limits\|auto] [--source <handle>\|--build <id>] [--wait]` | enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once) |
+| `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, research; the media drafts cut, onscreen, teaser, flips, threads, narrate, youtube) |
+| `archilyzer gen run` | `<task> [<question\|feedback>] --article <id> [--via api\|local\|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--entries a,b] [--force] [--autonomy propose\|limits\|auto] [--source <handle>\|--build <id>] [--wait]` | enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube) is a step on --iteration <n>, takes no words, --entries limits it, --force re-drafts only fields a model drafted; EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once) |
| `archilyzer reports move-to-articles` | `[--keep <site>/<id>,…] [--drafts] [--apply]` | ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply *(passthrough)* |
| `archilyzer reports convert` | `<sweep\|ask\|manifest> <in> --out <report.json> [--channels-dir <dir>] [--id <id>] [--title <title>]` | a /sweep report (markdown), an /ask answer or a report-to-video manifest as a report.json, written only when it validates (--channels-dir: widen spans from the cues, find posts' channels) |
| `archilyzer reports to-manifest` | `<report.json> --out <manifest.json> [--channels-dir <dir>] [--site-origin <url>]` | a starter report-to-video manifest from a report (a chapter card per section, a claim's still and clips stamped with its verdict, its posts) |
diff --git a/OPERATING.md b/OPERATING.md
@@ -164,7 +164,7 @@ umtool chain example-article 3
- In umtool: `/articles/new` starts an article with a sweep or with research (question, channels, dates, model,
cap; research takes an autonomy, defaulted from the settings, and needs no channel); the article's **Iterations**
tab (`/articles/<id>?tab=iterations`) lists its iterations and runs the rest (**New iteration**, **Copy with
- model**, **Narrate**, **Cancel**, **Make the video**, **Use this iteration**); `/articles/<id>/compare?a=&b=`
+ model**, **Narrate**, **Draft**, **Draft everything**, **Cancel**, **Make the video**, **Use this iteration**); `/articles/<id>/compare?a=&b=`
puts two side by side. The pages: [umtool/docs/sites.md](umtool/docs/sites.md).
- Each generation is an **iteration** of the article, `i1`, `i2`, … in `transcripts/reports/<id>/iterations/<n>/`,
never published ([REPORT.md](REPORT.md), "Iterations"). The article's `report.json` changes only when you choose
@@ -182,6 +182,39 @@ umtool chain example-article 3
podcast, attach, dedupe. A re-run resumes at the first step not done. The project is
`<projectsRoot>/<id>/i<n>/` (default `~/reports/articles`), off the corpus disk.
+**The media drafts** are steps on a done iteration's video cut, each drafting fields of its manifest:
+
+```sh
+pnpm ops report-draft --json '{"task":"onscreen","article":"example-article","iteration":3,"entries":["c01","c02"]}' --wait
+pnpm archilyzer gen run youtube --article example-article --iteration 3 --wait
+umtool chain example-article 3 --draft-all --model qwen3:8b
+```
+
+| Task | Field | Limits (code's) | Review |
+| --- | --- | --- | --- |
+| `cut` | the timeline's order (`drafted.timeline`) | ids from the report's citations only, 3 to `generation.cut.maxClips` (20); windows untouched | the project page's **Review drafts** |
+| `onscreen` | each clip's `onscreen.{title, subtitle}` | title ≤ 60, subtitle ≤ 90, one line; a subtitle quotes the clip's own words only | the On-screen table, **Review drafts** |
+| `teaser` | a teaser's `lines` (a cut with none gets one) | 3 to 5 lines ≤ 70, no quote read out | the teaser editor, **Review drafts** |
+| `flips` | `render.chrome.flips` | pairs over the cut's clips of two dates, THEN the earlier; needs the deck | **Review drafts** |
+| `threads` | `render.chrome.threads` and each clip's `thread` | 2 to 4 threads; needs the deck; not with flips | **Review drafts** |
+| `narrate` | a card's `narration` | third person; names and numbers from the report; no quote read out | the narration page, **Review drafts** |
+| `youtube` | `publish.youtube {title, description}` | title ≤ 100, summary ≤ 900; the build adds chapters and sources to `out/youtube.txt` | the YouTube section, **Review drafts** |
+
+- Every drafted field carries `drafted {task, model, at, iteration, attempt}`. A field you wrote or edited is never
+ replaced: the draft is kept in `<task>-draft.json` as an alternative, taken with **Use this**. `force` re-drafts
+ only a field a model drafted. `entries` limits a per-entry task to those entries.
+- In umtool: the project page's **draft** section has **Draft with** a model per task (force, the entries, the job's
+ progress, the last run's written, skipped and refused); the Iterations tab has the six beside **Narrate**. A
+ project not made from an iteration (`<projectsRoot>/<id>/i<n>/`) offers none.
+- **Draft everything** (the Iterations tab, or `umtool chain <id> <n> --draft-all [--model M]`) is the chain with
+ its drafts: current → windows → prepare → posts → manifest → cut → on-screen → teaser → flips → threads →
+ narration → voices → the fast build → podcast → YouTube (its chapters re-muxed so `out/youtube.txt` is written).
+ No attach, no dedupe. A draft refused or failed is recorded failed and the chain goes on; one with nothing to draft,
+ or flips and threads with no deck (or the other panel on), is skipped. A resume passes a draft that ran.
+- **The review gate:** approve or reject each drafted field (with a note) on `/browse/<project>/review`. A preview or
+ fast build warns of an unreviewed draft; a `final` build refuses one, and refuses a rejected one whatever the
+ flags; `--drafts-unreviewed` builds it anyway. A video revision that reorders the cut makes the order its draft.
+
**The policy** is `settings.generation`: where each task runs (`code` = Claude Code, `api` = the Claude API,
`local` = the local model), the models, the caps.
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -444,14 +444,14 @@ export const COMMANDS: Command[] = [
},
{
path: ["gen", "set"],
- usage: "<task> <code|api|local> route one generation task (sweep, revise-report, revise-video, narrate, research)",
+ usage: "<task> <code|api|local> route one generation task (sweep, revise-report, revise-video, research; the media drafts cut, onscreen, teaser, flips, threads, narrate, youtube)",
maxPositionals: 2,
run: async (ctx) => (await import("./gen")).genSetRow(ctx),
},
{
path: ["gen", "run"],
usage:
- "<task> [<question|feedback>] --article <id> [--via api|local|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--force] [--autonomy propose|limits|auto] [--source <handle>|--build <id>] [--wait] enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once)",
+ "<task> [<question|feedback>] --article <id> [--via api|local|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--entries a,b] [--force] [--autonomy propose|limits|auto] [--source <handle>|--build <id>] [--wait] enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube) is a step on --iteration <n>, takes no words, --entries limits it, --force re-drafts only fields a model drafted; EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once)",
flags: {
via: "string",
article: "string",
@@ -465,6 +465,7 @@ export const COMMANDS: Command[] = [
model: "string",
"max-usd": "string",
cards: "string",
+ entries: "string",
force: "boolean",
autonomy: "string",
source: "string",
diff --git a/common/bin/gen.test.ts b/common/bin/gen.test.ts
@@ -212,3 +212,21 @@ test("gen run research takes --autonomy; nothing else does", async () => {
// A continuation: a sweep naming the research run.
assert.deepEqual(gen.runBody("sweep", undefined, { article: "synth-a", iteration: "4", force: true }), { task: "sweep", article: "synth-a", iteration: 4, force: true });
});
+
+test("gen run a media draft: a step on --iteration, no words, --entries and --force (release 28)", () => {
+ assert.deepEqual(gen.runBody("onscreen", undefined, { article: "synth-a", iteration: "2", entries: "c01, c02", force: true }), {
+ task: "onscreen",
+ article: "synth-a",
+ iteration: 2,
+ entries: ["c01", "c02"],
+ force: true,
+ });
+ assert.deepEqual(gen.runBody("youtube", undefined, { article: "synth-a", iteration: "2", model: "qwen3:8b" }), { task: "youtube", article: "synth-a", iteration: 2, model: "qwen3:8b" });
+ assert.deepEqual(gen.runBody("cut", undefined, { article: "synth-a" }), { error: "gen run: a cut draft names its iteration (--iteration <n>)" });
+ assert.deepEqual(gen.runBody("teaser", "make it punchier", { article: "synth-a", iteration: "2" }), {
+ error: "gen run: a teaser draft takes no question or feedback: it drafts from the iteration's report and cut",
+ });
+ assert.deepEqual(gen.runBody("flips", undefined, { article: "synth-a", iteration: "2", "copy-of": "1" }), { error: "gen run: a flips draft is a step on its iteration: no --copy-of" });
+ assert.deepEqual(gen.runBody("sweep", "q", { article: "synth-a", entries: "c01" }), { error: "gen run: --entries is a media draft's" });
+});
+
diff --git a/common/bin/gen.ts b/common/bin/gen.ts
@@ -5,7 +5,9 @@
// archilyzer gen preset code|balanced|api|local route every task at once
// archilyzer gen set <task> code|api|local route one task
// archilyzer gen run <task> [<question|feedback>] --article <id> [--via api|local|code] […] [--wait]
-// enqueue a report-draft job (`pnpm ops report-draft`)
+// enqueue a report-draft job (`pnpm ops report-draft`);
+// a media draft (cut, onscreen, teaser, flips, threads,
+// narrate, youtube) takes --iteration, --entries, --force
//
// THROUGH THE EDITOR when it answers: `GET/POST /api/ops/settings` (its one
// settings writer) and `GET /api/ops/generation-usage`, with the token
@@ -33,6 +35,8 @@ import {
GENERATION_PRESETS,
GENERATION_PRESET_NAMES,
GENERATION_ROUTES,
+ MEDIA_STEP_TASKS,
+ isStepTask,
type GenerationPreset,
type GenerationRoute,
} from "../lib/generationSettings";
@@ -66,7 +70,7 @@ export type GenDeps = {
out?: Out;
};
-const TASKS_HELP = "sweep, revise-report, revise-video, narrate, research";
+const TASKS_HELP = `sweep, revise-report, revise-video, research, or a media draft: ${MEDIA_STEP_TASKS.join(", ")}`;
const isRoute = (v: unknown): v is GenerationRoute => typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v);
export function policyFrom(value: unknown): GenPolicy | null {
@@ -263,12 +267,19 @@ export function runBody(task: string, text: string | undefined, flags: Record<st
if (e) return { error: e };
}
const words = text?.trim();
+ // A media draft (release 28) is a step on the iteration it names; it takes
+ // no words — it drafts from the iteration's report and cut.
+ if (isStepTask(task)) {
+ if (body.iteration === undefined) return { error: `gen run: a ${task} draft names its iteration (--iteration <n>)` };
+ if (body.copyOf !== undefined) return { error: `gen run: a ${task} draft is a step on its iteration: no --copy-of` };
+ if (words || str("question") || str("feedback")) return { error: `gen run: a ${task} draft takes no question or feedback: it drafts from the iteration's report and cut` };
+ } else if (str("entries")) return { error: "gen run: --entries is a media draft's" };
if (words) body[task === "sweep" || task === "research" ? "question" : "feedback"] = words;
for (const k of ["question", "feedback", "from", "to", "model", "source", "build"] as const) {
const v = str(k);
if (v) body[k] = v;
}
- for (const k of ["channels", "cards"] as const) {
+ for (const k of ["channels", "cards", "entries"] as const) {
const v = str(k);
if (v) body[k] = v.split(",").map((x) => x.trim()).filter(Boolean);
}
diff --git a/common/lib/report/draft/tasks/onscreen.test.ts b/common/lib/report/draft/tasks/onscreen.test.ts
@@ -11,7 +11,7 @@ import os from "node:os";
import path from "node:path";
import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs";
import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "../../iterations";
-import { checkOnscreen, isVerbatimOf, onscreen, onscreenBatches, quotedParts, ONSCREEN_SPEC } from "./onscreen";
+import { checkOnscreen, isTitleCase, isVerbatimOf, onscreen, onscreenBatches, quotedParts, titleAsSentence, ONSCREEN_SPEC } from "./onscreen";
import type { DraftFile } from "./media";
import type { TaskDeps } from "./types";
@@ -124,6 +124,26 @@ test("onscreen's checks, each alone", () => {
assert.equal(isVerbatimOf("sel the", "I would never sell the bakery"), false, "whole words");
});
+test("onscreen: a Title Case title passes as its sentence case; an unknown name in one still fails (release 28 M9 ruling)", () => {
+ const u = { quote: "I would never sell the bakery to a chain", evidence: "Report: Synth Kitchen\nSection: The bakery\nClaim: The baker says she will not sell to a chain.\nQuote: \"I would never sell the bakery to a chain\"\nSource: Bread day, 2026-01-05" };
+ const hard = (title: string) => checkOnscreen({ title }, u).hard;
+ // Ordinary Title Case: every word capitalised, none a name.
+ assert.deepEqual(hard("The Baker Will Never Sell The Bakery"), []);
+ assert.deepEqual(hard("She Refuses To Sell To A Chain"), []);
+ assert.deepEqual(hard("Not For Sale, Says The Baker"), []);
+ // A name the evidence has keeps its capital and passes.
+ assert.deepEqual(hard("Synth Kitchen Will Not Sell"), []);
+ // A name it lacks still fails, Title Case or not.
+ assert.match(hard("Why Marco Says The Bakery Stays").join(), /name “Marco” is not in the clip's evidence/);
+ assert.match(hard("The Bakery Stays, Says Marco").join(), /name “Marco” is not in the clip's evidence/);
+ assert.match(hard("The bakery stays, says Marco").join(), /name “Marco” is not in the clip's evidence/);
+ assert.equal(isTitleCase("The Baker Will Never Sell"), true);
+ assert.equal(isTitleCase("The baker will never sell"), false);
+ assert.equal(isTitleCase("Bakery"), false, "one word is not a case");
+ assert.equal(titleAsSentence("Never Sell The Bakery To Marco", u.evidence), "Never sell the bakery to Marco");
+ assert.equal(titleAsSentence("The baker said no", u.evidence), "The baker said no", "a sentence-case title as it is");
+});
+
test("onscreen: the operator's text kept (forced, the draft an alternative); entries asks only those; batches fit the local cap", async () => {
const full = await kit("manifests/full.video.manifest.json");
const p = await project(full);
diff --git a/common/lib/report/draft/tasks/onscreen.ts b/common/lib/report/draft/tasks/onscreen.ts
@@ -61,6 +61,60 @@ export function isVerbatimOf(part: string, quote: string): boolean {
return !!p && ` ${strictNormalize(quote)} `.includes(` ${p} `);
}
+// The words a Title Case title leaves small, or capitalises with the rest:
+// neither is ever a name.
+const TITLE_SMALL = new Set(
+ `a an the and but or nor for so yet of to in on at by up as is it its from with into onto off out over under than
+that this these those be been being was were are am has have had do does did not no never ever all any each every
+more most much many some such own same other only just very too again once still also even then now here there
+when where why how what who whom which whose while if after before about against between through during without
+within upon via per vs`.split(/\s+/),
+);
+// Ordinary words a headline capitalises (say, deny, sell, …): never read as a
+// name in a Title Case title, in the evidence or not. Kept short: a word not
+// here and not in the evidence is a name's candidate, as before.
+const TITLE_ORDINARY = new Set(
+ `say said says tell told claim claims claimed admit admits admitted deny denies denied refuse refuses refused want
+wants wanted will would won't can can't could should must may might need needs get gets got make makes made take
+takes took give gives gave go goes went come comes came keep keeps kept see sees saw know knows knew think thinks
+thought call calls called ask asks asked answer answers answered change changes changed turn turns turned back
+sell sells sold sale buy buys bought pay pays paid win wins won lose loses lost start starts started stop stops stopped stay stays
+plan plans planned promise promises promised deal deals story stories question questions answer truth lie lies
+side sides vote votes rule rules line lines word words first last next new old big small long short true false
+real fake whole half day days week weeks month months year years time times later earlier late early again here
+yes no never always often sometimes nobody everybody somebody anyone everyone someone nothing everything something
+one two three four five six seven eight nine ten`.split(/\s+/),
+);
+const TITLE_WORD_RE = /[A-Za-z][A-Za-z'’-]*/g;
+const stemOf = (w: string) => w.toLowerCase().replace(/['’]s$/, "").replace(/(ing|ed|es|s|ly)$/, "");
+
+/** A title whose words (the small ones aside) all start with a capital, two at least. */
+export function isTitleCase(title: string): boolean {
+ const big = (title.match(TITLE_WORD_RE) ?? []).filter((w) => !TITLE_SMALL.has(w.toLowerCase()));
+ return big.length >= 2 && big.every((w) => /^[A-Z]/.test(w));
+}
+
+/**
+ * A Title Case title as the sentence it would be: past its first word, a word
+ * is lowercased when it is small, an ordinary headline word, or a word the
+ * evidence has in any case (by its stem); any other keeps its capital — a
+ * name's candidate, which the grounding then looks for. Any other title is
+ * returned as it is.
+ */
+export function titleAsSentence(title: string, evidence: string): string {
+ if (!isTitleCase(title)) return title;
+ const known = new Set((evidence.match(TITLE_WORD_RE) ?? []).map(stemOf));
+ let first = true;
+ return title.replace(TITLE_WORD_RE, (w) => {
+ if (first) {
+ first = false;
+ return w;
+ }
+ const low = w.toLowerCase();
+ return TITLE_SMALL.has(low) || TITLE_ORDINARY.has(low) || known.has(stemOf(w)) ? low : w;
+ });
+}
+
/** Every code check of one clip's on-screen text: `hard` refuses it. */
export function checkOnscreen(v: OnscreenValue, u: Pick<OnscreenUnit, "quote" | "evidence">): { hard: string[]; soft: string[] } {
const hard: string[] = [];
@@ -77,8 +131,11 @@ export function checkOnscreen(v: OnscreenValue, u: Pick<OnscreenUnit, "quote" |
for (const part of parts) {
if (!isVerbatimOf(part, u.quote)) hard.push(`the subtitle quotes “${part}”, which is not the clip's quote word for word`);
}
- // Names and numbers: in the evidence (a quoted part is the quote's own).
- const said = `${title}. ${sub.replace(QUOTED_RE, " ")}`;
+ // Names and numbers: in the evidence (a quoted part is the quote's own). A
+ // Title Case title is checked in its sentence case (titleAsSentence): its
+ // capitals are not a name's signal, so an ordinary word is lowercased and an
+ // unknown name still stands out.
+ const said = `${titleAsSentence(title, u.evidence)}. ${sub.replace(QUOTED_RE, " ")}`;
hard.push(...groundedProblems(said, u.evidence, "the clip's evidence"));
hard.push(...firstPersonProblems(`${title}. ${sub}`));
return { hard: [...new Set(hard)], soft: [] };
diff --git a/common/lib/report/draft/tasks/panelTasks.test.ts b/common/lib/report/draft/tasks/panelTasks.test.ts
@@ -338,6 +338,34 @@ test("threads: refused with operator's flips; forced over drafted flips replaces
assert.ok(p.lines.some((l) => /the drafted flips were removed/.test(l)));
});
+test("threads: a draft kept as an alternative carries the clips' assignments with the list (release 28 M9)", async () => {
+ const p = await project(await kit("manifests/full.video.manifest.json"));
+ const before = await p.manifestNow();
+ const answer = {
+ threads: [{ id: "shop", label: "The bakery" }, { id: "prize", label: "The contest" }],
+ clips: [
+ { clip: "c01", thread: "shop" },
+ { clip: "c02", thread: "shop" },
+ { clip: "c03", thread: "shop" },
+ { clip: "c04", thread: "prize" },
+ { clip: "c05", thread: "prize" },
+ { clip: "c06", thread: "prize" },
+ { clip: "c07", thread: "shop" },
+ ],
+ };
+ ol.push(jsonReply(answer), jsonReply(answer));
+ const out = await threads(p.input({ force: true }), p.deps);
+ assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`);
+ const now = await p.manifestNow();
+ assert.deepEqual(now.render.chrome.threads, before.render.chrome.threads, "the operator's threads stand");
+ const alt = (await p.draftNow("threads")).alternatives;
+ assert.equal(alt.length, 1);
+ assert.equal(alt[0]!.reason, "operator");
+ const v = alt[0]!.value as { list: { id: string }[]; clips: Record<string, string> };
+ assert.deepEqual(v.list.map((t) => t.id), ["shop", "prize"]);
+ assert.deepEqual(v.clips, { c01: "shop", c02: "shop", c03: "shop", c04: "prize", c05: "prize", c06: "prize", c07: "shop" });
+});
+
test("youtube: the better of two attempts, the summary's failing sentence removed; the operator's field kept and the draft an alternative", async () => {
const p = await project(await kit("manifests/basic.video.manifest.json"));
const title = "What the baker of Synth Kitchen says about the bakery";
diff --git a/common/lib/report/draft/tasks/revise-video.ts b/common/lib/report/draft/tasks/revise-video.ts
@@ -19,6 +19,7 @@ import { readIteration, type Iteration } from "../../iterations";
import { applyVideoOps, cutView, trimmedCutView, type AppliedVideoOp, type RefusedVideoOp, type ReportForVideo, type VideoManifest } from "../videoOps";
import { rewriteMomentBases, slugResolver } from "./links";
import { projectDirOf, readManifest, readProjectReport, seedProject, writeManifest } from "./project";
+import { fieldSignature, makeProvenance, stableStringify } from "../../drafted.mjs";
import { COMMON_REVISE_RULES, LOCAL_REVISE_RULES, OPS_SCHEMA, localOpsBatch, reviseCorpusTools } from "./revise-report";
import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
import type { TaskDeps, TaskResult } from "./types";
@@ -208,6 +209,15 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise<
applied: applied.map((a) => (a.warnings ? { ...a.op, warnings: a.warnings } : a.op)),
refused: refused.map((r) => ({ ...r.op, why: r.why })),
};
+ // Release 28 (the M9 ruling): ops that change the cut's order make that
+ // order a model's draft — reviewable as the cut's row, and redrafted by the
+ // cut task only with force. An order they leave as it was keeps the
+ // parent's mark (or none).
+ if (timelineOrderChanged(parent.manifest, manifest)) {
+ const m = manifest as VideoManifest & { drafted?: Record<string, unknown> };
+ m.drafted = { ...(m.drafted ?? {}), timeline: makeProvenance({ task: "revise-video", model, iteration: h.n, attempt: 1 }) };
+ h.log(`the cut's order changed: marked a draft of revise-video on ${model}`);
+ }
const dir = projectDirOf(iteration, input.projectsRoot);
const seeded = await seedProject(parent.dir, dir, manifest);
await writeManifest(dir, manifest);
@@ -218,3 +228,8 @@ async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise<
patch: { ops, projectDir: dir },
};
}
+
+/** Whether the timeline's order (its entries' ids, the cut's drafted field) differs between two manifests. */
+export function timelineOrderChanged(before: unknown, after: unknown): boolean {
+ return stableStringify(fieldSignature(before, { field: "timeline" })) !== stableStringify(fieldSignature(after, { field: "timeline" }));
+}
diff --git a/common/lib/report/draft/tasks/threads.ts b/common/lib/report/draft/tasks/threads.ts
@@ -249,12 +249,16 @@ export const THREADS_SPEC: MediaTaskSpec<ThreadsUnit, ThreadsValue, ThreadsInput
}
return best;
},
+ // The field is `{list}`; what an alternative keeps also carries `clips`, the
+ // clip → thread assignments, so umtool's "Use this" sets each clip's thread
+ // with the list (release 28 M9). `apply` writes the list alone.
toField(value, u) {
u.chosen = planThreads(value, u, u.manifest);
- return { list: u.chosen.list };
+ return { list: u.chosen.list, clips: u.chosen.clips };
},
apply(manifest, u, value, provenance, force, ctx) {
- const res = applyDraft(manifest, { field: "render.chrome.threads", value, provenance, force });
+ const { list } = value as { list: unknown };
+ const res = applyDraft(manifest, { field: "render.chrome.threads", value: { list }, provenance, force });
if (!res.applied) return res;
setClipThreads(manifest, u.chosen?.clips ?? {});
const m = manifest as VideoManifest & { render?: { chrome?: Record<string, unknown> } };
diff --git a/common/publish/siteDelete.ts b/common/publish/siteDelete.ts
@@ -1,7 +1,7 @@
// DELETE A SITE — a plan, then the delete (release 28 H5; `pnpm ops
-// delete-site`). The editor's Danger → Delete (`deleteSiteAction` →
-// lib/site.ts `deleteSite`) removes `sites/<id>/` and nothing else; this is
-// the scripted path, and it says first what goes, what stays and what refuses.
+// delete-site`, and since M9 the editor's Danger → Delete on /sites:
+// `planSiteDeleteAction`, then `deleteSiteAction`). It says first what goes,
+// what stays and what refuses.
//
// WHAT A SITE IS ON DISK (the survey, 2026-10-13):
// sites/<id>/ site.json (the pool: `channels`,
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,13 @@
# Changelog
## [Unreleased]
+- **umtool drafts each section of a report video with a model you pick.** A video project made from an article's iteration has a **draft** section: for the cut, the on-screen titles, the teaser, the flips, the threads, the narration and the YouTube text, **Draft with** and a model (the generation policy's models, the task's route chosen first), **force** (re-drafts only what a model drafted; what you wrote or edited is never replaced), and for a per-entry task the entries to draft. The job's progress shows while it runs; when it ends the page shows what it wrote, skipped and had refused by a check, the **drafted by** badge with **Approve** and **Reject**, and any draft kept aside with **Use this**. A project not made from an iteration says so and offers none. The article's Iterations tab gains the same drafts beside **Narrate**. Needs a restart of umtool.
+- **Draft everything.** One button on the Iterations tab (or `umtool chain <article> <n> --draft-all [--model M]`) runs the chain with every media draft in it, on the model you choose: the cut, on-screen, teaser, flips, threads and narration after the manifest, then the voices, a fast build and the podcast, then the YouTube text, whose chapters are re-muxed so `out/youtube.txt` is written. A draft the editor refuses or that fails is marked failed and the chain carries on; one with nothing to draft, or flips and threads with no on-screen deck (or with the other panel on), is skipped. It does not attach the video to the article: review the drafts first. Started again, it resumes after the last draft that ran. Needs a restart of umtool.
+- **A site's Delete shows its plan before anything goes.** On `/sites`, **Delete** lists what would be removed (the site, its publish state and last bundle, its staging), how much, what is kept and what refuses; **Confirm delete** removes it. A site with a deploy target, a recorded deploy or reports of its own is refused unless you tick the box and press **Delete with force**; a site whose directory is a link, or a publish stage running, is refused outright. The delete is `pnpm ops delete-site`'s, so it now removes the build state too.
+- **Use this on a threads draft sets each clip's thread too.** Taking a threads alternative writes the clips' assignments with the list, so no clip is left naming a thread that is gone.
+- **A video revision that reorders the cut makes the order a draft.** The order then has a review row, and the cut task redrafts it only with force. A revision that leaves the order alone keeps the mark it had.
+- **An on-screen title in Title Case is no longer refused as naming people.** Its capitals are not read as names: an ordinary word passes, and a name the clip's evidence lacks is still refused.
+- **Claude Code's `generate` and `/gen` know the media drafts.** `/gen` maps "draft the on-screen titles", "make a teaser", "YouTube description" and the like to the media tasks; `generate` checks that a media draft names its iteration, and its answer for a done draft says what to check for that task and that the approval is yours in umtool's review page. `archilyzer gen run` takes a media task with `--iteration` and `--entries`.
- **The editor drafts a report video's cut, on-screen text and teaser.** `pnpm ops report-draft --json '{"task": "cut" | "onscreen" | "teaser", "article", "iteration", "model"?, "entries"?, "force"?}'` runs on a done iteration's video project, as a step on it, like narration. **Cut** picks which of the report's citations the video shows and in what order, grouped under the report's sections; the code builds the timeline from the entries the cut already had (windows, quotes and on-screen text untouched), keeps a chapter card only while its section has a clip, keeps the title card and the teaser where they are, never drops a clip a post or a flip needs, and refuses an order the build would refuse. At most `settings.generation.cut.maxClips` entries (new, default 20), at least 3. **On-screen** writes each clip's title (at most 60 characters, no quotation marks) and subtitle (at most 90; it may quote only the clip's own words, exactly), several clips to a request. **Teaser** writes 3 to 5 lines that fit the teaser card, quoting nobody; a cut with no teaser gets one after its last clip. Every name and number must be in the report. Each drafted field carries its `drafted` mark and goes through the drafts review; a field you wrote or edited is never replaced (with `force` its draft is kept aside as an alternative). Each media draft has its own route in the generation policy (narration's, in every preset), and its job shows the entries done. Needs a restart of the editor and umtool.
- **A starter cut's order is marked as the converter's.** `archilyzer reports to-manifest` marks the timeline it writes as drafted by code (`drafted.timeline`, model `code`), so the cut task may redraft it without `force`; a cut converted before this release counts the same while its clips are still in the converter's order. A code-made order needs no review and shows no badge. Reordering it in umtool makes it yours.
- **New settings key `generation.cut.maxClips`** (SETTINGS.md): the most entries a drafted cut keeps (default 20).
diff --git a/editor/app/sites/actions.ts b/editor/app/sites/actions.ts
@@ -13,7 +13,6 @@ import {
import {
getSite,
writeSite,
- deleteSite,
isValidSiteId,
reservedSiteIdProblem,
parseRelatedSites,
@@ -30,6 +29,13 @@ import {
resolveDefaultGroupId,
} from "yt-dlp-transcript-common/lib/channelGroups";
import { migrateToSites } from "yt-dlp-transcript-common/controller/migrateToSites";
+import {
+ SiteDeleteRefusedError,
+ deleteSiteByPlan,
+ planSiteDelete,
+ siteDeleteBlocked,
+ type SiteDeletePlan,
+} from "yt-dlp-transcript-common/publish/siteDelete";
import { socialLinksForSave } from "yt-dlp-transcript-common/lib/socialLinks";
import { formValues, type FormState, type FormValues } from "../lib/formState";
import { reportSiteKeysFromForm } from "./lib/reportSiteKeys";
@@ -316,12 +322,41 @@ export async function saveSiteAction(
export type DeleteResult = { ok: true } | { ok: false; error: string };
+export type SiteDeletePlanResult = { ok: true; plan: SiteDeletePlan } | { ok: false; error: string };
+
+// Danger → Delete is plan-first (release 28 M9, through H5's
+// publish/siteDelete.ts, as `pnpm ops delete-site`): the plan — what is
+// removed (sites/<id>/, its publish state and bundle, compose's staging), what
+// is kept, what refuses — then the delete. Read only.
+export async function planSiteDeleteAction(siteId: string): Promise<SiteDeletePlanResult> {
+ try {
+ return { ok: true, plan: await planSiteDelete(siteId, getPaths()) };
+ } catch (err) {
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+}
+
+// The delete, its plan made again under the locks. `force` answers the
+// forceable refusals only (a deploy target, a deploy on record, reports of its
+// own); no site, a site dir that is a link and a publish stage running refuse
+// whatever.
export async function deleteSiteAction(
siteId: string,
-): Promise<DeleteResult> {
+ opts: { force?: boolean } = {},
+): Promise<DeleteResult & { plan?: SiteDeletePlan }> {
+ const force = opts.force === true;
try {
- await deleteSite(siteId, getPaths());
+ const plan = await planSiteDelete(siteId, getPaths());
+ if (siteDeleteBlocked(plan, force)) {
+ const why = plan.refusals.filter((r) => !force || !r.forceable).map((r) => r.reason);
+ return { ok: false, error: `refused: ${why.join("; ")}`, plan };
+ }
+ const r = await deleteSiteByPlan(siteId, getPaths(), { force });
+ if (r.failed.length) {
+ return { ok: false, error: `not everything was removed: ${r.failed.map((f) => `${f.path} (${f.error})`).join("; ")}`, plan: r.plan };
+ }
} catch (err) {
+ if (err instanceof SiteDeleteRefusedError) return { ok: false, error: err.message, plan: err.plan };
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
// No revalidatePath: the button refreshes the page itself (release 24 H5,
diff --git a/editor/app/sites/components/SiteListActions.tsx b/editor/app/sites/components/SiteListActions.tsx
@@ -2,32 +2,129 @@
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
-import { deleteSiteAction, migrateToSitesAction } from "../actions";
+import { deleteSiteAction, migrateToSitesAction, planSiteDeleteAction } from "../actions";
+import type { SiteDeletePlan } from "yt-dlp-transcript-common/publish/siteDelete";
// Both actions save without revalidating and refresh the page here (release 24
// H5, lib/formState.ts seedAfterSave says why).
+
+const size = (n: number) =>
+ n < 1024 ? `${n} B` : n < 1024 ** 2 ? `${(n / 1024).toFixed(1)} KiB` : n < 1024 ** 3 ? `${(n / 1024 ** 2).toFixed(1)} MiB` : `${(n / 1024 ** 3).toFixed(1)} GiB`;
+
+// Danger → Delete, plan first (release 28 M9): Delete asks for the plan —
+// what goes, what stays, what refuses — and nothing is removed until Confirm.
+// A plan refused only for reasons force answers (a deploy target, a deploy on
+// record, reports of its own) offers force behind its own confirmation; any
+// other refusal offers nothing.
export function DeleteSiteButton({ siteId }: { siteId: string }) {
const router = useRouter();
const [pending, start] = useTransition();
const [error, setError] = useState<string | null>(null);
+ const [plan, setPlan] = useState<SiteDeletePlan | null>(null);
+ const [forceOk, setForceOk] = useState(false);
+ const blocked = (force: boolean) => !!plan && plan.refusals.some((r) => !force || !r.forceable);
+ const run = (force: boolean) =>
+ start(async () => {
+ setError(null);
+ const res = await deleteSiteAction(siteId, { force });
+ if (!res.ok) {
+ setError(res.error);
+ if (res.plan) setPlan(res.plan);
+ } else {
+ setPlan(null);
+ router.refresh();
+ }
+ });
return (
- <span className="flex items-center gap-2">
- <button
- type="button"
- disabled={pending}
- onClick={() => {
- if (!confirm(`Delete site "${siteId}"? This cannot be undone.`)) return;
- start(async () => {
- const res = await deleteSiteAction(siteId);
- if (!res.ok) setError(res.error);
- else router.refresh();
- });
- }}
- className="px-2 py-1 rounded border border-destructive/30 text-xs text-destructive disabled:opacity-50"
- >
- {pending ? "Deleting…" : "Delete"}
- </button>
- {error && <span className="text-xs text-destructive">{error}</span>}
+ <span className="flex flex-col items-end gap-2">
+ <span className="flex items-center gap-2">
+ <button
+ type="button"
+ disabled={pending}
+ aria-expanded={!!plan}
+ onClick={() =>
+ start(async () => {
+ setError(null);
+ setForceOk(false);
+ const res = await planSiteDeleteAction(siteId);
+ if (res.ok) setPlan(res.plan);
+ else setError(res.error);
+ })
+ }
+ className="px-2 py-1 rounded border border-destructive/30 text-xs text-destructive disabled:opacity-50"
+ >
+ {pending && !plan ? "Planning…" : "Delete"}
+ </button>
+ {error && <span className="text-xs text-destructive">{error}</span>}
+ </span>
+ {plan && (
+ <div
+ role="region"
+ aria-label={`delete site ${siteId}`}
+ data-site-delete-plan={siteId}
+ className="w-full max-w-xl rounded border border-destructive/40 bg-destructive/5 p-3 text-xs"
+ >
+ <p className="font-medium" data-plan-summary="">
+ Delete site <code>{siteId}</code>: {plan.remove.length} path{plan.remove.length === 1 ? "" : "s"}, {size(plan.bytes)} in {plan.files} file
+ {plan.files === 1 ? "" : "s"}
+ </p>
+ {plan.refusals.length > 0 && (
+ <ul className="mt-1 list-disc pl-4 text-destructive" aria-label="refusals">
+ {plan.refusals.map((r) => (
+ <li key={r.reason} data-refusal={r.forceable ? "forceable" : "final"}>
+ {r.reason}
+ {r.forceable ? " (force answers it)" : " (force does not)"}
+ </li>
+ ))}
+ </ul>
+ )}
+ <ul className="mt-1 list-disc pl-4" aria-label="removed">
+ {plan.remove.map((e) => (
+ <li key={e.path} data-remove={e.label}>
+ <code>{e.label}</code> — {e.what}, {e.kind === "link" ? "a link" : `${size(e.bytes)} in ${e.files} file${e.files === 1 ? "" : "s"}`}
+ </li>
+ ))}
+ </ul>
+ <ul className="mt-1 list-disc pl-4 text-muted-foreground" aria-label="kept">
+ {plan.kept.map((k) => (
+ <li key={k.what}>
+ keeps {k.what}: {k.why}
+ </li>
+ ))}
+ </ul>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ {!blocked(false) && (
+ <button
+ type="button"
+ disabled={pending}
+ onClick={() => run(false)}
+ className="px-2 py-1 rounded bg-destructive text-white disabled:opacity-50"
+ >
+ {pending ? "Deleting…" : "Confirm delete"}
+ </button>
+ )}
+ {blocked(false) && !blocked(true) && (
+ <>
+ <label className="flex items-center gap-1">
+ <input type="checkbox" checked={forceOk} onChange={(e) => setForceOk(e.target.checked)} />
+ I understand: the refusals above are overridden, and nothing deployed is undeployed
+ </label>
+ <button
+ type="button"
+ disabled={pending || !forceOk}
+ onClick={() => run(true)}
+ className="px-2 py-1 rounded bg-destructive text-white disabled:opacity-50"
+ >
+ {pending ? "Deleting…" : "Delete with force"}
+ </button>
+ </>
+ )}
+ <button type="button" disabled={pending} onClick={() => setPlan(null)} className="px-2 py-1 rounded border border-border">
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
</span>
);
}
diff --git a/editor/e2e/site-delete.spec.ts b/editor/e2e/site-delete.spec.ts
@@ -0,0 +1,63 @@
+import { test, expect } from "@playwright/test";
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { pathExists, resetData, testPaths, writeSite } from "./helpers";
+
+// Danger → Delete on /sites, plan first (release 28 M9, through H5's
+// publish/siteDelete.ts): Delete shows what goes (sites/<id>/, its publish
+// state and bundle, compose's staging), what stays and what refuses; nothing
+// is removed until Confirm. A site with a deploy target is refused unless
+// forced, and force has its own confirmation. Temp sites in the fixture
+// corpus only.
+
+const sitesDir = () => join(testPaths().transcriptsDir, "sites");
+
+test("Delete shows the plan; Cancel removes nothing; Confirm removes the site and its build state", async ({ page }) => {
+ await resetData("empty");
+ await writeSite("scratch", { siteTitle: "Scratch Site" });
+ // Its build state, as a publish leaves it.
+ const builds = join(testPaths().transcriptsDir, ".export-builds", "scratch");
+ await mkdir(join(builds, "out"), { recursive: true });
+ await writeFile(join(builds, "out", "index.html"), "<p>scratch</p>");
+ await writeFile(join(builds, "built.json"), "{}");
+
+ await page.goto("/sites");
+ const row = page.getByRole("listitem").filter({ hasText: "Scratch Site" });
+ await row.getByRole("button", { name: /^delete$/i }).click();
+ const plan = page.getByRole("region", { name: "delete site scratch" });
+ await expect(plan).toBeVisible();
+ await expect(plan.locator("[data-plan-summary]")).toContainText("Delete site scratch: 2 paths");
+ await expect(plan.locator("[data-remove='sites/scratch/']")).toBeVisible();
+ await expect(plan.locator("[data-remove='export/.export-builds/scratch/']")).toContainText("2 files");
+ await expect(plan.getByRole("list", { name: "kept" })).toContainText("every channel's data");
+ await expect(plan.locator("[data-refusal]")).toHaveCount(0);
+
+ await plan.getByRole("button", { name: "Cancel" }).click();
+ await expect(plan).toHaveCount(0);
+ expect(await pathExists(join(sitesDir(), "scratch", "site.json"))).toBe(true);
+
+ await row.getByRole("button", { name: /^delete$/i }).click();
+ await page.getByRole("region", { name: "delete site scratch" }).getByRole("button", { name: "Confirm delete" }).click();
+ await expect(page.getByRole("link", { name: /Scratch Site/ })).toHaveCount(0);
+ expect(await pathExists(join(sitesDir(), "scratch"))).toBe(false);
+ expect(await pathExists(builds)).toBe(false);
+});
+
+test("a site with a deploy target is refused; force, behind its own confirmation, deletes it", async ({ page }) => {
+ await resetData("empty");
+ await writeSite("deployed", { siteTitle: "Deployed Site", cloudflareProject: "deployed-pages" });
+
+ await page.goto("/sites");
+ const row = page.getByRole("listitem").filter({ hasText: "Deployed Site" });
+ await row.getByRole("button", { name: /^delete$/i }).click();
+ const plan = page.getByRole("region", { name: "delete site deployed" });
+ await expect(plan.locator("[data-refusal='forceable']")).toContainText('it deploys to the Cloudflare Pages project "deployed-pages" (force answers it)');
+ await expect(plan.getByRole("list", { name: "kept" })).toContainText('the Pages project "deployed-pages"');
+ await expect(plan.getByRole("button", { name: "Confirm delete" })).toHaveCount(0);
+ const force = plan.getByRole("button", { name: "Delete with force" });
+ await expect(force).toBeDisabled();
+ await plan.getByRole("checkbox", { name: /I understand/ }).check();
+ await force.click();
+ await expect(page.getByRole("link", { name: /Deployed Site/ })).toHaveCount(0);
+ expect(await pathExists(join(sitesDir(), "deployed"))).toBe(false);
+});
diff --git a/editor/e2e/sites-crud.spec.ts b/editor/e2e/sites-crud.spec.ts
@@ -128,8 +128,9 @@ test("delete removes the site config", async ({ page }) => {
await writeSite("doomed", { siteTitle: "Doomed" });
await page.goto("/sites");
- page.once("dialog", (d) => d.accept());
- await page.getByRole("button", { name: /delete/i }).click();
+ // Plan first (release 28 M9): nothing goes until Confirm.
+ await page.getByRole("button", { name: /^delete$/i }).click();
+ await page.getByRole("region", { name: "delete site doomed" }).getByRole("button", { name: "Confirm delete" }).click();
await expect(page.getByText("Doomed")).toHaveCount(0);
expect(await pathExists(`${testPaths().transcriptsDir}/sites/doomed/site.json`)).toBe(
diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts
@@ -457,6 +457,30 @@ test("revise-video on a local model: one ops batch over the trimmed cut", async
assert.equal(m.timeline.find((e: { id: string }) => e.id === "the-bakery").heading, "About the bakery");
});
+test("revise-video: ops that change the cut's order mark it a draft of revise-video; ops that do not keep the parent's mark (release 28 M9 ruling)", async () => {
+ await drainFake();
+ await doneSweep("synth-basic", "basic", { manifest: true });
+ const parentMark = JSON.parse(await readFile(path.join(DRAFT, "manifests", "basic.video.manifest.json"), "utf8")).drafted?.timeline;
+ // A move: the order changes.
+ const moved = await createIteration("synth-basic", { kind: "revise-video", model: "qwen3:8b", parent: 1, feedback: "Put c03 first." }, paths);
+ ol.push(jsonReply({ ops: [{ op: "move", id: "c03", after: "title" }] }));
+ const a = await runTask({ task: "revise-video", article: "synth-basic", n: moved.n, origin: ORIGIN, maxUsd: 1, projectsRoot }, deps());
+ assert.equal(a.status, "done", a.summary);
+ const ma = JSON.parse(await readFile(path.join(projectOf(projectsRoot, "synth-basic", moved.n), "video.manifest.json"), "utf8"));
+ assert.equal(ma.timeline[1].id, "c03");
+ assert.deepEqual(
+ { task: ma.drafted.timeline.task, model: ma.drafted.timeline.model, iteration: ma.drafted.timeline.iteration, attempt: ma.drafted.timeline.attempt },
+ { task: "revise-video", model: "qwen3:8b", iteration: moved.n, attempt: 1 },
+ );
+ // A heading only: the order is the parent's, and so is its mark.
+ const renamed = await createIteration("synth-basic", { kind: "revise-video", model: "qwen3:8b", parent: 1, feedback: "Rename the-bakery." }, paths);
+ ol.push(jsonReply({ ops: [{ op: "heading", id: "the-bakery", text: "About the bakery" }] }));
+ const b = await runTask({ task: "revise-video", article: "synth-basic", n: renamed.n, origin: ORIGIN, maxUsd: 1, projectsRoot }, deps());
+ assert.equal(b.status, "done", b.summary);
+ const mb = JSON.parse(await readFile(path.join(projectOf(projectsRoot, "synth-basic", renamed.n), "video.manifest.json"), "utf8"));
+ assert.deepEqual(mb.drafted?.timeline, parentMark);
+});
+
// ─── release 28 M4–M6: flips, threads, youtube (lane E) ───
// i1 done with the basic report and the FULL manifest with its threads taken
diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts
@@ -35,7 +35,7 @@ type Sent = { url: string; method: string; body?: unknown };
// An editor that serves the policy, the day's usage, a report-draft POST, a
// job that runs for `runPolls` polls and then ends `end`, and the iteration.
-function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end?: string; iteration?: Record<string, unknown>; marker?: boolean } = {}) {
+function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end?: string; iteration?: Record<string, unknown>; marker?: boolean; task?: string } = {}) {
let policy = { ...POLICY, ...(opts.policy ?? {}) };
let polls = 0;
const runPolls = opts.runPolls ?? 0;
@@ -56,7 +56,7 @@ function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end
steps: [],
...(opts.iteration ?? {}),
};
- const marker = `@@report-draft ${JSON.stringify({ article: "synth-a", iteration: 3, task: "revise-report", status: opts.end ?? "done", summary: "2 op(s) applied, 1 refused — “A title”", usd: 0.45, minutes: 2.5 })}`;
+ const marker = `@@report-draft ${JSON.stringify({ article: "synth-a", iteration: 3, task: opts.task ?? "revise-report", status: opts.end ?? "done", summary: "2 op(s) applied, 1 refused — “A title”", usd: 0.45, minutes: 2.5 })}`;
const fake = fakeEditor((s) => {
const u = new URL(s.url);
if (u.pathname === "/api/ops/settings" && s.method === "GET") return { status: 200, body: { ok: true, key: "generation", value: policy } };
@@ -278,6 +278,11 @@ test("generate: the arguments are checked before any request; research is a task
for (const [args, re] of [
[{ task: "nope", article: "a" }, /task is one of sweep, revise-report, revise-video, narrate, research, cut, onscreen, teaser, flips, threads, youtube/],
[{ task: "cut", article: "a", iteration: 1, entries: [] }, /entries is a non-empty list/],
+ // The media drafts (release 28): a step on the iteration it names.
+ [{ task: "onscreen", article: "a" }, /a onscreen draft names the iteration it drafts on/],
+ [{ task: "teaser", article: "a", iteration: 1, copyOf: 1 }, /a teaser draft is a step on its iteration: it has no copyOf/],
+ [{ task: "youtube", article: "a", iteration: 1, feedback: "shorter" }, /feedback is not a youtube draft's/],
+ [{ task: "sweep", article: "a", question: "q", channels: ["c"], entries: ["c01"] }, /entries is a media draft's/],
[{ task: "sweep", article: "Not An Id" }, /article is an article id/],
[{ task: "sweep", article: "a", channels: [] }, /channels is a non-empty list/],
[{ task: "sweep", article: "a", iteration: 0 }, /iteration is an iteration number/],
@@ -295,6 +300,41 @@ test("generate: the arguments are checked before any request; research is a task
}
});
+test("generate: a media draft is a step on its iteration, routed like any task; done, the review is the operator's in umtool", async () => {
+ for (const task of ["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube"]) {
+ assert.ok(GENERATE_TASKS.includes(task), task);
+ const v = validateGenerateArgs({ task, article: "synth-a", iteration: 3, entries: ["c01"], force: true });
+ assert.equal(v.ok, true, task);
+ }
+ // Routed by the policy: the editor runs it on the route's model.
+ const e = editor({
+ task: "onscreen",
+ policy: { routes: { ...POLICY.routes, onscreen: "local" } },
+ iteration: {
+ kind: "sweep",
+ ops: undefined,
+ checks: [{ name: "onscreen", ok: false, detail: "3 title(s) written, 1 not written (a hard check)" }],
+ steps: [{ task: "onscreen", model: "qwen3:8b", status: "done", jobId: "job-1", detail: "3 title(s) written" }],
+ projectDir: "/srv/projects/synth-a/i3",
+ },
+ });
+ const a = await generateTool({ task: "onscreen", article: "synth-a", iteration: 3, entries: ["c01", "c02"], wait: true }, e.deps as never);
+ assert.ok(!a.isError, a.text);
+ assert.deepEqual(e.sentOf("/api/ops/report-draft")[0].body, { task: "onscreen", article: "synth-a", iteration: 3, entries: ["c01", "c02"] });
+ const queued = await generateTool({ task: "onscreen", article: "synth-a", iteration: 3 }, e.deps as never);
+ assert.match(queued.text, /drafting its onscreen on synth-a i3 on the policy's model/);
+ assert.match(a.text, /onscreen: 3 title\(s\) written/);
+ assert.match(a.text, /\*\*Review the draft — the approval is the operator's\.\*\* It drafted each clip's on-screen title and subtitle in the video project \(`\/srv\/projects\/synth-a\/i3`\)/);
+ assert.match(a.text, /`onscreen-draft\.json`/);
+ assert.match(a.text, /never by writing `drafts\.review\.json` yourself/);
+ assert.match(a.text, /A final build refuses any drafted field not approved/);
+ assert.doesNotMatch(a.text, /Review it — you are the reviewer/);
+ // A task routed to code is this session's, as any.
+ const code = await generateTool({ task: "youtube", article: "synth-a", iteration: 3 }, editor({ policy: { routes: { ...POLICY.routes, youtube: "code" } } }).deps as never);
+ assert.equal(code.isError, true);
+ assert.match(code.text, /youtube is routed to Claude Code/);
+});
+
test("resultMarkerOf reads the job's @@report-draft line", () => {
assert.deepEqual(resultMarkerOf(["x", '@@report-draft {"article":"a","iteration":2}', "y"]), { article: "a", iteration: 2 });
assert.equal(resultMarkerOf(["nothing here"]), null);
diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts
@@ -9,7 +9,7 @@ import {
import { AUTONOMIES } from "yt-dlp-transcript-common/lib/report/draft/research/decide";
import { describeEditorFailure, editorGet, editorPost, type EditorAnswer } from "./editorOps";
import type { FetchClipDeps, PollProgress } from "./fetchClip";
-import { reviewGuidance, type GenerationRoute, type PlanGeneration } from "./instructions";
+import { mediaReviewGuidance, reviewGuidance, type GenerationRoute, type PlanGeneration } from "./instructions";
import type { ToolAnswer } from "./archivalTools";
// ─── The Claude Code balance (release 27 S9; D8) ───
@@ -282,6 +282,14 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true;
if (body.model) return bad("give model or via, not both");
via = v;
}
+ // A media draft (release 28) is a step on a done iteration: it names it.
+ if (isStepTask(task)) {
+ if (body.iteration === undefined) return bad(`a ${task} draft names the iteration it drafts on (iteration)`);
+ if (body.copyOf !== undefined) return bad(`a ${task} draft is a step on its iteration: it has no copyOf`);
+ for (const k of ["question", "feedback", "channels", "from", "to"] as const) {
+ if (body[k] !== undefined) return bad(`${k} is not a ${task} draft's: it drafts from the iteration's report and cut`);
+ }
+ } else if (body.entries !== undefined) return bad("entries is a media draft's (cut, onscreen, teaser, flips, threads, narrate, youtube)");
if (args.wait !== undefined && typeof args.wait !== "boolean") return bad("wait is true or false");
return { ok: true, request: { kind: "start", body, ...(via ? { via } : {}), wait: args.wait === true, waitSeconds } };
}
@@ -421,7 +429,8 @@ export function renderIterationSummary(
lines.push(`Research: phase ${r.phase ?? "?"}, autonomy ${r.autonomy ?? "?"}${r.continuedBy ? `, continued by i${r.continuedBy}` : ""}`);
for (const note of (r.notes ?? []).slice(0, MAX_LISTED)) lines.push(` - ${note}`);
if (status === "done") lines.push("", researchGuidance(o.article, it.n));
- } else if (status === "done") lines.push("", reviewGuidance());
+ } else if (status === "done" && isStepTask(o.task)) lines.push("", mediaReviewGuidance(o.task, it.projectDir));
+ else if (status === "done") lines.push("", reviewGuidance());
else if (status === "failed") lines.push("", "It failed: say why to the operator. Running it again, or here instead, is their call.");
return lines.join("\n");
}
@@ -571,7 +580,8 @@ export const GENERATION_TOOLS = [
name: "generation_policy",
description:
"The operator's generation balance (settings.generation, read from the local editor): for each " +
- "generation task — sweep (a new cited report), revise-report, revise-video, narrate, research — whether this " +
+ "generation task — sweep (a new cited report), revise-report, revise-video, research, and the media drafts on a " +
+ "video cut (cut, onscreen, teaser, flips, threads, narrate, youtube) — whether this " +
"Claude Code session does it (code), the Claude API does it (api) or the local model does it " +
"(local), on which model; the spend caps; and the day's Claude API spend against the daily cap. " +
"With preset (code, balanced, api, local) it routes every task at once; with task and route it " +
@@ -585,7 +595,10 @@ export const GENERATION_TOOLS = [
enum: [...GENERATION_PRESET_NAMES],
description: "Route every task by this preset: code (all here), balanced, api, local.",
},
- task: { type: "string", description: "Route one task (with route): sweep, revise-report, revise-video, narrate, research." },
+ task: {
+ type: "string",
+ description: "Route one task (with route): sweep, revise-report, revise-video, research, cut, onscreen, teaser, flips, threads, narrate, youtube.",
+ },
route: { type: "string", enum: [...GENERATION_ROUTES], description: "Where that task runs." },
},
additionalProperties: false,
@@ -599,9 +612,13 @@ export const GENERATION_TOOLS = [
"with wait: true, follow it and return the iteration it made: status, cost, the ops applied and " +
"refused, the checks, and where its files are on the editor's disk. task sweep makes a new " +
"iteration of article from question over channels; revise-report and revise-video make one from " +
- "iteration and feedback; narrate voices a done iteration's cut; research finds what the corpus lacks " +
+ "iteration and feedback; research finds what the corpus lacks " +
"and proposes acquisitions under its autonomy (propose, limits, auto), and task sweep with a research " +
"run's iteration continues it over the widened scope. copyOf runs an iteration again on another model. " +
+ "The media drafts are steps on a done iteration's video cut (iteration names it): cut (which cited clips, in " +
+ "what order), onscreen (each clip's title and subtitle), teaser (its lines), flips (THEN/NOW pairs), threads, " +
+ "narrate (each card's narration) and youtube (the upload's title and summary); each drafted field is marked " +
+ "for the operator's review, and a field the operator wrote is never replaced. " +
"A task routed to code is refused: do it in this session. The wait is bounded (wait_seconds, " +
"default 90, at most 300) and polite (one poll every 5 s, a progress notification each); if the " +
"job is still running it answers its id — call again with job (and article, iteration) to keep " +
@@ -616,7 +633,7 @@ export const GENERATION_TOOLS = [
type: "integer",
minimum: 1,
description:
- "revise-report / revise-video: the iteration revised; narrate: the iteration voiced; sweep: the research run it continues; with job: the iteration to summarise.",
+ "revise-report / revise-video: the iteration revised; a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube): the done iteration whose cut it drafts; sweep: the research run it continues; with job: the iteration to summarise.",
},
question: { type: "string", description: "sweep / research: the question, in words." },
channels: { type: "array", items: { type: "string" }, description: "sweep / research: the channel slugs to read." },
@@ -635,7 +652,8 @@ export const GENERATION_TOOLS = [
entries: { type: "array", items: { type: "string" }, description: "A media draft (narrate, cut, onscreen, teaser, flips, threads, youtube): only these entry ids." },
force: {
type: "boolean",
- description: "narrate: redraft cards that already have narration; a sweep continuing a research run: continue while proposals still wait.",
+ description:
+ "A media draft: re-draft fields a model drafted (a field the operator wrote is never replaced; its draft is kept as an alternative); a sweep continuing a research run: continue while proposals still wait.",
},
autonomy: {
type: "string",
diff --git a/mcp/src/instructions.test.ts b/mcp/src/instructions.test.ts
@@ -1,6 +1,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { NARRATION_HARD_RULE, NARRATION_WRITING_RULES, buildSweepInstructions, buildAskInstructions, narrationStep } from "./instructions";
+import { MEDIA_REVIEW, NARRATION_HARD_RULE, NARRATION_WRITING_RULES, buildSweepInstructions, buildAskInstructions, mediaReviewGuidance, narrationStep } from "./instructions";
+import { MEDIA_STEP_TASKS } from "yt-dlp-transcript-common/lib/generationSettings";
import { parsePromptRequest } from "./promptRequest";
import { TOOLS } from "./server";
@@ -318,3 +319,17 @@ test("every tool a routed plan names exists", () => {
}
}
});
+
+test("every media task has its review guidance: the draft file, the fields, the operator's approval in umtool", () => {
+ assert.deepEqual(Object.keys(MEDIA_REVIEW).sort(), [...MEDIA_STEP_TASKS].sort());
+ for (const task of MEDIA_STEP_TASKS) {
+ const g = mediaReviewGuidance(task, "/p/a/i2");
+ assert.match(g, new RegExp(`\`${task === "narrate" ? "narration" : task}-draft\\.json\``), task);
+ assert.ok(g.includes(MEDIA_REVIEW[task]!.check), task);
+ assert.match(g, /\/browse\/<project>\/review/);
+ assert.match(g, /never by writing `drafts\.review\.json` yourself/);
+ assert.match(g, /--drafts-unreviewed/);
+ assert.match(g, /Use this/);
+ }
+});
+
diff --git a/mcp/src/instructions.ts b/mcp/src/instructions.ts
@@ -282,6 +282,63 @@ export function reviewGuidance(corpus?: string): string {
);
}
+// ─── The media drafts (release 28) ───
+//
+// A media draft (cut, onscreen, teaser, flips, threads, narrate, youtube) is a
+// STEP on a done iteration's video manifest: it writes drafted fields, each
+// marked with its provenance. The review is the operator's, in umtool, field
+// by field — the agent reads what was drafted and says what it would approve.
+
+// What each media task drafts, and what its review checks beyond the code's.
+export const MEDIA_REVIEW: Record<string, { what: string; check: string }> = {
+ cut: {
+ what: "the cut's clips and their order (ids from the report's citations only; the windows are untouched)",
+ check: "the order argues the report's case chapter by chapter, and no clip a conclusion rests on was dropped",
+ },
+ onscreen: {
+ what: "each clip's on-screen title and subtitle",
+ check: "each title says what its clip shows, and a subtitle's quote is the clip's own words and its speaker's",
+ },
+ teaser: {
+ what: "the teaser's 3 to 5 lines",
+ check: "the lines promise only what the cut delivers, and read no quote out",
+ },
+ flips: {
+ what: "THEN/NOW pairs over the cut's clips (the dates and the order are code's)",
+ check: "both clips of a pair speak to the topic it names, so the change it shows is real",
+ },
+ threads: {
+ what: "2 to 4 threads and each clip's thread (an outcome is its last clip's verdict)",
+ check: "each clip belongs to its thread, and each label names what the thread follows",
+ },
+ narrate: {
+ what: "each card's narration",
+ check: "it is third person and says nothing the report does not, and no line restates a quote",
+ },
+ youtube: {
+ what: "the upload's title and summary (the build adds the chapters and the sources to out/youtube.txt)",
+ check: "the summary says what the video shows, no more, and the title would not mislead",
+ },
+};
+
+// The review of a media draft — the step Claude Code owns after `generate`.
+export function mediaReviewGuidance(task: string, projectDir?: string): string {
+ const m = MEDIA_REVIEW[task];
+ const where = projectDir ? ` (\`${projectDir}\`)` : "";
+ return (
+ `**Review the draft — the approval is the operator's.** It drafted ${m ? m.what : "fields of the cut"} in the video ` +
+ `project${where}. (1) Read the project's \`${task === "narrate" ? "narration" : task}-draft.json\`: what each unit wrote, ` +
+ `skipped, or had refused by a check, and the alternatives it kept. (2) Read the drafted fields in the manifest` +
+ (m ? `, and check that ${m.check}` : "") +
+ `; spot-check against the report and, where a field restates speech, \`get_transcript\`. (3) Tell me which ` +
+ `drafted fields you would approve or reject, and why. I approve or reject each one in umtool — the project page's ` +
+ `**Review drafts**, \`/browse/<project>/review\` — never by writing \`drafts.review.json\` yourself. A final build ` +
+ `refuses any drafted field not approved (\`--drafts-unreviewed\` overrides, and that is my call). A field I wrote ` +
+ `or edited is never replaced: a draft of it is kept as an alternative, which I take with **Use this**. To draft ` +
+ `again, call \`generate\` with the same task and iteration (force: true re-drafts only fields a model drafted).`
+ );
+}
+
// The generate call a routed sweep makes, with its scope settled.
function generateSweepStep(req: PromptRequest, r: { route: GenerationRoute; model?: string; by: string }): string {
const article = req.article
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -9350,3 +9350,44 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
without chapters) when the manifest has a `publish.youtube` title. `muxChapters` returns `{chapters: [{start, end,
title}], total}`. The composition is `report-to-video/youtube.mjs` (`composeYoutubeText`, `youtubeChapters`,
`youtubeSources`, `momentLinkOf`, `youtubePreview`, `youtubeTextName`), exported as `umtool-report-to-video/youtube`.
+
+## Release 28 M9: the surfaces of the media drafts (verified 2026-10-14, branch `r28/surfaces`)
+
+- **Draft everything is a chain mode.** `umtool/lib/report/chain.mjs` `CHAIN_STEPS` carries every step with its
+ `modes` (`"video"`, `"draft-all"`); `chainStepsOf(mode)` is a chain's list. The generation steps are
+ `draft-<task>` (`optional: true`, `draft: <task>`), in the draft-all chain only: current → windows → prepare →
+ posts → manifest → draft-cut → draft-onscreen → draft-teaser → draft-flips → draft-threads → draft-narrate →
+ voices → video → podcast → draft-youtube. No attach, no dedupe. `CHAIN_STEP_NAMES` is still the default chain's
+ ten. The draft-all build never takes `--final`; `model` rides on the draft steps' argv (`--model`) only.
+- **A draft step is one `report-draft` job through the editor** (`chain-run.mjs` `draftStep`: POST
+ `/api/ops/report-draft`, GET `/api/ops/job/<id>` every `CHAIN_DRAFT_POLL_MS` (2 s), a chain cancel cancels the
+ job). It records `chain:draft-<task>` as `done` (the job's summary), `skipped` (`draftPrecheck`: flips and
+ threads with no `render.chrome` or with the other panel on, never asked; or `draftOutcome`: every unit of
+ `<task>-draft.json` skipped) or `failed` (refused at the ask, or the job failed) — and an optional step exits 0
+ either way, so the chain goes on. `doneSteps` counts an optional step `done`, `skipped` or `failed` as finished
+ (a resume passes it); a code step only `done`. The pure part is `chain-draft.mjs` (plain node).
+- **draft-youtube re-muxes a built cut's chapters** (`build-video --chapters-only --no-xfade --skip-fetch`) so
+ `out/youtube.txt` is written; with no `out/<slug>.mp4` the next build writes it.
+- **umtool's chain jobs are two kinds:** `chain <article> i<n>` and `draft-all <article> i<n>` (`chainKind(…,
+ mode)`); one umtool job runs at a time either way. `/api/articles/chain` takes `{draftAll, model}` and `?mode=`.
+- **A project names its iteration by its path:** `projectIteration(dir)` (`umtool/lib/articles/projectDraft.ts`)
+ is `<projectsRoot>/<article>/i<n>/` whose iteration exists and names that directory as its project (or none).
+ Any other project has no "Draft with". `draftRunSummary` reads a task's last run from `<task>-draft.json`;
+ `/api/articles/draft?project=` answers both.
+- **A threads alternative is `{list, clips}`** (`clips`: clip id → thread id); the task applies `{list}`.
+ `writeDraftedField` writes the list and sets each clip's `thread` from `clips` (removed from a clip in none),
+ refusing a clip the cut lacks and anything `validateThreadEntries` refuses. An alternative without `clips` writes
+ the list alone, as before.
+- **A revise-video whose ops change the timeline's order** (its ids, `fieldSignature`) sets `drafted.timeline =
+ {task: "revise-video", model, iteration, attempt: 1}`; one that does not keeps the parent's mark.
+- **onscreen checks a Title Case title in its sentence case** (`isTitleCase`, `titleAsSentence`): past the first
+ word a small word, an ordinary headline word (`TITLE_ORDINARY`) or a word the evidence has (by stem) is
+ lowercased; anything else keeps its capital and is a name's candidate. The first word is never checked as a
+ name (the grounding's rule, unchanged).
+- **The editor's site Delete is plan-first:** `planSiteDeleteAction` / `deleteSiteAction(siteId, {force})`
+ (`editor/app/sites/actions.ts`) over `publish/siteDelete.ts`; `lib/site.ts` `deleteSite` has no caller in the
+ editor now (lane C's "still removes `sites/<id>/` alone" above no longer holds).
+- **The umtool e2e stub drafts every media task:** the kit's article `mdraft` runs the real task (lane D's
+ `runMediaStep.ts`); the surfaces' article `msurf` is canned (`startCannedDraft`, through `applyDraft`, with a
+ draft file in the scaffold's shape and `entries` progress).
+
diff --git a/plans/release-28.md b/plans/release-28.md
@@ -846,6 +846,112 @@ Found and left:
Rulings on lane D's questions, built in M9: a video revision whose ops change the clip order marks `drafted.timeline`
with `revise-video` and its model (a model draft: reviewable, and the cut task needs `force`); an on-screen title in
Title Case is not refused for its capitals.
+### M9, as shipped (2026-10-14, lane G, `r28/surfaces`)
+
+The surfaces of the media drafts: "Draft with <model>" per section, Draft everything, the MCP and `/gen`, the two
+leftovers, and the two rulings added to the lane.
+- **Draft with <model>** is a **draft** section on a report-video project page (`DraftPanel.tsx`), one row per task:
+ the cut, on-screen titles, the teaser, flips, threads, narration, the YouTube text. A row has **Draft with** and the
+ model (the policy's API and local models, the task's route preselected), **force** (re-drafts only what a model
+ drafted; the UI says a field the operator wrote or edited is never replaced) and, for a per-entry task (on-screen,
+ teaser, narration), the entries to draft. It posts `report-draft {task, article, iteration, model, entries?,
+ force?}` through `/api/articles/generate` and follows the job (status, the queue, F3's progress, the last log line,
+ Cancel). When the job ends the page re-reads the manifest, the drafts and the server sections, and the row shows the
+ task's last run from its `<task>-draft.json`: written, kept as an alternative, refused by a check (with the reason),
+ skipped, the failing checks. The cut, flips, threads and YouTube rows carry M0's badge and alternatives with **Use
+ this**; per-entry fields keep theirs in the sections and on the review page. Flips and threads on a cut with no
+ deck say why and offer no button.
+- **Which iteration:** a project `<projectsRoot>/<article>/i<n>/` whose iteration exists and names that directory
+ (or none) (`projectIteration`). Any other project shows one line why and no control; an iteration not done says so.
+- **The Iterations tab** gains the six media drafts beside **Narrate** (a task select, a model, force, **Draft**) and
+ **Draft everything** (a model and the button, which opens and starts a chain panel in its own mode).
+- **Draft everything** (`chain.mjs`): `CHAIN_STEPS` carries each step's `modes`; the draft-all chain is current →
+ windows → prepare → posts → manifest → draft-cut → draft-onscreen → draft-teaser → draft-flips → draft-threads →
+ draft-narrate → voices → video → podcast → draft-youtube.
+ - Ruled here: the drafts sit after `manifest`, because a media task drafts the project's manifest, and the windows
+ are fetched from the report's citations before prepare, not from the cut. The brief's "cut → windows" cannot hold.
+ YouTube sits after the podcast as the brief says, and its step re-muxes a built cut's chapters
+ (`--chapters-only`), so `out/youtube.txt` is written then.
+ - No attach and no dedupe: a cut whose drafts nobody reviewed is not made the article's video.
+ - The build is the existing `video` step without `--final` (fast: `--no-xfade`). The default chain is unchanged,
+ its ten steps and labels as they were.
+ - A draft step is one `report-draft` job through the editor, followed every 2 s, cancelled with the chain. It is
+ recorded done, skipped or failed, and exits 0 either way: a missing draft never blocks a build.
+ - Skipped: flips with threads on, or threads with flips on (the pre-check; the second of the pair is never asked
+ once the first applied a panel), either with no deck, or a draft file whose every unit was skipped.
+ - Failed: refused at the ask, or the job failed.
+ - A resume passes an optional step that ran (done, skipped or failed); `--from` names one.
+ - `umtool chain <article> <n> --draft-all [--model M]`; `--final` with it is refused. The umtool job kind is
+ `draft-all <article> i<n>`.
+- **MCP and `/gen`:**
+ - `generate` refuses a media draft with no iteration, a `copyOf`, a question, feedback, channels or dates, and
+ `entries` on a task that is not a media draft. The tools' texts name the media tasks.
+ - A done media draft's answer is `mediaReviewGuidance(task, projectDir)`: read `<task>-draft.json`, read the
+ drafted fields and check what that task needs (`MEDIA_REVIEW`), say what to approve; the operator approves or
+ rejects in umtool's review page, never by writing `drafts.review.json`; the final gate; force's rule.
+ - `.claude/commands/gen.md` maps phrasings to each media task and says Draft everything is umtool's.
+ - `archilyzer gen run <media task> --iteration <n> [--entries a,b] [--force]` takes no words; COMMANDS.md
+ regenerated.
+- **Leftovers:**
+ - The editor's site **Delete** on `/sites` is plan-first through H5's `publish/siteDelete.ts`
+ (`planSiteDeleteAction`, `deleteSiteAction(id, {force})`). The plan shows the paths, files and size removed,
+ what is kept and the refusals; then **Confirm delete**. A plan refused only for forceable reasons offers
+ **Delete with force** behind an "I understand" box; any other refusal offers nothing. It now also removes the
+ site's build state and staging.
+ - **Use this on a threads alternative** writes the clips' assignments too. The threads task's alternative is
+ `{list, clips}` and the task applies `{list}`. `writeDraftedField` sets each clip's `thread`, removes it from a
+ clip in none, and refuses a clip the cut lacks or what `validateThreadEntries` refuses. An alternative without
+ `clips` writes the list alone, as before.
+- **The two rulings added to the lane:**
+ - **A revise-video that reorders the cut** (its timeline's ids, `fieldSignature`) sets `drafted.timeline =
+ {task: "revise-video", model, iteration, attempt: 1}`. The reorder is then a model's draft: it has the cut's
+ review row, and the cut task needs `force` to redraft it. A revision that keeps the order keeps the parent's mark
+ (or none).
+ - **A Title Case on-screen title** (every word but the small ones capitalised, two at least) is checked in its
+ sentence case (`titleAsSentence`): past the first word, a small word, an ordinary headline word
+ (`TITLE_ORDINARY`) or a word the clip's evidence has (by stem) is lowercased; any other keeps its capital and
+ is looked for as a name. So "She Refuses To Sell To A Chain" passes, "The Bakery Stays, Says Marco" still fails
+ on Marco. The first word is never a name's candidate (the grounding's rule, unchanged).
+
+| Commit | What |
+| --- | --- |
+| `f6de9a9e` | umtool: the chain's optional generation steps (`chain.mjs` modes, `chain-run.mjs` `draftStep`, `chain-draft.mjs`), `umtool chain --draft-all [--model]`; `chain-draft.test.mjs` (6), `chain.test.mjs` (+2) |
+| `18e2542e` | umtool: `DraftPanel.tsx` on the project page, the Iterations tab's drafts and Draft everything, `ChainPanel` modes, `/api/articles/draft`, the chain route's `draftAll`/`model`, `entries` in report-draft bodies, job progress in umtool's job view |
+| `ea232bbc` | merge of `r28/integration` (lane D) |
+| `81da836d` | common: revise-video's order mark; onscreen's Title Case check; MCP `draftTasks.test.ts` (+1), `onscreen.test.ts` (+1) |
+| `d1dda928` | threads' alternative `{list, clips}`; `writeDraftedField` sets the clips' threads; `panelTasks.test.ts` (+1), `drafted-writer.test.mjs` (+1) |
+| `82fd4ab8` | MCP `generate` checks and `mediaReviewGuidance`; `/gen`; `archilyzer gen run` media tasks; COMMANDS.md; `generation.test.ts` (+1), `instructions.test.ts` (+1), `gen.test.ts` (+1) |
+| `e3b6af2e` | editor: the site Delete plan-first; e2e `site-delete.spec.ts` (2), `sites-crud.spec.ts` follows the plan |
+| `189bc376` | umtool e2e `media-surfaces.spec.ts` (2), `fixtures/media-surfaces-fixture.mjs` (msurf), the stub's canned drafts for every media task |
+| `c4235bb5` | OPERATING.md "Generate and iterate" (the media tasks' table, Draft everything, the gate), `umtool/docs/authoring.md` |
+| `2d257fbe` | the stub's narration makes its card auto-length; msurf's clips inside the cached window |
+| (this commit) | this record, FACTS "Release 28 M9", CHANGELOG; `publish/siteDelete.ts`'s header names the editor's path |
+
+Gates (from the worktree root; counts at the branch's start `f7b8dae9`, after the merge of lane D `ea232bbc`, and at
+the tip):
+- tsc (all packages) clean before every commit.
+- common 4076 → 4089 after the merge → 4092/4092 (+3).
+- mcp 349 → 349 → 352/352 (+3).
+- editor unit 295 → 295 → 295/295 (none added).
+- `test:scripts` 880 + 3 skipped → 881 + 3 skipped after the merge → 890 + 3 skipped, 0 failed (+9).
+- `docs cli|files|env --check`, `settings example --check`: clean (COMMANDS.md regenerated in `82fd4ab8`).
+- umtool e2e, single specs in the foreground (the prebuild's capped `next build`: 396 s, most of it waiting for
+ memory beside the integration suite):
+ - `media-surfaces.spec.ts`: 1 passed, 1 failed twice (the chain's fast build: a stub narration longer than its
+ card, then a clip outside the cached window — fixture fixes in `2d257fbe`), then 2/2 in 48.8 s.
+ - `article-iterations.spec.ts` + `projects.spec.ts` 27/27 (52.0 s); `media-draft.spec.ts` + `draft-review.spec.ts`
+ 6/6 (28.8 s); `media-draft-e.spec.ts` + `onscreen.spec.ts` 9/9 (42.3 s).
+- Editor e2e `site-delete.spec.ts` + `sites-crud.spec.ts` 22/22 (34.9 s; its prebuild's capped `next build`, 76 s).
+- umtool capped build with the corpus linked, through the heavy slot (5 GB): ok, 301 s wall (most of it waiting for
+ the slot); the link removed.
+
+Found and left:
+- `draft-youtube`'s re-mux passes `--no-xfade`, Draft everything's build. A cut built final before it would be
+ re-muxed with hard-cut offsets; Draft everything never builds final.
+- The iteration's draft steps (`onscreen`, …) and the chain's (`chain:draft-onscreen`) are two records of one run;
+ the Iterations tab shows the first beside the step list.
+- `generate`'s summary of a media draft still lists the iteration's directory files (sweep.md, report.json) above
+ the video project; harmless, not trimmed.
## Not in this release
diff --git a/umtool/app/api/articles/chain/route.ts b/umtool/app/api/articles/chain/route.ts
@@ -2,7 +2,7 @@ import { isReportId } from "yt-dlp-transcript-common/lib/report/schema";
import { cancelJob, getJob, startJob } from "@/lib/jobs";
import { ARTICLES_DIR } from "@/lib/paths";
import { planChain } from "@/lib/report/chain.mjs";
-import { chainKind, chainViewOf, errorResponse, projectsRootOf, readArticleIterations, readPolicy } from "@/lib/articles/generation";
+import { chainKind, chainViewOf, errorResponse, projectsRootOf, readArticleIterations, readPolicy, type ChainMode } from "@/lib/articles/generation";
export const dynamic = "force-dynamic";
@@ -12,9 +12,13 @@ export const dynamic = "force-dynamic";
// iteration's `steps`, so a start resumes at the first step not done, or at
// `from`. The projects root is the editor's policy's (generation.projectsRoot).
//
-// GET ?article=<id>&n=<n> -> { chain } the steps, where it resumes, its job
-// POST { article, n, from? } -> { ok, job } started
-// POST { cancel: <jobId> } -> { cancelled }
+// GET ?article=<id>&n=<n>[&mode=draft-all] -> { chain } the steps, where it resumes, its job
+// POST { article, n, from?, draftAll?, model? } -> { ok, job } started
+// POST { cancel: <jobId> } -> { cancelled }
+//
+// `draftAll` is Draft everything (release 28 M9): the chain with its
+// generation steps — each a report-draft job on `model` (else the task's
+// route) — and the fast build; a job of its own kind, resumed as the chain is.
function parse(article: unknown, n: unknown): { article: string; n: number } | string {
const a = String(article ?? "");
const k = Number(n);
@@ -23,19 +27,21 @@ function parse(article: unknown, n: unknown): { article: string; n: number } | s
return { article: a, n: k };
}
-async function chainOf(article: string, n: number) {
+async function chainOf(article: string, n: number, mode: ChainMode = "video") {
const its = await readArticleIterations(article);
const it = its.iterations.find((r) => r.n === n);
if (!it) return null;
- return chainViewOf(article, it);
+ return chainViewOf(article, it, mode);
}
+const modeOf = (v: unknown): ChainMode => (v === "draft-all" || v === true ? "draft-all" : "video");
+
export async function GET(request: Request) {
const url = new URL(request.url);
const p = parse(url.searchParams.get("article"), url.searchParams.get("n"));
if (typeof p === "string") return Response.json({ error: p }, { status: 400 });
try {
- const chain = await chainOf(p.article, p.n);
+ const chain = await chainOf(p.article, p.n, modeOf(url.searchParams.get("mode")));
if (!chain) return Response.json({ error: `no iteration i${p.n}` }, { status: 404 });
return Response.json({ chain }, { headers: { "cache-control": "no-store" } });
} catch (err) {
@@ -44,7 +50,7 @@ export async function GET(request: Request) {
}
export async function POST(request: Request) {
- const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; from?: unknown; cancel?: unknown };
+ const body = (await request.json().catch(() => ({}))) as { article?: unknown; n?: unknown; from?: unknown; cancel?: unknown; draftAll?: unknown; model?: unknown };
if (body.cancel !== undefined) {
const id = String(body.cancel);
if (!getJob(id)) return Response.json({ error: "no such job" }, { status: 404 });
@@ -60,10 +66,13 @@ export async function POST(request: Request) {
projectsRoot = undefined; // the editor unreachable: the chain reads settings.json itself
}
const from = body.from ? String(body.from) : null;
- const plan = planChain({ articlesDir: ARTICLES_DIR, article: p.article, n: p.n, from, ...(projectsRoot ? { projectsRoot } : {}) });
- if (plan.steps.length === 0) return Response.json({ error: "every step of the chain is done — pick a step to run from" }, { status: 400 });
- const job = startJob(chainKind(p.article, p.n), plan.steps);
- return Response.json({ ok: true, job: { id: job.id }, chain: await chainOf(p.article, p.n) });
+ const mode = modeOf(body.draftAll === true);
+ const model = typeof body.model === "string" && body.model.trim() ? body.model.trim() : undefined;
+ if (model && mode !== "draft-all") return Response.json({ error: "a model is Draft everything's (draftAll): the model its drafts run on" }, { status: 400 });
+ const plan = planChain({ articlesDir: ARTICLES_DIR, article: p.article, n: p.n, from, mode, ...(model ? { model } : {}), ...(projectsRoot ? { projectsRoot } : {}) });
+ if (plan.steps.length === 0) return Response.json({ error: `every step of ${mode === "draft-all" ? "Draft everything" : "the chain"} is done — pick a step to run from` }, { status: 400 });
+ const job = startJob(chainKind(p.article, p.n, mode), plan.steps);
+ return Response.json({ ok: true, job: { id: job.id }, chain: await chainOf(p.article, p.n, mode) });
} catch (err) {
return Response.json({ error: (err as Error).message }, { status: 400 });
}
diff --git a/umtool/app/api/articles/delete/route.ts b/umtool/app/api/articles/delete/route.ts
@@ -55,7 +55,12 @@ export async function POST(request: Request) {
try {
const plan: DeletePlan = n === null ? await planArticleDelete(article, opts) : await planIterationDelete(article, n, opts);
const job = runningJob();
- if (job && (n === null ? job.kind.startsWith(`chain ${article} `) : job.kind === chainKind(article, n))) {
+ if (
+ job &&
+ (n === null
+ ? job.kind.startsWith(`chain ${article} `) || job.kind.startsWith(`draft-all ${article} `)
+ : job.kind === chainKind(article, n) || job.kind === chainKind(article, n, "draft-all"))
+ ) {
plan.refusals.push({ reason: `${job.kind} is running here: cancel the chain, or wait for it`, forceable: false });
}
if (n === null) {
diff --git a/umtool/app/api/articles/draft/route.ts b/umtool/app/api/articles/draft/route.ts
@@ -0,0 +1,21 @@
+import { resolveReport } from "@/lib/report/serve.mjs";
+import { draftRuns, projectIteration } from "@/lib/articles/projectDraft";
+
+export const dynamic = "force-dynamic";
+
+// A VIDEO PROJECT'S DRAFTS (release 28 M9): the iteration it was made from
+// (the media tasks are report-draft steps on it; a project that names none
+// has no "Draft with") and each task's last run, from its `<task>-draft.json`.
+// A draft is STARTED through /api/articles/generate (the editor's
+// report-draft), never here: this route reads.
+//
+// GET ?project=<id> -> { link: {ok, article, n, status} | {ok: false, why}, runs: {<task>: summary} }
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await resolveReport(url.searchParams.get("project") ?? "");
+ if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
+ return Response.json(
+ { link: await projectIteration(r.project.dir), runs: await draftRuns(r.project.dir) },
+ { headers: { "cache-control": "no-store" } },
+ );
+}
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/components/articles/ChainPanel.tsx b/umtool/components/articles/ChainPanel.tsx
@@ -1,9 +1,9 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { badgeVariants } from "@/components/ui/badge";
-import type { ChainView } from "@/lib/articles/generation";
+import type { ChainMode, ChainView } from "@/lib/articles/generation";
// MAKE THE VIDEO for one iteration (release 27 S8): the pipeline chain's ten
// steps (lib/report/chain.mjs) as a umtool job — what each step last did, where
@@ -15,16 +15,33 @@ const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neut
failed: "blocking",
running: "open",
cancelled: "info",
+ skipped: "neutral",
};
-export default function ChainPanel({ article, n, label }: { article: string; n: number; label: string }) {
+export default function ChainPanel({
+ article,
+ n,
+ label,
+ mode = "video",
+ model,
+ autoStart = false,
+}: {
+ article: string;
+ n: number;
+ label: string;
+ mode?: ChainMode;
+ model?: string;
+ autoStart?: boolean;
+}) {
+ const draftAll = mode === "draft-all";
+ const started = useRef(false);
const [chain, setChain] = useState<ChainView | null>(null);
const [from, setFrom] = useState<string>("");
const [error, setError] = useState("");
const [sending, setSending] = useState(false);
const load = useCallback(async () => {
- const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}`, { cache: "no-store" });
+ const r = await fetch(`/api/articles/chain?article=${encodeURIComponent(article)}&n=${n}${draftAll ? "&mode=draft-all" : ""}`, { cache: "no-store" });
const b = await r.json();
if (!r.ok) {
setError(b.error ?? `HTTP ${r.status}`);
@@ -32,7 +49,7 @@ export default function ChainPanel({ article, n, label }: { article: string; n:
}
setChain(b.chain);
return b.chain as ChainView;
- }, [article, n]);
+ }, [article, n, draftAll]);
const running = chain?.job?.state === "running";
useEffect(() => {
@@ -44,11 +61,14 @@ export default function ChainPanel({ article, n, label }: { article: string; n:
return () => clearInterval(t);
}, [running, load]);
- async function start() {
+ const start = useCallback(async () => {
setError("");
setSending(true);
try {
- const r = await fetch("/api/articles/chain", { method: "POST", body: JSON.stringify({ article, n, ...(from ? { from } : {}) }) });
+ const r = await fetch("/api/articles/chain", {
+ method: "POST",
+ body: JSON.stringify({ article, n, ...(from ? { from } : {}), ...(draftAll ? { draftAll: true, ...(model ? { model } : {}) } : {}) }),
+ });
const b = await r.json();
if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
if (b.chain) setChain(b.chain);
@@ -58,7 +78,15 @@ export default function ChainPanel({ article, n, label }: { article: string; n:
} finally {
setSending(false);
}
- }
+ }, [article, n, from, draftAll, model, load]);
+
+ useEffect(() => {
+ if (!autoStart || started.current) return;
+ started.current = true;
+ void start();
+ // Once, on mount: a re-render must not start it again.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [autoStart]);
async function cancel() {
if (!chain?.job) return;
@@ -68,16 +96,31 @@ export default function ChainPanel({ article, n, label }: { article: string; n:
const startAt = from || chain?.resumeAt || "";
return (
- <section aria-label={`${label} video chain`} data-chain={label} className="mt-2 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2 text-[12px]">
+ <section
+ aria-label={`${label} ${draftAll ? "Draft everything" : "video chain"}`}
+ data-chain={label}
+ data-chain-mode={mode}
+ className="mt-2 rounded border border-[var(--color-line)] bg-[var(--color-ink)] p-2 text-[12px]"
+ >
+ {draftAll && (
+ <p className="mb-1 text-[11px] text-[var(--color-dim)]">
+ {model ? <span className="font-mono">{model}</span> : "each task's route"} · a draft that fails does not stop the chain · the build is the fast one · review the drafts before a final build
+ </p>
+ )}
{chain && (
- <ol className="grid gap-x-4 gap-y-0.5 sm:grid-flow-col sm:grid-rows-5">
+ <ol className={`grid gap-x-4 gap-y-0.5 sm:grid-flow-col ${draftAll ? "sm:grid-rows-8" : "sm:grid-rows-5"}`}>
{chain.steps.map((s, i) => (
- <li key={s.name} data-chain-step={s.name} data-step-status={s.status} className="flex items-center gap-2">
+ <li key={s.name} data-chain-step={s.name} data-step-status={s.status} title={s.detail ?? undefined} className="flex items-center gap-2">
<span className="num w-5 text-right text-[var(--color-dim)]">{i + 1}</span>
- <span className={s.name === startAt && !running ? "text-[var(--color-sel)]" : ""}>{s.label}</span>
+ <span className={s.name === startAt && !running ? "text-[var(--color-sel)]" : s.optional ? "italic" : ""}>{s.label}</span>
{s.status !== "pending" && (
<span className={badgeVariants({ variant: STATUS_VARIANT[s.status] ?? "neutral", size: "sm" })}>{s.status}</span>
)}
+ {s.optional && s.status !== "pending" && s.status !== "running" && s.detail && (
+ <span data-chain-step-detail="" className="truncate text-[11px] text-[var(--color-dim)]">
+ {s.detail}
+ </span>
+ )}
</li>
))}
</ol>
@@ -110,8 +153,8 @@ export default function ChainPanel({ article, n, label }: { article: string; n:
))}
</select>
</label>
- <Button size="sm" variant="primary" disabled={sending || (!from && !chain?.resumeAt)} onClick={start}>
- Run the chain
+ <Button size="sm" variant="primary" disabled={sending || (!from && !chain?.resumeAt)} onClick={() => void start()}>
+ {draftAll ? "Run Draft everything" : "Run the chain"}
</Button>
</>
)}
diff --git a/umtool/components/articles/IterationsTab.tsx b/umtool/components/articles/IterationsTab.tsx
@@ -29,6 +29,17 @@ const STATUS_VARIANT: Record<string, "on" | "blocking" | "open" | "info" | "neut
cancelled: "info",
};
+// The media drafts beside narrate (release 28): each a report-draft STEP on a
+// done iteration's video manifest.
+const MEDIA_TASKS: { task: string; label: string }[] = [
+ { task: "cut", label: "the cut" },
+ { task: "onscreen", label: "on-screen titles" },
+ { task: "teaser", label: "the teaser" },
+ { task: "flips", label: "flips" },
+ { task: "threads", label: "threads" },
+ { task: "youtube", label: "YouTube text" },
+];
+
// The report-draft task that made an iteration of this kind (a copy re-runs it).
const TASK_OF: Record<string, string | null> = { sweep: "sweep", "revise-report": "revise-report", "revise-video": "revise-video", research: "research" };
@@ -197,8 +208,15 @@ function IterationCard({
comparing: boolean;
onCompare: (on: boolean) => void;
}) {
- const [open, setOpen] = useState<"new" | "chain" | null>(null);
+ const [open, setOpen] = useState<"new" | "chain" | "draft-all" | null>(null);
const g = ctx.policy?.generation;
+ const routeModel = (t: string) => (g?.routes[t as keyof typeof g.routes] === "api" ? g?.models.api : g?.models.local) ?? "";
+ const [mediaTask, setMediaTask] = useState(MEDIA_TASKS[0].task);
+ const [mediaModel, setMediaModel] = useState(() => routeModel(MEDIA_TASKS[0].task));
+ const [mediaForce, setMediaForce] = useState(false);
+ const [allModel, setAllModel] = useState(() => routeModel("onscreen"));
+ // Each press of Draft everything mounts a fresh panel that starts it.
+ const [allRun, setAllRun] = useState(0);
const [copyModel, setCopyModel] = useState(() => ctx.allModels.find((m) => m !== it.model) ?? it.model);
const [narrateModel, setNarrateModel] = useState(g?.routes.narrate === "api" ? g.models.api : (g?.models.local ?? ""));
const [copyExtractor, setCopyExtractor] = useState(g?.models.extractor ?? "");
@@ -355,6 +373,53 @@ function IterationCard({
</Button>
</span>
)}
+ {done && it.hasManifest && !runningStep && (
+ <span className="flex items-center gap-1" data-media-draft={it.n}>
+ <select
+ aria-label={`draft task for ${it.label}`}
+ className={field}
+ value={mediaTask}
+ onChange={(e) => {
+ setMediaTask(e.target.value);
+ setMediaModel(routeModel(e.target.value));
+ }}
+ >
+ {MEDIA_TASKS.map((t) => (
+ <option key={t.task} value={t.task}>
+ {t.label}
+ </option>
+ ))}
+ </select>
+ <ModelSelect label={`draft model for ${it.label}`} value={mediaModel} onChange={setMediaModel} models={ctx.allModels} />
+ <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]" title="re-draft fields a model drafted; a field you wrote or edited is never replaced">
+ <input type="checkbox" checked={mediaForce} onChange={(e) => setMediaForce(e.target.checked)} aria-label={`force: re-draft drafted fields of ${it.label}`} />
+ force
+ </label>
+ <Button
+ size="sm"
+ onClick={() =>
+ void ctx.post({ task: mediaTask, article: ctx.article, iteration: it.n, model: mediaModel, ...(mediaForce ? { force: true } : {}) })
+ }
+ >
+ Draft
+ </Button>
+ </span>
+ )}
+ {done && it.reportFrom !== null && (
+ <span className="flex items-center gap-1">
+ <ModelSelect label={`Draft everything model for ${it.label}`} value={allModel} onChange={setAllModel} models={ctx.allModels} />
+ <Button
+ size="sm"
+ aria-expanded={open === "draft-all"}
+ onClick={() => {
+ setOpen("draft-all");
+ setAllRun((k) => k + 1);
+ }}
+ >
+ Draft everything
+ </Button>
+ </span>
+ )}
{done && it.reportFrom !== null && (
<Button size="sm" aria-expanded={open === "chain"} onClick={() => setOpen(open === "chain" ? null : "chain")}>
Make the video
@@ -376,6 +441,9 @@ function IterationCard({
</div>
{open === "new" && <NewIterationForm it={it} ctx={ctx} onDone={() => setOpen(null)} />}
{open === "chain" && <ChainPanel article={ctx.article} n={it.n} label={it.label} />}
+ {open === "draft-all" && (
+ <ChainPanel key={allRun} article={ctx.article} n={it.n} label={it.label} mode="draft-all" model={allModel} autoStart={allRun > 0} />
+ )}
</article>
);
}
diff --git a/umtool/components/projects/DraftPanel.tsx b/umtool/components/projects/DraftPanel.tsx
@@ -0,0 +1,355 @@
+"use client";
+
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { badgeVariants } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { DraftAlternatives, DraftBadge, announceDraftsChanged, useDrafts } from "./drafts";
+import { announceManifestChanged } from "./timelineApi";
+import type { DraftRowView, DraftRunSummary, ProjectIteration } from "@/lib/articles/projectDraft";
+
+// DRAFT WITH <MODEL> (release 28 M9): each draftable section of the cut —
+// the cut, on-screen, teaser, flips, threads, narration, YouTube — drafted by
+// a model as a `report-draft` step on the iteration the project was made
+// from (umtool's /api/articles/generate → the editor). The models are the
+// policy's, the task's route preselected; `force` re-drafts only fields a
+// model drafted (a field you wrote or edited is never replaced — its draft is
+// kept as an alternative); a per-entry task may be limited to the entries
+// ticked. While the job runs its progress shows; when it ends the page is
+// re-read: the badges, the alternatives with Use this, and what the task's
+// draft file says it wrote, skipped and refused.
+
+type Policy = { generation: { routes: Record<string, string>; models: { api: string; local: string } }; models: { api: string[]; local: string[] } };
+type JobView = { status: string; queue: { key?: string; position?: number } | null; progress: { metric: string; current: number; target: number } | null; tail: string[] };
+
+const field = "rounded border border-[var(--color-line)] bg-[var(--color-ink)] px-1.5 py-0.5 text-[12px] text-[var(--color-text)]";
+const ENDED = ["done", "failed", "cancelled"];
+
+function RunLine({ run }: { run: DraftRunSummary }) {
+ const c = run.counts;
+ const parts = [
+ c.applied ? `${c.applied} written` : "",
+ c.kept ? `${c.kept} kept as an alternative` : "",
+ c.refused ? `${c.refused} refused by a check` : "",
+ c.skipped ? `${c.skipped} skipped` : "",
+ c.none ? `${c.none} with no draft` : "",
+ ].filter(Boolean);
+ const failing = run.checks.filter((ch) => !ch.ok);
+ const problems = run.units.filter((u) => u.outcome === "refused" || u.outcome === "kept" || u.outcome === "none");
+ return (
+ <div data-draft-run={run.task} className="mt-1 text-[11px] text-[var(--color-dim)]">
+ <span>
+ last run{run.model ? <span className="font-mono"> {run.model}</span> : null}
+ {run.at ? `, ${new Date(run.at).toLocaleString()}` : ""}: {parts.join(" · ") || "nothing"}
+ </span>
+ {failing.map((ch) => (
+ <p key={ch.name} data-draft-check={ch.name} className="text-[var(--color-dirty)]">
+ check {ch.name}: {ch.detail ?? "failed"}
+ </p>
+ ))}
+ {problems.length > 0 && (
+ <ul className="list-disc pl-4">
+ {problems.slice(0, 8).map((u) => (
+ <li key={u.id} data-draft-unit={u.id} data-draft-outcome={u.outcome}>
+ <span className="font-mono">{u.label ?? u.id}</span>: {u.why ?? u.outcome}
+ </li>
+ ))}
+ {problems.length > 8 && <li>… and {problems.length - 8} more ({run.file})</li>}
+ </ul>
+ )}
+ </div>
+ );
+}
+
+function DraftRow({
+ project,
+ row,
+ link,
+ policy,
+ run,
+ runningJob,
+ view,
+ onEnded,
+}: {
+ project: string;
+ row: DraftRowView;
+ link: Extract<ProjectIteration, { ok: true }>;
+ policy: Policy | null;
+ run: DraftRunSummary | undefined;
+ runningJob: string | null;
+ view: ReturnType<typeof useDrafts>;
+ onEnded: () => void | Promise<void>;
+}) {
+ const g = policy?.generation;
+ const routeModel = g ? (g.routes[row.task] === "api" ? g.models.api : g.models.local) : "";
+ const models = policy ? [...new Set([routeModel, ...policy.models.api, ...policy.models.local].filter(Boolean))] : [];
+ const [model, setModel] = useState(routeModel);
+ useEffect(() => {
+ if (!model && routeModel) setModel(routeModel);
+ }, [routeModel, model]);
+ const [force, setForce] = useState(false);
+ const [picked, setPicked] = useState<string[]>([]);
+ const [jobId, setJobId] = useState<string | null>(runningJob);
+ const [job, setJob] = useState<JobView | null>(null);
+ const [error, setError] = useState("");
+ const [sending, setSending] = useState(false);
+
+ useEffect(() => {
+ if (runningJob) setJobId(runningJob);
+ }, [runningJob]);
+
+ // The latest callback, so the poll below depends on the job alone; and each
+ // job's end is told once (a re-render after the refresh must not tell it again).
+ const ended = useRef(onEnded);
+ ended.current = onEnded;
+ const told = useRef<string | null>(null);
+ useEffect(() => {
+ if (!jobId) return;
+ let alive = true;
+ let stop = false;
+ const tick = async () => {
+ if (stop) return;
+ try {
+ const r = await fetch(`/api/articles/job?id=${encodeURIComponent(jobId)}&tail=6`, { cache: "no-store" });
+ const b = await r.json();
+ if (!alive) return;
+ if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
+ setJob(b.job);
+ if (ENDED.includes(b.job.status)) {
+ stop = true;
+ if (told.current !== jobId) {
+ told.current = jobId;
+ void ended.current();
+ }
+ }
+ } catch (e) {
+ if (alive) setError((e as Error).message);
+ }
+ };
+ void tick();
+ const t = setInterval(tick, 2000);
+ return () => {
+ alive = false;
+ clearInterval(t);
+ };
+ }, [jobId]);
+
+ const active = !!jobId && !!job && !ENDED.includes(job.status);
+ const start = async () => {
+ setError("");
+ setSending(true);
+ try {
+ const body = {
+ task: row.task,
+ article: link.article,
+ iteration: link.n,
+ ...(model ? { model } : {}),
+ ...(force ? { force: true } : {}),
+ ...(picked.length ? { entries: picked } : {}),
+ };
+ const r = await fetch("/api/articles/generate", { method: "POST", body: JSON.stringify(body) });
+ const b = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(b.error ?? `HTTP ${r.status}`);
+ setJob(null);
+ setJobId(String(b.jobId));
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setSending(false);
+ }
+ };
+ const cancel = async () => {
+ if (!jobId) return;
+ const r = await fetch("/api/articles/job", { method: "POST", body: JSON.stringify({ cancel: jobId }) });
+ if (!r.ok) setError(((await r.json().catch(() => ({}))) as { error?: string }).error ?? `HTTP ${r.status}`);
+ };
+ const p = job?.progress;
+ const queued = job?.status === "queued" && (job.queue?.position ?? 0) > 0;
+
+ return (
+ <li data-draft-task={row.task} data-draft-job={job?.status ?? (jobId ? "asking" : "")} className="border-t border-[var(--color-line)] py-1.5 first:border-t-0">
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
+ <h3 className="text-[13px] text-[var(--color-text)]">{row.label}</h3>
+ <span className="text-[11px] text-[var(--color-dim)]">{row.writes}</span>
+ <span data-draft-state="" className="ml-auto text-[11px]">
+ {row.state}
+ </span>
+ </div>
+ {row.blocked ? (
+ <p data-draft-blocked="" className="text-[11px] text-[var(--color-dim)]">
+ {row.blocked}
+ </p>
+ ) : (
+ <div className="mt-1 flex flex-wrap items-center gap-2">
+ <Button size="sm" variant="primary" aria-label={`Draft ${row.label}`} disabled={!policy || sending || active} onClick={() => void start()}>
+ Draft with
+ </Button>
+ <select aria-label={`model for ${row.label}`} className={`${field} font-mono`} value={model} onChange={(e) => setModel(e.target.value)} disabled={!policy}>
+ {models.map((m) => (
+ <option key={m} value={m}>
+ {m}
+ {m === routeModel ? " (route)" : ""}
+ </option>
+ ))}
+ </select>
+ <label className="flex items-center gap-1 text-[11px] text-[var(--color-dim)]">
+ <input type="checkbox" checked={force} onChange={(e) => setForce(e.target.checked)} aria-label={`force: re-draft ${row.label}`} />
+ force — re-drafts only what a model drafted; a field you wrote or edited is never replaced
+ </label>
+ {row.entries && row.entries.length > 0 && (
+ <details className="text-[11px]">
+ <summary className="cursor-pointer text-[var(--color-dim)]">{picked.length ? `${picked.length} of ${row.entries.length} entries` : `every entry (${row.entries.length})`}</summary>
+ <div className="mt-1 flex max-h-40 flex-col gap-0.5 overflow-auto">
+ {row.entries.map((e) => (
+ <label key={e.id} className="flex items-center gap-1">
+ <input
+ type="checkbox"
+ aria-label={`only ${e.id} (${row.label})`}
+ checked={picked.includes(e.id)}
+ onChange={(ev) => setPicked(ev.target.checked ? [...picked, e.id] : picked.filter((x) => x !== e.id))}
+ />
+ <span className="font-mono">{e.label}</span>
+ </label>
+ ))}
+ </div>
+ </details>
+ )}
+ </div>
+ )}
+ {jobId && job && !ENDED.includes(job.status) && (
+ <div data-draft-progress={row.task} className="mt-1 flex flex-wrap items-center gap-2 text-[11px]">
+ <span role="status" className="text-[var(--color-dirty)]">
+ {queued ? `queued, ${job.queue?.position} ahead on ${job.queue?.key}` : job.status}
+ {p ? ` — ${p.metric} ${p.current}/${p.target}` : ""}
+ </span>
+ {job.tail.length > 0 && <span className="truncate font-mono text-[var(--color-dim)]">{job.tail[job.tail.length - 1]}</span>}
+ <Button size="sm" variant="destructive" aria-label={`Cancel the ${row.label} draft`} onClick={() => void cancel()}>
+ Cancel
+ </Button>
+ </div>
+ )}
+ {jobId && job && ENDED.includes(job.status) && (
+ <p data-draft-ended={job.status} className={`mt-1 text-[11px] ${job.status === "done" ? "text-[var(--color-dim)]" : "text-[var(--color-bad)]"}`}>
+ the draft {job.status === "done" ? "is done" : job.status}
+ {job.status !== "done" && job.tail.length ? `: ${job.tail.filter((l) => !l.startsWith("@@")).slice(-1)[0] ?? ""}` : ""}
+ </p>
+ )}
+ {run && <RunLine run={run} />}
+ {row.address && (
+ <div className="mt-1">
+ <DraftBadge address={row.address} view={view.view} act={view.act} compact />
+ <DraftAlternatives address={row.address} view={view.view} act={view.act} />
+ </div>
+ )}
+ {!row.address && run && run.alternatives > 0 && (
+ <Link href={`/browse/${project}/review`} className="text-[11px] text-[var(--color-sel)] hover:underline">
+ {run.alternatives} alternative(s) kept — review them
+ </Link>
+ )}
+ {error && (
+ <p role="alert" className="mt-1 text-[11px] text-[var(--color-bad)]">
+ {error}
+ </p>
+ )}
+ </li>
+ );
+}
+
+export default function DraftPanel({
+ project,
+ link,
+ rows,
+ runs: initialRuns,
+}: {
+ project: string;
+ link: ProjectIteration;
+ rows: DraftRowView[];
+ runs: Partial<Record<string, DraftRunSummary>>;
+}) {
+ const router = useRouter();
+ const view = useDrafts(project);
+ const [policy, setPolicy] = useState<Policy | null>(null);
+ const [policyError, setPolicyError] = useState("");
+ const [runs, setRuns] = useState(initialRuns);
+ const [running, setRunning] = useState<Record<string, string>>(link.ok ? link.running : {});
+
+ useEffect(() => {
+ if (!link.ok) return;
+ let alive = true;
+ void (async () => {
+ const r = await fetch("/api/articles/policy", { cache: "no-store" }).catch(() => null);
+ const b = r ? await r.json().catch(() => ({})) : {};
+ if (!alive) return;
+ if (r?.ok && b.policy) setPolicy(b.policy as Policy);
+ else setPolicyError(b.error ?? "the editor did not answer");
+ })();
+ return () => {
+ alive = false;
+ };
+ }, [link.ok]);
+
+ // A draft ended: the manifest changed under every section — re-read it all.
+ const onEnded = useCallback(async (): Promise<void> => {
+ const r = await fetch(`/api/articles/draft?project=${encodeURIComponent(project)}`, { cache: "no-store" }).catch(() => null);
+ if (r?.ok) {
+ const b = await r.json();
+ setRuns(b.runs ?? {});
+ if (b.link?.ok) setRunning(b.link.running ?? {});
+ }
+ announceManifestChanged(project);
+ announceDraftsChanged(project);
+ router.refresh();
+ }, [project, router]);
+
+ return (
+ <section aria-label="draft with a model" data-draft-panel={link.ok ? `${link.article}/i${link.n}` : ""} className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2">
+ <div className="mb-1 flex flex-wrap items-baseline gap-3">
+ <h2 className="micro">draft</h2>
+ {link.ok && (
+ <span className="text-[11px] text-[var(--color-dim)]">
+ steps on{" "}
+ <Link href={`/articles/${link.article}?tab=iterations`} className="font-mono text-[var(--color-sel)] hover:underline">
+ {link.article} i{link.n}
+ </Link>
+ </span>
+ )}
+ {link.ok && (
+ <span className={badgeVariants({ variant: "info", size: "sm" })}>a final build refuses a draft nobody approved</span>
+ )}
+ </div>
+ {!link.ok ? (
+ <p data-draft-unlinked="" className="text-[12px] text-[var(--color-dim)]">
+ {link.why}
+ </p>
+ ) : link.status !== "done" ? (
+ <p data-draft-unlinked="" className="text-[12px] text-[var(--color-dim)]">
+ {link.article} i{link.n} is {link.status}: a draft runs over a done iteration
+ </p>
+ ) : (
+ <>
+ {policyError && (
+ <p role="alert" className="text-[12px] text-[var(--color-bad)]">
+ {policyError}: drafting needs the editor
+ </p>
+ )}
+ <ul>
+ {rows.map((row) => (
+ <DraftRow
+ key={row.task}
+ project={project}
+ row={row}
+ link={link}
+ policy={policy}
+ run={runs[row.task]}
+ runningJob={running[row.task] ?? null}
+ view={view}
+ onEnded={onEnded}
+ />
+ ))}
+ </ul>
+ </>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx
@@ -23,6 +23,8 @@ import { narrationsOf } from "umtool-report-to-video/narration";
import { draftedFields, isCodeDraft } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
import { readAlternatives } from "@/lib/report/drafts.mjs";
import DeliverSection from "./DeliverSection";
+import DraftPanel from "./DraftPanel";
+import { draftRowsOf, draftRuns, projectIteration } from "@/lib/articles/projectDraft";
import FetchUnfetchedButton from "./FetchUnfetchedButton";
import OnscreenSection from "./OnscreenSection";
import PodcastExport from "./PodcastExport";
@@ -156,6 +158,10 @@ export default async function ReportProject({
// (A field a code path made — the converter's timeline — is not a draft to review.)
const draftedCount = draftedFields(m).filter((d) => !isCodeDraft(d.provenance)).length;
const alternativesCount = (await readAlternatives(project.dir)).length;
+ // "Draft with" (release 28 M9): the iteration the project was made from, and
+ // each media task's last run here.
+ const draftLink = await projectIteration(project.dir);
+ const draftRunsNow = draftLink.ok ? await draftRuns(project.dir) : {};
// Provenance splits by SHAPE: a scalar or a URL stays in the table; a long
// string, or one with a newline, is prose the author wrote and reads as a
@@ -477,6 +483,13 @@ export default async function ReportProject({
entries={entries.map((e) => ({ id: e.id, kind: e.kind }))}
/>
+ {/* --- drafting it ----------------------------------------------- */}
+ {/* Each draftable section drafted by a model, as a step on the
+ iteration the project was made from. After the build chain (a
+ draft changes what the next build makes), before the sections it
+ writes into. */}
+ <DraftPanel project={project.id} link={draftLink} rows={draftRowsOf(m as Record<string, unknown>)} runs={draftRunsNow} />
+
{/* --- what is drawn over it --------------------------------------- */}
{/* The on-screen panel: its settings, its words and a live preview of
both. After the build chain, because "re-render on-screen" is a run
diff --git a/umtool/docs/authoring.md b/umtool/docs/authoring.md
@@ -117,6 +117,7 @@ sweep** makes the report once it is in (OPERATING.md, "Research runs").
```sh
pnpm ops report-draft --json '{"task":"sweep","article":"<id>","question":"…","channels":["<slug>"]}' --wait
umtool chain <id> <n> # the iteration to a video and a podcast
+umtool chain <id> <n> --draft-all # Draft everything: the media drafts, voices, the fast cut, the podcast
pnpm ops report-draft --json '{"task":"revise-video","article":"<id>","iteration":<n>,"feedback":"…"}' --wait
pnpm ops report-draft --json '{"task":"narrate","article":"<id>","iteration":<n>}' --wait
```
@@ -137,6 +138,22 @@ pnpm ops report-draft --json '{"task":"narrate","article":"<id>","iteration":<n>
is removed. The manifest before it is kept in
`revisions/<stamp>-auto-before-narration.manifest.json`, the draft in
`narration-draft.json`.
+- **The media drafts** (cut, on-screen, teaser, flips, threads, narration,
+ YouTube) each draft fields of the iteration's cut, marked as drafts: the
+ project page's **draft** section (**Draft with** a model per task), the
+ Iterations tab, or `pnpm ops report-draft` with `iteration`. A field you
+ wrote or edited is never replaced; the draft waits in `<task>-draft.json`
+ as an alternative (**Use this**). `force` re-drafts a model's field only.
+ The limits per task are OPERATING.md's table ("Generate and iterate").
+- **Draft everything** (`umtool chain <id> <n> --draft-all [--model M]`)
+ drafts them all in the chain's order, then voices, builds the fast cut and
+ the podcast, then drafts the YouTube text and writes `out/youtube.txt`. A
+ failed draft does not stop it; flips and threads need the deck, and one
+ panel only.
+- **Review every draft before a final build:** `/browse/<project>/review`,
+ approve or reject with a note. A fast build warns; `--preset final`
+ refuses an unapproved or rejected draft (`--drafts-unreviewed` overrides
+ the unapproved).
- **Then review it as a hand-made cut:** `umtool check`, steps 4–6, and a fast
pass watched end to end. A generated window is the cue span plus its pad, so
widen or lock it as in step 4.
diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs
@@ -20,6 +20,7 @@ import { spawn, spawnSync } from "node:child_process";
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync, statSync } from "node:fs";
import path from "node:path";
import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs";
+import { applyDraft, draftedOf, isCodeDraft, makeProvenance, ownerOf } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
import { fileURLToPath } from "node:url";
const PORT = portFor("EDITOR_STUB_PORT");
@@ -112,6 +113,9 @@ function writeWindow(dir, name, seconds) {
// `iteration` continues a research run, as the editor does.
// Sentinels: a question or feedback containing "slow" keeps running until
// cancelled; feedback "refuse" is refused (400) as the editor refuses.
+// A media draft (release 28) runs the real task over the kit's article
+// (mdraft; startMediaDraft), canned over the surfaces' (msurf;
+// startCannedDraft) — every isStepTask step answered.
const ARTICLES = process.env.ARTICLES_DIR ?? "";
const GEN_PROJECTS = process.env.E2E_GEN_PROJECTS ?? "";
const PRESETS = {
@@ -432,10 +436,150 @@ function startMediaDraft(body, id) {
return { jobId: id, iteration: n };
}
+// The surfaces' article (release 28 M9, media-surfaces-fixture.mjs) is drafted
+// CANNED, every media task: its fixed value written through applyDraft —
+// the mark, the operator's field never replaced (kept as an alternative), a
+// field already written skipped unless force — and a `<task>-draft.json`
+// beside the manifest in the scaffold's shape, the step recorded on the
+// iteration and the job's progress reported as `entries`. What each task
+// does on msurf's cuts (no deck, no teaser entry):
+// cut its two clips swapped done
+// onscreen a title and subtitle per clip (entries) done
+// teaser refused by a check (the stub's) failed
+// flips, threads no deck to draw on failed
+// narrate a line on each card that has none done
+// youtube a title and a summary done
+const CANNED_ARTICLES = new Set(["msurf"]);
+const MEDIA_TASKS = new Set(["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube"]);
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+
+function cannedUnits(task, m, body) {
+ const tl = m.timeline ?? [];
+ const pick = (es) => (Array.isArray(body.entries) ? es.filter((e) => body.entries.includes(e.id)) : es);
+ switch (task) {
+ case "cut": {
+ const clips = tl.filter((e) => e.type === "clip").map((e) => e.id);
+ const at = clips.slice(0, 2).map((id) => tl.findIndex((e) => e.id === id));
+ const order = [...tl];
+ if (at.length === 2) [order[at[0]], order[at[1]]] = [order[at[1]], order[at[0]]];
+ return [{ id: "cut", target: { field: "timeline" }, value: order }];
+ }
+ case "onscreen":
+ return pick(tl.filter((e) => e.type === "clip")).map((e) => ({
+ id: e.id,
+ target: { entry: e.id, field: "onscreen" },
+ value: { title: `What ${e.id} shows`, subtitle: "From the county vote" },
+ }));
+ case "teaser":
+ return [{ id: "teaser", target: { entry: "teaser", field: "lines" }, value: ["The county", "The vote"], hard: ["(the stub) 2 lines: a teaser has 3 to 5"] }];
+ case "flips":
+ case "threads":
+ return { refused: `the cut has no on-screen deck (render.chrome) to draw the ${task} on` };
+ case "narrate":
+ return pick(tl.filter((e) => e.type === "card")).map((e) => ({
+ id: e.id,
+ target: { entry: e.id, field: "narration" },
+ value: { text: `${e.heading ?? "This part"}, as the channel told it.` },
+ }));
+ case "youtube":
+ return [{ id: "youtube", target: { field: "publish.youtube" }, value: { title: "The county vote, as the channel told it", description: "The channel said it twice, and the county voted." } }];
+ }
+ return [];
+}
+
+function readFieldOf(m, t) {
+ if (t.entry) return (m.timeline ?? []).find((e) => e.id === t.entry)?.[t.field];
+ if (t.field === "timeline") return m.timeline;
+ if (t.field === "publish.youtube") return m.publish?.youtube;
+ return undefined;
+}
+
+function cannedRun(job, body) {
+ const { task, article, n } = job;
+ const it = readIt(article, n);
+ const dir = it.projectDir;
+ const file = path.join(dir, "video.manifest.json");
+ const m = JSON.parse(readFileSync(file, "utf8"));
+ const model = body.model ?? generation.models.local;
+ const at = new Date().toISOString();
+ const draftFile = path.join(dir, task === "narrate" ? "narration-draft.json" : `${task}-draft.json`);
+ const earlier = existsSync(draftFile) ? (JSON.parse(readFileSync(draftFile, "utf8")).alternatives ?? []) : [];
+ const units = {};
+ const alternatives = [];
+ let applied = 0;
+ let summary;
+ const planned = cannedUnits(task, m, body);
+ if (!Array.isArray(planned)) {
+ summary = planned.refused;
+ } else {
+ planned.forEach((u, i) => {
+ job.progress = { metric: "entries", initial: 0, current: i, target: planned.length };
+ const has = readFieldOf(m, u.target) !== undefined && !(u.target.field === "timeline" && isCodeDraft(draftedOf(m, u.target)));
+ if (has && !body.force) {
+ units[u.id] = { target: u.target, skipped: `the field has a value (${ownerOf(m, u.target)}'s): force re-drafts a draft` };
+ return;
+ }
+ const chosen = { value: u.value, hard: u.hard ?? [], soft: [] };
+ units[u.id] = { target: u.target, attempts: [chosen], chosen };
+ if (chosen.hard.length) return;
+ const provenance = makeProvenance({ task, model, at, iteration: n, attempt: 1 });
+ const force = !!body.force || (u.target.field === "timeline" && isCodeDraft(draftedOf(m, u.target)));
+ const r = applyDraft(m, { ...u.target, value: u.value, provenance, force });
+ units[u.id].applied = r.applied ? "applied" : r.reason;
+ // As narrate's afterApply: a narrated card is as long as its words.
+ if (r.applied && u.target.field === "narration") for (const e of m.timeline) if (e.id === u.target.entry) e.seconds = "auto";
+ if (r.applied) applied++;
+ else alternatives.push({ target: u.target, value: u.value, provenance, reason: r.reason });
+ });
+ job.progress = { metric: "entries", initial: 0, current: planned.length, target: planned.length };
+ if (applied) writeFileSync(file, JSON.stringify(m, null, 2) + "\n");
+ const refused = Object.values(units).filter((u) => u.chosen?.hard?.length).length;
+ summary =
+ applied || alternatives.length
+ ? `${applied} ${task} field(s) drafted${alternatives.length ? `, ${alternatives.length} as alternatives (see ${path.basename(draftFile)})` : ""}`
+ : `no ${task} drafted (see ${path.basename(draftFile)})${refused ? `: ${refused} refused by a check` : ""}`;
+ }
+ const ok = applied > 0 || alternatives.length > 0;
+ writeFileSync(
+ draftFile,
+ JSON.stringify(
+ { task, model, at, article, iteration: n, units, checks: [{ name: task, ok, detail: summary }], alternatives: [...earlier, ...alternatives].slice(-5) },
+ null,
+ 2,
+ ) + "\n",
+ );
+ const status = ok ? "done" : "failed";
+ const cur = readIt(article, n);
+ patchIt(article, n, { steps: cur.steps.map((s) => (s.jobId === job.id ? { ...s, status, endedAt: at, minutes: 0.1, detail: summary } : s)) });
+ job.status = status;
+ job.log.push(`${task}: ${summary}`, `@@report-draft ${JSON.stringify({ article, iteration: n, task, status, summary })}`);
+}
+
+function startCannedDraft(body, id) {
+ const { task, article } = body;
+ const n = body.iteration;
+ const it = readIt(article, n);
+ if (it.status !== "done") throw new Error(`"${article}" i${n} is ${it.status}: a ${task} draft runs over a done iteration`);
+ const model = body.model ?? generation.models.local;
+ patchIt(article, n, { steps: [...it.steps, { task, model, status: "running", startedAt: new Date().toISOString(), jobId: id }] });
+ const job = { id, article, n, task, status: "queued", log: [`report-draft ${task} ${article} i${n} (stub: canned)`], timers: [] };
+ draftJobs.set(id, job);
+ job.timers.push(
+ setTimeout(() => {
+ job.status = "running";
+ job.progress = { metric: "entries", initial: 0, current: 0, target: 1 };
+ job.log.push(`drafting the ${task} (stub)`);
+ }, 400),
+ );
+ job.timers.push(setTimeout(() => cannedRun(job, body), 1600));
+ return { jobId: id, iteration: n };
+}
+
function startDraft(body) {
const { task, article } = body;
const now = new Date().toISOString();
const id = `stub-draft-${nextJob++}`;
+ if (MEDIA_TASKS.has(task) && CANNED_ARTICLES.has(article)) return startCannedDraft(body, id);
if (MEDIA_RUN.has(task)) return startMediaDraft(body, id);
let n;
if (task === "narrate") {
@@ -490,7 +634,7 @@ function cancelDraft(id) {
job.log.push("cancelled");
job.child?.kill();
const it = readIt(job.article, job.n);
- if (job.task === "narrate" || MEDIA_RUN.has(job.task)) {
+ if (job.task === "narrate" || MEDIA_RUN.has(job.task) || MEDIA_TASKS.has(job.task)) {
patchIt(job.article, job.n, { steps: it.steps.map((s) => (s.jobId === id ? { ...s, status: "cancelled" } : s)) });
} else {
patchIt(job.article, job.n, { status: "cancelled", endedAt: new Date().toISOString() });
@@ -587,7 +731,13 @@ function generationRoute(req, res, url, auth) {
const tail = Number(url.searchParams.get("tail") ?? 0);
return json(res, 200, {
ok: true,
- job: { id: j.id, kind: j.kind ?? "report-draft", status: j.status, ...(j.status === "queued" ? { queue: { key: "draft:api", position: 1, queued: 2 } } : {}) },
+ job: {
+ id: j.id,
+ kind: j.kind ?? "report-draft",
+ status: j.status,
+ ...(j.status === "queued" ? { queue: { key: "draft:api", position: 1, queued: 2 } } : {}),
+ ...(j.progress ? { progress: j.progress } : {}),
+ },
...(tail ? { tail: j.log.slice(-tail) } : {}),
});
}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -25,6 +25,7 @@ import { songCapabilities } from "./song-capabilities.mjs";
import { makeSitesFixture } from "./sites-fixture.mjs";
import { makeIterationsFixture } from "./iterations-fixture.mjs";
import { makeMediaDraftFixture } from "./media-draft-fixture.mjs";
+import { makeMediaSurfacesFixture } from "./media-surfaces-fixture.mjs";
import { makeDeleteFixture } from "./delete-fixture.mjs";
import { makeDraftReviewFixture } from "./draft-review-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
@@ -1922,6 +1923,8 @@ const { sites: SITES, articles: ARTICLES } = makeSitesFixture({ dest, reports, c
makeIterationsFixture({ dest, articles: ARTICLES });
// Release 28: the media drafts' article (mdraft), one iteration per task.
makeMediaDraftFixture({ dest, articles: ARTICLES });
+// Release 28 M9: "Draft with" and Draft everything (msurf), drafted canned by the stub.
+makeMediaSurfacesFixture({ dest, articles: ARTICLES, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// The release 27 follow-up's deletes: psi (in the making) and
// reports/delete-fixture (a project with two takes); article-delete.spec.ts
// writes its draft (omega) itself.
diff --git a/umtool/e2e/fixtures/media-surfaces-fixture.mjs b/umtool/e2e/fixtures/media-surfaces-fixture.mjs
@@ -0,0 +1,83 @@
+// What media-surfaces.spec.ts drafts on (release 28 M9): `msurf`, an article
+// in the making whose two done iterations each have a video project that
+// builds offline (two clips inside the cached 0–9 s window the build
+// fixtures share, its fetchPad included; a title card and a chapter card; no
+// deck) — the chain recorded done to its
+// manifest, so Draft everything starts at its first draft:
+//
+// articles/msurf/iterations/{1,2} sweep, qwen3:8b, done; current … manifest done
+// gen-projects/msurf/i1/ "Draft with" on the project page: the cut
+// (the converter's order), on-screen, and an
+// operator's publish.youtube (forced: an alternative)
+// gen-projects/msurf/i2/ Draft everything on the Iterations tab
+//
+// The editor stub drafts this article's media CANNED (editor-stub.mjs
+// cannedDraft): every media task, its field written through applyDraft with its
+// mark and a `<task>-draft.json` beside it. Synthetic: the fixture's own
+// channel and invented lines.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const MEDIA_SURFACES_ARTICLE = "msurf";
+const AT = "2026-10-13T10:00:00.000Z";
+const CODE = { task: "convert", model: "code", at: "2026-10-13T00:00:00.000Z", attempt: 1 };
+const CITE = (start, end, quote) => ({ kind: "video", channel: "testchan", id: "vid1", start, end, quote, speaker: "Test Channel", date: "2024-03-15" });
+
+const put = (file, value) => {
+ mkdirSync(path.dirname(file), { recursive: true });
+ writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2) + "\n");
+};
+
+/**
+ * @param {{ dest: string, articles: string, manifest: Function, cachedWindow: string }} o
+ * `manifest` is make-fixture's manifest(slug, title, provenance, timeline);
+ * `cachedWindow` the vid1 0-9 s window the build fixtures share.
+ */
+export function makeMediaSurfacesFixture({ dest, articles, manifest, cachedWindow }) {
+ const report = {
+ format: "archilyzer-report",
+ version: 1,
+ id: MEDIA_SURFACES_ARTICLE,
+ kind: "sweep",
+ title: "The county vote, as the channel told it",
+ citations: { c01: CITE(3, 4.5, "and because"), c02: CITE(4.5, 6, "another whole sentence") },
+ sections: [{ id: "s1", title: "The county", body: "She said it [and because](cite:c01), then [another whole sentence](cite:c02)." }],
+ };
+ for (const n of [1, 2]) {
+ const dir = path.join(articles, MEDIA_SURFACES_ARTICLE, "iterations", String(n));
+ const project = path.join(dest, "gen-projects", MEDIA_SURFACES_ARTICLE, `i${n}`);
+ put(path.join(dir, "iteration.json"), {
+ format: "archilyzer-iteration",
+ version: 1,
+ article: MEDIA_SURFACES_ARTICLE,
+ n,
+ kind: "sweep",
+ parent: null,
+ copyOf: null,
+ model: "qwen3:8b",
+ question: "What did the channel say about the county vote?",
+ scope: { channels: ["testchan"] },
+ status: "done",
+ usage: {},
+ steps: ["current", "windows", "prepare", "posts", "manifest"].map((s) => ({ task: `chain:${s}`, status: "done", startedAt: AT, endedAt: AT, minutes: 0.1, detail: "the fixture's" })),
+ projectDir: project,
+ createdAt: AT,
+ updatedAt: AT,
+ endedAt: AT,
+ });
+ put(path.join(dir, "report.json"), report);
+ const m = manifest(`msurf-i${n}`, "The county vote", { siteOrigin: "https://archive.example" }, [
+ { type: "card", id: "title", style: "title", seconds: 4, heading: "The county vote" },
+ { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 4.5, cite: 3, section: 0, lock: true, quote: "and because" },
+ { type: "card", id: "k01", style: "chapter", seconds: 3, heading: "The county" },
+ { type: "clip", id: "c02", video: "vid1", start: 4.5, end: 6.0, cite: 4.5, section: 0, lock: true, quote: "another whole sentence" },
+ ]);
+ m.drafted = { timeline: CODE };
+ // i1's YouTube text is the operator's: a forced draft is kept as an alternative.
+ if (n === 1) m.publish = { youtube: { title: "The operator's own title", description: "Written by hand." } };
+ put(path.join(project, "video.manifest.json"), m);
+ put(path.join(project, "report.json"), report);
+ mkdirSync(path.join(project, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(project, "out", "clips-raw", path.basename(cachedWindow)));
+ }
+}
diff --git a/umtool/e2e/media-surfaces.spec.ts b/umtool/e2e/media-surfaces.spec.ts
@@ -0,0 +1,144 @@
+import { test, expect } from "@playwright/test";
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { WARM_TIMEOUT, warm } from "./warm";
+
+// ---------------------------------------------------------------------------
+// Release 28 M9, the surfaces of the media drafts:
+// - "Draft with <model>" per section on a project page: the job asked of the
+// editor (its model, its entries, its force), followed to its end; then
+// the section re-read — the badge, the last run, the alternative kept for
+// the operator's field and Use this; a project made from no iteration
+// offers none, and says why;
+// - Draft everything on the Iterations tab: the chain with its drafts, a
+// refused draft recorded failed and passed, the panels skipped, the
+// voices, the fast build and the podcast, then the YouTube draft and
+// out/youtube.txt.
+// The editor stub drafts this article canned (fixtures/editor-stub.mjs
+// cannedDraft); the build, the voices (the stub's tone) and the podcast are
+// real. Fixture: fixtures/media-surfaces-fixture.mjs.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const STUB_LOG = path.join(FIXTURE, "editor-stub.requests.json");
+const ARTICLE = "msurf";
+const PROJECT = `gen-projects/${ARTICLE}/i1`;
+const projectDir = (n: number) => path.join(FIXTURE, "gen-projects", ARTICLE, `i${n}`);
+const manifestOf = (n: number) => JSON.parse(readFileSync(path.join(projectDir(n), "video.manifest.json"), "utf8"));
+const asked = () =>
+ (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; article?: string; [k: string]: unknown }[]).filter((r) => r.route === "report-draft" && r.article === ARTICLE);
+
+test.beforeAll(async ({ playwright }) => {
+ test.setTimeout(WARM_TIMEOUT);
+ await warm(playwright, [`/browse/${PROJECT}`, `/api/articles/draft?project=${encodeURIComponent(PROJECT)}`, "/api/articles/policy", `/articles/${ARTICLE}?tab=iterations`]);
+});
+
+test("Draft with <model> per section: the job followed, the badge, the last run, an alternative and Use this", async ({ page }) => {
+ test.setTimeout(180_000);
+ await page.goto(`/browse/${PROJECT}`);
+ const panel = page.getByRole("region", { name: "draft with a model" });
+ await expect(panel).toHaveAttribute("data-draft-panel", `${ARTICLE}/i1`);
+ // Seven sections; flips and threads say why they cannot draft on this cut.
+ await expect(panel.locator("[data-draft-task]")).toHaveCount(7);
+ await expect(panel.locator("[data-draft-task='flips'] [data-draft-blocked]")).toContainText("this cut has none (render.chrome)");
+ const cut = panel.locator("[data-draft-task='cut']");
+ // The policy's models, the route's preselected.
+ await expect(cut.getByRole("combobox", { name: "model for the cut" })).toHaveValue("qwen3:8b");
+
+ // The cut: drafted over the converter's order; its badge and its review.
+ await cut.getByRole("combobox", { name: "model for the cut" }).selectOption("claude-sonnet-5-5");
+ await cut.getByRole("button", { name: "Draft the cut" }).click();
+ await expect(cut).toHaveAttribute("data-draft-job", "done", { timeout: 30_000 });
+ expect(asked().at(-1)).toMatchObject({ task: "cut", article: ARTICLE, iteration: 1, model: "claude-sonnet-5-5", authorization: "Bearer umtool-e2e-token" });
+ await expect(cut.locator("[data-draft-badge='cut/*/timeline'] [data-draft-by]")).toHaveText("drafted by claude-sonnet-5-5");
+ await expect(cut.locator("[data-draft-run='cut']")).toContainText("1 written");
+ expect(manifestOf(1).timeline.filter((e: { type: string }) => e.type === "clip").map((e: { id: string }) => e.id)).toEqual(["c02", "c01"]);
+ await cut.locator("[data-draft-badge='cut/*/timeline']").getByRole("button", { name: "Approve" }).click();
+ await expect(cut.locator("[data-draft-badge='cut/*/timeline']")).toHaveAttribute("data-state", "approved");
+
+ // On-screen, limited to the entry ticked.
+ const onscreen = panel.locator("[data-draft-task='onscreen']");
+ await onscreen.locator("summary").click();
+ await onscreen.getByRole("checkbox", { name: "only c01 (on-screen titles)" }).check();
+ await onscreen.getByRole("button", { name: "Draft on-screen titles" }).click();
+ await expect(onscreen).toHaveAttribute("data-draft-job", "done", { timeout: 30_000 });
+ expect(asked().at(-1)).toMatchObject({ task: "onscreen", entries: ["c01"] });
+ await expect(onscreen.locator("[data-draft-run='onscreen']")).toContainText("1 written");
+ const m = manifestOf(1);
+ const c01 = m.timeline.find((e: { id: string }) => e.id === "c01");
+ expect(c01.onscreen).toEqual({ title: "What c01 shows", subtitle: "From the county vote" });
+ expect(c01.drafted.onscreen).toMatchObject({ task: "onscreen", model: "qwen3:8b", iteration: 1 });
+ expect(m.timeline.find((e: { id: string }) => e.id === "c02").onscreen).toBeUndefined();
+
+ // YouTube: the operator's text. Unforced, nothing to draft; forced, the
+ // draft is kept as an alternative, and Use this writes it.
+ const yt = panel.locator("[data-draft-task='youtube']");
+ await yt.getByRole("button", { name: "Draft YouTube text" }).click();
+ await expect(yt).toHaveAttribute("data-draft-job", "failed", { timeout: 30_000 });
+ await expect(yt.locator("[data-draft-run='youtube']")).toContainText("1 skipped");
+ await yt.getByRole("checkbox", { name: "force: re-draft YouTube text" }).check();
+ await yt.getByRole("button", { name: "Draft YouTube text" }).click();
+ await expect(yt.locator("[data-draft-run='youtube']")).toContainText("1 kept as an alternative", { timeout: 30_000 });
+ expect(asked().at(-1)).toMatchObject({ task: "youtube", force: true });
+ expect(manifestOf(1).publish.youtube.title).toBe("The operator's own title");
+ const alt = yt.locator("[data-draft-alternatives='youtube/*/publish.youtube']");
+ await expect(alt).toContainText("The county vote, as the channel told it");
+ await alt.getByRole("button", { name: "Use this" }).click();
+ await expect.poll(() => manifestOf(1).publish.youtube.title, { timeout: 15_000 }).toBe("The county vote, as the channel told it");
+ // Taken, it is the operator's: no mark.
+ expect(manifestOf(1).drafted?.["publish.youtube"]).toBeUndefined();
+
+ // A project made from no iteration offers no draft, and says why.
+ await page.goto("/browse/reports/youtube-fixture");
+ await expect(page.getByRole("region", { name: "draft with a model" }).locator("[data-draft-unlinked]")).toContainText("not made from an article's iteration");
+});
+
+test("Draft everything: every draft in order on the model chosen, a refused one passed, the panels skipped, then the fast build, the podcast and out/youtube.txt", async ({ page }) => {
+ test.setTimeout(420_000);
+ await page.goto(`/articles/${ARTICLE}?tab=iterations`);
+ const two = page.locator("[data-iteration='2']");
+ // The Iterations tab's per-step drafts, beside Narrate.
+ await expect(two.getByRole("combobox", { name: "draft task for i2" })).toBeVisible();
+ await two.getByRole("combobox", { name: "Draft everything model for i2" }).selectOption("qwen3:8b");
+ const before = asked().length;
+ await two.getByRole("button", { name: "Draft everything" }).click();
+ const chain = page.getByRole("region", { name: "i2 Draft everything" });
+ await expect(chain.locator("[data-chain-step]")).toHaveCount(15);
+ const step = (name: string) => chain.locator(`[data-chain-step='${name}']`);
+ await expect(step("draft-youtube")).toHaveAttribute("data-step-status", "done", { timeout: 360_000 });
+ await expect(chain.locator("[data-chain-job]")).toHaveAttribute("data-chain-job", "done", { timeout: 30_000 });
+ for (const [name, status] of [
+ ["current", "done"],
+ ["manifest", "done"],
+ ["draft-cut", "done"],
+ ["draft-onscreen", "done"],
+ ["draft-teaser", "failed"],
+ ["draft-flips", "skipped"],
+ ["draft-threads", "skipped"],
+ ["draft-narrate", "done"],
+ ["voices", "done"],
+ ["video", "done"],
+ ["podcast", "done"],
+ ["draft-youtube", "done"],
+ ] as const) {
+ await expect(step(name), name).toHaveAttribute("data-step-status", status);
+ }
+ await expect(step("draft-flips")).toContainText("no on-screen deck");
+ // The drafts the editor was asked for, in order, on the model chosen (flips
+ // and threads never asked: no deck to draw them on).
+ const drafts = asked().slice(before);
+ expect(drafts.map((r) => r.task)).toEqual(["cut", "onscreen", "teaser", "narrate", "youtube"]);
+ expect(drafts.every((r) => r.model === "qwen3:8b" && r.iteration === 2)).toBe(true);
+ const m = manifestOf(2);
+ expect(m.drafted.timeline).toMatchObject({ task: "cut", model: "qwen3:8b" });
+ expect(m.timeline.find((e: { id: string }) => e.id === "k01").narration.text).toBe("The county, as the channel told it.");
+ expect(m.publish.youtube.title).toBe("The county vote, as the channel told it");
+ // The fast build, the podcast and the YouTube text are on disk.
+ const out = path.join(projectDir(2), "out");
+ expect(existsSync(path.join(out, "msurf-i2.mp4"))).toBe(true);
+ const text = readFileSync(path.join(out, "youtube.txt"), "utf8");
+ expect(text.split("\n")[0]).toBe("The county vote, as the channel told it");
+ expect(text).toContain("Sources");
+});
diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts
@@ -22,7 +22,7 @@ import {
} from "yt-dlp-transcript-common/lib/generationSettings";
import { PRICES } from "yt-dlp-transcript-common/lib/llm/prices";
import { agentToken } from "@/lib/annotations/agentAuth.mjs";
-import { CHAIN_STEPS, DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainStart, doneSteps } from "@/lib/report/chain.mjs";
+import { DEFAULT_PROJECTS_ROOT, REPO_ROOT, chainStart, chainStepsOf, doneSteps } from "@/lib/report/chain.mjs";
import { recentJobs, type Job } from "@/lib/jobs";
import { sitesPaths } from "./sites";
@@ -189,6 +189,8 @@ export type DraftJobView = {
kind: string | null;
status: string;
queue: { key?: string; position?: number } | null;
+ /** The job's progress (release 28 F3: a draft's `turns`, `cards` or `entries`), when it reports one. */
+ progress: { metric: string; current: number; target: number } | null;
tail: string[];
};
@@ -200,11 +202,16 @@ export async function readDraftJob(id: string, tail = 12): Promise<DraftJobView>
);
const job = answer.job ?? {};
const queue = (answer.queue ?? job.queue ?? null) as DraftJobView["queue"];
+ const p = job.progress as { metric?: unknown; current?: unknown; target?: unknown } | undefined;
return {
id,
kind: typeof job.kind === "string" ? job.kind : null,
status: String(job.status ?? "unknown"),
queue,
+ progress:
+ p && typeof p.current === "number"
+ ? { metric: typeof p.metric === "string" ? p.metric : "progress", current: p.current, target: typeof p.target === "number" ? p.target : p.current }
+ : null,
tail: Array.isArray(answer.tail) ? answer.tail.map(String) : [],
};
}
@@ -262,8 +269,10 @@ export type IterationRow = {
currentVideo: boolean;
};
+export type ChainMode = "video" | "draft-all";
export type ChainView = {
- steps: { name: string; label: string; status: string }[];
+ mode: ChainMode;
+ steps: { name: string; label: string; status: string; optional: boolean; detail: string | null }[];
/** Where a start resumes: the first step not done, or null (all done). */
resumeAt: string | null;
job: { id: string; state: string; stepIndex: number; of: number; label: string; error: string | null; log: string[] } | null;
@@ -372,26 +381,28 @@ export async function readToday(daily: number): Promise<{ day: string; usd: numb
// ─── The chain ("make the video") ───
-/** The chain job's kind for an iteration, as lib/jobs.ts records it. */
-export const chainKind = (article: string, n: number) => `chain ${article} ${iterationLabel(n)}`;
+/** The chain job's kind for an iteration, as lib/jobs.ts records it (Draft everything's is its own). */
+export const chainKind = (article: string, n: number, mode: ChainMode = "video") =>
+ `${mode === "draft-all" ? "draft-all" : "chain"} ${article} ${iterationLabel(n)}`;
/** The projects root the editor's policy names (`~` expanded), else the default. */
export function projectsRootOf(gen: GenerationSettings): string {
return gen.projectsRoot ? expandHome(gen.projectsRoot) : DEFAULT_PROJECTS_ROOT;
}
-export function chainViewOf(article: string, it: IterationRow): ChainView {
+export function chainViewOf(article: string, it: IterationRow, mode: ChainMode = "video"): ChainView {
const done = new Set(doneSteps({ steps: it.steps }));
- const byTask = new Map(it.steps.map((s) => [s.task, s.status]));
- const job: Job | undefined = recentJobs(30).find((j) => j.kind === chainKind(article, it.n));
+ const byTask = new Map(it.steps.map((s) => [s.task, s]));
+ const job: Job | undefined = recentJobs(30).find((j) => j.kind === chainKind(article, it.n, mode));
+ const defs = chainStepsOf(mode) as { name: string; label: string; optional?: boolean }[];
return {
- steps: CHAIN_STEPS.map((s: { name: string; label: string }) => ({
- name: s.name,
- label: s.label,
- status: byTask.get(`chain:${s.name}`) ?? "pending",
- })),
+ mode,
+ steps: defs.map((s) => {
+ const rec = byTask.get(`chain:${s.name}`);
+ return { name: s.name, label: s.label, status: rec?.status ?? "pending", optional: s.optional === true, detail: rec?.detail ?? null };
+ }),
// chain.mjs's JSDoc types `done` by its default ([]), so it is cast.
- resumeAt: (chainStart as (o: { done: string[] }) => string | null)({ done: [...done] }),
+ resumeAt: (chainStart as (o: { done: string[]; mode: string }) => string | null)({ done: [...done], mode }),
job: job
? {
id: job.id,
diff --git a/umtool/lib/articles/projectDraft.ts b/umtool/lib/articles/projectDraft.ts
@@ -0,0 +1,230 @@
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { readIteration } from "yt-dlp-transcript-common/lib/report/iterations";
+import { draftedFields, ownerOf, reviewAddress } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
+import { isReportId } from "yt-dlp-transcript-common/lib/report/schema";
+import { draftFileOf } from "@/lib/report/chain-draft.mjs";
+import { sitesPaths } from "./sites";
+
+// "DRAFT WITH" ON A PROJECT PAGE (release 28 M9): which iteration a video
+// project was made from — the media tasks are report-draft STEPS on a done
+// iteration, so a project that names none has nothing to draft with — and
+// what each task's last run left in its `<task>-draft.json` beside the
+// manifest (what it wrote, what it skipped, what a check refused, what it
+// kept as an alternative). Read only. SERVER-ONLY.
+
+/** The media tasks a project page drafts, in Draft everything's order. */
+export const PROJECT_DRAFT_TASKS = ["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube"] as const;
+export type ProjectDraftTask = (typeof PROJECT_DRAFT_TASKS)[number];
+
+export type ProjectIteration =
+ | { ok: true; article: string; n: number; status: string; running: Record<string, string> }
+ | { ok: false; why: string };
+
+/**
+ * The iteration a project directory belongs to: `<projectsRoot>/<article>/i<n>/`
+ * (common's projectOf), whose iteration exists and names this directory as its
+ * project (or names none). Else why not, in one line.
+ */
+export async function projectIteration(dir: string): Promise<ProjectIteration> {
+ const abs = path.resolve(dir);
+ const m = /^i(\d+)$/.exec(path.basename(abs));
+ const article = path.basename(path.dirname(abs));
+ if (!m || !isReportId(article)) {
+ return { ok: false, why: "this project was not made from an article's iteration (its folder is not <article>/i<n>), so no draft task can name one" };
+ }
+ const n = Number(m[1]);
+ const it = await readIteration(article, n, sitesPaths()).catch(() => null);
+ if (!it) return { ok: false, why: `no iteration i${n} of the article "${article}": the drafts are steps on an iteration` };
+ if (it.projectDir && path.resolve(it.projectDir) !== abs) {
+ return { ok: false, why: `${article} i${n} names another project (${it.projectDir})` };
+ }
+ // A draft still running on it (a step with its job): the page follows it.
+ const running: Record<string, string> = {};
+ for (const s of it.steps) if (s.status === "running" && s.jobId && !s.task.startsWith("chain:")) running[s.task] = s.jobId;
+ return { ok: true, article, n, status: it.status, running };
+}
+
+export type DraftUnitSummary = {
+ id: string;
+ label: string | null;
+ /** applied | skipped | refused (a hard check) | kept (an alternative: the field is the operator's, or a draft without force) | none */
+ outcome: "applied" | "skipped" | "refused" | "kept" | "none";
+ why: string | null;
+};
+export type DraftRunSummary = {
+ task: ProjectDraftTask;
+ file: string;
+ model: string | null;
+ at: string | null;
+ units: DraftUnitSummary[];
+ counts: Record<DraftUnitSummary["outcome"], number>;
+ checks: { name: string; ok: boolean; detail: string | null }[];
+ alternatives: number;
+};
+
+type RawUnit = {
+ label?: unknown;
+ skipped?: unknown;
+ applied?: unknown;
+ chosen?: { hard?: unknown } | null;
+};
+
+const strings = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []);
+
+/** One task's last run, from its draft file, or null (never run here, or unreadable). */
+export async function draftRunSummary(dir: string, task: ProjectDraftTask): Promise<DraftRunSummary | null> {
+ const file = draftFileOf(task);
+ let doc: Record<string, unknown>;
+ try {
+ doc = JSON.parse(await readFile(path.join(dir, file), "utf8"));
+ } catch {
+ return null;
+ }
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) return null;
+ const units: DraftUnitSummary[] = [];
+ const raw = doc.units && typeof doc.units === "object" ? (doc.units as Record<string, RawUnit>) : {};
+ for (const [id, u] of Object.entries(raw)) {
+ const label = typeof u?.label === "string" ? u.label : null;
+ if (typeof u?.skipped === "string") units.push({ id, label, outcome: "skipped", why: u.skipped });
+ else if (u?.applied === "applied") units.push({ id, label, outcome: "applied", why: null });
+ else if (typeof u?.applied === "string") units.push({ id, label, outcome: "kept", why: u.applied === "operator" ? "the field is yours: kept as an alternative" : `kept as an alternative (${u.applied})` });
+ else {
+ const hard = strings(u?.chosen?.hard);
+ units.push({ id, label, outcome: hard.length ? "refused" : "none", why: hard.length ? hard.join("; ") : u?.chosen ? null : "no draft" });
+ }
+ }
+ const counts = { applied: 0, skipped: 0, refused: 0, kept: 0, none: 0 };
+ for (const u of units) counts[u.outcome] += 1;
+ const checks = Array.isArray(doc.checks)
+ ? (doc.checks as { name?: unknown; ok?: unknown; detail?: unknown }[])
+ .filter((c) => typeof c?.name === "string")
+ .map((c) => ({ name: String(c.name), ok: c.ok === true, detail: typeof c.detail === "string" ? c.detail : null }))
+ : [];
+ return {
+ task,
+ file,
+ model: typeof doc.model === "string" ? doc.model : null,
+ at: typeof doc.at === "string" ? doc.at : null,
+ units,
+ counts,
+ checks,
+ alternatives: Array.isArray(doc.alternatives) ? doc.alternatives.length : 0,
+ };
+}
+
+/** Every task's last run in this project. */
+export async function draftRuns(dir: string): Promise<Partial<Record<ProjectDraftTask, DraftRunSummary>>> {
+ const out: Partial<Record<ProjectDraftTask, DraftRunSummary>> = {};
+ for (const t of PROJECT_DRAFT_TASKS) {
+ const s = await draftRunSummary(dir, t);
+ if (s) out[t] = s;
+ }
+ return out;
+}
+
+// ─── The rows the project page's Draft section draws ───
+
+export type DraftRowView = {
+ task: ProjectDraftTask;
+ /** The section's name. */
+ label: string;
+ /** What the task writes, and the code's limits. */
+ writes: string;
+ /** What the field holds now, in a few words. */
+ state: string;
+ /** The review address of a whole-cut field (its badge and alternatives), else null (per entry: the review page). */
+ address: string | null;
+ /** The entries a per-entry task may be limited to, else null. */
+ entries: { id: string; label: string }[] | null;
+ /** Why it cannot draft on this cut (no deck for flips and threads), else null. */
+ blocked: string | null;
+};
+
+type Entry = { id?: unknown; type?: unknown; heading?: unknown; onscreen?: { title?: unknown; subtitle?: unknown }; narration?: { text?: unknown }; lines?: unknown };
+
+const ownerWords = (o: "empty" | "drafted" | "operator") => (o === "empty" ? "empty" : o === "drafted" ? "drafted" : "yours (never replaced)");
+
+/** The Draft section's rows for a manifest, in Draft everything's order. */
+export function draftRowsOf(manifest: Record<string, unknown>): DraftRowView[] {
+ const tl = (Array.isArray(manifest.timeline) ? manifest.timeline : []) as Entry[];
+ const drafted = draftedFields(manifest);
+ const nDrafted = (field: string) => drafted.filter((d) => d.field === field).length;
+ const ids = (es: Entry[]) => [...new Set(es.map((e) => (typeof e.id === "string" ? e.id : "")).filter(Boolean))];
+ const labelOf = (e: Entry) => `${String(e.id)}${typeof e.heading === "string" && e.heading ? ` — ${e.heading}` : ""}`;
+ const listOf = (es: Entry[]) => ids(es).map((id) => ({ id, label: labelOf(es.find((e) => e.id === id)!) }));
+ const render = (manifest.render ?? {}) as { chrome?: unknown };
+ const deck = !!render.chrome && typeof render.chrome === "object";
+ const clips = tl.filter((e) => e.type === "clip");
+ const cards = tl.filter((e) => e.type === "card");
+ const teasers = tl.filter((e) => e.type === "teaser");
+ const withOnscreen = tl.filter((e) => e.onscreen && (typeof e.onscreen.title === "string" || typeof e.onscreen.subtitle === "string")).length;
+ const narrated = cards.filter((e) => typeof e.narration?.text === "string" && e.narration.text.trim()).length;
+ const withLines = teasers.filter((e) => Array.isArray(e.lines) && e.lines.length > 0).length;
+ const whole = (field: string) => reviewAddress({ field });
+ return [
+ {
+ task: "cut",
+ label: "the cut",
+ writes: "which cited clips, in what order (ids from the citations only; windows untouched)",
+ state: `${clips.length} clip(s); the order is ${ownerWords(ownerOf(manifest, { field: "timeline" }))}`,
+ address: whole("timeline"),
+ entries: null,
+ blocked: null,
+ },
+ {
+ task: "onscreen",
+ label: "on-screen titles",
+ writes: "a title (≤ 60) and a subtitle (≤ 90) per entry, grounded in its claim and quote",
+ state: `${withOnscreen} of ${tl.length} entries written, ${nDrafted("onscreen")} drafted`,
+ address: null,
+ entries: listOf(tl),
+ blocked: null,
+ },
+ {
+ task: "teaser",
+ label: "the teaser",
+ writes: "3 to 5 lines of ≤ 70, no quote read out",
+ state: teasers.length ? `${withLines} of ${teasers.length} teaser(s) written, ${nDrafted("lines")} drafted` : "no teaser entry in the cut",
+ address: null,
+ entries: teasers.length ? listOf(teasers) : null,
+ blocked: null,
+ },
+ {
+ task: "flips",
+ label: "flips",
+ writes: "THEN/NOW pairs over the cut's clips, of different dates (the left panel)",
+ state: deck ? `the flips are ${ownerWords(ownerOf(manifest, { field: "render.chrome.flips" }))}` : "no on-screen deck",
+ address: whole("render.chrome.flips"),
+ entries: null,
+ blocked: deck ? null : "flips are drawn by the on-screen deck, and this cut has none (render.chrome)",
+ },
+ {
+ task: "threads",
+ label: "threads",
+ writes: "2 to 4 threads and each clip's thread (the left panel; not with flips)",
+ state: deck ? `the threads are ${ownerWords(ownerOf(manifest, { field: "render.chrome.threads" }))}` : "no on-screen deck",
+ address: whole("render.chrome.threads"),
+ entries: null,
+ blocked: deck ? null : "threads are drawn by the on-screen deck, and this cut has none (render.chrome)",
+ },
+ {
+ task: "narrate",
+ label: "narration",
+ writes: "each card's narration, third person, every line grounded",
+ state: `${narrated} of ${cards.length} card(s) narrated, ${nDrafted("narration")} drafted`,
+ address: null,
+ entries: cards.length ? listOf(cards) : null,
+ blocked: null,
+ },
+ {
+ task: "youtube",
+ label: "YouTube text",
+ writes: "a title (≤ 100) and a summary (≤ 900); the build adds chapters and sources to out/youtube.txt",
+ state: `the title and description are ${ownerWords(ownerOf(manifest, { field: "publish.youtube" }))}`,
+ address: whole("publish.youtube"),
+ entries: null,
+ blocked: null,
+ },
+ ];
+}
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 () => {
diff --git a/umtool/lib/report/drafted-writer.test.mjs b/umtool/lib/report/drafted-writer.test.mjs
@@ -103,3 +103,25 @@ test("writeDraftedField: Use this writes an alternative as the operator's, check
await assert.rejects(writeDraftedField(p.dir, { field: "publish.youtube", value: { title: 3 } }), StructureRefused);
assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before);
});
+
+test("writeDraftedField: a threads alternative's clips set each clip's thread with the list (release 28 M9)", async (t) => {
+ const p = await project(t);
+ const clipIds = (await p.read()).timeline.filter((e) => e.type === "clip").map((e) => e.id);
+ const [first, ...others] = clipIds;
+ const clips = Object.fromEntries([[first, "solo"], ...others.map((id) => [id, "rest"])]);
+ const list = [{ id: "solo", label: "One clip" }, { id: "rest", label: "The others" }];
+ await writeDraftedField(p.dir, { field: "render.chrome.threads", value: { list, clips } });
+ const m = await p.read();
+ assert.deepEqual(m.render.chrome.threads, { list }, "the field is the list alone");
+ assert.equal(m.timeline.find((e) => e.id === first).thread, "solo");
+ assert.ok(others.every((id) => m.timeline.find((e) => e.id === id).thread === "rest"));
+ assert.ok(!marks(m).includes("*:render.chrome.threads"), "taken, it is the operator's");
+ // A clip the cut lacks, or a thread left with no clip, is refused; the file stays.
+ const before = await readFile(path.join(p.dir, MANIFEST_NAME), "utf8");
+ await assert.rejects(writeDraftedField(p.dir, { field: "render.chrome.threads", value: { list, clips: { nope: "solo" } } }), /clips this cut does not have: nope/);
+ await assert.rejects(
+ writeDraftedField(p.dir, { field: "render.chrome.threads", value: { list, clips: Object.fromEntries(clipIds.map((id) => [id, "rest"])) } }),
+ /thread solo has no clip/,
+ );
+ assert.equal(await readFile(path.join(p.dir, MANIFEST_NAME), "utf8"), before);
+});
diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs
@@ -31,6 +31,7 @@ import {
} from "umtool-report-to-video/ledger-totals";
import { isCalendarDate } from "umtool-report-to-video/attribution";
import { normalizeOnscreen, validateChrome, validatePosts, validateTeaser, validateTeasers } from "umtool-report-to-video/deck";
+import { validateThreadEntries } from "yt-dlp-transcript-common/lib/report/panels.mjs";
import { applySectionEnter } from "./sections.mjs";
import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck";
import { validateNarration } from "umtool-report-to-video/narration";
@@ -1109,8 +1110,12 @@ export async function updateNarration(dir, id, text, { token = null, at = null }
* lines a teaser's lines (validateTeaser)
* narration a card's narration object (validateNarration)
* render.chrome.flips the deck's flips (validateChrome)
- * render.chrome.threads the deck's thread list (validateChrome; each
- * clip's `thread` key is the build's to check)
+ * render.chrome.threads the deck's thread list (validateChrome); a value
+ * that carries `clips` ({clip id: thread id}, what a
+ * threads draft keeps, release 28 M9) sets each
+ * clip's `thread` too — removed from a clip in none
+ * — and the entries are checked as the build checks
+ * them (validateThreadEntries)
* publish.youtube `{ title, description }` (validatePublish)
*
* The cut's order ("timeline") is not taken this way: an order replaces every
@@ -1155,12 +1160,34 @@ export async function writeDraftedField(dir, { entry = null, field, value }, { t
throw new Error("flips and threads are drawn by the on-screen deck, and this manifest has none — turn the deck on first");
}
const key = field === "render.chrome.flips" ? "flips" : "threads";
- const chrome = { ...render.chrome, [key]: copy() };
+ const v = copy();
+ // A threads draft's assignments ride beside its list; the field is the list.
+ let clips = null;
+ if (key === "threads" && v && typeof v === "object" && !Array.isArray(v) && "clips" in v) {
+ clips = v.clips;
+ delete v.clips;
+ if (!clips || typeof clips !== "object" || Array.isArray(clips) || Object.values(clips).some((t) => typeof t !== "string" || !t)) {
+ throw new StructureRefused(["the threads' clips must map a clip id to a thread id"]);
+ }
+ const known = new Set((m.timeline ?? []).filter((e) => e?.type === "clip").map((e) => e.id));
+ const strays = Object.keys(clips).filter((id) => !known.has(id));
+ if (strays.length) throw new StructureRefused([`the threads name clips this cut does not have: ${strays.join(", ")}`]);
+ }
+ const chrome = { ...render.chrome, [key]: v };
const { chrome: _old, ...rest } = render;
const already = new Set(validateChrome(render.chrome, rest));
const errors = validateChrome(chrome, rest).filter((e) => !already.has(e));
if (errors.length) throw new StructureRefused(errors);
m.render = { ...render, chrome };
+ if (clips) {
+ for (const e of m.timeline ?? []) {
+ if (e?.type !== "clip") continue;
+ if (clips[e.id]) e.thread = clips[e.id];
+ else delete e.thread;
+ }
+ const entryErrors = validateThreadEntries(m);
+ if (entryErrors.length) throw new StructureRefused(entryErrors);
+ }
return { entry: null, field, value: chrome[key] };
});
}