// The tasks' pure parts (release 27, S5). The tasks end to end, over the MCP's // own corpus tools and the fake model servers, are mcp/src/draftTasks.test.ts. import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { ORIGIN, POSTS, cuesOf } from "../../../../testing/draft/corpus.mjs"; import { NARRATION_WRITING_RULES, rulesForModel, ruleForModel } from "../authoringRules"; import { momentHref, platformVideo, rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; import { chunksOf, lintClaim, locate, parseEnumerate, parseTranscripts, windowsOf } from "./sweep-pipeline"; import { pickCorpusBuild, siteOriginOf } from "./corpusSource"; import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes"; import { cardContext, chooseDraft } from "./narrate"; import { groundingInputOf } from "../grounding"; const DRAFT_SWEEPS = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../testing/draft/sweeps"); const stubCorpus = (slugs: Record) => ({ calls: [] as unknown[], async call(name: string, args: Record = {}) { this.calls.push([name, args]); if (name !== "get_video_metadata") throw new Error(`no ${name}`); const slug = slugs[String(args.video_id)]; if (!slug || (args.channel && args.channel !== slug)) throw new Error("not found"); return `${JSON.stringify({ id: args.video_id, channelSlug: slug })}\n\n(corpus: x)`; }, }); test("authoring rules: a model's prompt takes the rules without their examples, and without the tag rule", () => { const rules = rulesForModel(NARRATION_WRITING_RULES, { tags: false }); assert.equal(rules.length, NARRATION_WRITING_RULES.length - 1); assert.equal(rules[0], "Short sentences; fragments are fine."); for (const r of rules) { assert.ok(!r.includes("One file."), r); assert.ok(!/<[a-z]+>/.test(r), r); } assert.equal(ruleForModel("Say it plainly (e.g. like this)."), "Say it plainly."); assert.equal(rulesForModel(NARRATION_WRITING_RULES).length, NARRATION_WRITING_RULES.length); }); test("links: moment links are built on the origin; a platform URL and another origin's link are rewritten", async () => { assert.equal(momentHref(ORIGIN, "synth-kitchen", "bread-day-01", 15.7), `${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=15`); const corpus = stubCorpus({ "bread-day-01": "synth-kitchen" }); const r = slugResolver(corpus, ["synth-other", "synth-kitchen"]); const md = [ "- a [Bread day @ 0:15](https://video.example/watch?v=bread-day-01&t=15s)", "- b [Bread day @ 0:20](https://youtu.be/bread-day-01?t=20)", "- c [Elsewhere @ 0:05](https://other.example/?v=synth-kitchen%2Fpie-stream-02&t=5)", "- d [post](https://other.example/?v=synth-social%2F17&vm=post)", `- e [Kept @ 0:30](${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=30)`, "- f [Unknown](https://video.example/watch?v=nope&t=3)", "- g [An X post](https://x.com/someone/status/123)", ].join("\n"); const out = await rewriteLinks(md, r, ORIGIN); assert.equal(out.fixed, 4); assert.ok(out.md.includes(`(${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=15)`)); assert.ok(out.md.includes(`(${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=20)`)); assert.ok(out.md.includes(`(${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=5)`)); assert.ok(out.md.includes(`(${ORIGIN}/?v=synth-social%2F17&vm=post)`)); assert.ok(out.md.includes("https://video.example/watch?v=nope&t=3"), "a recording not in the corpus is left"); assert.ok(out.md.includes("https://x.com/someone/status/123")); // The resolver asks once per video. const asked = corpus.calls.filter((c) => (c as [string, { video_id: string }])[1].video_id === "bread-day-01").length; assert.equal(asked, 2, "synth-other, then synth-kitchen — and cached for the second link"); }); test("links: a Twitch VOD is linked as the archive's v — by platform, never because the id is digits", async () => { // A directory id with the platform known: the record id the archive serves. assert.equal(momentHref(ORIGIN, "synth-twitch", "2468013579", 61.2, "twitch"), `${ORIGIN}/?v=synth-twitch%2Fv2468013579&t=61`); assert.equal(momentHref(ORIGIN, "synth-twitch", "v2468013579", 61, "twitch"), `${ORIGIN}/?v=synth-twitch%2Fv2468013579&t=61`); // An X status id is digits too: never a v. assert.equal(momentHref(ORIGIN, "synth-social", "1850000000000000000", 4, "x"), `${ORIGIN}/?v=synth-social%2F1850000000000000000&t=4`); assert.equal(momentHref(ORIGIN, "synth-social", "1850000000000000000", 4), `${ORIGIN}/?v=synth-social%2F1850000000000000000&t=4`); // A twitch.tv/videos/ URL is the platform saying so; its t is h/m/s. assert.deepEqual(platformVideo("https://www.twitch.tv/videos/2468013579?t=1h2m3s"), { id: "v2468013579", seconds: 3723 }); assert.equal(platformVideo("https://www.twitch.tv/somebody"), null); const r = slugResolver(stubCorpus({ v2468013579: "synth-twitch" }), ["synth-twitch"]); const out = await rewriteLinks("- [Stream @ 1:02:03](https://www.twitch.tv/videos/2468013579?t=1h2m3s)", r, ORIGIN); assert.equal(out.fixed, 1); assert.ok(out.md.includes(`(${ORIGIN}/?v=synth-twitch%2Fv2468013579&t=3723)`), out.md); }); test("links: get_transcripts' moment_base becomes the origin's, by the moment_base's own slug or by asking", async () => { const text = [ "## Pie stream\n- video_id: pie-stream-02 | channel: Synth Kitchen\n- source: https://video.example/watch?v=pie-stream-02\n- moment_base: https://video.example/watch?v=pie-stream-02&t=\n[0:10|10] hello", "## Bread\n- video_id: bread-day-01 | channel: Synth Kitchen\n- source: https://video.example/watch?v=bread-day-01\n[0:15|15] there", "## Public\n- video_id: flat-loaf-01 | channel: Other\n- moment_base: https://pub.example/?v=synth-other%2Fflat-loaf-01&t=\n[0:05|5] x", ].join("\n---\n"); const r = slugResolver(stubCorpus({ "pie-stream-02": "synth-kitchen", "bread-day-01": "synth-kitchen" }), ["synth-kitchen"]); const out = await rewriteMomentBases(text, r, ORIGIN); assert.ok(out.includes(`- moment_base: ${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=`)); assert.ok(out.includes(`- source: https://video.example/watch?v=bread-day-01\n- moment_base: ${ORIGIN}/?v=synth-kitchen%2Fbread-day-01&t=`)); assert.ok(out.includes(`moment_base: ${ORIGIN}/?v=synth-other%2Fflat-loaf-01&t=`)); assert.equal(out.split("\n---\n").length, 3); }); test("pipeline helpers: enumerate lines, transcript blocks, windows, chunks, the verbatim locate, the claim lint", () => { const vids = parseEnumerate( "1 match(es)\n\n- pie-stream-02 | video | Synth Kitchen | 2026-02-10 | 2 match(es) | Pie stream\n- 17 | post | Synth Social | 2026-02-11 | 1 match(es) | a post", "contest", ); assert.deepEqual(vids, [{ id: "pie-stream-02", channel: "Synth Kitchen", date: "2026-02-10", title: "Pie stream", hits: { contest: 2 } }]); const parsed = parseTranscripts( "## Pie stream\n- video_id: pie-stream-02\n- moment_base: https://x/?v=a%2Fb&t=\n[0:05|5] one\n[0:10|10] two\n…\n[3:00|180] three\n---\n## No id\n[0:01|1] x", ); const p = parsed.get("pie-stream-02")!; assert.equal(p.title, "Pie stream"); assert.equal(p.lines.length, 4); assert.deepEqual(windowsOf(p.lines), [[[5, "one"], [10, "two"]], [[180, "three"]]]); assert.deepEqual(windowsOf([[0, "a"], [200, "b"]]).length, 2, "a gap over 90 s splits"); const long = Array.from({ length: 10 }, (_, i) => [i * 5, "x".repeat(100)] as [number, string]); const chunks = chunksOf(long, 600); assert.ok(chunks.length > 1); assert.deepEqual(chunks[1]!.slice(0, 3), chunks[0]!.slice(-3), "chunks overlap by three lines"); const chunk: [number, string][] = [[10, "I did not enter the contest"], [15, "this year at all"]]; assert.equal(locate("not enter the contest this year", chunk), 10); assert.equal(locate("contest this year", chunk), 10); assert.equal(locate("I did enter the contest", chunk), null); assert.equal(locate("ente the", chunk), null, "whole words only"); assert.deepEqual(lintClaim("She entered", "I did not enter"), ["negation: the quote has a not/never/no the claim does not"]); assert.match(lintClaim("She says 3 pies", "maybe two pies").join(" "), /hedge dropped.*number 3/); }); test("corpus source: the newest public build holding every channel; a named build must hold them; the site's origin", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "draft-builds-")); try { const build = async (id: string, slugs: string[], ageS: number) => { const out = path.join(root, "builds", id, "out"); await mkdir(out, { recursive: true }); await writeFile(path.join(out, "corpus.json"), JSON.stringify({ channels: slugs.map((slug) => ({ slug })) })); const t = new Date(Date.now() - ageS * 1000); await utimes(path.join(out, "corpus.json"), t, t); }; await build("alpha", ["a", "b"], 100); await build("beta", ["a", "b", "c"], 10); await build("beta-private", ["a", "b", "c", "d"], 1); const dir = path.join(root, "builds"); assert.equal((await pickCorpusBuild(["a", "b"], { exportBuildsDir: dir })).build, "beta"); assert.equal((await pickCorpusBuild(["d"], { exportBuildsDir: dir })).build, "beta-private"); assert.equal((await pickCorpusBuild(["a"], { exportBuildsDir: dir, want: "alpha" })).build, "alpha"); await assert.rejects(pickCorpusBuild(["c"], { exportBuildsDir: dir, want: "alpha" }), /does not hold c/); await assert.rejects(pickCorpusBuild(["z"], { exportBuildsDir: dir }), /no composed build holds all of z/); await mkdir(path.join(root, "sites", "beta"), { recursive: true }); await writeFile(path.join(root, "sites", "beta", "site.json"), JSON.stringify({ siteUrl: "https://beta.example/" })); assert.equal(await siteOriginOf("beta-private", path.join(root, "sites")), "https://beta.example"); assert.equal(await siteOriginOf("alpha", path.join(root, "sites")), null); } finally { await rm(root, { recursive: true, force: true }); } }); test("quotes: the strict check over cues and posts; the failing finding dropped, the rest kept byte for byte", async () => { const md = [ "# T", "", "## S", "", `- She did not enter: "I did not enter the contest this year" [Pie @ 0:10](${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=10)`, `- She entered: "I did enter the contest this year" [Pie @ 0:11](${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=11)`, `- Posted: "No, I did not enter the pie contest." [post by synthbaker, 2026-02-11](${ORIGIN}/?v=synth-social%2F1700000000000000001&vm=post)`, `- Posted wrong: "The second shop closed in the spring." [post by synthbaker, 2026-03-02](${ORIGIN}/?v=synth-social%2F1700000000000000002&vm=post)`, "", ].join("\n"); const c = await convertSweepText(md, { id: "t-1", cuesOf }); assert.ok(c.ok); const postTextOf = async (ch: string, id: string) => POSTS.find((p) => p.channelSlug === ch && p.id === id)?.text ?? null; const problems = await checkQuotes(c.report, { cuesOf, postTextOf }); assert.equal(problems.length, 2); assert.match(problems[0]!.why, /not verbatim within 90 s/); assert.match(problems[0]!.near!, /\[10\] I did not enter the contest this year/); assert.match(problems[1]!.why, /not the post's words/); const d = dropFailedFindings(md, problems); assert.equal(d.dropped.length, 2); assert.ok(!d.md.includes("I did enter the contest this year")); assert.ok(!d.md.includes("The second shop closed")); assert.ok(d.md.includes(md.split("\n")[4]!), "the good finding as it was"); // An outside verifier adds what it found; an inexact (a warning) is not one. const more = await checkQuotes(c.report, { cuesOf, postTextOf, verifyReport: async () => [ { citation: "p01", status: "drift", message: "x" }, { citation: "c01", status: "inexact" }, { citation: "c99", status: "en-orig-drift", message: "served en rewrote it" }, ], }); assert.ok(more.some((p) => /verify-quotes: en-orig-drift — served en rewrote it/.test(p.why))); assert.ok(!more.some((p) => /inexact/.test(p.why)), "an inexact is a warning, not a problem"); assert.ok(more.length > problems.length); }); test("quotes: a generated fragment is a failing quote whose repair hint is the full sentence (testing/draft/sweeps/fragment.md)", async () => { const md = await readFile(path.join(DRAFT_SWEEPS, "fragment.md"), "utf8"); const c = await convertSweepText(md, { id: "frag", cuesOf }); assert.ok(c.ok); if (!c.ok) return; const problems = await checkQuotes(c.report, { cuesOf }); assert.equal(problems.length, 3); const by = Object.fromEntries(problems.map((p) => [p.quote, p])); assert.equal(by["I paid for the"]!.fragment!.sentence, "I paid for the new mixer myself"); assert.match(by["I paid for the"]!.why, /a fragment \(ends on “the”\).*quote the whole sentence: "I paid for the new mixer myself"/); assert.equal(by["my lawyer told me not to"]!.fragment!.sentence, "my lawyer told me not to talk about the lease"); assert.match(by["I did not"]!.why, /under 4 words.*"I did not enter the contest this year"/); // Still a fragment after the repair round: the finding goes, the whole one stays. const d = dropFailedFindings(md, problems); assert.equal(d.dropped.length, 3); assert.ok(d.md.includes('"I have never met the other finalist"')); // A verify-quotes `fragment` is a warning, not one more problem. const more = await checkQuotes(c.report, { cuesOf, verifyReport: async () => [{ citation: "c04", status: "fragment" }] }); assert.equal(more.length, 3); }); test("narrate: a card's evidence; the better draft kept, failing sentences removed, never rewritten", async () => { const report = { title: "The baker", summary: "She talks about the contest.", sections: [{ title: "The contest", claims: [{ text: "She did not enter [x](cite:c1)", citations: ["c1"] }] }], citations: { c1: { quote: "I did not enter the contest this year", date: "2026-02-10" } }, }; const ctx = cardContext({ type: "card", id: "c", style: "chapter", heading: "The contest" }, report)!; assert.match(ctx.text, /- Claim: She did not enter x \(2026-02-10\)\n {2}Quote: I did not enter the contest this year/); assert.deepEqual(ctx.quotes, ["I did not enter the contest this year"]); assert.equal(cardContext({ type: "card", id: "c", style: "chapter", heading: "Nope" }, report), null); assert.match(cardContext({ type: "card", id: "t", style: "title" }, report)!.text, /OPENING card/); const g = { ...groundingInputOf(report), quotes: ctx.quotes }; const best = chooseDraft( [ { text: "She stayed out of the contest this year. She said I did not enter the contest this year.", hard: ["repeats a quote"], soft: [] }, { text: "x", hard: ["a", "b"], soft: [] }, ], g, 45, ); assert.deepEqual(best.hard, []); assert.equal(best.text.includes("I did not enter the contest this year"), false); assert.ok(best.soft.some((s) => s.startsWith("trimmed"))); }); test("corpus cues: get_transcript's timestamped lines as cues, each ending where the next begins", async () => { const { parseTimestampedTranscript, corpusCuesOf } = await import("./corpusCues"); const text = "# Pie\n\n## Transcript\n\n[[0:00](https://v.example/watch?v=p)] good evening\n[[0:05](https://v.example/watch?v=p&t=5s)] a lot of you asked\n[[1:02:03](https://v.example/watch?v=p&t=3723s)] late line\n\n(corpus: x)"; const cues = parseTimestampedTranscript(text); assert.deepEqual(cues.map((c) => [c.start, c.text]), [[0, "good evening"], [5, "a lot of you asked"], [3723, "late line"]]); assert.equal(cues[0]!.end, 4.99); let calls = 0; const of = corpusCuesOf({ call: async () => (calls++, text) }); assert.equal((await of("c", "p"))!.length, 3); await of("c", "p"); assert.equal(calls, 1, "read once per recording"); assert.equal(await corpusCuesOf({ call: async () => { throw new Error("no"); } })("c", "x"), null); }); test("a two-line finding whose quote failed the strict check is dropped (the claim on the bullet, the quote under it)", async () => { const md = await readFile(new URL("../../../../testing/draft/sweeps/two-line.md", import.meta.url), "utf8"); const { md: out, dropped } = dropFailedFindings(md, [ { citation: "c1", channel: "synth-kitchen", id: "bread-day-01", second: 15, quote: "I would never sell the bakery to a chain", why: "not verbatim" }, ]); assert.equal(dropped.length, 1); assert.doesNotMatch(out, /would not sell the bakery|I would never sell/); assert.match(out, /we never said that about the old oven/); });