// 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 { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, 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 { deckChrome, deckRefusedDetail, deckStepDetail, 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" }, social: { end: "done", summary: "2 social posts 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("the social draft (release 29 G2): done, and its posts written to out/x.txt and out/bluesky.txt — no build needed", async () => { const file = path.join(PROJECT, "video.manifest.json"); const link = "https://archilyzer.example/articles/synth-basic/"; put(file, { ...baseManifest, publish: { x: { post: `The post.\n\n${link}`, thread: ["Two."] }, bluesky: { post: `The post.\n\n${link}` } } }); const r = await (await step("draft-social")).done; assert.equal(r.code, 0, r.out); assert.deepEqual(requests.at(-1), { task: "social", article: "synth-basic", iteration: 1 }); assert.equal(recorded("draft-social").status, "done"); assert.equal(recorded("draft-social").detail, "2 social posts drafted; out/x.txt and out/bluesky.txt written"); assert.equal(readFileSync(path.join(PROJECT, "out", "x.txt"), "utf8"), `The post.\n\n${link}\n\n— 2/2 —\nTwo.\n`); assert.equal(readFileSync(path.join(PROJECT, "out", "bluesky.txt"), "utf8"), `The post.\n\n${link}\n`); // A re-draft that leaves Bluesky with no post removes its old file (review fix). put(file, { ...baseManifest, publish: { x: { post: `The post.\n\n${link}` } } }); const again = await (await step("draft-social")).done; assert.equal(again.code, 0, again.out); assert.equal(recorded("draft-social").detail, "2 social posts drafted; out/x.txt written"); assert.equal(existsSync(path.join(PROJECT, "out", "bluesky.txt")), false); put(file, baseManifest); }); test("the deck step on a frame too small for the deck says so, adds nothing, and the chain goes on", async () => { const file = path.join(PROJECT, "video.manifest.json"); put(file, { ...baseManifest, render: { ...baseManifest.render, width: 640, height: 360 } }); const before = readFileSync(file, "utf8"); const r = await (await step("deck")).done; assert.equal(r.code, 0, r.out); assert.equal(recorded("deck").status, "failed"); assert.match(recorded("deck").detail, /^frame too small for the deck \(640×360\): .*needs \d+px but a \d+px deck leaves/); assert.equal(readFileSync(file, "utf8"), before); assert.match(deckRefusedDetail(["render.chrome.engine must be \"hyperframes\""], {}), /^the deck was refused: /); put(file, baseManifest); }); 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("the deck step (release 29 G1): the minimal deck on a cut with none, a snapshot first; a cut with one is left as it is", async () => { const file = path.join(PROJECT, "video.manifest.json"); put(file, baseManifest); assert.match(draftPrecheck("flips", json(file)), /no on-screen deck/); const asked = requests.length; const r = await (await step("deck")).done; assert.equal(r.code, 0, r.out); assert.equal(requests.length, asked, "no model, no editor"); assert.equal(recorded("deck").status, "done"); assert.equal(recorded("deck").detail, deckStepDetail(true)); const m = json(file); assert.deepEqual(m.render.chrome, deckChrome()); assert.deepEqual({ ...m, render: { ...m.render, chrome: undefined } }, { ...baseManifest, render: { ...baseManifest.render, chrome: undefined } }, "nothing else changed"); assert.ok(readdirSync(path.join(PROJECT, "revisions")).some((f) => f.includes("auto-before-deck"))); assert.equal(draftPrecheck("flips", m), null); const before = readFileSync(file, "utf8"); const again = await (await step("deck")).done; assert.equal(again.code, 0, again.out); assert.equal(recorded("deck").detail, "deck already there: the cut's render.chrome is kept as it is"); assert.equal(readFileSync(file, "utf8"), before); put(file, baseManifest); }); test("draftPrecheck and draftOutcome, pure", () => { assert.notEqual(deckChrome(), deckChrome(), "a fresh object each call"); 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"); });