// The flips, threads and youtube drafts (release 28, M4–M6): every code check // refuses what it should — dates, order, counts, lengths, ids, grounding — the // better of two attempts, the repair, the one left panel, and the operator's // field kept with the draft as an alternative. The fake ollama answers; the // corpus is the synthetic one's records (their upload dates). import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, 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 { recordOf } from "../../../../testing/draft/corpus.mjs"; import { createIteration, projectOf, updateIteration, writeIterationFile } from "../../iterations"; import { groundingInputOf } from "../grounding"; import { validateFlipEntries, validateFlips, validateThreadEntries, validateThreads } from "../../panels.mjs"; import type { VideoManifest } from "../videoOps"; import { isoDay, whenOf, type ClipFact } from "./clipEvidence"; import { flips, planFlips, sideWords, swapEntries } from "./flips"; import { planThreads, threads } from "./threads"; import { summaryProblems, titleProblems, youtube, YOUTUBE_SUMMARY_MAX } from "./youtube"; import type { DraftFile } 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(), "panel-tasks-")); ol = await startFakeOllama(); }); after(async () => { await ol.close(); await rm(tmp, { recursive: true, force: true }); }); // The full manifest with no left panel (its threads taken off). async function deckManifest() { const m = await kit("manifests/full.video.manifest.json"); delete m.render.chrome.threads; for (const e of m.timeline) delete e.thread; return m; } // The corpus as the tasks read it: get_video_metadata answers a record (no cues). const corpus = { source: "fake", tools: [], call: async (name: string, args: Record = {}) => { if (name !== "get_video_metadata") return ""; const r = recordOf(String(args.channel), String(args.video_id)); if (!r) throw new Error("video not found"); const { cues: _c, ...meta } = r; return JSON.stringify(meta); }, }; let caseN = 0; 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, cuesOf: async () => null, paths, log: (l) => lines.push(l), now: () => new Date("2026-10-13T12:00:00.000Z"), }; const input = (o: { force?: boolean } = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o }); const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); const draftNow = async (task: string) => JSON.parse(await readFile(path.join(dir, `${task}-draft.json`), "utf8")) as DraftFile; return { dir, deps, lines, input, manifestNow, draftNow, report }; } const P = { task: "cut", model: "qwen3:8b", at: "2026-10-13T11:00:00.000Z", iteration: 1, attempt: 1 }; // ─── pure ─── test("dates and words are code's: isoDay, whenOf, sideWords verbatim and cut at a word", () => { assert.equal(isoDay("20260105"), "2026-01-05"); assert.equal(isoDay("2026-03-01T10:00:00Z"), "2026-03-01"); assert.equal(isoDay("March"), null); assert.equal(whenOf("2026-01-05"), "Jan 2026"); assert.deepEqual(sideWords("I would never sell the bakery to a chain", "Never sell the BAKERY"), { words: "never sell the bakery" }); assert.deepEqual(sideWords("I would never sell the bakery to a chain", "I'd never sell it"), { words: "I would never sell the bakery to a chain", soft: "its words are not the clip's quote: the quote is used", }); const long = Array.from({ length: 40 }, (_, i) => `word${i}`).join(" "); const cut = sideWords(long, undefined).words; assert.ok(cut.length <= 110 && cut.endsWith("…") && long.startsWith(cut.slice(0, -1)), cut); assert.deepEqual( swapEntries([{ type: "clip", id: "a" }, { type: "card", id: "x" }, { type: "clip", id: "b" }], [["a", "b"]]).map((e) => e.id), ["b", "x", "a"], ); }); const clip = (id: string, index: number, date: string | null, quote = `the words of ${id}`, verdict?: string): ClipFact => ({ id, index, quote, claim: verdict ? { text: "", verdict } : null, section: null, date, dateFrom: date ? "record" : null, }); test("planFlips: ids, one pair per clip, dates (the earlier is THEN; one day is no pair), order, the topic's length and grounding", async () => { const m = (await deckManifest()) as VideoManifest; const g = groundingInputOf(await kit("reports/basic.report.json")); const clips = [clip("c01", 2, "2026-01-05"), clip("c02", 3, "2026-01-05"), clip("c04", 6, "2026-02-10"), clip("c07", 9, "2026-03-01"), clip("c05", 7, null)]; const unit = { clips, g, reorderable: false, dropThreads: false, maxPairs: 2 }; // The model's THEN is the later recording: code turns it round. const ok = planFlips({ pairs: [{ topic: "The bakery", then: "c07", now: "c01" }] }, unit, m); assert.deepEqual(ok.problems, []); assert.deepEqual(ok.flips.pairs[0], { id: "the-bakery", topic: "The bakery", then: { entry: "c01", when: "Jan 2026", words: "the words of c01" }, now: { entry: "c07", when: "Mar 2026", words: "the words of c07" }, }); const bad = planFlips( { pairs: [ { topic: "The oven", then: "c01", now: "c02" }, { topic: "The contest", then: "c99", now: "c04" }, { topic: "The contest", then: "c05", now: "c04" }, { topic: "A topic that is far too long for the panel", then: "c04", now: "c07" }, ], }, unit, m, ); const all = [...bad.problems, ...bad.pairProblems.flat()].join(" | "); assert.match(all, /4 pairs: at most 2/); assert.match(all, /c01 and c02 are of the same day \(2026-01-05\)/); assert.match(all, /c99 is not a clip of the cut/); assert.match(all, /c05's recording has no date/); assert.match(all, /the topic is 42 characters \(at most 32\)/); // A name the report does not have; a clip in two pairs. const two = planFlips({ pairs: [{ topic: "The bakery of Gordon", then: "c01", now: "c07" }, { topic: "The oven", then: "c04", now: "c07" }] }, unit, m); assert.match(two.pairProblems[0]!.join(" "), /name “Gordon” is not in the report/); assert.equal(two.pairProblems[1]!.length, 0, "a refused pair leaves its clips free"); const three = planFlips({ pairs: [{ topic: "The bakery", then: "c01", now: "c07" }, { topic: "The oven", then: "c04", now: "c07" }] }, unit, m); assert.match(three.pairProblems[1]!.join(" "), /c07 is already in a pair/); }); test("planFlips: THEN after NOW in the cut is refused when the order is the operator's, swapped when it is a draft; the build's validators pass", async () => { const m = (await deckManifest()) as VideoManifest; // c07 (Mar) before c01 (Jan) in the cut. m.timeline = swapEntries(m.timeline, [["c01", "c07"]]); const g = groundingInputOf(await kit("reports/basic.report.json")); const at = (id: string) => m.timeline.findIndex((e) => e.id === id); const clips = [clip("c01", at("c01"), "2026-01-05"), clip("c07", at("c07"), "2026-03-01")]; const v = { pairs: [{ topic: "The bakery", then: "c01", now: "c07" }] }; const refused = planFlips(v, { clips, g, reorderable: false, dropThreads: false, maxPairs: 1 }, m); assert.match(refused.pairProblems[0]!.join(" "), /THEN c01 \(2026-01-05\) plays after NOW c07 \(2026-03-01\) and the cut's order is not a draft/); const swapped = planFlips(v, { clips, g, reorderable: true, dropThreads: false, maxPairs: 1 }, m); assert.deepEqual([...swapped.problems, ...swapped.pairProblems.flat()], []); assert.deepEqual(swapped.swaps, [["c01", "c07"]]); const after = JSON.parse(JSON.stringify(m)); after.timeline = swapEntries(after.timeline, swapped.swaps); after.render.chrome.flips = swapped.flips; assert.deepEqual([...validateFlips(swapped.flips), ...validateFlipEntries(after)], []); }); test("planThreads: 2 to 4, labels, ids, assignments, every thread a clip; the outcome is the last clip's verdict in the manifest", async () => { const m = (await deckManifest()) as VideoManifest; const g = groundingInputOf(await kit("reports/basic.report.json")); const at = (id: string) => m.timeline.findIndex((e) => e.id === id); const clips = ["c01", "c02", "c03", "c04", "c05", "c06", "c07"].map((id) => clip(id, at(id), null)); const unit = { clips, g, dropFlips: false }; const one = planThreads({ threads: [{ id: "a", label: "The bakery" }], assign: [{ clip: "c01", thread: "a" }] }, unit, m); assert.match(one.problems.join(" "), /1 thread\(s\): 2 to 4/); const bad = planThreads( { threads: [ { id: "bakery", label: "The bakery" }, { id: "bakery", label: "The bakery again" }, { id: "x y!", label: "A label that is much too long for the rail" }, ], assign: [ { clip: "c01", thread: "bakery" }, { clip: "c99", thread: "bakery" }, { clip: "c02", thread: "nowhere" }, { clip: "c03", thread: "bakery" }, { clip: "c03", thread: "x y!" }, ], }, unit, m, ); const all = [...bad.problems, ...bad.threadProblems.flat()].join(" | "); assert.match(all, /the id bakery is listed twice/); assert.match(all, /the label is 42 characters \(at most 32\)/); assert.match(all, /c99 is not a clip of the cut/); assert.match(all, /c02 is put in nowhere, which is not a listed thread/); assert.match(all, /c03 is put in two threads \(bakery, x-y\)/); // The outcome: code's, from the manifest — c07 (CONTRADICTED) is the bakery's last clip; c06 (NOT_FOUND) the contest's. const good = planThreads( { threads: [{ id: "bakery", label: "The bakery" }, { id: "contest", label: "The contest" }], assign: ["c01", "c02", "c03", "c07"].map((c) => ({ clip: c, thread: "bakery" })).concat(["c04", "c05"].map((c) => ({ clip: c, thread: "contest" }))), }, unit, m, ); assert.deepEqual(good.problems, []); assert.deepEqual(good.list, [ { id: "bakery", label: "The bakery", outcome: { verdict: "CONTRADICTED" } }, { id: "contest", label: "The contest", outcome: { verdict: "PARTLY" } }, ]); const after = JSON.parse(JSON.stringify(m)); after.render.chrome.threads = { list: good.list }; for (const e of after.timeline) if (good.clips[e.id]) e.thread = good.clips[e.id]; assert.deepEqual([...validateThreads({ list: good.list }), ...validateThreadEntries(after)], []); }); test("youtube's checks: lengths, one line, links, third person, names and numbers, quotes word for word", async () => { const g = groundingInputOf(await kit("reports/basic.report.json")); assert.deepEqual(titleProblems("What the baker of Synth Kitchen says about the bakery", g).hard, []); assert.match(titleProblems("x".repeat(101), g).hard.join(" "), /101 characters \(at most 100\)/); assert.match(titleProblems("Synth Kitchen in 2027", g).hard.join(" "), /number 2027 is not in the report/); assert.match(titleProblems("What Gordon says about the bakery", g).hard.join(" "), /name “Gordon” is not in the report/); assert.match(summaryProblems("I would never sell it, she says.", g).hard.join(" "), /the narrator is third person/); assert.deepEqual(summaryProblems('She says "I would never sell the bakery to a chain" on the bread day.', g).hard, []); assert.match(summaryProblems('She says "I will sell the bakery".', g).hard.join(" "), /is not what a cited clip says, word for word/); assert.match(summaryProblems("See 0:15 for the bakery.", g).hard.join(" "), /no links, timestamps/); assert.match(summaryProblems("a ".repeat(YOUTUBE_SUMMARY_MAX), g).hard.join(" "), /at most 900/); }); // ─── the tasks, over the fake ollama ─── test("flips refuses a cut with no deck, and one with threads unless forced over drafted threads — which it then replaces, and says so", async () => { const basic = await project(await kit("manifests/basic.video.manifest.json")); const none = await flips(basic.input(), basic.deps); assert.equal(none.status, "failed"); assert.match(none.summary, /drawn by the on-screen deck \(render\.chrome\), and this cut has none/); // The full manifest's threads are hand-written: the operator's, refused even forced. const full = await project(await kit("manifests/full.video.manifest.json")); assert.match((await flips(full.input(), full.deps)).summary, /share the left panel: the threads are the operator's/); assert.match((await flips(full.input({ force: true }), full.deps)).summary, /the threads are the operator's — remove them first/); // Drafted threads: refused unforced, replaced forced. const m = await kit("manifests/full.video.manifest.json"); m.drafted = { "render.chrome.threads": P }; const drafted = await project(m); assert.match((await flips(drafted.input(), drafted.deps)).summary, /force replaces drafted threads/); ol.push(jsonReply({ pairs: [{ topic: "The bakery's size", then: "c01", now: "c07" }] })); const out = await flips(drafted.input({ force: true }), drafted.deps); assert.equal(out.status, "done", `${out.summary}\n${drafted.lines.join("\n")}`); const now = await drafted.manifestNow(); assert.equal(now.render.chrome.threads, undefined); assert.ok(now.timeline.every((e: { thread?: string }) => e.thread === undefined), "every clip's thread goes with the list"); assert.equal(now.drafted["render.chrome.threads"], undefined); assert.equal(now.drafted["render.chrome.flips"].task, "flips"); assert.ok(drafted.lines.some((l) => /the drafted threads were removed/.test(l))); }); test("flips: a pair the other way round in a drafted cut swaps the clips (the timeline re-marked); a refused pair dropped when the rest stand", async () => { const m = await deckManifest(); m.timeline = swapEntries(m.timeline, [["c01", "c07"]]); m.drafted = { timeline: { ...P, model: "code" } }; const p = await project(m); const bad = { pairs: [{ topic: "The bakery's size", then: "c01", now: "c07" }, { topic: "The lease and Gordon", then: "c04", now: "c02" }] }; ol.push(jsonReply(bad), jsonReply(bad)); const out = await flips(p.input(), p.deps); assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); assert.equal(ol.remaining(), 0, "both attempts asked"); const now = await p.manifestNow(); assert.deepEqual(now.render.chrome.flips.pairs.map((x: { then: { entry: string }; now: { entry: string } }) => [x.then.entry, x.now.entry]), [["c01", "c07"]]); assert.ok(now.timeline.findIndex((e: { id: string }) => e.id === "c01") < now.timeline.findIndex((e: { id: string }) => e.id === "c07")); assert.equal(now.drafted.timeline.task, "flips", "the order is this draft's now"); assert.deepEqual([...validateFlips(now.render.chrome.flips), ...validateFlipEntries(now)], []); const file = await p.draftNow("flips"); assert.match(JSON.stringify(file.units.flips!.chosen), /1 refused pair\(s\) dropped/); assert.ok(p.lines.some((l) => /the cut's order changed so THEN plays first: c01 ⇄ c07/.test(l))); }); test("flips: the operator's flips stand, forced or not; a forced draft is kept as an alternative", async () => { const p = await project(await kit("manifests/flips.video.manifest.json")); const skipped = await flips(p.input(), p.deps); assert.equal(skipped.status, "failed"); assert.match(String((await p.draftNow("flips")).units.flips!.skipped), /the operator's/); ol.push(jsonReply({ pairs: [{ topic: "The contest", then: "c04", now: "c07" }] })); const out = await flips(p.input({ force: true }), p.deps); assert.equal(out.status, "done", out.summary); const now = await p.manifestNow(); assert.equal(now.render.chrome.flips.pairs[0].id, "chain", "the operator's pairs stand"); const alt = (await p.draftNow("flips")).alternatives; assert.equal(alt.length, 1); assert.equal(alt[0]!.reason, "operator"); assert.deepEqual((alt[0]!.value as { pairs: { topic: string }[] }).pairs.map((x) => x.topic), ["The contest"]); }); test("threads: refused with operator's flips; forced over drafted flips replaces them; a refused thread dropped when two stand", async () => { const op = await project(await kit("manifests/flips.video.manifest.json")); assert.match((await threads(op.input({ force: true }), op.deps)).summary, /the flips are the operator's — remove them first/); const m = await kit("manifests/flips.video.manifest.json"); m.drafted = { "render.chrome.flips": { ...P, task: "flips" } }; const p = await project(m); const answer = { threads: [{ id: "bakery", label: "The bakery" }, { id: "contest", label: "The contest" }, { id: "lease", label: "The lease and Gordon" }], clips: [ { clip: "c01", thread: "bakery" }, { clip: "c02", thread: "bakery" }, { clip: "c04", thread: "contest" }, { clip: "c06", thread: "lease" }, { clip: "c07", thread: "bakery" }, ], }; 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.equal(now.render.chrome.flips, undefined); assert.equal(now.drafted["render.chrome.flips"], undefined); assert.deepEqual(now.render.chrome.threads.list.map((t: { id: string }) => t.id), ["bakery", "contest"]); const thread = (id: string) => now.timeline.find((e: { id: string }) => e.id === id).thread; assert.equal(thread("c06"), undefined, "the dropped thread's clip is in none"); assert.equal(thread("c07"), "bakery"); assert.deepEqual([...validateThreads(now.render.chrome.threads), ...validateThreadEntries(now)], []); 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 }; 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"; ol.push( jsonReply({ title, description: "Synth Kitchen's baker will not sell the bakery. We think she is right." }), jsonReply({ title: `${title} in 2027`, description: "She will not sell." }), ); const out = await youtube(p.input(), p.deps); assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); const now = await p.manifestNow(); assert.deepEqual(now.publish.youtube, { title, description: "Synth Kitchen's baker will not sell the bakery." }); assert.equal(now.drafted["publish.youtube"].attempt, 2); // The operator edits it (the mark goes): a forced re-draft is an alternative. now.publish.youtube.title = "The baker on the bakery"; delete now.drafted; await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(now)); ol.push(jsonReply({ title, description: "Synth Kitchen's baker will not sell the bakery." })); const again = await youtube(p.input({ force: true }), p.deps); assert.equal(again.status, "done", again.summary); assert.equal((await p.manifestNow()).publish.youtube.title, "The baker on the bakery"); const alt = (await p.draftNow("youtube")).alternatives; assert.equal(alt.at(-1)!.reason, "operator"); assert.equal((alt.at(-1)!.value as { title: string }).title, title); });