// The media task scaffold (release 28, M0): a toy task over the fake ollama // — two attempts, the better kept, an operator's field never replaced and its // draft kept as an alternative — and narrate on it writing its drafted marks. // Real iterations store and project in a temp dir; no model but the fake. import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; 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 { reviewAddress } from "../../drafted.mjs"; import { narrate } from "./narrate"; import { mergeAlternatives, rankAttempts, runMediaTask, type DraftAlternative, type DraftFile, type MediaTaskSpec, type MediaUnit, } from "./media"; import type { TaskDeps } from "./types"; const DRAFT = new URL("../../../../testing/draft/", import.meta.url); const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); let tmp: string; let ol: FakeOllama; before(async () => { tmp = await mkdtemp(path.join(os.tmpdir(), "media-task-")); ol = await startFakeOllama(); }); after(async () => { await ol.close(); await rm(tmp, { recursive: true, force: true }); }); let caseN = 0; // A done sweep iteration with a project holding `manifest` and the basic report. async function project(manifest: unknown) { caseN++; const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) }; const projectsRoot = path.join(tmp, `projects-${caseN}`); await mkdir(paths.articlesDir, { recursive: true }); await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); const report = await kit("reports/basic.report.json"); await writeIterationFile("synth-basic", 1, "report.json", report, paths); const dir = projectOf(projectsRoot, "synth-basic", 1); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`); await writeFile(path.join(dir, "report.json"), JSON.stringify(report)); await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths); const lines: string[] = []; const deps: TaskDeps = { llm: { ollama: { baseUrl: ol.url } }, corpus: { source: "none", tools: [], call: async () => "" }, cuesOf: async () => null, paths, log: (l) => lines.push(l), now: () => new Date("2026-10-13T12:00:00.000Z"), }; const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); return { dir, paths, projectsRoot, deps, lines, manifestNow }; } // A toy task: a title for each clip, at most 20 characters, never "BAD". type ToyUnit = MediaUnit & { quote: string }; const TOY: MediaTaskSpec = { task: "toy", units: (ctx) => ctx.manifest.timeline .filter((e) => e.type === "clip") .slice(0, 3) .map((e) => ({ id: e.id, target: { entry: e.id, field: "onscreen" }, quote: String(e.quote ?? "") })), schema: () => ({ type: "object", properties: { title: { type: "string" } }, required: ["title"] }), system: () => "Write a short title. Rules: at most 20 characters.", user: (u) => `Quote: ${u.quote}`, parse: (a) => ({ title: String((a as { title?: unknown }).title ?? "").trim() }), check: (v) => ({ hard: [...(v.title.length > 20 ? [`${v.title.length} characters (at most 20)`] : []), ...(v.title === "BAD" ? ["bad"] : [])], soft: v.title.endsWith("!") ? ["an exclamation"] : [], }), }; test("the scaffold: two attempts and the better kept; the operator's field kept and the draft an alternative; marks, snapshot, draft file", async () => { const m = await kit("manifests/full.video.manifest.json"); const p = await project(m); // c01 has hand-written on-screen text (the operator's); c02 and c03 none. ol.push( // c01 (forced): clean — but the field is the operator's. jsonReply({ title: "Not for sale?" }), // c02: too long, then clean. jsonReply({ title: "A title far too long for the frame" }), jsonReply({ title: "The old oven" }), // c03: a soft flag, then worse (hard): the first is kept. jsonReply({ title: "The mixer!" }), jsonReply({ title: "BAD" }), ); const out = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, force: true }, p.deps); assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); assert.equal(ol.remaining(), 0); assert.match(out.summary, /^2 field\(s\) drafted, 1 as alternatives \(see toy-draft\.json\) \(undo: revisions\/.*-auto-before-toy\.manifest\.json\)$/); const after = await p.manifestNow(); const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id); assert.deepEqual(e("c01").onscreen, m.timeline.find((x: { id: string }) => x.id === "c01").onscreen, "the operator's words stand"); assert.equal(e("c01").drafted, undefined); assert.deepEqual(e("c02").onscreen, { title: "The old oven" }); assert.deepEqual(e("c02").drafted.onscreen, { task: "toy", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 2 }); assert.deepEqual(e("c03").onscreen, { title: "The mixer!" }); assert.equal(e("c03").drafted.onscreen.attempt, 1, "the better of two: the first"); assert.equal((await readdir(path.join(p.dir, "revisions"))).length, 1); const file = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile; assert.equal(file.task, "toy"); assert.equal(file.iteration, 1); assert.equal((file.units.c02!.attempts as unknown[]).length, 2); assert.equal(file.units.c01!.applied, "operator"); assert.equal(file.units.c02!.applied, "applied"); assert.deepEqual(file.alternatives.map((a) => [a.target, a.value, a.reason]), [[{ entry: "c01", field: "onscreen" }, { title: "Not for sale?" }, "operator"]]); assert.equal(file.checks.find((c) => c.name === "toy")!.ok, true); const it = (await readIteration("synth-basic", 1, p.paths))!; assert.equal(it.status, "done", "a step leaves the iteration's status"); assert.equal(it.steps.find((s) => s.task === "toy")!.status, "done"); // Again, unforced: every field has a value now, so nothing is asked; the // alternative from the run before is carried over. const again = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot }, p.deps); assert.equal(again.status, "failed"); assert.match(again.summary, /no field drafted/); const file2 = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile; assert.match(String(file2.units.c02!.skipped), /has a value \(a draft\); force re-drafts it/); assert.match(String(file2.units.c01!.skipped), /the operator's/); assert.equal(file2.alternatives.length, 1); }); test("the scaffold: entries keeps only the named units; a unit with no clean value is not written", async () => { const m = await kit("manifests/full.video.manifest.json"); const p = await project(m); ol.push(jsonReply({ title: "BAD" }), jsonReply({ title: "BAD" })); const out = await runMediaTask(TOY, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, entries: ["c02"] }, p.deps); assert.equal(out.status, "failed"); assert.equal(ol.remaining(), 0, "only c02 was asked"); const file = JSON.parse(await readFile(path.join(p.dir, "toy-draft.json"), "utf8")) as DraftFile; assert.deepEqual(Object.keys(file.units), ["c02"]); assert.deepEqual(await p.manifestNow(), m, "nothing written"); const it = (await readIteration("synth-basic", 1, p.paths))!; assert.equal(it.checks!.find((c) => c.name === "toy")!.ok, false); }); test("rankAttempts and mergeAlternatives", () => { const a = { value: 1, hard: ["x"], soft: [] }; const b = { value: 2, hard: [], soft: ["y", "z"] }; const c = { value: 3, hard: [], soft: ["y", "z"] }; assert.deepEqual(rankAttempts([a, b, c]).map((x) => x.value), [2, 3, 1], "stable among equals"); const alt = (entry: string, title: string): DraftAlternative => ({ target: { entry, field: "onscreen" }, value: { title }, provenance: { task: "toy", model: "m", at: "2026-10-13T00:00:00.000Z", attempt: 1 }, reason: "operator", }); const many = Array.from({ length: 7 }, (_, i) => alt("c01", `t${i}`)); const merged = mergeAlternatives(many.slice(0, 4), [...many.slice(4), alt("c01", "t0"), alt("c02", "x")]); assert.deepEqual( merged.map((x) => `${reviewAddress(x.target)}:${(x.value as { title: string }).title}`), ["onscreen/c01/onscreen:t3", "onscreen/c01/onscreen:t4", "onscreen/c01/onscreen:t5", "onscreen/c01/onscreen:t6", "onscreen/c01/onscreen:t0", "onscreen/c02/onscreen:x"], "five per field, the newest; a repeat keeps its newest place", ); }); test("narrate on the scaffold: a narration it writes carries drafted.narration; the operator's is kept and its draft an alternative", async () => { const m = await kit("manifests/basic.video.manifest.json"); const contest = m.timeline.find((e: { id: string }) => e.id === "the-contest"); contest.narration = { text: "Words the operator wrote." }; const p = await project(m); // Each card's words by its heading, however many times it is asked. const byCard = (body: { messages: { content: string }[] }) => { const user = body.messages.at(-1)!.content; if (/heading on screen: The bakery/.test(user)) return jsonReply({ text: "First, the bakery. She won't sell it, and she paid for the mixer herself." }); if (/heading on screen: The contest/.test(user)) return jsonReply({ text: "Then the contest. She stayed out of it this year." }); return jsonReply({ text: "What does the baker say about her bakery? And about the contest?" }); }; ol.push(byCard, byCard, byCard, byCard, byCard, byCard); const out = await narrate({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot, force: true }, p.deps); assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); assert.match(out.summary, /^2 card\(s\) narrated, 1 as alternatives \(see narration-draft\.json\)/); const after = await p.manifestNow(); const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id); assert.equal(e("the-bakery").narration.text, "First, the bakery. She won't sell it, and she paid for the mixer herself."); assert.equal(e("the-bakery").seconds, "auto"); assert.deepEqual(e("the-bakery").drafted, { narration: { task: "narrate", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 1 } }); assert.equal(e("title").drafted.narration.task, "narrate"); assert.equal(e("the-contest").narration.text, "Words the operator wrote."); assert.equal(e("the-contest").drafted, undefined); const file = JSON.parse(await readFile(path.join(p.dir, "narration-draft.json"), "utf8")) as DraftFile; assert.deepEqual(file.alternatives.map((a) => [a.target.entry, (a.value as { text: string }).text]), [["the-contest", "Then the contest. She stayed out of it this year."]]); const revisions = await readdir(path.join(p.dir, "revisions")); assert.match(revisions[0]!, /-auto-before-narration\.manifest\.json$/); const it = (await readIteration("synth-basic", 1, p.paths))!; assert.equal(it.checks!.find((c) => c.name === "narration")!.ok, true); }); test("the scaffold in batches (release 28): one ask for several units, the re-ask only for the refused; progress per batch; an owner hook", async () => { const m = await kit("manifests/basic.video.manifest.json"); m.timeline.find((e: { id: string }) => e.id === "c01").onscreen = { title: "x" }; const p = await project(m); // A fake of its own: the script above may have turns left. const own = await startFakeOllama(); p.deps.llm = { ollama: { baseUrl: own.url } }; const progress: { metric: string; current: number; total?: number }[] = []; p.deps.progress = (x) => progress.push(x); const BATCHED: MediaTaskSpec = { ...TOY, task: "toy-batch", // c01 counts as nobody's although it will have a value (the cut's hook). owner: (manifest, u) => (u.id === "c01" ? "empty" : undefined) ?? (manifest.timeline.find((e) => e.id === u.id)?.onscreen ? "operator" : "empty"), batch: { group: (us) => [us.slice(0, 2), us.slice(2)], schema: () => ({ type: "object", properties: { entries: { type: "array", items: { type: "object" } } }, required: ["entries"] }), system: () => TOY.system(null as never, null as never), user: (us) => us.map((u) => `${u.id}: ${u.quote}`).join("\n"), split: (a) => Object.fromEntries(((a as { entries: { id: string; title: string }[] }).entries ?? []).map((e) => [e.id, e])), }, }; const asked: string[] = []; const reply = (entries: { id: string; title: string }[]) => (body: { messages: { content: string }[] }) => { asked.push(body.messages.at(-1)!.content); return jsonReply({ entries }); }; own.push( // c01 + c02: c02 refused; c01 clean. reply([{ id: "c01", title: "Not for sale" }, { id: "c02", title: "BAD" }]), // the re-ask: c02 alone. reply([{ id: "c02", title: "The old oven" }]), // c03 alone in its batch, and no draft for it. reply([]), reply([{ id: "c03", title: "The mixer" }]), ); const out = await runMediaTask(BATCHED, { article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot: p.projectsRoot }, p.deps); await own.close(); assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); assert.equal(own.remaining(), 0); assert.equal(asked.length, 4); assert.match(asked[1]!, /^c02: we never said/); assert.match(asked[1]!, /Your last drafts were refused: c02: bad/); assert.match(asked[3]!, /c03: no draft for c03 in the answer/); const after = await p.manifestNow(); const e = (id: string) => after.timeline.find((x: { id: string }) => x.id === id); // The hook let c01 be asked; the writer still keeps the operator's words. assert.deepEqual([e("c01").onscreen, e("c02").onscreen, e("c03").onscreen], [{ title: "x" }, { title: "The old oven" }, { title: "The mixer" }]); const file = JSON.parse(await readFile(path.join(p.dir, "toy-batch-draft.json"), "utf8")) as DraftFile; assert.deepEqual(file.alternatives.map((a) => [a.target.entry, a.reason]), [["c01", "operator"]]); assert.equal(e("c02").drafted.onscreen.attempt, 2); assert.deepEqual(progress, [ { metric: "entries", current: 0, total: 3 }, { metric: "entries", current: 2, total: 3 }, { metric: "entries", current: 3, total: 3 }, ]); });