Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit cebf0b1a412a2a378f34dd428fc483bbe3f08a96
parent 64fb4350e806af06d36c58541e0e738caa15fd64
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 23:10:42 -0400

Merge r28/media-d: release 28 M1 cut, M2 on-screen, M3 teaser, the media task framework hooks

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

# Conflicts:
#	plans/release-28.md

Diffstat:
MSETTINGS.md | 10++++++++++
Mcommon/controller/reportDraft.ts | 14++++++++++++--
Mcommon/lib/generationSettings.test.ts | 6++++++
Mcommon/lib/generationSettings.ts | 16++++++++++++++++
Mcommon/lib/report/convertManifest.ts | 10++++++++++
Mcommon/lib/report/draft/grounding.ts | 37+++++++++++++++++++++++++------------
Acommon/lib/report/draft/tasks/cut.test.ts | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/cut.ts | 419+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/deckChecks.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/index.ts | 27++++++++++++++-------------
Mcommon/lib/report/draft/tasks/media.test.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/media.ts | 186++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Mcommon/lib/report/draft/tasks/narrate.ts | 1+
Acommon/lib/report/draft/tasks/onscreen.test.ts | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/onscreen.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/teaser.test.ts | 143+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/teaser.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/types.ts | 5+++++
Mcommon/lib/report/drafted.d.mts | 2++
Mcommon/lib/report/drafted.mjs | 9+++++++++
Mcommon/lib/settingsDocs.ts | 2++
Mcommon/lib/settingsSchema.ts | 1+
Mcommon/testing/draft/manifests/basic.video.manifest.json | 10+++++++++-
Mcommon/testing/draft/manifests/paragraphs.video.manifest.json | 10+++++++++-
Mcommon/testing/draft/manifests/posts-only.video.manifest.json | 10+++++++++-
Acommon/testing/draft/runMediaStep.ts | 73+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/runs/cut.json | 20++++++++++++++++++++
Acommon/testing/draft/runs/onscreen.json | 20++++++++++++++++++++
Acommon/testing/draft/runs/teaser.json | 20++++++++++++++++++++
Meditor/CHANGELOG.md | 3+++
Meditor/e2e/report-draft.spec.ts | 45+++++++++++++++++++++++++++++++++++++++++++--
Mplans/FACTS.md | 29+++++++++++++++++++++++++++--
Mplans/release-28.md | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msettings.json.example | 3+++
Mumtool/app/api/articles/generate/route.ts | 5++++-
Mumtool/components/projects/ReportProject.tsx | 5+++--
Mumtool/e2e/fixtures/editor-stub.mjs | 52++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/media-draft-fixture.mjs | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/e2e/media-draft.spec.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/articles/generation.ts | 2+-
Mumtool/report-to-video/drafts-review.mjs | 6++++--
Mumtool/report-to-video/drafts-review.test.mjs | 14++++++++++++++
43 files changed, 2293 insertions(+), 91 deletions(-)

diff --git a/SETTINGS.md b/SETTINGS.md @@ -966,6 +966,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `web` | object — see below | The web an agent may read for context (below). Read-only and paced: one request at a time, 3 s apart. | | `citationOrigin` | `""` | The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site. | | `research` | object — see below | A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'. | +| `cut` | object — see below | The cut task's limits (below). | | `verdicts` | object — see below | The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`. | #### `generation.routes` @@ -1020,6 +1021,12 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `newChannelsNeedApproval` | `true` | Under `limits`, a new channel waits for approval. (A new channel is always created on no site.) | | `postWalksNeedApproval` | `true` | Under `limits`, a walk over an account's post history (`fetch-posts` full or older) waits for approval. | +#### `generation.cut` + +| Key | Default | Description | +|---|---|---| +| `maxClips` | `20` | The most entries a drafted cut keeps: clips and stills chosen from the report's citations (at least 3; the code refuses a longer selection, whatever the model says). | + #### `generation.verdicts` | Key | Default | Description | @@ -1075,6 +1082,9 @@ Default: "searchUrl": "" }, "citationOrigin": "", + "cut": { + "maxClips": 20 + }, "research": { "autonomy": "propose", "maxItemsPerRun": 20, diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -43,7 +43,7 @@ import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { JobProgress } from "../jobs/registry"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; -import type { Paths } from "../lib/paths"; +import { getPaths, type Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import { GENERATION_TASKS, capFor, isStepTask, type GenerationSettings, type GenerationTask } from "../lib/generationSettings"; import { PROJECT_URL } from "../lib/project"; @@ -62,6 +62,7 @@ import { diskPostChannelOf } from "../lib/report/convert-server"; import { readAllPosts } from "../lib/posts-server"; import { runTask, type TaskDeps, type TaskInput, type TaskResult, pickCorpusBuild, siteOriginOf } from "../lib/report/draft/tasks/index"; import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues"; +import { loadDeckChecks, type DeckChecks } from "../lib/report/draft/tasks/deckChecks"; import type { CorpusToolsLike } from "../lib/report/draft/tasks/types"; import { verifyReportQuotes } from "../bin/reports-check"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; @@ -478,6 +479,7 @@ async function runReportDraft( } return p.then((m) => m.get(id) ?? null); }; + let deck: Promise<DeckChecks> | undefined; const taskDeps: TaskDeps = { llm: llmConfigOf(gen, paths, provider === "local" ? { onLog, signal } : undefined), corpus, @@ -497,6 +499,9 @@ async function runReportDraft( // The task's count as the job's progress (release 28 F3): turns, cards // or entries, the runner's own `current` (nothing on disk re-counts it). progress: (p) => o.setProgress?.({ metric: p.metric, initial: 0, target: Math.max(p.total ?? p.current, p.current), current: p.current }), + // The build's validators, from this checkout's umtool (loaded once, when + // a media task first asks). + deckChecks: () => (deck ??= loadDeckChecks(paths.monorepoRoot || getPaths().monorepoRoot)), signal, ...(deps.now ? { now: deps.now } : {}), ...(body.task === "research" && deps.researchEditor ? { editor: deps.researchEditor, editorChannels: () => editorChannelsOf(paths) } : {}), @@ -550,7 +555,12 @@ async function runReportDraft( ...(body.entries ? { entries: body.entries } : {}), ...(body.force ? { force: true } : {}), }; - input = body.task === "narrate" ? { task: "narrate", ...step, ...(body.cards ? { cards: body.cards } : {}) } : { task: body.task, ...step }; + input = + body.task === "narrate" + ? { task: "narrate", ...step, ...(body.cards ? { cards: body.cards } : {}) } + : body.task === "cut" + ? { task: "cut", ...step, maxClips: gen.cut.maxClips } + : { task: body.task, ...step }; break; } } diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -105,6 +105,12 @@ test("the media drafts (release 28): steps, each with narrate's route in every p assert.equal(sanitizeGeneration({ routes: { ...GENERATION_PRESETS.api, teaser: "local" } }).preset, "custom"); }); +test("cut (release 28 M1): the most entries a drafted cut keeps, 20 by default, a whole number from 3", () => { + assert.equal(sanitizeGeneration(undefined).cut.maxClips, 20); + assert.equal(sanitizeGeneration({ cut: { maxClips: 12 } }).cut.maxClips, 12); + for (const bad of [2, 12.5, -1, "12", null]) assert.equal(sanitizeGeneration({ cut: { maxClips: bad } }).cut.maxClips, 20, String(bad)); +}); + test("generation settings: the verdict bench's bar (fractions, clamped) and the ticked models; none by default", () => { assert.deepEqual(DEFAULT_GENERATION_SETTINGS.verdicts, { bar: { agreement: 0, contradictedRecall: 0, notFoundRecall: 0 }, models: [] }); assert.deepEqual(sanitizeGeneration({}).verdicts, DEFAULT_GENERATION_SETTINGS.verdicts); diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -55,6 +55,8 @@ export type GenerationResearch = { postWalksNeedApproval: boolean; }; +// The cut task's limits (release 28 M1). +export type GenerationCut = { maxClips: number }; // The verdict bench's bar and the models that cleared it (release 28 M7): // the bar is the operator's, set on umtool's /bench after reading a run; // `models` are the passing models the operator ticked — never set @@ -75,6 +77,7 @@ export type GenerationSettings = { web: GenerationWeb; citationOrigin: string; research: GenerationResearch; + cut: GenerationCut; verdicts: GenerationVerdicts; }; @@ -97,6 +100,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = { web: { provider: "duckduckgo", searchUrl: "" }, citationOrigin: "", research: { ...DEFAULT_GENERATION_RESEARCH }, + cut: { maxClips: 20 }, verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [] }, }; @@ -117,6 +121,7 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { citationOrigin: "The origin a generated report's moment links cite when its corpus build's site has no public URL (a private build). Blank = the project site.", research: "A research run's default autonomy and its limits (below). A run may name its own autonomy; the limits are the settings'.", + cut: "The cut task's limits (below).", verdicts: "The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`.", }; @@ -132,6 +137,11 @@ export const GENERATION_VERDICT_BAR_FIELD_DOCS: FieldDocs<GenerationVerdictBar> notFoundRecall: "The least share of the claims the operator ruled NOT_FOUND that the model must rule so.", }; +export const GENERATION_CUT_FIELD_DOCS: FieldDocs<GenerationCut> = { + maxClips: + "The most entries a drafted cut keeps: clips and stills chosen from the report's citations (at least 3; the code refuses a longer selection, whatever the model says).", +}; + export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = { sweep: "A new report from a question: `code` (/sweep in Claude Code), `api` (the agent on `models.api`) or `local` (the code-driven pipeline on `models.local`).", "revise-report": "A report iteration from feedback, through checked ops.", @@ -248,6 +258,12 @@ export function sanitizeGeneration(value: unknown): GenerationSettings { projectsRoot: str(r.projectsRoot, d.projectsRoot), web: { provider: "duckduckgo", searchUrl: url(w.searchUrl, d.web.searchUrl) }, citationOrigin: url(r.citationOrigin, d.citationOrigin), + cut: { + maxClips: (() => { + const ct = r.cut && typeof r.cut === "object" && !Array.isArray(r.cut) ? (r.cut as Record<string, unknown>) : {}; + return typeof ct.maxClips === "number" && Number.isInteger(ct.maxClips) && ct.maxClips >= 3 && ct.maxClips <= 500 ? ct.maxClips : d.cut.maxClips; + })(), + }, research: { autonomy: (AUTONOMIES as readonly string[]).includes(String(rs.autonomy)) ? (rs.autonomy as Autonomy) : dr.autonomy, maxItemsPerRun: Math.floor(count(rs.maxItemsPerRun, dr.maxItemsPerRun, 10_000)), diff --git a/common/lib/report/convertManifest.ts b/common/lib/report/convertManifest.ts @@ -36,6 +36,9 @@ // them: relative to ITS directory (the CLI says so when the report is written // elsewhere). // +// The starter's timeline is marked drafted by code (`drafted.timeline`, +// `{task: "convert", model: "code"}`): the cut task may redraft its order. +// // A report → a STARTER manifest: no cold open — a title card, then per section // a chapter card, its body's citations in order, and per claim its source // sentence's still (an `image`) and its video and audio citations (`clip`s), @@ -65,6 +68,10 @@ import { isVerdict, type Verdict } from "./verdicts"; import { parseReport } from "./validate"; import { reportFullTitle } from "./views"; import type { Problem } from "../citations/validate"; +import { makeProvenance } from "./drafted.mjs"; + +// The provenance task of a timeline this converter made (`model: "code"`). +export const CONVERT_TASK = "convert"; type Obj = Record<string, unknown>; @@ -566,6 +573,9 @@ export async function reportToManifest(raw: unknown, opts: ManifestOptions = {}) timelineNodes: [], timeline, ...(posts.length ? { posts } : {}), + // The order is code's (release 28 M1): the cut task may redraft it, and it + // needs no review. An operator's reorder in umtool clears the mark. + drafted: { timeline: makeProvenance({ task: CONVERT_TASK, model: "code", at: opts.today ? `${opts.today}T00:00:00.000Z` : new Date(), attempt: 1 }) }, }; return { ok: true, manifest, warnings }; } diff --git a/common/lib/report/draft/grounding.ts b/common/lib/report/draft/grounding.ts @@ -213,23 +213,25 @@ export function sentencesOf(text: string): string[] { const hasWord = (normText: string, w: string) => ` ${normText} `.includes(` ${w} `); -export function checkNarration(text: string, input: GroundingInput): GroundingResult { - const hard = new Set<string>(); - const soft = new Set<string>(); +/** + * The numbers (digits or words) and names (a capitalised word past a + * sentence's first that is not a common one) in `text` that `reference` does + * not have, as sentences naming `where` ("the report"; a media task's own + * evidence). What checkNarration grounds; release 28's on-screen and teaser + * drafts ground the same way. + */ +export function groundedProblems(text: string, reference: string, where = "the report"): string[] { + const out = new Set<string>(); const low = text.toLowerCase(); - if (/<[^>]+>/.test(text)) hard.add("has a tag in angle brackets"); - for (const b of BANNED_PHRASES) if (low.includes(b)) hard.add(`stock phrase “${b}”`); - - const ref = input.reference; - const refNorm = strictNormalize(ref); - const refNums = new Set(ref.replace(/,/g, "").match(/\d+/g) ?? []); + const refNorm = strictNormalize(reference); + const refNums = new Set(reference.replace(/,/g, "").match(/\d+/g) ?? []); for (const d of text.match(/\d[\d,]*/g) ?? []) { - if (!refNums.has(d.replace(/,/g, ""))) hard.add(`number ${d} is not in the report`); + if (!refNums.has(d.replace(/,/g, ""))) out.add(`number ${d} is not in ${where}`); } for (const w of low.match(/[a-z]+/g) ?? []) { const n = NUM_WORDS[w]; if (n === undefined) continue; - if (!hasWord(refNorm, w) && !refNums.has(String(n))) hard.add(`number “${w}” is not in the report`); + if (!hasWord(refNorm, w) && !refNums.has(String(n))) out.add(`number “${w}” is not in ${where}`); } for (const sent of sentencesOf(text)) { const toks = sent.match(/[A-Za-z][A-Za-z'’.-]*/g) ?? []; @@ -237,9 +239,20 @@ export function checkNarration(text: string, input: GroundingInput): GroundingRe const t = raw.replace(/^[.\-’']+|[.\-’']+$/g, ""); if (!/^[A-Z]/.test(t) || COMMON_CAPS.has(t)) continue; const n = strictNormalize(t.replace(/['’]s$/, "")); - if (n && !refNorm.includes(n)) hard.add(`name “${t}” is not in the report`); + if (n && !refNorm.includes(n)) out.add(`name “${t}” is not in ${where}`); } } + return [...out]; +} + +export function checkNarration(text: string, input: GroundingInput): GroundingResult { + const hard = new Set<string>(); + const soft = new Set<string>(); + const low = text.toLowerCase(); + if (/<[^>]+>/.test(text)) hard.add("has a tag in angle brackets"); + for (const b of BANNED_PHRASES) if (low.includes(b)) hard.add(`stock phrase “${b}”`); + + for (const p of groundedProblems(text, input.reference)) hard.add(p); if (/(^|\s)'[^']+(\s[^']+){3,}'/.test(text) || /["“”]/.test(text)) { hard.add("text in quotation marks: no quotes in narration"); } diff --git a/common/lib/report/draft/tasks/cut.test.ts b/common/lib/report/draft/tasks/cut.test.ts @@ -0,0 +1,209 @@ +// TASK cut (release 28 M1) over the S0 kit's manifests and the basic report, +// against the fake ollama: each code check refuses what it should, the better +// of two attempts is kept, the timeline is BUILT by code from the entries it +// had (and the umtool lint passes on it), the order's owner is the M1 ruling's, +// and an operator's order is never replaced. Real iterations store and project +// in a temp dir; the build's validators loaded from this checkout. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "../../iterations"; +import { reportToManifest } from "../../convertManifest"; +import { buildCut, checkCut, cut, cutCandidates, isConverterOrder, parseCut, pinnedEntries, CUT_SPEC } from "./cut"; +import { loadDeckChecks, type DeckChecks } from "./deckChecks"; +import type { DraftFile } from "./media"; +import type { TaskDeps } from "./types"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(HERE, "../../../../.."); +const DRAFT = new URL("../../../../testing/draft/", import.meta.url); +const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); +const run = promisify(execFile); + +let tmp: string; +let ol: FakeOllama; +let deck: DeckChecks; +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "cut-task-")); + ol = await startFakeOllama(); + deck = await loadDeckChecks(ROOT); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +let caseN = 0; +async function project(manifest: unknown, report?: 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 r = report ?? (await kit("reports/basic.report.json")); + await writeIterationFile("synth-basic", 1, "report.json", r, 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(r)); + await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths); + const lines: string[] = []; + const progress: unknown[] = []; + const deps: TaskDeps = { + llm: { ollama: { baseUrl: ol.url } }, + corpus: { source: "none", tools: [], call: async () => "" }, + cuesOf: async () => null, + paths, + log: (l) => lines.push(l), + progress: (p) => progress.push(p), + now: () => new Date("2026-10-13T12:00:00.000Z"), + deckChecks: async () => deck, + }; + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const draft = async () => JSON.parse(await readFile(path.join(dir, "cut-draft.json"), "utf8")) as DraftFile; + const input = (o: Record<string, unknown> = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o }); + return { dir, paths, projectsRoot, deps, lines, progress, manifestNow, draft, input }; +} + +const ids = (m: { timeline: { id: string }[] }) => m.timeline.map((e) => e.id); + +test("cut, the recorded run: the better of two attempts, the timeline built from the entries it had, marked, and the umtool lint passes", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + assert.equal(m.drafted.timeline.model, "code", "the converter marks its order"); + const p = await project(m); + const r = await kit("runs/cut.json"); + ol.push(...r.turns); + const out = await cut(p.input({ maxClips: 20 }), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(ol.remaining(), 0); + assert.match(out.summary, /^1 cut\(s\) drafted \(undo: revisions\/.*-auto-before-cut\.manifest\.json\)$/); + const after = await p.manifestNow(); + assert.deepEqual(ids(after), ["title", "the-contest", "c04", "c06", "the-bakery", "c03", "c01"]); + // Entries untouched: the same objects, moved. + for (const e of after.timeline) assert.deepEqual(e, m.timeline.find((x: { id: string }) => x.id === e.id)); + assert.deepEqual(after.drafted.timeline, { task: "cut", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 2 }); + const file = await p.draft(); + const u = file.units.cut as { attempts: { hard: string[] }[]; applied: string }; + assert.equal(u.applied, "applied"); + assert.equal(u.attempts.length, 2); + assert.match(u.attempts[0]!.hard.join("\n"), /not a candidate of this cut: c09/); + assert.match(u.attempts[0]!.hard.join("\n"), /chosen more than once: c01/); + assert.deepEqual(p.progress, [ + { metric: "entries", current: 0, total: 1 }, + { metric: "entries", current: 1, total: 1 }, + ]); + const it = (await readIteration("synth-basic", 1, p.paths))!; + assert.equal(it.status, "done"); + assert.equal(it.steps.find((s) => s.task === "cut")!.status, "done"); + // The umtool lint over the written manifest (a node child, as a build runs it). + const lint = await run(process.execPath, [path.join(ROOT, "umtool/report-to-video/lint.mjs"), path.join(p.dir, "video.manifest.json"), "--json"]).catch((e) => e); + const res = JSON.parse(lint.stdout); + assert.deepEqual(res.errors, [], lint.stdout); +}); + +test("cut's checks: ids, twice, the cap and the floor, a pinned id, headings, and what would not build", async () => { + const report = await kit("reports/basic.report.json"); + const unitOf = async (m: unknown, maxClips = 20) => { + const p = await project(m, report); + const ctx = { manifest: m, report, input: p.input({ maxClips }), handle: { deps: p.deps, log: () => {} } } as never; + return { u: ((await CUT_SPEC.units(ctx)) as never[])[0] as never, m: m as never }; + }; + const basic = await kit("manifests/basic.video.manifest.json"); + const { u } = await unitOf(basic, 4); + const g = (...groups: [string, string[]][]) => ({ groups: groups.map(([heading, clips]) => ({ heading, clips })) }); + const hard = (v: ReturnType<typeof g>, man: unknown = basic, unit: never = u) => checkCut(v, unit, man as never).hard; + assert.deepEqual(hard(g(["The bakery", ["c01", "c02"]], ["The contest", ["c04"]])), []); + assert.match(hard(g(["The bakery", ["c01", "c02", "c99"]]))[0]!, /not a candidate of this cut: c99/); + assert.match(hard(g(["The bakery", ["c01", "c02", "c02"]])).join(), /chosen more than once: c02/); + assert.match(hard(g(["The bakery", ["c01", "c02", "c03"]], ["The contest", ["c04", "c05"]])).join(), /5 ids chosen \(at most 4\)/); + assert.match(hard(g(["The bakery", ["c01", "c02"]])).join(), /2 ids chosen \(at least 3\)/); + assert.match(hard(g(["The oven", ["c01", "c02", "c03"]])).join(), /"The oven" is not a section heading of this cut/); + assert.match(hard(g(["The bakery", ["c01"]], ["the bakery", ["c02", "c03"]])).join(), /"the bakery" heads two groups/); + // A post rides on c02: it must stay. + const withPost = { ...basic, posts: [{ id: "p01", platform: "x", date: "2026-01-05", text: "x", url: "https://x.com/i/status/1", attachTo: "c02" }] }; + const pu = (await unitOf(withPost)).u; + assert.match(hard(g(["The bakery", ["c01", "c03"]], ["The contest", ["c04"]]), withPost, pu).join(), /c02 must stay \(post p01 rides on it\)/); + // The full kit's threads: dropping every contest clip leaves a thread with none. + const full = await kit("manifests/full.video.manifest.json"); + const fu = (await unitOf(full)).u; + assert.match(hard(g(["The bakery", ["c01", "c02", "c03"]]), full, fu).join(), /the cut would not build: render\.chrome\.threads: thread contest has no clip/); + assert.deepEqual(hard(g(["The contest", ["c05"]], ["The bakery", ["c03", "c01"]]), full, fu), []); + // parse: a flat list is one group; empty groups go. + assert.deepEqual(parseCut({ clips: [" c01 ", "c02"] }), { groups: [{ heading: "", clips: ["c01", "c02"] }] }); + assert.throws(() => parseCut({ nope: 1 }), /no "groups"/); +}); + +test("buildCut: cards kept for sections with entries, a card with nothing dropped, head and tail in place, twins together, nothing invented", async () => { + const full = await kit("manifests/full.video.manifest.json"); + const report = await kit("reports/basic.report.json"); + const cands = cutCandidates(full, report); + assert.deepEqual(cands.map((c) => [c.citation, c.entry, c.chapter]), [ + ["c01", "c01", "The bakery"], ["c02", "c02", "The bakery"], ["c03", "c03", "The bakery"], + ["c04", "c04", "The contest"], ["c05", "c05", "The contest"], ["c06", "c06", "The contest"], + ]); + // c07 is cited by no citation of this report: after the last candidate, it stays with the teaser. + const t = buildCut(full, cands, { groups: [{ heading: "The contest", clips: ["c06", "c04"] }, { heading: "The bakery", clips: ["c03"] }] }); + assert.deepEqual(t.map((e) => e.id), ["title", "the-contest", "c06", "c04", "the-bakery", "c03", "c07", "fin"]); + // No chapter for a group with no heading; the bakery card dropped (nothing left in it). + const t2 = buildCut(full, cands, { groups: [{ heading: "The contest", clips: ["c04", "c05", "c02"] }] }); + assert.deepEqual(t2.map((e) => e.id), ["title", "the-contest", "c04", "c05", "c02", "c07", "fin"]); + // Variant twins move together; a hand-added entry stays in its chapter. + const tw = structuredClone(full); + const i = tw.timeline.findIndex((e: { id: string }) => e.id === "c02"); + tw.timeline.splice(i + 1, 0, { ...tw.timeline[i], variant: "full", start: 26 }, { type: "image", id: "still-1", src: "s.png", seconds: 4, title: "A still" }); + const t3 = buildCut(tw, cutCandidates(tw, report), { groups: [{ heading: "The contest", clips: ["c04"] }, { heading: "The bakery", clips: ["c02"] }] }); + assert.deepEqual(t3.map((e) => `${e.id}${e.variant ? `/${e.variant}` : ""}`), ["title", "the-contest", "c04", "the-bakery", "still-1", "c02", "c02/full", "c07", "fin"]); + // Pins: posts and flips. + const flips = await kit("manifests/flips.video.manifest.json"); + assert.deepEqual([...pinnedEntries(flips).keys()], ["c01", "c07"]); +}); + +test("who owns the order (the M1 ruling): code's is drafted over, the converter's unmarked too; a model's needs force; the operator's never", async () => { + const basic = await kit("manifests/basic.video.manifest.json"); + const report = await kit("reports/basic.report.json"); + const answer = jsonReply({ groups: [{ heading: "The bakery", clips: ["c03", "c02", "c01"] }] }); + // (2) No mark, the converter's order: code-made. + const unmarked = structuredClone(basic); + delete unmarked.drafted; + assert.equal(await isConverterOrder(unmarked, report), true); + const p1 = await project(unmarked); + ol.push(answer); + assert.equal((await cut(p1.input(), p1.deps)).status, "done"); + assert.deepEqual(ids(await p1.manifestNow()), ["title", "the-bakery", "c03", "c02", "c01"]); + // A model's draft: skipped without force, redrafted with it. + const again = await cut(p1.input(), p1.deps); + assert.equal(again.status, "failed"); + assert.match(String((await p1.draft()).units.cut!.skipped), /has a value \(a draft\); force re-drafts it/); + ol.push(answer); + assert.equal((await cut(p1.input({ force: true }), p1.deps)).status, "done"); + // The operator's: unmarked and not the converter's order — never replaced, even forced. + const mine = structuredClone(unmarked); + const [a, b] = [2, 3].map((i) => mine.timeline[i]); + mine.timeline.splice(2, 2, b, a); + assert.equal(await isConverterOrder(mine, report), false); + const p2 = await project(mine); + const skipped = await cut(p2.input(), p2.deps); + assert.equal(skipped.status, "failed"); + assert.match(String((await p2.draft()).units.cut!.skipped), /the operator's/); + ol.push(answer); + const forced = await cut(p2.input({ force: true }), p2.deps); + assert.equal(forced.status, "done"); + assert.match(forced.summary, /0 cut\(s\) drafted, 1 as alternatives/); + assert.deepEqual(ids(await p2.manifestNow()), ids(mine), "the operator's order stands"); + const alt = (await p2.draft()).alternatives; + assert.deepEqual([alt.length, alt[0]!.reason, (alt[0]!.value as { id: string }[]).map((e) => e.id).join(" ")], [1, "operator", "title the-bakery c03 c02 c01"]); + assert.equal(ol.remaining(), 0); +}); + +test("the converter marks its timeline as code's, at the day it was made", async () => { + const made = await reportToManifest(await kit("reports/basic.report.json"), { today: "2026-10-13" }); + assert.ok(made.ok); + assert.deepEqual((made.manifest as { drafted: unknown }).drafted, { timeline: { task: "convert", model: "code", at: "2026-10-13T00:00:00.000Z", attempt: 1 } }); +}); diff --git a/common/lib/report/draft/tasks/cut.ts b/common/lib/report/draft/tasks/cut.ts @@ -0,0 +1,419 @@ +// TASK cut — which of the report's citations a video's cut keeps, and in what +// order (release 28 M1). A STEP on a done iteration (./media.ts), one unit: +// the timeline's ORDER (`drafted.timeline`). +// +// The model sees the report's claims (section, text, verdict) with the +// citation ids the cut can show and their quotes, and answers an ordered list +// of ids grouped under the section headings. Code checks it — ids only from +// the candidates, none twice, at least CUT_MIN_CLIPS and at most `maxClips` +// (settings.generation.cut.maxClips), every pinned id kept (a post rides on +// it, a flip names it), headings that are the cut's — and then BUILDS the +// timeline itself (`buildCut`): the existing entries of the chosen citations, +// untouched (their windows, cite, quote, on-screen text: fetch and snap stay +// code), chapter cards kept for the sections that still have entries and +// dropped when nothing is left (S7's rule), the title card and everything +// before the first chapter, the teaser and everything after the last clip, +// kept where they are. It never invents an entry. The built cut must pass the +// build's own validators as the cut it replaces did (`TaskDeps.deckChecks`). +// +// WHO OWNS THE ORDER (the M1 ruling). A timeline marked by a code path +// (`model: "code"` — the converter's, `convertManifest.ts`) is nobody's: the +// task drafts it without `force`. So is an unmarked one whose clips, in order, +// are exactly what the converter makes from the project's report (a project +// from before release 28). One marked by a model is a draft (`force` +// redrafts it); any other is the operator's, never replaced: the draft goes +// to cut-draft.json as an alternative. +// +// Q0: counts are code's; the prompt carries rules only; the better of two +// attempts is kept; the local prompt is fitted under its cap. + +import { applyDraft, draftedOf, isCodeDraft, makeProvenance } from "../../drafted.mjs"; +import { citedIds } from "../../convertShared"; +import { reportToManifest, CONVERT_TASK } from "../../convertManifest"; +import { providerOf } from "../../../llm"; +import type { ManifestEntry, VideoManifest } from "../videoOps"; +import { fitLocalAsk } from "./revise-report"; +import type { DeckChecks } from "./deckChecks"; +import { runMediaTask, type MediaContext, type MediaReport, type MediaSkip, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import type { TaskDeps, TaskResult } from "./types"; + +export const CUT_MIN_CLIPS = 3; +export const DEFAULT_MAX_CLIPS = 20; +// The room a re-ask's words take on top of the fitted prompt. +const RETRY_ROOM_CHARS = 1500; + +export type CutInput = MediaTaskInput & { + // settings.generation.cut.maxClips (the job passes it). + maxClips?: number; +}; + +/** One citation the cut can show: its entry in the timeline, and what the report says of it. */ +export type CutCandidate = { + citation: string; + entry: string; + kind: "clip" | "still"; + // The chapter it sits under now (its card's heading), or "". + chapter: string; + claim: { id?: string; text: string; verdict?: string } | null; + quote: string; + label: string; + date: string; +}; + +/** The model's answer, as code reads it. */ +export type CutValue = { groups: { heading: string; clips: string[] }[] }; + +type Obj = Record<string, any>; +const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v); +const norm = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim().toLowerCase(); +const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); +const isChapter = (e: Obj) => e?.type === "card" && e?.style === "chapter"; +const isCandidateType = (e: Obj) => e?.type === "clip" || e?.type === "image"; + +/** + * The citation each clip or still of the timeline shows: its id when the + * report has a citation of that id (the converter's rule), else the video + * citation of its recording and second. First entry per citation. + */ +export function cutCandidates(manifest: VideoManifest, report: MediaReport): CutCandidate[] { + const cites: Record<string, Obj> = isObj(report.citations) ? report.citations : {}; + const used = new Set<string>(); + const claimOf = new Map<string, { id?: string; text: string; verdict?: string }>(); + for (const s of Array.isArray(report.sections) ? report.sections : []) { + for (const c of Array.isArray(s?.claims) ? s.claims : []) { + const ids = [...(Array.isArray(c?.citations) ? c.citations : []), ...citedIds(typeof c?.findings === "string" ? c.findings : undefined)]; + if (c?.sourceQuote?.citation) ids.unshift(c.sourceQuote.citation); + for (const id of ids) { + if (!claimOf.has(id)) claimOf.set(id, { ...(c.id ? { id: c.id } : {}), text: stripCites(String(c.text ?? "")), ...(c.verdict ? { verdict: c.verdict } : {}) }); + } + } + } + const slug = isObj(manifest.provenance) ? manifest.provenance.channelSlug : undefined; + const out: CutCandidate[] = []; + let chapter = ""; + for (const e of manifest.timeline) { + if (isChapter(e)) chapter = String(e.heading ?? ""); + if (!isCandidateType(e)) continue; + let cid: string | null = cites[e.id] && !used.has(e.id) ? e.id : null; + if (!cid && e.type === "clip") { + const ch = e.channel ?? slug; + cid = + Object.entries(cites).find( + ([id, c]) => + !used.has(id) && (c.kind === "video" || c.kind === "audio") && c.channel === ch && c.id === e.video && typeof c.start === "number" && Math.floor(c.start) === e.cite, + )?.[0] ?? null; + } + if (!cid || used.has(cid)) continue; + used.add(cid); + const c = cites[cid]!; + out.push({ + citation: cid, + entry: e.id, + kind: e.type === "clip" ? "clip" : "still", + chapter, + claim: claimOf.get(cid) ?? null, + quote: String(e.quote ?? c.quote ?? ""), + label: String(c.label ?? ""), + date: String(e.date ?? c.date ?? ""), + }); + } + return out; +} + +/** The entries something else names, which a cut must keep: posts ride on them, flips pair them. */ +export function pinnedEntries(manifest: VideoManifest): Map<string, string> { + const out = new Map<string, string>(); + for (const p of Array.isArray(manifest.posts) ? manifest.posts : []) { + if (isObj(p) && typeof p.attachTo === "string" && p.attachTo) out.set(p.attachTo, `post ${p.id ?? "?"} rides on it`); + } + const pairs = isObj(manifest.render) && isObj(manifest.render.chrome) && isObj(manifest.render.chrome.flips) ? manifest.render.chrome.flips.pairs : null; + for (const pr of Array.isArray(pairs) ? pairs : []) { + for (const side of ["then", "now"]) { + const id = isObj(pr?.[side]) ? pr[side].entry : null; + if (typeof id === "string" && id) out.set(id, `flip ${pr.id ?? "?"} pairs it`); + } + } + return out; +} + +/** + * The cut the answer makes (pure; the timeline's entries only, never a new + * one): what is before the first chapter or citation entry stays first, what + * is after the last citation entry stays last (the teaser), and between them + * each group plays under its chapter card (kept only when the group keeps an + * entry), its chosen entries in the answer's order. An entry no citation + * names (a hand-added clip, a still) stays with its chapter, after its card; + * a chapter only such entries keep goes after the groups. Variant twins (one + * id, several entries) move together. + */ +export function buildCut(manifest: VideoManifest, candidates: readonly CutCandidate[], value: CutValue): ManifestEntry[] { + const T = manifest.timeline; + const entryOf = new Map(candidates.map((c) => [c.citation, c.entry])); + const candidateEntries = new Set(candidates.map((c) => c.entry)); + const isCand = (e: ManifestEntry) => candidateEntries.has(e.id) && isCandidateType(e); + const first = T.findIndex((e) => isChapter(e) || isCand(e)); + let last = -1; + T.forEach((e, i) => { + if (isCand(e)) last = i; + }); + if (first < 0 || last < 0) return T.map((e) => ({ ...e })); + const head = T.slice(0, first); + const tail = T.slice(last + 1).filter((e) => !isChapter(e)); + // The chapters between: a card (or none, before the first) and the entries + // under it that no citation names. + type Chapter = { card: ManifestEntry | null; others: ManifestEntry[] }; + const chapters: Chapter[] = [{ card: null, others: [] }]; + for (const e of T.slice(first, last + 1)) { + if (isChapter(e)) { + // A variant twin of a card already seen joins it. + if (chapters.some((c) => c.card?.id === e.id)) continue; + chapters.push({ card: e, others: [] }); + } else if (!isCand(e)) chapters.at(-1)!.others.push(e); + } + const twins = (id: string) => T.filter((e) => e.id === id); + const cardTwins = (c: ManifestEntry) => twins(c.id).filter(isChapter); + const byHeading = new Map<string, Chapter>(); + for (const c of chapters) if (c.card && !byHeading.has(norm(c.card.heading))) byHeading.set(norm(c.card.heading), c); + const placed = new Set<Chapter>(); + const middle: ManifestEntry[] = [...chapters[0]!.others]; + placed.add(chapters[0]!); + for (const g of value.groups) { + const ids = g.clips.map((cid) => entryOf.get(cid)).filter((x): x is string => !!x); + if (!ids.length) continue; + const ch = g.heading.trim() ? byHeading.get(norm(g.heading)) : undefined; + if (ch && !placed.has(ch)) { + placed.add(ch); + middle.push(...cardTwins(ch.card!), ...ch.others); + } + for (const id of ids) middle.push(...twins(id).filter(isCand)); + } + for (const c of chapters) { + if (placed.has(c) || !c.others.length) continue; + middle.push(...(c.card ? cardTwins(c.card) : []), ...c.others); + } + return JSON.parse(JSON.stringify([...head, ...middle, ...tail])) as ManifestEntry[]; +} + +const clipOrder = (timeline: readonly Obj[]) => timeline.filter((e) => e?.type === "clip").map((e) => e.id); + +/** Is this timeline's clip order exactly the converter's from the report (a cut nobody reordered)? */ +export async function isConverterOrder(manifest: VideoManifest, report: MediaReport): Promise<boolean> { + try { + const made = await reportToManifest(report, {}); + if (!made.ok) return false; + const want = clipOrder(made.manifest.timeline as Obj[]); + const have = clipOrder(manifest.timeline); + return want.length === have.length && want.every((id, i) => id === have[i]); + } catch { + return false; + } +} + +type CutUnit = MediaUnit & { + candidates: CutCandidate[]; + pinned: Map<string, string>; + headings: string[]; + max: number; + // The order is code's (a converter mark, or the converter's order unmarked). + codeMade: boolean; + deck: DeckChecks | null; + // The build's validator errors of the cut as read (unindexed): the draft may not add any. + before: Set<string>; +}; + +const words = (s: string, n: number) => { + const w = s.split(/\s+/).filter(Boolean); + return w.length <= n ? w.join(" ") : `${w.slice(0, n).join(" ")} …`; +}; + +// The evidence, at a level of detail: 0 the quotes in full, 1 shortened, +// 2 none, 3 claims shortened too. +function evidenceText(u: CutUnit, report: MediaReport, level: number): string { + const lines = [`Report: ${String(report.title ?? "")}`, "", "Candidates, by the section each sits in now:"]; + let chapter: string | null = null; + let claim: string | null = null; + for (const c of u.candidates) { + if (c.chapter !== chapter) { + chapter = c.chapter; + claim = null; + lines.push("", `## ${c.chapter || "(before the first section)"}`); + } + const ct = c.claim ? `${c.claim.verdict ? `[${c.claim.verdict}] ` : ""}${level >= 3 ? words(c.claim.text, 15) : c.claim.text}` : "(no claim: cited in the section's text)"; + if (ct !== claim) { + claim = ct; + lines.push(`- Claim: ${ct}`); + } + const where = [c.kind === "still" ? "a still" : "a clip", c.label, c.date].filter(Boolean).join(", "); + const q = level >= 2 || !c.quote ? "" : ` — "${level === 1 ? words(c.quote, 10) : words(c.quote, 40)}"`; + lines.push(` - ${c.citation} (${where})${q}`); + } + const pinned = u.candidates.filter((c) => u.pinned.has(c.entry)); + lines.push("", `Section headings: ${u.headings.map((h) => `"${h}"`).join(", ") || "(none)"}`); + if (pinned.length) lines.push(`Must stay: ${pinned.map((c) => `${c.citation} (${u.pinned.get(c.entry)})`).join("; ")}`); + lines.push(`Choose from ${CUT_MIN_CLIPS} to ${u.max} ids.`); + return lines.join("\n"); +} + +export function cutSystem(max: number): string { + const rules = [ + "Use only the citation ids listed under the candidates, each at most once.", + `Choose at least ${CUT_MIN_CLIPS} and at most ${max} ids in all.`, + "Keep every id listed under Must stay.", + "Order the ids so the video builds its case: each one sets up or supports what follows, and the strongest evidence is not buried in the middle.", + "Group them under the report's section headings, written exactly as given, in the order the groups play; each heading heads at most one group. An id may move to the group where it argues best.", + "When two candidates show the same thing, keep the clearer one and leave the other out.", + "Do not add anything that is not a candidate: no new clips, no new headings.", + ]; + return ( + "You choose the clips of a short evidence video cut from a cited report, and their order. " + + `Rules: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + + 'Answer with "groups": a list of {"heading", "clips"} in play order, "clips" the citation ids in play order.' + ); +} + +const SCHEMA = { + type: "object", + properties: { + groups: { + type: "array", + items: { + type: "object", + properties: { heading: { type: "string" }, clips: { type: "array", items: { type: "string" } } }, + required: ["heading", "clips"], + }, + }, + }, + required: ["groups"], +}; + +/** The model's answer to a CutValue (a throw is a hard failure). */ +export function parseCut(answer: unknown): CutValue { + const a = isObj(answer) ? answer : {}; + const raw = Array.isArray(a.groups) ? a.groups : Array.isArray(a.clips) ? [{ heading: "", clips: a.clips }] : null; + if (!raw) throw new Error('no "groups" in the answer'); + const groups = raw.map((g: unknown) => { + const o = isObj(g) ? g : {}; + const clips = (Array.isArray(o.clips) ? o.clips : []).map((x: unknown) => String(x ?? "").trim()).filter(Boolean); + return { heading: String(o.heading ?? "").replace(/\s+/g, " ").trim(), clips }; + }); + return { groups: groups.filter((g: { clips: string[] }) => g.clips.length) }; +} + +const LIST_AT_MOST = 6; +// A validator's sentence with its timeline positions taken out: a reorder +// moves an old problem, it does not make a new one. +const unindexed = (e: string) => e.replace(/\[\d+\]/g, "[]"); +const listed = (xs: string[]) => (xs.length > LIST_AT_MOST ? [...xs.slice(0, LIST_AT_MOST), `and ${xs.length - LIST_AT_MOST} more`] : xs).join(", "); + +/** Every code check of a cut: `hard` refuses it. */ +export function checkCut(value: CutValue, u: CutUnit, manifest: VideoManifest): { hard: string[]; soft: string[] } { + const hard: string[] = []; + const known = new Map(u.candidates.map((c) => [c.citation, c])); + const ids = value.groups.flatMap((g) => g.clips); + const unknown = [...new Set(ids.filter((id) => !known.has(id)))]; + if (unknown.length) hard.push(`not a candidate of this cut: ${listed(unknown)} (choose only the ids listed)`); + const twice = [...new Set(ids.filter((id, i) => ids.indexOf(id) !== i))]; + if (twice.length) hard.push(`chosen more than once: ${listed(twice)}`); + const n = new Set(ids.filter((id) => known.has(id))).size; + if (n > u.max) hard.push(`${n} ids chosen (at most ${u.max})`); + if (n < CUT_MIN_CLIPS) hard.push(`${n} ids chosen (at least ${CUT_MIN_CLIPS})`); + const missing = u.candidates.filter((c) => u.pinned.has(c.entry) && !ids.includes(c.citation)); + for (const c of missing) hard.push(`${c.citation} must stay (${u.pinned.get(c.entry)})`); + const headings = new Set(u.headings.map(norm)); + const seen = new Set<string>(); + for (const g of value.groups) { + if (!g.heading) continue; + const h = norm(g.heading); + if (!headings.has(h)) hard.push(`"${g.heading}" is not a section heading of this cut (${u.headings.map((x) => `"${x}"`).join(", ")})`); + else if (seen.has(h)) hard.push(`"${g.heading}" heads two groups`); + seen.add(h); + } + if (!hard.length && u.deck) { + const next = { ...manifest, timeline: buildCut(manifest, u.candidates, value) }; + const added = u.deck.validatorErrors(next).filter((e) => !u.before.has(unindexed(e))); + for (const e of added.slice(0, LIST_AT_MOST)) hard.push(`the cut would not build: ${e}`); + } + return { hard, soft: [] }; +} + +/** The cut as a media task (./media.ts): one unit, the timeline's order. */ +export const CUT_SPEC: MediaTaskSpec<CutUnit, CutValue, CutInput> = { + task: "cut", + noun: "cut", + verb: "drafted", + progressMetric: "entries", + async units(ctx) { + const { manifest, report, input } = ctx; + const candidates = cutCandidates(manifest, report); + if (candidates.length < CUT_MIN_CLIPS) { + return [{ id: "cut", skipped: `only ${candidates.length} of the report's citations are in the cut (a cut needs ${CUT_MIN_CLIPS})` } satisfies MediaSkip]; + } + let deck: DeckChecks | null = null; + try { + deck = (await ctx.handle.deps.deckChecks?.()) ?? null; + } catch (e) { + ctx.handle.log(` the build's validators are not loaded (${(e as Error).message}); the cut is checked without them`); + } + const mark = draftedOf(manifest, { field: "timeline" }); + const codeMade = mark ? isCodeDraft(mark) : await isConverterOrder(manifest, report); + // The chapters a group may play under: the cards before the last + // candidate (one after it has nothing to head, and is dropped). + const lastAt = Math.max(...candidates.map((c) => manifest.timeline.findIndex((e) => e.id === c.entry))); + const headings: string[] = []; + for (const e of manifest.timeline.slice(0, lastAt)) { + if (isChapter(e) && e.heading && !headings.some((h) => norm(h) === norm(e.heading))) headings.push(String(e.heading)); + } + return [ + { + id: "cut", + target: { field: "timeline" }, + label: "the cut's clips and order", + candidates, + pinned: pinnedEntries(manifest), + headings, + max: Math.max(CUT_MIN_CLIPS, input.maxClips ?? DEFAULT_MAX_CLIPS), + codeMade, + deck, + before: new Set(deck ? deck.validatorErrors(manifest).map(unindexed) : []), + }, + ]; + }, + owner(manifest, u) { + const mark = draftedOf(manifest, { field: "timeline" }); + if (mark) return isCodeDraft(mark) ? "empty" : "drafted"; + return u.codeMade ? "empty" : "operator"; + }, + schema: () => SCHEMA, + system: (u) => cutSystem(u.max), + user(u, ctx: MediaContext<CutInput>) { + const ask = "\n\nChoose the cut's ids and their order."; + const build = (maxChars: number) => { + for (let level = 0; level <= 3; level++) { + const t = evidenceText(u, ctx.report, level) + ask; + if (t.length <= maxChars || level === 3) return t; + } + return ""; + }; + if (providerOf(ctx.input.model) !== "local") return build(Number.POSITIVE_INFINITY); + const system = cutSystem(u.max); + return fitLocalAsk({ llm: ctx.handle.deps.llm, model: ctx.input.model, system, schema: SCHEMA, build: (max) => build(max - RETRY_ROOM_CHARS) }).user; + }, + parse: (answer) => parseCut(answer), + check: (value, u, ctx) => checkCut(value, u, ctx.manifest), + toField: (value, u, manifest) => buildCut(manifest, u.candidates, value), + apply(manifest, u, value, provenance, force) { + const mark = draftedOf(manifest, { field: "timeline" }); + // A code-made order is nobody's: drafted over as a draft would be. One + // with no mark is given the converter's first, so the writer sees a draft. + if (u.codeMade && !mark) { + manifest.drafted = { ...(isObj(manifest.drafted) ? manifest.drafted : {}), timeline: makeProvenance({ task: CONVERT_TASK, model: "code", attempt: 1 }) }; + } + const code = u.codeMade || isCodeDraft(mark); + return applyDraft(manifest, { field: "timeline", value, provenance, force: force || code }); + }, + describe: (v) => v.groups.map((g) => `${g.heading || "—"}: ${g.clips.join(" ")}`).join(" | "), +}; + +export async function cut(input: CutInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(CUT_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/deckChecks.ts b/common/lib/report/draft/tasks/deckChecks.ts @@ -0,0 +1,45 @@ +// The build's own validators, for a media task's code checks (release 28). +// +// A drafted teaser must pass `validateTeaser` (the frame's fit per role), and +// a drafted cut must leave the manifest as valid as it found it (posts that +// ride on a clip, flips and threads that name clips). Those rules live in +// umtool's report-to-video (`deck.mjs`, `lint.mjs` `validatorErrors`: what a +// build runs before it renders) — plain `.mjs` that common does not depend on +// (it depends on common). So they are loaded at run time from the checkout, +// natively (the editor is never a standalone bundle: AGENTS.md, "The runtime +// container"), and handed to a task as `TaskDeps.deckChecks`. + +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +export type DeckChecks = { + // umtool/report-to-video/deck.mjs: a teaser entry's problems ([] = it builds). + validateTeaser(entry: unknown, where?: string): string[]; + // umtool/report-to-video/lint.mjs: every validator a build runs on the whole + // manifest, as sentences. + validatorErrors(manifest: unknown): string[]; +}; + +// The checkout's report-to-video directory. +export const deckDirOf = (repoRoot: string) => path.join(/* turbopackIgnore: true */ repoRoot, "umtool", "report-to-video"); + +const load = (file: string) => import(/* webpackIgnore: true */ /* turbopackIgnore: true */ pathToFileURL(file).href); + +/** The validators, from the checkout at `repoRoot` (throws when it has no umtool). */ +export async function loadDeckChecks(repoRoot: string): Promise<DeckChecks> { + const dir = deckDirOf(repoRoot); + const [deck, lint] = await Promise.all([load(path.join(dir, "deck.mjs")), load(path.join(dir, "lint.mjs"))]); + if (typeof deck.validateTeaser !== "function" || typeof lint.validatorErrors !== "function") { + throw new Error(`${dir}: no validateTeaser / validatorErrors (an older checkout?)`); + } + return { + validateTeaser: (entry, where) => deck.validateTeaser(entry, where), + validatorErrors: (manifest) => { + try { + return lint.validatorErrors(manifest); + } catch (e) { + return [(e as Error).message]; + } + }, + }; +} diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts @@ -3,8 +3,11 @@ import type { MediaStepTask } from "../../../generationSettings"; import type { MediaTaskInput } from "./media"; +import { cut, type CutInput } from "./cut"; import { flips } from "./flips"; import { narrate, type NarrateInput } from "./narrate"; +import { onscreen, type OnscreenInput } from "./onscreen"; +import { teaser, type TeaserInput } from "./teaser"; import { research, type ResearchInput } from "./research"; import { reviseReport, type ReviseReportInput } from "./revise-report"; import { reviseVideo, type ReviseVideoInput } from "./revise-video"; @@ -22,6 +25,10 @@ export { sweepPipeline, type SweepPipelineInput } from "./sweep-pipeline"; export { reviseReport, type ReviseReportInput } from "./revise-report"; export { reviseVideo, type ReviseVideoInput } from "./revise-video"; export { narrate, NARRATE_SPEC, type NarrateInput } from "./narrate"; +export { cut, CUT_SPEC, CUT_MIN_CLIPS, DEFAULT_MAX_CLIPS, buildCut, cutCandidates, isConverterOrder, type CutInput } from "./cut"; +export { loadDeckChecks, type DeckChecks } from "./deckChecks"; +export { teaser, TEASER_SPEC, TEASER_MIN_LINES, TEASER_MAX_LINES, TEASER_LINE_MAX, checkTeaser, type TeaserInput } from "./teaser"; +export { onscreen, ONSCREEN_SPEC, ONSCREEN_TITLE_MAX, ONSCREEN_SUBTITLE_MAX, checkOnscreen, type OnscreenInput } from "./onscreen"; // The media task scaffold (release 28, M0): what every media task is. export { ALTERNATIVES_PER_FIELD, @@ -61,18 +68,10 @@ export type TaskInput = | ({ task: "revise-video" } & ReviseVideoInput) | ({ task: "narrate" } & NarrateInput) | ({ task: "research" } & ResearchInput) - | ({ task: Exclude<MediaStepTask, "narrate"> } & MediaTaskInput); - -// A media task this build does not have: the step is recorded on the -// iteration as failed, saying so (release 28 lanes D and E replace these). -export function notImplementedTask(input: { task: string } & MediaTaskInput, deps: TaskDeps): Promise<TaskResult> { - return runOnIteration( - { article: input.article, n: input.n, deps, step: { task: input.task, model: input.model, ...(input.jobId ? { jobId: input.jobId } : {}) } }, - async () => { - throw new TaskInputError(`${input.task} is not implemented in this build`); - }, - ); -} + | ({ task: "cut" } & CutInput) + | ({ task: "onscreen" } & OnscreenInput) + | ({ task: "teaser" } & TeaserInput) + | ({ task: Exclude<MediaStepTask, "narrate" | "cut" | "onscreen" | "teaser"> } & MediaTaskInput); export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { switch (input.task) { @@ -95,9 +94,11 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { case "youtube": return youtube(input, deps); case "cut": + return cut(input, deps); case "onscreen": + return onscreen(input, deps); case "teaser": - return notImplementedTask(input, deps); + return teaser(input, deps); } } diff --git a/common/lib/report/draft/tasks/media.test.ts b/common/lib/report/draft/tasks/media.test.ts @@ -199,3 +199,61 @@ test("narrate on the scaffold: a narration it writes carries drafted.narration; 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<ToyUnit, { title: string }> = { + ...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 }, + ]); +}); diff --git a/common/lib/report/draft/tasks/media.ts b/common/lib/report/draft/tasks/media.ts @@ -38,8 +38,9 @@ // // Q0 binds every spec: counts and lengths are enforced in `check`, never only // asked for; prompts carry rules, never worked examples; a local prompt stays -// under 8k tokens. Progress reporting is not here yet (release 28 F3 adds -// `TaskDeps.progress`; phase 2 wires the media tasks to it). +// under 8k tokens. Progress: `h.progress` counts the units drafted of those +// to draft (`spec.progressMetric`, default "entries"; narrate's "cards"). +// Batching (`spec.batch`, release 28 M2) asks several units at once. import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; @@ -164,6 +165,31 @@ export type MediaTaskSpec<U extends MediaUnit, V, I extends MediaTaskInput = Med apply?(manifest: VideoManifest, unit: U, value: unknown, provenance: Provenance, force: boolean, ctx: MediaContext<I>): ApplyDraftResult; // A line for the log per unit kept; default the value as JSON. describe?(value: V, unit: U): string; + // Who owns the unit's field, for the skip (default drafted.mjs `ownerOf`): + // "empty" is drafted, anything else only with `force`. The cut's: a + // timeline the converter made is nobody's. + owner?(manifest: VideoManifest, unit: U, ctx: MediaContext<I>): "empty" | "drafted" | "operator"; + // What the job's progress counts (release 28 F3); default "entries". + progressMetric?: "cards" | "entries"; + // Several units in one ask (the local model's 8k prompt holds more than + // one on-screen line). Without it, one ask per unit. + batch?: MediaBatch<U, I>; +}; + +/** + * Units asked together: `group` cuts the units to draft into asks (each list + * one ask, in order); `split` gives each unit's own answer out of the + * batch's, keyed by unit id (one with none is that attempt's hard failure), + * which `parse` and `check` then judge as a single unit's. A re-ask carries + * only the units the first ask did not settle cleanly (`retry`'s words). + */ +export type MediaBatch<U extends MediaUnit, I extends MediaTaskInput = MediaTaskInput> = { + group(units: U[], ctx: MediaContext<I>): U[][]; + schema(units: U[], ctx: MediaContext<I>): object; + system(units: U[], ctx: MediaContext<I>): string; + user(units: U[], ctx: MediaContext<I>): string; + split(answer: unknown, units: U[], ctx: MediaContext<I>): Record<string, unknown>; + retry?(failing: { id: string; last: MediaAttempt<unknown> }[]): string; }; export const isSkip = (u: MediaUnit | MediaSkip): u is MediaSkip => typeof (u as MediaSkip).skipped === "string"; @@ -246,6 +272,82 @@ export async function loadMediaContext<I extends MediaTaskInput>(h: TaskHandle, const refusedFor = <V>(last: MediaAttempt<V>) => `\n\nYour last draft was refused for: ${[...last.hard, ...last.soft].join("; ")}. Write it again without those problems.`; +const batchRefusedFor = <V>(failing: { id: string; last: MediaAttempt<V> }[]) => + `\n\nYour last drafts were refused: ${failing.map((f) => `${f.id}: ${[...f.last.hard, ...f.last.soft].join("; ")}`).join(" | ")}. ` + + "Write those again without those problems."; + +// At most two asks per unit: alone (the spec's schema, system and user), or +// with the others of its batch (`spec.batch`); the second ask carries only the +// units the first did not settle cleanly, and what each was refused for. +async function askUnits<U extends MediaUnit, V, I extends MediaTaskInput>( + spec: MediaTaskSpec<U, V, I>, + h: TaskHandle, + ctx: MediaContext<I>, + group: U[], +): Promise<Map<string, MediaAttempt<V>[]>> { + const { deps } = h; + const out = new Map<string, MediaAttempt<V>[]>(group.map((u) => [u.id, []])); + const judge = (raw: unknown, u: U): MediaAttempt<V> => { + try { + const value = spec.parse(raw, u, ctx); + return { value, ...spec.check(value, u, ctx) }; + } catch (e) { + return { value: null, hard: [(e as Error).message], soft: [] }; + } + }; + const ask = (system: string, user: string, schema: object) => + structuredAnswer<unknown>({ llm: deps.llm, model: ctx.input.model, system, user, schema, meter: h.meter, signal: deps.signal }); + const b = spec.batch; + // Computed once per unit (a batch: once for the whole), as narrate always did. + const first = b ? { system: b.system(group, ctx), user: b.user(group, ctx) } : null; + const single = new Map(b ? [] : group.map((u) => [u.id, { system: spec.system(u, ctx), user: spec.user(u, ctx) }])); + let pending = group; + for (let k = 0; k < 2 && pending.length; k++) { + deps.signal?.throwIfAborted(); + if (!b) { + const u = pending[0]!; + const list = out.get(u.id)!; + const extra = list.length ? (spec.retry ?? refusedFor)(list.at(-1)!, u) : ""; + let a: MediaAttempt<V>; + try { + a = judge(await ask(single.get(u.id)!.system, single.get(u.id)!.user + extra, spec.schema(u, ctx)), u); + } catch (e) { + if (deps.signal?.aborted) throw e; + list.push({ value: null, hard: [(e as Error).message], soft: [] }); + continue; + } + list.push(a); + h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, ...a }]); + if (!a.hard.length && !a.soft.length) pending = []; + continue; + } + // A batch: the first ask is the whole group's; a re-ask names only the + // units still refused or flagged. + const failing = pending.map((u) => ({ id: u.id, last: out.get(u.id)!.at(-1) })).filter((f): f is { id: string; last: MediaAttempt<V> } => !!f.last); + const user = (k === 0 ? first!.user : b.user(pending, ctx)) + (failing.length ? (b.retry ?? batchRefusedFor)(failing) : ""); + const system = k === 0 ? first!.system : b.system(pending, ctx); + let answers: Record<string, unknown>; + try { + answers = b.split(await ask(system, user, b.schema(pending, ctx)), pending, ctx); + } catch (e) { + if (deps.signal?.aborted) throw e; + for (const u of pending) out.get(u.id)!.push({ value: null, hard: [(e as Error).message], soft: [] }); + continue; + } + for (const u of pending) { + const a: MediaAttempt<V> = + answers[u.id] === undefined ? { value: null, hard: [`no draft for ${u.id} in the answer`], soft: [] } : judge(answers[u.id], u); + out.get(u.id)!.push(a); + h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, batch: pending.length, ...a }]); + } + pending = pending.filter((u) => { + const last = out.get(u.id)!.at(-1)!; + return last.hard.length > 0 || last.soft.length > 0; + }); + } + return out; +} + /** * Run one media task over an iteration (the shape above). The result is the * step's: `done` when at least one unit kept a clean value (applied, or kept @@ -286,67 +388,53 @@ async function mediaBody<U extends MediaUnit, V, I extends MediaTaskInput>( const kept: { unit: U; value: V; attempt: 1 | 2 }[] = []; h.log(`${spec.task} on i${h.n}, ${input.model} (${dir})`); + // The units to draft: the ones asked for, with a field nobody owns (or + // `force`); the rest are recorded as skipped. + const eligible: U[] = []; for (const u of await spec.units(ctx)) { if (only && !only.has(u.id) && !(!isSkip(u) && u.target.entry && only.has(u.target.entry))) continue; if (isSkip(u)) { units[u.id] = { skipped: u.skipped }; continue; } - const owner = ownerOf(manifest, u.target); + const owner = spec.owner ? spec.owner(manifest, u, ctx) : ownerOf(manifest, u.target); if (owner !== "empty" && !input.force) { units[u.id] = { target: u.target, skipped: `has a value (${owner === "operator" ? "the operator's" : "a draft"}); force re-drafts it` }; continue; } - const system = spec.system(u, ctx); - const user = spec.user(u, ctx); - const attempts: MediaAttempt<V>[] = []; - for (let k = 0; k < 2; k++) { - deps.signal?.throwIfAborted(); - const extra = attempts.length ? (spec.retry ?? refusedFor)(attempts.at(-1)!, u) : ""; - let a: MediaAttempt<V>; - try { - const answer = await structuredAnswer<unknown>({ - llm: deps.llm, - model: input.model, - system, - user: user + extra, - schema: spec.schema(u, ctx), - meter: h.meter, - signal: deps.signal, - }); - try { - const value = spec.parse(answer, u, ctx); - a = { value, ...spec.check(value, u, ctx) }; - } catch (e) { - a = { value: null, hard: [(e as Error).message], soft: [] }; + eligible.push(u); + } + + // Progress (release 28 F3): the units drafted of those to draft. + const metric = spec.progressMetric ?? "entries"; + let drafted = 0; + h.progress({ metric, current: 0, total: eligible.length }); + const groups = spec.batch ? spec.batch.group(eligible, ctx).filter((g) => g.length) : eligible.map((u) => [u]); + for (const group of groups) { + const attemptsOf = await askUnits(spec, h, ctx, group); + for (const u of group) { + const attempts = attemptsOf.get(u.id) ?? []; + const ranked = rankAttempts(attempts, score); + let chosen: MediaAttempt<V> | null = ranked[0] ?? null; + let attemptNo = (chosen ? attempts.indexOf(chosen) + 1 : 1) as 1 | 2; + if (chosen && chosen.hard.length) { + const fixed = spec.repair?.(attempts, u, ctx) ?? null; + if (fixed && !fixed.hard.length && fixed.value !== null) { + chosen = fixed; + attemptNo = Math.min(2, attempts.length) as 1 | 2; } - } catch (e) { - if (deps.signal?.aborted) throw e; - attempts.push({ value: null, hard: [(e as Error).message], soft: [] }); - continue; } - attempts.push(a); - h.turns([{ kind: spec.turnKind ?? spec.task, unit: u.id, attempt: k + 1, ...a }]); - if (!a.hard.length && !a.soft.length) break; - } - const ranked = rankAttempts(attempts, score); - let chosen: MediaAttempt<V> | null = ranked[0] ?? null; - let attemptNo = (chosen ? attempts.indexOf(chosen) + 1 : 1) as 1 | 2; - if (chosen && chosen.hard.length) { - const fixed = spec.repair?.(attempts, u, ctx) ?? null; - if (fixed && !fixed.hard.length && fixed.value !== null) { - chosen = fixed; - attemptNo = Math.min(2, attempts.length) as 1 | 2; + units[u.id] = { target: u.target, ...(u.label ? { label: u.label } : {}), attempts, chosen }; + drafted++; + if (!chosen || chosen.hard.length || chosen.value === null) { + h.log(` ${u.id}: NOT written — ${chosen?.hard.join("; ") ?? "no draft"}`); + continue; } + kept.push({ unit: u, value: chosen.value, attempt: attemptNo }); + const said = spec.describe ? spec.describe(chosen.value, u) : JSON.stringify(chosen.value); + h.log(` ${u.id}: ${said}${chosen.soft.length ? ` [flag: ${chosen.soft.join("; ")}]` : ""}`); } - units[u.id] = { target: u.target, ...(u.label ? { label: u.label } : {}), attempts, chosen }; - if (!chosen || chosen.hard.length || chosen.value === null) { - h.log(` ${u.id}: NOT written — ${chosen?.hard.join("; ") ?? "no draft"}`); - continue; - } - kept.push({ unit: u, value: chosen.value, attempt: attemptNo }); - const said = spec.describe ? spec.describe(chosen.value, u) : JSON.stringify(chosen.value); - h.log(` ${u.id}: ${said}${chosen.soft.length ? ` [flag: ${chosen.soft.join("; ")}]` : ""}`); + h.progress({ metric, current: drafted, total: eligible.length }); } const refused = Object.values(units).filter((r) => (r.chosen as MediaAttempt<V> | null | undefined)?.hard?.length).length; diff --git a/common/lib/report/draft/tasks/narrate.ts b/common/lib/report/draft/tasks/narrate.ts @@ -124,6 +124,7 @@ export const NARRATE_SPEC: MediaTaskSpec<NarrateUnit, string, NarrateInput> = { turnKind: "narration", noun: "card", verb: "narrated", + progressMetric: "cards", units(ctx) { const out: (NarrateUnit | MediaSkip)[] = []; const only = ctx.input.cards?.length ? new Set(ctx.input.cards) : null; diff --git a/common/lib/report/draft/tasks/onscreen.test.ts b/common/lib/report/draft/tasks/onscreen.test.ts @@ -0,0 +1,156 @@ +// TASK onscreen (release 28 M2) over the S0 kit's manifests and the basic +// report, against the fake ollama: several clips in one ask, the re-ask only +// for the refused, each code check refusing what it should, the better of two +// kept, a clip with no clean draft not written, the operator's text kept and +// the draft an alternative. Real iterations store and project in a temp dir. + +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 { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "../../iterations"; +import { checkOnscreen, isVerbatimOf, onscreen, onscreenBatches, quotedParts, ONSCREEN_SPEC } from "./onscreen"; +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(), "onscreen-task-")); + ol = await startFakeOllama(); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +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 progress: unknown[] = []; + const deps: TaskDeps = { + llm: { ollama: { baseUrl: ol.url } }, + corpus: { source: "none", tools: [], call: async () => "" }, + cuesOf: async () => null, + paths, + log: (l) => lines.push(l), + progress: (p) => progress.push(p), + now: () => new Date("2026-10-13T12:00:00.000Z"), + }; + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const draft = async () => JSON.parse(await readFile(path.join(dir, "onscreen-draft.json"), "utf8")) as DraftFile; + const input = (o: Record<string, unknown> = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o }); + return { dir, paths, deps, lines, progress, manifestNow, draft, input, report }; +} + +const entry = (m: { timeline: { id: string }[] }, id: string) => m.timeline.find((e) => e.id === id) as Record<string, any>; + +test("onscreen, the recorded run: six clips in one ask, the four refused asked again, the better of two kept, a clip with none clean not written", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + const p = await project(m); + const r = await kit("runs/onscreen.json"); + const asked: string[] = []; + ol.push(...r.turns.map((t: unknown) => (body: { messages: { content: string }[] }) => (asked.push(body.messages.at(-1)!.content), t))); + const out = await onscreen(p.input(), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(ol.remaining(), 0); + assert.equal(asked.length, 2, "one ask for six clips, one re-ask"); + assert.match(asked[0]!, /### Clip c01[\s\S]*### Clip c06/); + assert.doesNotMatch(asked[1]!, /### Clip c01|### Clip c05/); + assert.match(asked[1]!, /Your last drafts were refused: c02: the title has quotation marks/); + assert.match(out.summary, /^5 clip\(s\) titled \(undo: /); + const after = await p.manifestNow(); + assert.deepEqual(entry(after, "c01").onscreen, { title: "She will not sell to a chain", subtitle: '"I would never sell the bakery to a chain"' }); + assert.deepEqual(entry(after, "c02").onscreen, { title: "The oven story, denied", subtitle: '"we never said that about the old oven"' }); + assert.deepEqual(entry(after, "c03").onscreen, { title: "Who paid for the mixer", subtitle: '"I paid for the new mixer myself"' }); + assert.equal(entry(after, "c04").onscreen.title, "Out of the contest this year"); + assert.equal(entry(after, "c04").drafted.onscreen.attempt, 2); + assert.equal(entry(after, "c05").drafted.onscreen.attempt, 1); + assert.equal(entry(after, "c06").onscreen, undefined, "no clean draft: not written"); + const file = await p.draft(); + const c06 = file.units.c06 as { attempts: { hard: string[] }[] }; + assert.match(c06.attempts[0]!.hard.join(), /number 2024 is not in the clip's evidence/); + assert.match(c06.attempts[1]!.hard.join(), /name “Marco” is not in the clip's evidence/); + const c04 = file.units.c04 as { attempts: { hard: string[] }[] }; + assert.match(c04.attempts[0]!.hard.join(), /the title is \d+ characters \(at most 60\)/); + const c03 = file.units.c03 as { attempts: { hard: string[] }[] }; + assert.match(c03.attempts[0]!.hard.join(), /the subtitle quotes “I bought the mixer”, which is not the clip's quote word for word/); + assert.deepEqual(p.progress, [ + { metric: "entries", current: 0, total: 6 }, + { metric: "entries", current: 6, total: 6 }, + ]); + const it = (await readIteration("synth-basic", 1, p.paths))!; + assert.equal(it.checks!.find((c) => c.name === "onscreen")!.ok, false, "a clip not written fails the check"); + assert.equal(it.steps.find((s) => s.task === "onscreen")!.status, "done"); +}); + +test("onscreen's checks, each alone", () => { + const u = { quote: "I would never sell the bakery to a chain", evidence: "Report: Synth Kitchen\nSection: The bakery\nQuote: \"I would never sell the bakery to a chain\"\nSource: Bread day, 2026-01-05" }; + const hard = (title: string, subtitle?: string) => checkOnscreen({ title, ...(subtitle ? { subtitle } : {}) }, u).hard; + assert.deepEqual(hard("Not for sale", "The baker on a chain"), []); + assert.deepEqual(hard("Not for sale", '"never sell the bakery"'), [], "a verbatim part of the quote"); + assert.deepEqual(hard("Not for sale", "“Never sell the bakery,” on Bread day"), [], "curly marks, case and punctuation aside"); + assert.match(hard("x".repeat(61)).join(), /the title is 61 characters \(at most 60\)/); + assert.match(hard("Not for sale", "y".repeat(91)).join(), /the subtitle is 91 characters \(at most 90\)/); + assert.match(hard("Not for\nsale").join(), /the title is more than one line/); + assert.match(hard('"Not for sale"').join(), /the title has quotation marks/); + assert.match(hard("The ‘chain’ line").join(), /the title has quotation marks/); + assert.deepEqual(hard("She won't sell"), [], "an apostrophe is not a quotation"); + assert.match(hard("Not for sale", '"never sell it"').join(), /quotes “never sell it”, which is not the clip's quote word for word/); + assert.match(hard("Not for sale", 'She said "never sell').join(), /quotation marks do not pair up/); + assert.match(hard("Not for sale", "Sold in 2025").join(), /number 2025 is not in the clip's evidence/); + assert.deepEqual(hard("Not for sale", "Bread day, 2026"), []); + assert.match(hard("Not for sale", "Her friend Marco agrees").join(), /name “Marco” is not in the clip's evidence/); + assert.match(hard("I will never sell").join(), /the narrator is third person/); + assert.deepEqual(quotedParts('a "b c" d «e»'), { parts: ["b c", "e"], balanced: true }); + assert.equal(isVerbatimOf("sell the", "I would never sell the bakery"), true); + assert.equal(isVerbatimOf("sel the", "I would never sell the bakery"), false, "whole words"); +}); + +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); + // c01 and c04 hold the operator's text: skipped unforced, so c02 alone is asked. + ol.push(jsonReply({ entries: [{ id: "c02", title: "The oven story, denied", subtitle: "" }] })); + const one = await onscreen(p.input({ entries: ["c01", "c02", "c04"] }), p.deps); + assert.equal(one.status, "done", `${one.summary}\n${p.lines.join("\n")}`); + const f1 = await p.draft(); + assert.deepEqual(Object.keys(f1.units).sort(), ["c01", "c02", "c04"]); + assert.match(String(f1.units.c01!.skipped), /the operator's/); + // Forced over c01: its words stand, the draft is an alternative. + ol.push(jsonReply({ entries: [{ id: "c01", title: "She will not sell to a chain", subtitle: "" }] })); + const forced = await onscreen(p.input({ entries: ["c01"], force: true }), p.deps); + assert.match(forced.summary, /^0 clip\(s\) titled, 1 as alternatives/); + const after = await p.manifestNow(); + assert.deepEqual(entry(after, "c01").onscreen, entry(full, "c01").onscreen); + assert.deepEqual(entry(after, "c02").onscreen, { title: "The oven story, denied" }); + const alt = (await p.draft()).alternatives; + assert.deepEqual(alt.map((a) => [a.target.entry, a.reason, (a.value as { title: string }).title]), [["c01", "operator", "She will not sell to a chain"]]); + assert.equal(ol.remaining(), 0); + + // Batches: at most eight, and as many as fit a small cap. + const ctx = { manifest: full, report: p.report, input: p.input(), handle: { deps: p.deps } } as never; + const units = (await ONSCREEN_SPEC.units(ctx)) as never[]; + const many = Array.from({ length: 20 }, (_, i) => ({ ...(units[i % units.length] as object), id: `x${i}` })) as never[]; + assert.deepEqual(onscreenBatches(many, ctx).map((b) => b.length), [8, 8, 4]); + const small = { ...(ctx as object), handle: { deps: { ...p.deps, llm: { ollama: { baseUrl: ol.url, promptCapTokens: 1100 } } } } } as never; + const sizes = onscreenBatches(many, small).map((b) => b.length); + assert.ok(sizes.every((n) => n >= 1 && n < 8) && sizes.reduce((a, b) => a + b, 0) === 20, String(sizes)); +}); diff --git a/common/lib/report/draft/tasks/onscreen.ts b/common/lib/report/draft/tasks/onscreen.ts @@ -0,0 +1,207 @@ +// TASK onscreen — each clip's on-screen title and subtitle (release 28 M2). +// A STEP on a done iteration (./media.ts): one unit per clip entry (or the +// `entries` asked for), the field `onscreen.{title, subtitle}`. +// +// The evidence of a clip is what the report says of it: the claim it cites +// (its text and verdict), its section, its quote, its source and date. Several +// clips are asked in one call (`batch`), as many as fit the local model's +// prompt cap (at most ONSCREEN_BATCH_MAX); a re-ask carries only the clips +// refused. Code checks every line: the title at most 60 characters, the +// subtitle at most 90, one line each; the title quotes nothing, and the +// subtitle quotes only words of the clip's own quote, verbatim (inside +// quotation marks); no name or number the evidence does not have; and the +// narrator's third person outside a quotation. The better of two attempts is +// kept; a clip whose on-screen text is the operator's is never replaced. + +import { strictNormalize } from "../../../citations/verify"; +import { CHARS_PER_TOKEN, ollamaConfigOf, promptCapOf, providerOf, structuredPromptEstimate } from "../../../llm"; +import { firstPersonProblems, groundedProblems } from "../grounding"; +import type { ManifestEntry } from "../videoOps"; +import { cutCandidates } from "./cut"; +import { runMediaTask, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import type { TaskDeps, TaskResult } from "./types"; + +export const ONSCREEN_TITLE_MAX = 60; +export const ONSCREEN_SUBTITLE_MAX = 90; +// The most clips one ask carries (an API model too: a review reads them as a set). +export const ONSCREEN_BATCH_MAX = 8; +// The room a re-ask's words take on top of a batch's prompt. +const RETRY_ROOM_CHARS = 1500; + +export type OnscreenInput = MediaTaskInput; + +export type OnscreenValue = { title: string; subtitle?: string }; + +type OnscreenUnit = MediaUnit & { + entry: ManifestEntry; + // The clip's own words: what the subtitle may quote. + quote: string; + // The evidence block shown to the model; names and numbers are grounded in it. + evidence: string; +}; + +type Obj = Record<string, any>; +const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v); + +// A quotation: double marks (straight or curly), guillemets, or curly singles. +const QUOTED_RE = /"([^"]*)"|“([^”]*)”|«([^»]*)»|‘([^’]*)’/g; +const QUOTE_MARKS_RE = /["“”«»„‟]|‘[^’]*’/; + +/** The quoted parts of a line, and whether its marks pair up. */ +export function quotedParts(text: string): { parts: string[]; balanced: boolean } { + const parts: string[] = []; + for (const m of text.matchAll(QUOTED_RE)) parts.push((m[1] ?? m[2] ?? m[3] ?? m[4] ?? "").trim()); + const rest = text.replace(QUOTED_RE, " "); + return { parts, balanced: !/["“”«»„‟]/.test(rest) && !/‘/.test(rest) }; +} + +/** Is `part` the quote's own words, in order (punctuation and case aside)? */ +export function isVerbatimOf(part: string, quote: string): boolean { + const p = strictNormalize(part); + return !!p && ` ${strictNormalize(quote)} `.includes(` ${p} `); +} + +/** 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[] = []; + const title = v.title; + const sub = v.subtitle ?? ""; + if (!title.trim()) hard.push("no title"); + for (const [name, text, max] of [["title", title, ONSCREEN_TITLE_MAX], ["subtitle", sub, ONSCREEN_SUBTITLE_MAX]] as const) { + if (/[\r\n]/.test(text)) hard.push(`the ${name} is more than one line`); + if (text.trim().length > max) hard.push(`the ${name} is ${text.trim().length} characters (at most ${max})`); + } + if (QUOTE_MARKS_RE.test(title)) hard.push("the title has quotation marks: a title quotes nobody"); + const { parts, balanced } = quotedParts(sub); + if (!balanced) hard.push("the subtitle's quotation marks do not pair up"); + 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, " ")}`; + hard.push(...groundedProblems(said, u.evidence, "the clip's evidence")); + hard.push(...firstPersonProblems(`${title}. ${sub}`)); + return { hard: [...new Set(hard)], soft: [] }; +} + +const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); + +function unitsOf(ctx: MediaContext<OnscreenInput>): OnscreenUnit[] { + const { manifest, report } = ctx; + const byEntry = new Map(cutCandidates(manifest, report).map((c) => [c.entry, c])); + const out: OnscreenUnit[] = []; + const seen = new Set<string>(); + let chapter = ""; + for (const e of manifest.timeline) { + if (e.type === "card" && e.style === "chapter") chapter = String(e.heading ?? ""); + if (e.type !== "clip" || seen.has(e.id)) continue; + seen.add(e.id); + const c = byEntry.get(e.id); + const verdict = c?.claim?.verdict ?? (isObj(e.claim) ? e.claim.verdict : undefined); + const quote = String(e.quote ?? c?.quote ?? ""); + const lines = [ + `Report: ${String(report.title ?? "")}`, + chapter ? `Section: ${chapter}` : "", + c?.claim ? `Claim${verdict ? ` [${verdict}]` : ""}: ${stripCites(c.claim.text)}` : verdict ? `Verdict: ${verdict}` : "", + quote ? `Quote: "${quote}"` : "", + [c?.label, c?.date || e.date].filter(Boolean).length ? `Source: ${[c?.label, c?.date || e.date].filter(Boolean).join(", ")}` : "", + ].filter(Boolean); + out.push({ id: e.id, target: { entry: e.id, field: "onscreen" }, label: chapter || undefined, entry: e, quote, evidence: lines.join("\n") }); + } + return out; +} + +export function onscreenSystem(): string { + const rules = [ + "For each clip, write the text shown on screen while it plays: a title that says what the clip shows, in plain words, and a subtitle that adds who, when or what is at stake.", + `The title is one line of at most ${ONSCREEN_TITLE_MAX} characters, and it has no quotation marks.`, + `The subtitle is one line of at most ${ONSCREEN_SUBTITLE_MAX} characters. It may quote the speaker only with words from that clip's quote, exactly as they are, inside double quotation marks.`, + "Use only names and numbers that appear in that clip's evidence.", + "Write in the third person, in sentence case: no I, me, my, we or our outside a quotation.", + "Say what the clip shows; do not add facts, and do not put the verdict in the speaker's mouth.", + ]; + return ( + "You write on-screen text for the clips of a short evidence video. " + + `Rules: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + + 'Answer with "entries": one {"id", "title", "subtitle"} per clip, its id exactly as given.' + ); +} + +const SCHEMA = { + type: "object", + properties: { + entries: { + type: "array", + items: { + type: "object", + properties: { id: { type: "string" }, title: { type: "string" }, subtitle: { type: "string" } }, + required: ["id", "title", "subtitle"], + }, + }, + }, + required: ["entries"], +}; + +const userOf = (units: OnscreenUnit[]) => + `${units.map((u) => `### Clip ${u.id}\n${u.evidence}`).join("\n\n")}\n\nWrite the on-screen title and subtitle of ${units.length === 1 ? "this clip" : `each of these ${units.length} clips`}.`; + +/** The units in asks: as many per ask as fit the local prompt cap, at most ONSCREEN_BATCH_MAX. */ +export function onscreenBatches(units: OnscreenUnit[], ctx: Pick<MediaContext<OnscreenInput>, "input" | "handle">): OnscreenUnit[][] { + const local = providerOf(ctx.input.model) === "local"; + const cap = local ? promptCapOf(ollamaConfigOf(ctx.handle.deps.llm, ctx.input.model)) - Math.ceil(RETRY_ROOM_CHARS / CHARS_PER_TOKEN) : Number.POSITIVE_INFINITY; + const system = onscreenSystem(); + const out: OnscreenUnit[][] = []; + let cur: OnscreenUnit[] = []; + for (const u of units) { + const next = [...cur, u]; + const fits = next.length <= ONSCREEN_BATCH_MAX && (!local || structuredPromptEstimate({ system, user: userOf(next), schema: SCHEMA }) <= cap); + if (fits || !cur.length) cur = next; + else { + out.push(cur); + cur = [u]; + } + } + if (cur.length) out.push(cur); + return out; +} + +/** One clip's answer to its value (a throw is a hard failure). */ +export function parseOnscreen(raw: unknown): OnscreenValue { + const o = isObj(raw) ? raw : {}; + const title = typeof o.title === "string" ? o.title.trim() : ""; + const subtitle = typeof o.subtitle === "string" ? o.subtitle.trim() : ""; + if (!title && !subtitle) throw new Error("no title and no subtitle"); + return { title, ...(subtitle ? { subtitle } : {}) }; +} + +/** On-screen text as a media task (./media.ts): one unit per clip, asked in batches. */ +export const ONSCREEN_SPEC: MediaTaskSpec<OnscreenUnit, OnscreenValue, OnscreenInput> = { + task: "onscreen", + noun: "clip", + verb: "titled", + progressMetric: "entries", + units: (ctx) => unitsOf(ctx), + schema: () => SCHEMA, + system: () => onscreenSystem(), + user: (u) => userOf([u]), + batch: { + group: (units, ctx) => onscreenBatches(units, ctx), + schema: () => SCHEMA, + system: () => onscreenSystem(), + user: (units) => userOf(units), + split(answer) { + const list = isObj(answer) && Array.isArray(answer.entries) ? answer.entries : []; + const out: Record<string, unknown> = {}; + for (const e of list) if (isObj(e) && typeof e.id === "string" && !(e.id.trim() in out)) out[e.id.trim()] = e; + return out; + }, + }, + parse: (raw) => parseOnscreen(raw), + check: (v, u) => checkOnscreen(v, u), + toField: (v) => ({ title: v.title, ...(v.subtitle ? { subtitle: v.subtitle } : {}) }), + describe: (v) => `${v.title}${v.subtitle ? ` — ${v.subtitle}` : ""}`, +}; + +export async function onscreen(input: OnscreenInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(ONSCREEN_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/teaser.test.ts b/common/lib/report/draft/tasks/teaser.test.ts @@ -0,0 +1,143 @@ +// TASK teaser (release 28 M3) over the S0 kit's manifests and the basic +// report, against the fake ollama: a cut with no teaser gets one after its +// last clip; each code check refuses what it should (count, length, one line, +// quotation marks, a quote's run, names and numbers, the build's own +// validateTeaser); the better of two kept; the operator's lines kept and the +// draft an alternative; the umtool lint passes on what is written. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { createIteration, projectOf, updateIteration, writeIterationFile } from "../../iterations"; +import { loadDeckChecks, type DeckChecks } from "./deckChecks"; +import { checkTeaser, claimGist, parseTeaser, teaser, teaserEvidence } from "./teaser"; +import type { DraftFile } from "./media"; +import type { TaskDeps } from "./types"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const ROOT = path.resolve(HERE, "../../../../.."); +const DRAFT = new URL("../../../../testing/draft/", import.meta.url); +const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); +const run = promisify(execFile); + +let tmp: string; +let ol: FakeOllama; +let deck: DeckChecks; +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "teaser-task-")); + ol = await startFakeOllama(); + deck = await loadDeckChecks(ROOT); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +let caseN = 0; +async function project(manifest: unknown, withDeck = true) { + 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"), + ...(withDeck ? { deckChecks: async () => deck } : {}), + }; + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const draft = async () => JSON.parse(await readFile(path.join(dir, "teaser-draft.json"), "utf8")) as DraftFile; + const input = (o: Record<string, unknown> = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o }); + return { dir, deps, lines, manifestNow, draft, input, report }; +} + +test("teaser, the recorded run: a cut with none gets one after its last clip; the better of two kept; the umtool lint passes", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + const p = await project(m); + const r = await kit("runs/teaser.json"); + ol.push(...r.turns); + const out = await teaser(p.input(), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(ol.remaining(), 0); + const after = await p.manifestNow(); + assert.deepEqual(after.timeline.map((e: { id: string }) => e.id).slice(-2), ["c06", "teaser"]); + const t = after.timeline.at(-1); + assert.deepEqual(t, { + type: "teaser", + id: "teaser", + lines: ["Synth Kitchen", "The bakery", "The contest", "What the baker says"], + drafted: { lines: { task: "teaser", model: "qwen3:8b", at: "2026-10-13T12:00:00.000Z", iteration: 1, attempt: 2 } }, + }); + const first = ((await p.draft()).units.teaser as { attempts: { hard: string[] }[] }).attempts[0]!.hard.join("\n"); + assert.match(first, /line 2 repeats a quote \("would never sell the bakery"\)/); + assert.match(first, /line 4: number “two” is not in the report/); + const lint = await run(process.execPath, [path.join(ROOT, "umtool/report-to-video/lint.mjs"), path.join(p.dir, "video.manifest.json"), "--json"]).catch((e) => e); + assert.deepEqual(JSON.parse(lint.stdout).errors, [], lint.stdout); +}); + +test("teaser's checks, each alone; the build's validateTeaser is one of them", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + const report = await kit("reports/basic.report.json"); + const u = { id: "teaser", entry: null, evidence: teaserEvidence(report, m), quotes: Object.values(report.citations).map((c) => (c as { quote: string }).quote), deck }; + const hard = (lines: string[], unit: typeof u = u) => checkTeaser(lines, unit).hard; + assert.deepEqual(hard(["Synth Kitchen", "The bakery", "The contest"]), []); + assert.match(hard(["Synth Kitchen", "The bakery"]).join(), /2 lines \(3 to 5\)/); + assert.match(hard(["Synth Kitchen", "The bakery", "The contest", "The bakery", "The contest", "Synth Kitchen"]).join(), /6 lines \(3 to 5\)/); + assert.match(hard(["Synth Kitchen", "The bakery", "x".repeat(71)]).join(), /line 3 is 71 characters \(at most 70\)/); + assert.match(hard(["Synth Kitchen", "The\nbakery", "The contest"]).join(), /line 2 is more than one line/); + assert.match(hard(["Synth Kitchen", "“The bakery”", "The contest"]).join(), /line 2 has quotation marks/); + assert.deepEqual(hard(["Synth Kitchen", "The baker's bakery", "The contest"]), [], "an apostrophe is not a quotation"); + assert.match(hard(["Synth Kitchen", "The bakery", "In 2025"]).join(), /line 3: number 2025 is not in the report/); + assert.match(hard(["Synth Kitchen", "The bakery", "Ask Marco"]).join(), /line 3: name “Marco” is not in the report/); + // A middle line is a title: past its row's fit the build refuses it. + assert.match(hard(["Synth Kitchen", "The bakery and the contest and the oven", "The contest"]).join(), /it would not build: .*lines\[1\]/); + // Without the build's check nothing is written. + assert.match(hard(["Synth Kitchen", "The bakery", "The contest"], { ...u, deck: null as never }).join(), /not available, so the lines are not written/); + assert.equal(claimGist('She says she would not sell: "I would never sell the bakery to a chain"'), "She says she would not sell"); + assert.deepEqual(parseTeaser({ lines: [" a ", { text: "b" }, ""] }), ["a", "b"]); + assert.throws(() => parseTeaser({}), /no "lines"/); +}); + +test("teaser: the operator's lines kept (forced, the draft an alternative); a teaser with no deck check is not written", async () => { + const full = await kit("manifests/full.video.manifest.json"); + const p = await project(full); + const skipped = await teaser(p.input(), p.deps); + assert.equal(skipped.status, "failed"); + assert.match(String((await p.draft()).units.fin!.skipped), /the operator's/); + ol.push(jsonReply({ lines: ["Synth Kitchen", "The bakery", "The contest"] })); + const forced = await teaser(p.input({ force: true }), p.deps); + assert.match(forced.summary, /^0 teaser\(s\) drafted, 1 as alternatives/); + assert.deepEqual((await p.manifestNow()).timeline.at(-1).lines, full.timeline.at(-1).lines); + assert.deepEqual((await p.draft()).alternatives.map((a) => [a.target.entry, a.reason]), [["fin", "operator"]]); + // Dates in the evidence: the full kit's clips carry none, the evidence says so by leaving them out. + assert.doesNotMatch(teaserEvidence(p.report, full), /Sources dated/); + const dated = structuredClone(full); + dated.timeline.find((e: { id: string }) => e.id === "c07").date = "2026-03-01"; + dated.timeline.find((e: { id: string }) => e.id === "c01").date = "2026-01-05"; + assert.match(teaserEvidence(p.report, dated), /Sources dated: January 2026 to March 2026/); + + const q = await project(await kit("manifests/basic.video.manifest.json"), false); + ol.push(jsonReply({ lines: ["Synth Kitchen", "The bakery", "The contest"] }), jsonReply({ lines: ["Synth Kitchen", "The bakery", "The contest"] })); + const none = await teaser(q.input(), q.deps); + assert.equal(none.status, "failed"); + assert.equal((await q.manifestNow()).timeline.some((e: { type: string }) => e.type === "teaser"), false, "no teaser added"); + assert.equal(ol.remaining(), 0); +}); diff --git a/common/lib/report/draft/tasks/teaser.ts b/common/lib/report/draft/tasks/teaser.ts @@ -0,0 +1,207 @@ +// TASK teaser — the lines of the cut's teaser card (release 28 M3). A STEP on +// a done iteration (./media.ts): one unit per teaser entry, the field `lines`. +// +// The evidence is the report as a whole: its title and subtitle, its section +// titles, each claim's gist (its words, the quoted ones taken out) and the +// days its sources are from. The lines are TEASER_MIN_LINES to +// TEASER_MAX_LINES, each one line of at most TEASER_LINE_MAX characters; the +// first is drawn as the overline, the middle ones as titles and the last as +// the kicker (a date, or the turn), and each must fit its role's row — which +// the build's own `validateTeaser` judges (umtool's deck.mjs, through +// `TaskDeps.deckChecks`; a teaser it cannot check is not written). No line +// reads a quote out: no quotation marks, and no run of TEASER_QUOTE_RUN words +// from any citation's quote. No name or number the evidence does not have. +// +// A cut with no teaser gets one: an entry `{type: "teaser", id: "teaser"}` +// after its last clip, its lines written through applyDraft as any empty +// field — the operator deletes it like any entry. + +import { strictNormalize } from "../../../citations/verify"; +import { applyDraft, entriesWithId } from "../../drafted.mjs"; +import { groundedProblems } from "../grounding"; +import type { ManifestEntry, VideoManifest } from "../videoOps"; +import type { DeckChecks } from "./deckChecks"; +import { runMediaTask, type MediaContext, type MediaReport, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import type { TaskDeps, TaskResult } from "./types"; + +export const TEASER_MIN_LINES = 3; +export const TEASER_MAX_LINES = 5; +export const TEASER_LINE_MAX = 70; +// A run this long copied from a quote is the quote read out. +export const TEASER_QUOTE_RUN = 5; +// The row each role fits (deck.mjs TEASER_LIMITS.fit): the prompt's rule; the +// build's validator is the check. +const ROLE_FIT = { overline: 64, title: 34, kicker: 56 }; +export const NEW_TEASER_ID = "teaser"; + +export type TeaserInput = MediaTaskInput; + +type TeaserUnit = MediaUnit & { + // The teaser entry as it is (null: the cut has none, and the task adds it). + entry: ManifestEntry | null; + evidence: string; + quotes: string[]; + deck: DeckChecks | null; +}; + +type Obj = Record<string, any>; +const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v); +const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); +const QUOTE_MARKS_RE = /["“”«»„‟]|‘[^’]*’|(^|\s)'[^']+'(?=[\s.,;:!?]|$)/; + +/** A claim's gist: its words with every quoted part (and the colon before it) taken out. */ +export function claimGist(text: string): string { + return stripCites(text) + .replace(/:?\s*("[^"]*"|“[^”]*”)/g, "") + .replace(/\s+/g, " ") + .replace(/[\s:,;]+$/, "") + .trim(); +} + +const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + +/** The report as the teaser may use it: titles, section titles, claim gists, the days of its sources. */ +export function teaserEvidence(report: MediaReport, manifest: VideoManifest): string { + const lines = [`Report: ${String(report.title ?? "")}`]; + if (report.subtitle) lines.push(`Subtitle: ${String(report.subtitle)}`); + for (const s of Array.isArray(report.sections) ? report.sections : []) { + const gists = (Array.isArray(s?.claims) ? s.claims : []).map((c: Obj) => claimGist(String(c?.text ?? ""))).filter(Boolean); + if (!gists.length) continue; + lines.push(`Section: ${String(s.title ?? "")}`); + for (const g of gists.slice(0, 8)) lines.push(`- ${g}`); + } + const days = new Set<string>(); + for (const c of Object.values(isObj(report.citations) ? report.citations : {})) if (typeof (c as Obj)?.date === "string") days.add((c as Obj).date.slice(0, 10)); + for (const e of manifest.timeline) if (typeof e.date === "string") days.add(e.date.slice(0, 10)); + const sorted = [...days].filter((d) => /^\d{4}-\d{2}/.test(d)).sort(); + if (sorted.length) { + const month = (d: string) => `${MONTHS[Number(d.slice(5, 7)) - 1] ?? ""} ${d.slice(0, 4)}`.trim(); + lines.push(`Sources dated: ${month(sorted[0]!)}${sorted.length > 1 && month(sorted.at(-1)!) !== month(sorted[0]!) ? ` to ${month(sorted.at(-1)!)}` : ""}`); + } + return lines.join("\n"); +} + +/** The quote words a line repeats in a run of TEASER_QUOTE_RUN or more, or null. */ +export function quoteRunIn(line: string, quotes: readonly string[]): string | null { + const said = ` ${strictNormalize(line)} `; + for (const q of quotes) { + const w = strictNormalize(q).split(" ").filter(Boolean); + for (let k = 0; k + TEASER_QUOTE_RUN <= w.length; k++) { + const run = w.slice(k, k + TEASER_QUOTE_RUN).join(" "); + if (said.includes(` ${run} `)) return run; + } + } + return null; +} + +/** The teaser entry these lines would make. */ +export const teaserEntryOf = (u: Pick<TeaserUnit, "entry" | "id">, lines: string[]): ManifestEntry => + ({ ...(u.entry ?? { type: "teaser", id: u.id }), lines }) as ManifestEntry; + +/** Every code check of a teaser's lines: `hard` refuses them. */ +export function checkTeaser(lines: string[], u: Pick<TeaserUnit, "entry" | "id" | "evidence" | "quotes" | "deck">): { hard: string[]; soft: string[] } { + const hard: string[] = []; + if (lines.length < TEASER_MIN_LINES || lines.length > TEASER_MAX_LINES) hard.push(`${lines.length} lines (${TEASER_MIN_LINES} to ${TEASER_MAX_LINES})`); + lines.forEach((l, i) => { + const n = `line ${i + 1}`; + if (!l.trim()) hard.push(`${n} is empty`); + if (/[\r\n]/.test(l)) hard.push(`${n} is more than one line`); + if (l.trim().length > TEASER_LINE_MAX) hard.push(`${n} is ${l.trim().length} characters (at most ${TEASER_LINE_MAX})`); + if (QUOTE_MARKS_RE.test(l)) hard.push(`${n} has quotation marks: a teaser reads no quote out`); + const run = quoteRunIn(l, u.quotes); + if (run) hard.push(`${n} repeats a quote ("${run}"): the clips say it; the teaser does not read it out`); + for (const p of groundedProblems(l, u.evidence, "the report")) hard.push(`${n}: ${p}`); + }); + if (!hard.length) { + if (!u.deck) hard.push("the build's teaser check (deck.mjs validateTeaser) is not available, so the lines are not written"); + else for (const e of u.deck.validateTeaser(teaserEntryOf(u, lines), `teaser ${u.id}`)) hard.push(`it would not build: ${e}`); + } + return { hard, soft: [] }; +} + +export function teaserSystem(): string { + const rules = [ + `Write ${TEASER_MIN_LINES} to ${TEASER_MAX_LINES} short lines, each one line of plain words.`, + `The first line is the overline (at most ${ROLE_FIT.overline} characters): who or what the video is about.`, + `The middle lines are titles (each at most ${ROLE_FIT.title} characters): the questions or findings the video turns on, without giving the answers away.`, + `The last line is the kicker (at most ${ROLE_FIT.kicker} characters): when, or the turn the video ends on.`, + "Read no quote out: no quotation marks, and do not repeat the speakers' words.", + "Use only names, numbers and dates that appear in the evidence.", + "Write in the third person.", + ]; + return ( + "You write the teaser card that closes a short evidence video: a few lines that slam in one after another. " + + `Rules: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + + 'Answer with "lines": the lines in order.' + ); +} + +const SCHEMA = { type: "object", properties: { lines: { type: "array", items: { type: "string" } } }, required: ["lines"] }; + +/** The model's answer to lines (a throw is a hard failure). */ +export function parseTeaser(answer: unknown): string[] { + const a = isObj(answer) ? answer : {}; + if (!Array.isArray(a.lines)) throw new Error('no "lines" in the answer'); + return a.lines.map((l: unknown) => (typeof l === "string" ? l : isObj(l) && typeof l.text === "string" ? l.text : String(l ?? "")).trim()).filter((l: string) => l !== ""); +} + +// A free id for a new teaser: "teaser", else "teaser-2", … +function freeId(manifest: VideoManifest): string { + const ids = new Set(manifest.timeline.map((e) => e.id)); + if (!ids.has(NEW_TEASER_ID)) return NEW_TEASER_ID; + for (let i = 2; ; i++) if (!ids.has(`${NEW_TEASER_ID}-${i}`)) return `${NEW_TEASER_ID}-${i}`; +} + +async function teaserUnits(ctx: MediaContext<TeaserInput>): Promise<TeaserUnit[]> { + const { manifest, report } = ctx; + let deck: DeckChecks | null = null; + try { + deck = (await ctx.handle.deps.deckChecks?.()) ?? null; + } catch (e) { + ctx.handle.log(` the build's teaser check is not loaded (${(e as Error).message})`); + } + const evidence = teaserEvidence(report, manifest); + const quotes = Object.values(isObj(report.citations) ? report.citations : {}) + .map((c) => String((c as Obj)?.quote ?? "")) + .concat(manifest.timeline.map((e) => String(e.quote ?? ""))) + .filter(Boolean); + const seen = new Set<string>(); + const teasers = manifest.timeline.filter((e) => e.type === "teaser" && !seen.has(e.id) && seen.add(e.id)); + const base = { evidence, quotes, deck }; + if (!teasers.length) { + const id = freeId(manifest); + return [{ id, target: { entry: id, field: "lines" }, label: "a new teaser after the last clip", entry: null, ...base }]; + } + return teasers.map((e) => ({ id: e.id, target: { entry: e.id, field: "lines" }, entry: e, ...base })); +} + +/** The teaser as a media task (./media.ts): one unit per teaser entry, or one new teaser. */ +export const TEASER_SPEC: MediaTaskSpec<TeaserUnit, string[], TeaserInput> = { + task: "teaser", + noun: "teaser", + verb: "drafted", + progressMetric: "entries", + units: (ctx) => teaserUnits(ctx), + schema: () => SCHEMA, + system: () => teaserSystem(), + user: (u) => `Evidence (the only facts you may use):\n${u.evidence}\n\nWrite the teaser's lines.`, + parse: (answer) => parseTeaser(answer), + check: (lines, u) => checkTeaser(lines, u), + apply(manifest, u, value, provenance, force) { + // No teaser yet: add one after the last clip, then write its lines as any + // empty field. + if (!u.entry && !entriesWithId(manifest, u.id).length) { + let at = -1; + manifest.timeline.forEach((e, i) => { + if (e.type === "clip") at = i; + }); + manifest.timeline.splice(at < 0 ? manifest.timeline.length : at + 1, 0, { type: "teaser", id: u.id } as ManifestEntry); + } + return applyDraft(manifest, { entry: u.id, field: "lines", value, provenance, force }); + }, + describe: (lines) => lines.join(" / "), +}; + +export async function teaser(input: TeaserInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(TEASER_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts @@ -14,6 +14,7 @@ import type { CuesOf, PostChannelOf } from "../../convertShared"; import type { readIteration } from "../../iterations"; import type { Report } from "../../schema"; import type { ResearchEditor } from "../research/tools"; +import type { DeckChecks } from "./deckChecks"; // The iterations store's paths (S4 takes them on every call). export type StorePaths = NonNullable<Parameters<typeof readIteration>[2]>; @@ -62,6 +63,10 @@ export type TaskDeps = { log?: (line: string) => void; // Progress, as the task counts it (the editor job's setProgress). progress?: (p: TaskProgress) => void; + // The build's validators (umtool's report-to-video, loaded from the + // checkout: ./deckChecks.ts) — a media task's checks that the cut it + // drafts still builds (release 28). + deckChecks?: () => Promise<DeckChecks>; signal?: AbortSignal; }; diff --git a/common/lib/report/drafted.d.mts b/common/lib/report/drafted.d.mts @@ -23,6 +23,8 @@ export function isEntryField(field: string): field is DraftedEntryField; export function isManifestField(field: string): field is DraftedManifestField; export function provenanceProblems(v: unknown, where: string): string[]; export function makeProvenance(p: { task: string; model: string; at?: Date | string; iteration?: number; attempt?: number }): Provenance; +/** A mark a code path made (`model: "code"`): needs no review (release 28 M1). */ +export function isCodeDraft(p: unknown): boolean; export function entriesWithId(manifest: unknown, id: string): Record<string, any>[]; export function readField(manifest: unknown, target: DraftTarget): unknown; export function isEmptyField(field: string, v: unknown): boolean; diff --git a/common/lib/report/drafted.mjs b/common/lib/report/drafted.mjs @@ -105,6 +105,15 @@ export function makeProvenance({ task, model, at = new Date(), iteration, attemp }; } +/** + * A mark a CODE path made (`model: "code"`): the converter's timeline + * (release 28 M1). It says who made the field so a task may redraft it, and + * it needs no review — the drafts review and the final gate leave it out. + * + * @param {unknown} p + */ +export const isCodeDraft = (p) => isObj(p) && p.model === "code"; + /** Every timeline entry with this id (a cut's `variant` twins share one). */ export function entriesWithId(manifest, id) { return (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => isObj(e) && e.id === id); diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -28,6 +28,7 @@ import { GENERATION_MODELS_FIELD_DOCS, GENERATION_RESEARCH_FIELD_DOCS, GENERATION_ROUTES_FIELD_DOCS, + GENERATION_CUT_FIELD_DOCS, GENERATION_SETTINGS_FIELD_DOCS, GENERATION_WEB_FIELD_DOCS, GENERATION_VERDICTS_FIELD_DOCS, @@ -289,6 +290,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, { path: "generation.caps", docs: GENERATION_CAPS_FIELD_DOCS, defaults: fromObject(d.generation.caps) }, { path: "generation.web", docs: GENERATION_WEB_FIELD_DOCS, defaults: fromObject(d.generation.web) }, { path: "generation.research", docs: GENERATION_RESEARCH_FIELD_DOCS, defaults: fromObject(d.generation.research) }, + { path: "generation.cut", docs: GENERATION_CUT_FIELD_DOCS, defaults: fromObject(d.generation.cut) }, { path: "generation.verdicts", docs: GENERATION_VERDICTS_FIELD_DOCS, defaults: fromObject(d.generation.verdicts) }, { path: "generation.verdicts.bar", docs: GENERATION_VERDICT_BAR_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.bar) }, ], diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -82,6 +82,7 @@ import { sanitizeTts, type TtsSettings } from "./ttsSettings"; import { sanitizeGeneration, type GenerationSettings } from "./generationSettings"; export { GENERATION_CAPS_FIELD_DOCS, + GENERATION_CUT_FIELD_DOCS, GENERATION_MODELS_FIELD_DOCS, GENERATION_RESEARCH_FIELD_DOCS, GENERATION_ROUTES_FIELD_DOCS, diff --git a/common/testing/draft/manifests/basic.video.manifest.json b/common/testing/draft/manifests/basic.video.manifest.json @@ -126,5 +126,13 @@ "cite": 40, "quote": "my lawyer told me not to talk about the lease" } - ] + ], + "drafted": { + "timeline": { + "task": "convert", + "model": "code", + "at": "2026-10-13T00:00:00.000Z", + "attempt": 1 + } + } } diff --git a/common/testing/draft/manifests/paragraphs.video.manifest.json b/common/testing/draft/manifests/paragraphs.video.manifest.json @@ -79,5 +79,13 @@ "cite": 5, "quote": "we tried the sourdough recipe from last week" } - ] + ], + "drafted": { + "timeline": { + "task": "convert", + "model": "code", + "at": "2026-10-13T00:00:00.000Z", + "attempt": 1 + } + } } diff --git a/common/testing/draft/manifests/posts-only.video.manifest.json b/common/testing/draft/manifests/posts-only.video.manifest.json @@ -76,5 +76,13 @@ "siteChannel": "synth-social", "postId": "1700000000000000002" } - ] + ], + "drafted": { + "timeline": { + "task": "convert", + "model": "code", + "at": "2026-10-13T00:00:00.000Z", + "attempt": 1 + } + } } diff --git a/common/testing/draft/runMediaStep.ts b/common/testing/draft/runMediaStep.ts @@ -0,0 +1,73 @@ +// A media draft run for real over a fixture iteration, its model the fake +// ollama scripted with the task's recorded run (`runs/<task>.json`) — what +// umtool's e2e editor stub does with a `report-draft` of a media task +// (release 28: umtool/e2e/media-draft.spec.ts). Test-only; synthetic. +// +// tsx common/testing/draft/runMediaStep.ts --task cut --article mdraft --n 1 \ +// --articles <ARTICLES_DIR> --projects <projectsRoot> [--model qwen3:8b] \ +// [--entries c01,c02] [--force] [--job <id>] +// +// The task records its own step on the iteration (running, then its end). The +// last line printed is `@@report-draft {article, iteration, task, status, +// summary}`; the exit code is 0 when the step is done. + +import { mkdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { startFakeOllama } from "../llm/fakeOllama.mjs"; +import { isStepTask } from "../../lib/generationSettings"; +import { loadDeckChecks, runTask, type TaskInput } from "../../lib/report/draft/tasks/index"; + +const HERE = path.dirname(/* turbopackIgnore: true */ fileURLToPath(import.meta.url)); +const ROOT = path.resolve(/* turbopackIgnore: true */ HERE, "../../.."); + +const argv = process.argv.slice(2); +const flag = (name: string) => { + const i = argv.indexOf(`--${name}`); + return i < 0 ? undefined : argv[i + 1]; +}; +const task = flag("task") ?? ""; +const article = flag("article") ?? ""; +const n = Number(flag("n")); +const articlesDir = flag("articles") ?? ""; +const projectsRoot = flag("projects") ?? ""; +if (!isStepTask(task) || !article || !Number.isInteger(n) || !articlesDir || !projectsRoot) { + console.error("usage: runMediaStep.ts --task <media task> --article <id> --n <i> --articles <dir> --projects <dir> [--model m] [--entries a,b] [--force] [--job id]"); + process.exit(2); +} + +const run = JSON.parse(await readFile(path.join(/* turbopackIgnore: true */ HERE, "runs", `${task}.json`), "utf8")) as { model: string; turns: unknown[] }; +const ol = await startFakeOllama(); +ol.push(...(run.turns as never[])); +const exportIndexDir = path.join(articlesDir, "..", ".export-index-media-draft"); +await mkdir(exportIndexDir, { recursive: true }); +const entries = flag("entries")?.split(",").map((x) => x.trim()).filter(Boolean); +const jobId = flag("job"); +const input = { + task, + article, + n, + model: flag("model") ?? run.model, + projectsRoot, + ...(entries?.length ? { entries } : {}), + ...(argv.includes("--force") ? { force: true } : {}), + ...(jobId ? { jobId } : {}), +} as TaskInput; +let code = 1; +try { + const res = await runTask(input, { + llm: { ollama: { baseUrl: ol.url } }, + corpus: { source: "none", tools: [], call: async () => "" }, + cuesOf: async () => null, + paths: { articlesDir, exportIndexDir }, + log: (l) => console.log(l), + deckChecks: () => loadDeckChecks(ROOT), + }); + console.log(`@@report-draft ${JSON.stringify({ article, iteration: n, task, status: res.status, summary: res.summary })}`); + code = res.status === "done" ? 0 : 1; +} catch (e) { + console.log(`@@report-draft ${JSON.stringify({ article, iteration: n, task, status: "failed", summary: (e as Error).message })}`); +} finally { + await ol.close(); +} +process.exit(code); diff --git a/common/testing/draft/runs/cut.json b/common/testing/draft/runs/cut.json @@ -0,0 +1,20 @@ +{ + "task": "cut", + "model": "qwen3:8b", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"groups\": [{\"heading\": \"The contest\", \"clips\": [\"c04\", \"c06\", \"c09\"]}, {\"heading\": \"The bakery\", \"clips\": [\"c03\", \"c01\", \"c01\"]}]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"groups\": [{\"heading\": \"The contest\", \"clips\": [\"c04\", \"c06\"]}, {\"heading\": \"The bakery\", \"clips\": [\"c03\", \"c01\"]}]}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/runs/onscreen.json b/common/testing/draft/runs/onscreen.json @@ -0,0 +1,20 @@ +{ + "task": "onscreen", + "model": "qwen3:8b", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"entries\": [{\"id\": \"c01\", \"title\": \"She will not sell to a chain\", \"subtitle\": \"\\\"I would never sell the bakery to a chain\\\"\"}, {\"id\": \"c02\", \"title\": \"\\\"Never said that\\\"\", \"subtitle\": \"On the old oven\"}, {\"id\": \"c03\", \"title\": \"Who paid for the mixer\", \"subtitle\": \"\\\"I bought the mixer\\\"\"}, {\"id\": \"c04\", \"title\": \"She did not enter the contest this year, she says, and explains it\", \"subtitle\": \"Pie stream\"}, {\"id\": \"c05\", \"title\": \"Why she stayed out\", \"subtitle\": \"The judges were her friends\"}, {\"id\": \"c06\", \"title\": \"Lease talks in 2024\", \"subtitle\": \"Her lawyer said to keep quiet\"}]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"entries\": [{\"id\": \"c02\", \"title\": \"The oven story, denied\", \"subtitle\": \"\\\"we never said that about the old oven\\\"\"}, {\"id\": \"c03\", \"title\": \"Who paid for the mixer\", \"subtitle\": \"\\\"I paid for the new mixer myself\\\"\"}, {\"id\": \"c04\", \"title\": \"Out of the contest this year\", \"subtitle\": \"From the pie stream\"}, {\"id\": \"c06\", \"title\": \"Lease talks with Marco\", \"subtitle\": \"Her lawyer said to keep quiet\"}]}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/runs/teaser.json b/common/testing/draft/runs/teaser.json @@ -0,0 +1,20 @@ +{ + "task": "teaser", + "model": "qwen3:8b", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"lines\": [\"Synth Kitchen\", \"She would never sell the bakery\", \"The contest\", \"Two streams later\"]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"lines\": [\"Synth Kitchen\", \"The bakery\", \"The contest\", \"What the baker says\"]}" + }, + "done": true + } + ] +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,9 @@ # Changelog ## [Unreleased] +- **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). - **A research run on `auto` continues into its sweep by itself.** Once its acquisitions settle — every job it started has ended and nothing waits for your yes or no — the editor runs the same sweep **Continue into a sweep** would, on the run's own model, and the run's queue in umtool says **continued automatically by i<n>**. The caps hold: the sweep's per-job cap applies, and past the day's API total it is not started; the queue says so, and it is tried again the next day (UTC). A channel the run acquired into that is in no site build yet is left out of the sweep, with the warning "not in any build yet: <slug> — rebuild the site and continue again" on the queue and on the sweep; a run with nothing it could sweep waits for a newer build. `propose` and `limits` runs are still continued by you, and an editor booted idle (`ARCHILYZER_IDLE_BOOT`) continues nothing. Needs a restart of the editor and umtool. - **The editor drafts a report video's flips, threads and YouTube text.** `pnpm ops report-draft --json '{"task": "flips" | "threads" | "youtube", "article", "iteration", "model"?, "force"?}'` runs on a done iteration's video project. **Flips** pairs a clip with a later one on the same topic: the model picks the clips and names the topic, and the dates (the recordings'), the THEN/NOW order, the `when` lines and the words (the clip's own quote, word for word) are set by code. **Threads** groups the clips into 2 to 4 labelled threads; a thread's verdict stamp is its last clip's ruling, never the model's. **YouTube** writes `publish.youtube`'s title and a one-paragraph summary, with every name and number from the report, in the third person, quoting only what a clip says. Flips and threads share the left panel, so each refuses a cut that has the other unless forced over a draft of it, which it then replaces. Each drafted field carries its `drafted` mark and goes through the drafts review. - **A build writes the YouTube text: `out/youtube.txt`.** When the manifest has `publish.youtube`, the build writes the title, the summary, the chapters from its own chapter list, and a moment link for each cited clip, in cut order, each once. The chapters follow YouTube's rules: they start at 0:00, there are at least three, and each lasts ten seconds or more. A shorter one is folded into the one before it; when the list still falls short it is left out, and the build says why. umtool's project page shows the text with **Copy**. Before a build, it shows the same text without the chapters. diff --git a/editor/e2e/report-draft.spec.ts b/editor/e2e/report-draft.spec.ts @@ -1,11 +1,11 @@ import { test, expect, type APIRequestContext } from "@playwright/test"; -import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; // By relative path, as digest.spec.ts imports common: the test kit's fakes and // the synthetic corpus are plain .mjs. -import { FAKE_KEY, startFakeAnthropic, textTurn, type FakeAnthropic } from "../../common/testing/llm/fakeAnthropic.mjs"; +import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, type FakeAnthropic } from "../../common/testing/llm/fakeAnthropic.mjs"; import { ORIGIN, writeDraftCorpus } from "../../common/testing/draft/corpus.mjs"; import { baseUrl } from "./baseUrl"; import { resetData, testPaths, writeSettings } from "./helpers"; @@ -157,3 +157,44 @@ test("the daily cap: a job that would start past the day's API total is refused, expect(body.error).toContain("$4.00 daily cap"); await expect(readFile(join(testPaths().transcriptsDir, "reports", "synth-daily", "iterations", "1", "iteration.json"))).rejects.toThrow(/ENOENT/); }); + +test("a media draft (release 28 M3): a teaser on the API, a step on the done iteration, checked by the build's own validator loaded in the editor", async ({ request }) => { + test.setTimeout(120_000); + await setup(); + // A done sweep iteration whose project holds the kit's basic cut and report. + const kit = join(RUNS, ".."); + const article = "synth-teaser"; + const project = join(keyDir, "projects", article, "i1"); + const report = JSON.parse(await readFile(join(kit, "reports", "basic.report.json"), "utf8")); + const itDir = join(testPaths().transcriptsDir, "reports", article, "iterations", "1"); + await mkdir(itDir, { recursive: true }); + await mkdir(project, { recursive: true }); + const at = new Date().toISOString(); + await writeFile( + join(itDir, "iteration.json"), + JSON.stringify({ + format: "archilyzer-iteration", version: 1, article, n: 1, kind: "sweep", parent: null, copyOf: null, model: "claude-sonnet-5-5", + question: "q", scope: { channels: ["synth-kitchen"] }, status: "done", usage: {}, steps: [], projectDir: project, createdAt: at, updatedAt: at, endedAt: at, + }), + ); + await writeFile(join(itDir, "report.json"), JSON.stringify(report)); + await writeFile(join(project, "report.json"), JSON.stringify(report)); + await writeFile(join(project, "video.manifest.json"), await readFile(join(kit, "manifests", "basic.video.manifest.json"), "utf8")); + api.push(toolTurn("answer", { lines: ["Synth Kitchen", "The bakery", "The contest", "What the baker says"] })); + const { status, body } = await draft(request, { task: "teaser", article, iteration: 1, model: "claude-sonnet-5-5" }); + expect(status, body.error).toBe(200); + expect(body.iteration).toBe(1); + const job = await jobUntil(request, body.jobId!, (s) => ["done", "failed", "cancelled"].includes(s)); + expect(job.job?.status ?? job.status, JSON.stringify(job.tail)).toBe("done"); + expect((job.job as { progress?: unknown } | undefined)?.progress).toMatchObject({ metric: "entries", initial: 0, current: 1, target: 1 }); + const it = await iterationJson(article, 1); + expect(it.steps.find((s: { task: string }) => s.task === "teaser")).toMatchObject({ status: "done", jobId: body.jobId }); + const m = JSON.parse(await readFile(join(project, "video.manifest.json"), "utf8")); + expect(m.timeline.at(-1)).toMatchObject({ type: "teaser", id: "teaser", lines: ["Synth Kitchen", "The bakery", "The contest", "What the baker says"] }); + expect(m.timeline.at(-1).drafted.lines).toMatchObject({ task: "teaser", model: "claude-sonnet-5-5", iteration: 1, attempt: 1 }); + // The editor ran the build's validateTeaser (a teaser it cannot check is not written). + const draftFile = JSON.parse(await readFile(join(project, "teaser-draft.json"), "utf8")); + expect(draftFile.units.teaser.applied).toBe("applied"); + expect(api.remaining()).toBe(0); +}); + diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9202,8 +9202,8 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri operator. `applyDraft(manifest, { entry?, field, value, provenance, force? })` is the one writer every task uses: `{ applied: true }` or `{ applied: false, reason: "operator" | "drafted" | "missing" }`. The operator's field is never replaced, `force` or not; `force` only re-drafts a field still marked. An entry id names every - entry with it (variant twins). A timeline with no `drafted.timeline` is the operator's — M1 decides what the - converter's order counts as. + entry with it (variant twins). A timeline with no `drafted.timeline` is the operator's to `ownerOf` — but the cut + task counts the converter's order as code's (M1, below). - **An edit clears the mark.** umtool's manifest writer (`lib/report/manifest.mjs` `writeManifestAtomic`) re-reads the file and runs `clearEditedDrafts(before, after)` on EVERY write: a marked field whose `fieldSignature` changed loses its mark; orphans go. A mark the write itself added is kept. `writeDraftedField` @@ -9232,6 +9232,31 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri reason }] }`; alternatives from earlier runs are carried over, newest five per field. The step is recorded in the iteration's `steps` (a done iteration's status is left). umtool reads alternatives from every `*-draft.json` beside the manifest (`lib/report/drafts.mjs` `readAlternatives`). +- **The media steps (release 28, lane D).** `MEDIA_STEP_TASKS` / `isStepTask` (`generationSettings.ts`) is the one list + of tasks that run as a step on a done iteration (`narrate, cut, onscreen, teaser, flips, threads, youtube`); each has a + route (narrate's in every preset) and a narration's cap; a `report-draft` step body is `{task, article, iteration, + model?, entries?, force?}`. The scaffold reports progress per ask (`progressMetric`, default `entries`; narrate + `cards`), may batch units (`spec.batch`) and may say who owns a unit's field for the skip (`spec.owner`); the + writer is always `applyDraft`. A task reaches the build's validators through `TaskDeps.deckChecks` + (`tasks/deckChecks.ts`: umtool's `deck.mjs` `validateTeaser` and `lint.mjs` `validatorErrors`, imported natively + from the checkout; the editor job passes `loadDeckChecks(paths.monorepoRoot)`). +- **cut** (`tasks/cut.ts`): one unit, `drafted.timeline`. The model answers citation ids grouped under section + headings; code checks them (candidates only, once each, 3 to `generation.cut.maxClips` (20), pinned clips kept — + posts' `attachTo`, flips' entries — headings the cut's, no new `validatorErrors`) and BUILDS the timeline + (`buildCut`) from the entries it had. **A timeline marked `model: "code"` is nobody's**: `reportToManifest` marks + its own `{task: "convert", model: "code"}`, an unmarked timeline in the converter's clip order counts as code's + (`isConverterOrder`), the cut drafts over either without `force`; `isCodeDraft` marks need no review (no review + row, no final-gate error). +- **onscreen** (`tasks/onscreen.ts`): one unit per clip, asked in batches (≤ 8, within the local cap); title ≤ 60 + with no quotation marks, subtitle ≤ 90 quoting only the clip's own quote word for word, one line each, names and + numbers in the clip's evidence (`groundedProblems`), third person outside quotes. +- **teaser** (`tasks/teaser.ts`): one unit per teaser entry; none → a `{type: "teaser", id: "teaser"}` after the last + clip, through `applyDraft`. 3 to 5 lines ≤ 70, no quotation marks, no 5-word run of a quote, grounded, and + `validateTeaser` passes — without `deckChecks` nothing is written. +- **`groundedProblems(text, reference, where)`** (`grounding.ts`) is the names-and-numbers check narration, on-screen + and teaser share (a sentence's first word is not checked as a name). +- **umtool's e2e stub runs cut, onscreen and teaser for real** (`common/testing/draft/runMediaStep.ts`, a tsx child + over the fixture iteration's project, the fake ollama on `runs/<task>.json`); the task records its own step. ## Release 28 lane B: quality and progress (verified 2026-10-13, branch `r28/quality` @ `48dbc5de`) - **The narrator is third person** (`grounding.ts`): a first-person word outside double quotes is a HARD grounding problem whose text starts `the narrator is third person`. A media task that calls `checkNarration` refuses it with no change of its own. `GroundingInput.sources` (each quote's speaker and `c03 (label @ m:ss)`) names the line it restates; `groundingInputOf` fills it. diff --git a/plans/release-28.md b/plans/release-28.md @@ -699,6 +699,145 @@ questions: F1 continues only `auto` runs, on the research run's model, and needs heartbeat is off (an acquisition job's end is the trigger); lane E's first-word name check stays as built; a threads alternative's "Use this" carries the clips' assignments (M9). M9 (lane G, `r28/surfaces`) started from `f7b8dae9` beside lane D. +### Media wiring, as shipped (2026-10-13, lane D, `r28/media-d`) + +Step 0: the six new media tasks are steps, as narrate was, through one list. Committed first and alone (`ea4e9072`); +lane E branched from it. +- `MEDIA_STEP_TASKS` (`narrate, cut, onscreen, teaser, flips, threads, youtube`) and `isStepTask` in + `generationSettings.ts` are the one list. `GENERATION_TASKS` and `TASK_NAMES` contain them. Every `=== "narrate"` + step check asks `isStepTask`: the controller's body, enqueue, job and usage row; the MCP's step lookup and wording; + the ops row; the route's doc. +- **Routes:** each new task takes narrate's route in every preset (`balanced`: local). +- **A settings file from before:** one that routes release 27's first four tasks keeps its preset. A task it does not + name takes that preset's route; S11's research rule is generalised. A partial patch names no preset. +- **The body** of a media draft is `{task, article, iteration, model?, entries?, force?}` (narrate's `cards` kept). It + is refused as narrate's is: no iteration, a `copyOf`, `entries` on a non-step task. Its cap is a narration's. +- The tasks not yet built refused at the job as a failed step, "not implemented in this build". All six are built + now, and the refusal is gone at the merge. +- umtool's generate forwards `entries`. +- SETTINGS.md, settings.json.example and COMMANDS.md regenerated. + +### M1, as shipped (2026-10-13, lane D, `r28/media-d`) + +The cut task (`cut`): which of the report's citations the video keeps, and in what order. It is one unit, the +timeline's ORDER (`drafted.timeline`). +- **Candidates** (`cutCandidates`): each clip or still whose id is a report citation (the converter's rule), else the + video citation of its recording and second. The model sees them by the chapter they sit in, with: + - each claim's text and verdict; + - the source and date; + - the quote, shortened step by step until the local prompt fits (`fitLocalAsk`). +- **The answer** is citation ids grouped under the section headings. +- **Code refuses:** + - an id not a candidate; + - an id twice; + - more than `settings.generation.cut.maxClips` (new; default 20; a whole number from 3) or fewer than 3; + - a dropped clip a post rides on or a flip names (`pinnedEntries`); + - a heading not the cut's, or one heading two groups; + - any error the build's own validators (`lint.mjs` `validatorErrors`) give the built cut that the cut as read did + not have (compared with timeline positions taken out). A thread left with no clip is caught this way. +- **Code builds the timeline** (`buildCut`), never inventing an entry: + - the chosen entries, untouched, with variant twins together; + - a chapter card where its group keeps an entry; a card with nothing left is dropped (S7's rule); + - everything before the first chapter or citation entry first, and everything after the last one last (the + teaser); + - an entry no citation names stays with its chapter, after its card. +- **The build's validators** reach a common task through `TaskDeps.deckChecks` (`tasks/deckChecks.ts`): umtool's + `deck.mjs` and `lint.mjs`, loaded natively from the checkout (`import(/* turbopackIgnore: true */ …)`). The editor + job passes `loadDeckChecks(paths.monorepoRoot)`. The editor's e2e proves it in the built server. +- **The ruling on lane A's question, as built:** + - `reportToManifest` marks its timeline `drafted.timeline {task: "convert", model: "code", at, attempt: 1}`, `at` + the day it was made (`today`). The kit's derived manifests were regenerated. + - An unmarked timeline whose clip order is exactly the converter's from the project's report is code's too + (`isConverterOrder`). + - A code-made order is drafted over without `force`. The cut's `apply` gives an unmarked one the converter's mark + first, then writes through `applyDraft`. One marked by a model needs `force`. Any other is the operator's: its + draft is kept as an alternative. + - `isCodeDraft` (drafted.mjs): `draftsReviewRows` leaves a code mark out, so there is no row, no badge and no + final-gate error. umtool's "Review drafts — N" count leaves it out too. These are lane A's files; the change is + additive, a filter and an import each. + - An operator's reorder in umtool clears the mark as any edit does. +- **The scaffold** (`media.ts`, additive): + - `spec.owner`, who owns a unit's field for the skip. The writer is still `applyDraft`. + - `spec.batch` (M2). + - Progress: `h.progress({metric: spec.progressMetric ?? "entries", current, total})` at 0 and after each ask. + Narrate's metric is `cards`. Lane E's three get `entries` for free. + +### M2, as shipped (2026-10-13, lane D, `r28/media-d`) + +The on-screen task (`onscreen`): each clip's `onscreen.{title, subtitle}`. One unit per clip entry (or the `entries` +asked for). +- **Evidence:** the report's title, the clip's section, its claim (text, verdict), its quote and source. +- **Batches:** several clips per ask (`spec.batch`) — as many as fit the local prompt cap measured by + `structuredPromptEstimate`, at most `ONSCREEN_BATCH_MAX` (8). The re-ask carries only the clips refused, with each + one's reasons. +- **Code refuses:** + - a title over 60 characters or a subtitle over 90; + - more than one line; + - a title with any quotation marks (an apostrophe is not one); + - a subtitle quoting anything but the clip's own quote, word for word (`strictNormalize`, whole words), or with + marks that do not pair up; + - a name or number the clip's evidence lacks; + - the first person outside a quotation (Q1's `firstPersonProblems`). +- **`grounding.ts` `groundedProblems(text, reference, where)`:** the names and numbers check `checkNarration` ran + inline, now one function that both use. The wording is unchanged for narration. + +### M3, as shipped (2026-10-13, lane D, `r28/media-d`) + +The teaser task (`teaser`): a teaser's `lines`. One unit per teaser entry. +- **A cut with no teaser** gets one: `{type: "teaser", id: "teaser"}` (else `teaser-2`, …) after its last clip, its + lines written through `applyDraft` as an empty field. Nothing is added when the draft is refused. +- **Evidence:** the report's title and subtitle, section titles, claim gists (`claimGist`: the quoted words taken + out), and the months its sources and clips are dated. +- **Code refuses:** + - fewer than 3 or more than 5 lines; + - a line over 70 characters, or on two lines; + - quotation marks; + - a run of 5 words from any quote; + - a name or number the evidence lacks; + - anything `deck.mjs` `validateTeaser` refuses (the row each role fits: overline, title, kicker). Without that + check (no `deckChecks`), nothing is written. +- **The prompt** states each role's fit as a rule; the check is the build's. + +| Commit | What | +| --- | --- | +| `ea4e9072` | step 0: `MEDIA_STEP_TASKS`, `isStepTask`, routes in every preset, the old-file preset rule, the step body with `entries`, the not-implemented refusal; the MCP, the ops row, the route doc; SETTINGS.md, COMMANDS.md | +| `54400684` | the scaffold: `spec.batch`, `spec.owner`, progress; `tasks/deckChecks.ts` and `TaskDeps.deckChecks`; a batch test | +| `fbf1e11d` | M1: `tasks/cut.ts` (+ 5 tests), `generation.cut.maxClips`, the converter's code mark, `isCodeDraft` and the review's exemption, `runs/cut.json`, the kit regenerated | +| `1a47547c` | M2: `tasks/onscreen.ts` (+ 3 tests), `groundedProblems`, `runs/onscreen.json` | +| `2cd6e68d` | M3: `tasks/teaser.ts` (+ 3 tests), `runs/teaser.json` | +| `c11db375` | umtool e2e `media-draft.spec.ts`: the stub runs a media step for real (`testing/draft/runMediaStep.ts`, a tsx child, the fake ollama on the kit's run); fixture `mdraft` | +| `6ff39f31` | merge of `r28/integration` (lanes C, E, F): cut beside verdicts in the settings, the dispatcher with all six | +| `4d0dee5c` | editor e2e: a teaser through the real editor job on the fake API; the runner's paths opt out of tracing | +| (this commit) | these records, FACTS, CHANGELOG | + +Lane D's gates (from the worktree root): +- **tsc** (all packages): clean before every commit. +- **Unit suites**, counted at the branch's start (`7e14a060`), after the merge, and at the tip: + - common: 4042 at the start (3 failing: two settings-doc tests read mid-edit, and the `fetchPosts` drain flake); 4050/4050 at M1; 4089/4089 after the merge; 4089/4089 at the tip. + - editor: 290 → 292 at step 0 → 295 after the merge; 295/295 at the tip. + - mcp: 346 → 349 after the merge; 349/349 at the tip. + - `test:scripts`: 874 (870 pass, 3 skipped, 1 `queue-lock` timing flake) at the start → 875 at M1 (+1, the code-mark review test) → 884 after the merge; 884 at the tip (881 pass, 2 skipped, 1 `queue-lock.test.mjs` timing failure under the full run's load, 37/37 alone). +- **Docs:** `docs env|files|cli --check` and `settings example --check` clean. +- **umtool e2e**, single specs in the foreground: + - `media-draft.spec.ts` 3/3 (14.6 s; the first run failed 3/3 waiting on a tab that does not poll a job it did not + start, so the spec now polls the iterations API, then opens the tab); + - `article-iterations.spec.ts` + `draft-review.spec.ts` 7/7 (40.3 s). + - The first run's prebuild was umtool's capped build. +- **Editor e2e** `report-draft.spec.ts` alone: 4/4 (17.9 s). Its prebuild was the editor's capped `next build`: + compiled in 21.8 s, 52 s in all, heavy slot, 5 GB. +- **umtool capped build**, corpus linked, through the heavy slot (5 GB): compiled in 9.1 s; the link removed. + +Found and left: +- **Lane E's flips swap** a THEN after its NOW when `ownerOf(timeline)` is `"drafted"`. With the converter's mark, a + converter-made cut is `"drafted"`, so flips may reorder it. This is consistent with the ruling: a code-made order is + nobody's. +- **A revise-video iteration copies its parent's manifest, mark included.** An order it changed through its ops + stays marked as code's or the cut's, and the cut task may redraft it. Its ops are a model's work from the operator's + feedback; whether that order is the operator's is a ruling for M9. +- **Folding lane E's tasks into `media-draft.spec.ts` was not cheap.** flips needs the corpus's records for its + dates, and the stub's runner has no corpus tools (common cannot import the MCP's). Both specs stay. +- **The Iterations tab does not follow a step it did not start.** A media draft asked through the API shows on reload. + M9's buttons start their own. ## Not in this release diff --git a/settings.json.example b/settings.json.example @@ -274,6 +274,9 @@ "searchUrl": "" }, "citationOrigin": "", + "cut": { + "maxClips": 20 + }, "research": { "autonomy": "propose", "maxItemsPerRun": 20, diff --git a/umtool/app/api/articles/generate/route.ts b/umtool/app/api/articles/generate/route.ts @@ -4,7 +4,7 @@ export const dynamic = "force-dynamic"; // START A GENERATION (release 27 S8): the body is `pnpm ops report-draft`'s — // { task, article, iteration?, model?, extractorModel?, feedback?, question?, -// channels?, from?, to?, copyOf?, maxUsd?, cards?, force?, autonomy? } — +// channels?, from?, to?, copyOf?, maxUsd?, cards?, entries?, force?, autonomy? } — // forwarded to the editor, which // creates the iteration and runs the job. Answers { ok, jobId, iteration }. // @@ -13,6 +13,9 @@ export const dynamic = "force-dynamic"; // a new iteration task revise-report | revise-video, iteration, feedback // copy with model the iteration's task, copyOf, model // narration task narrate, iteration, model (a step) +// a media draft task cut | onscreen | teaser | flips | threads | +// youtube, iteration, model, entries?, force? (a step, +// release 28) // research task research, question, channels?, model, autonomy // (release 27 S11: its queue is /api/articles/research) // continue research task sweep, iteration (the research run), model diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx @@ -20,7 +20,7 @@ import { listSnapshots, readSnapshot } from "@/lib/report/snapshots.mjs"; import { listTakes } from "@/lib/report/takes.mjs"; import { podcastFor } from "@/lib/report/serve.mjs"; import { narrationsOf } from "umtool-report-to-video/narration"; -import { draftedFields } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { draftedFields, isCodeDraft } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; import { readAlternatives } from "@/lib/report/drafts.mjs"; import DeliverSection from "./DeliverSection"; import FetchUnfetchedButton from "./FetchUnfetchedButton"; @@ -153,7 +153,8 @@ export default async function ReportProject({ const takes = await listTakes(project.dir); const narrated = narrationsOf(m).length; // The drafts review (release 28): drafted fields, and alternatives kept. - const draftedCount = draftedFields(m).length; + // (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; // Provenance splits by SHAPE: a scalar or a URL stays in the table; a long diff --git a/umtool/e2e/fixtures/editor-stub.mjs b/umtool/e2e/fixtures/editor-stub.mjs @@ -16,10 +16,11 @@ // entry, ready when its own endpoint answers. import http from "node:http"; -import { spawnSync } from "node:child_process"; +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 { fileURLToPath } from "node:url"; const PORT = portFor("EDITOR_STUB_PORT"); const CHANNELS = process.env.CHANNELS_DIR ?? ""; @@ -386,10 +387,56 @@ function continuation(article, rn, force, given) { return { kind: "sweep", parent: rn, copyOf: null, question: r.question, scope: { channels: given ?? channels } }; } +// The media drafts (release 28) run FOR REAL: the common task over the +// fixture iteration's project, its model the fake ollama scripted with the +// test kit's recorded run (common/testing/draft/runMediaStep.ts, a child under +// tsx). The task records its own step; the job follows the child. +const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); +const MEDIA_RUN = new Set(["cut", "onscreen", "teaser"]); +function startMediaDraft(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 job = { id, article, n, task, status: "queued", log: [`report-draft ${task} ${article} i${n} (stub: the task, the fake model)`], timers: [], child: null }; + draftJobs.set(id, job); + const args = [ + path.join(REPO, "common/testing/draft/runMediaStep.ts"), + "--task", task, "--article", article, "--n", String(n), "--articles", ARTICLES, "--projects", GEN_PROJECTS, "--job", id, + ...(body.model ? ["--model", body.model] : []), + ...(Array.isArray(body.entries) ? ["--entries", body.entries.join(",")] : []), + ...(body.force ? ["--force"] : []), + ]; + job.timers.push( + setTimeout(() => { + if (job.status !== "queued") return; + job.status = "running"; + const child = spawn(path.join(REPO, "node_modules/.bin/tsx"), args, { cwd: REPO, stdio: ["ignore", "pipe", "pipe"] }); + job.child = child; + let buf = ""; + const take = (d) => { + buf += d; + const lines = buf.split("\n"); + buf = lines.pop(); + job.log.push(...lines.filter(Boolean)); + }; + child.stdout.on("data", take); + child.stderr.on("data", take); + child.on("close", (code) => { + if (buf) job.log.push(buf); + if (job.status === "cancelled") return; + job.status = code === 0 ? "done" : "failed"; + }); + }, 500), + ); + return { jobId: id, iteration: n }; +} + function startDraft(body) { const { task, article } = body; const now = new Date().toISOString(); const id = `stub-draft-${nextJob++}`; + if (MEDIA_RUN.has(task)) return startMediaDraft(body, id); let n; if (task === "narrate") { n = body.iteration; @@ -441,8 +488,9 @@ function cancelDraft(id) { for (const t of job.timers) clearTimeout(t); job.status = "cancelled"; job.log.push("cancelled"); + job.child?.kill(); const it = readIt(job.article, job.n); - if (job.task === "narrate") { + if (job.task === "narrate" || MEDIA_RUN.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() }); diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -24,6 +24,7 @@ import { SONG_DATA } from "../../song/paths.mjs"; 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 { makeDeleteFixture } from "./delete-fixture.mjs"; import { makeDraftReviewFixture } from "./draft-review-fixture.mjs"; import { makeYoutubeFixture } from "./youtube-fixture.mjs"; @@ -1919,6 +1920,8 @@ writeProject("timeline-fixture", { const { sites: SITES, articles: ARTICLES } = makeSitesFixture({ dest, reports, channels: CHANNELS }); // Release 27: an article in the making (zeta), its projects, today's usage. makeIterationsFixture({ dest, articles: ARTICLES }); +// Release 28: the media drafts' article (mdraft), one iteration per task. +makeMediaDraftFixture({ dest, articles: ARTICLES }); // 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-draft-fixture.mjs b/umtool/e2e/fixtures/media-draft-fixture.mjs @@ -0,0 +1,58 @@ +// What media-draft.spec.ts drafts on (release 28 M1–M3; lane E's tasks add +// iterations): `mdraft`, an article in the making whose done iterations each +// have a video project made from the S0 test kit's basic report — the +// converter's cut, its order marked as code's. One iteration per task, so no +// spec depends on another's draft: +// +// articles/mdraft/iterations/{1,2,3} sweep, qwen3:8b, done; the kit's report +// gen-projects/mdraft/i{1,2,3}/ video.manifest.json (the kit's basic +// cut) and report.json +// i1 the cut task's i2 the onscreen task's i3 the teaser task's +// +// The editor stub runs the media task for real over it, its model the fake +// ollama scripted with the kit's recorded run (common/testing/draft/ +// runMediaStep.ts). Synthetic: the kit's invented channel and lines. +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const KIT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../common/testing/draft"); +const AT = "2026-10-13T10:00:00.000Z"; +export const MEDIA_DRAFT_ARTICLE = "mdraft"; +export const MEDIA_DRAFT_ITERATIONS = { cut: 1, onscreen: 2, teaser: 3 }; + +const put = (file, value) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, typeof value === "string" ? value : JSON.stringify(value, null, 2) + "\n"); +}; + +export function makeMediaDraftFixture({ dest, articles }) { + const report = JSON.parse(readFileSync(path.join(KIT, "reports", "basic.report.json"), "utf8")); + const manifest = readFileSync(path.join(KIT, "manifests", "basic.video.manifest.json"), "utf8"); + for (const n of Object.values(MEDIA_DRAFT_ITERATIONS)) { + const dir = path.join(articles, MEDIA_DRAFT_ARTICLE, "iterations", String(n)); + const project = path.join(dest, "gen-projects", MEDIA_DRAFT_ARTICLE, `i${n}`); + put(path.join(dir, "iteration.json"), { + format: "archilyzer-iteration", + version: 1, + article: MEDIA_DRAFT_ARTICLE, + n, + kind: "sweep", + parent: null, + copyOf: null, + model: "qwen3:8b", + question: "What does the baker say about the bakery?", + scope: { channels: ["synth-kitchen"] }, + status: "done", + usage: {}, + steps: [], + projectDir: project, + createdAt: AT, + updatedAt: AT, + endedAt: AT, + }); + put(path.join(dir, "report.json"), { ...report, id: MEDIA_DRAFT_ARTICLE }); + put(path.join(project, "video.manifest.json"), manifest); + put(path.join(project, "report.json"), { ...report, id: MEDIA_DRAFT_ARTICLE }); + } +} diff --git a/umtool/e2e/media-draft.spec.ts b/umtool/e2e/media-draft.spec.ts @@ -0,0 +1,87 @@ +import { test, expect, type Page } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { WARM_TIMEOUT, warm } from "./warm"; + +// --------------------------------------------------------------------------- +// The media drafts (release 28 M1–M3; lane E adds flips, threads, youtube): +// each task asked through umtool's generate, run by the editor stub FOR REAL +// — the common task over the fixture iteration's project, its model the fake +// ollama scripted with the test kit's recorded run — and followed on the +// iteration to its step's end, shown on the Iterations tab. Then the project's manifest +// says what was drafted, marked with its provenance. +// +// mdraft an article in the making; i1, i2, i3 each a done sweep with the +// kit's basic cut (fixtures/media-draft-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 = "mdraft"; +const manifestOf = (n: number) => JSON.parse(readFileSync(path.join(FIXTURE, "gen-projects", ARTICLE, `i${n}`, "video.manifest.json"), "utf8")); +const draftFileOf = (n: number, task: string) => JSON.parse(readFileSync(path.join(FIXTURE, "gen-projects", ARTICLE, `i${n}`, `${task}-draft.json`), "utf8")); +const lastAsked = () => + (JSON.parse(readFileSync(STUB_LOG, "utf8")) as { route?: string; [k: string]: unknown }[]).filter((r) => r.route === "report-draft").at(-1); +const ids = (m: { timeline: { id: string }[] }) => m.timeline.map((e) => e.id); +const entry = (m: { timeline: { id: string }[] }, id: string) => m.timeline.find((e) => e.id === id) as Record<string, any>; + +test.beforeAll(async ({ playwright }) => { + test.setTimeout(WARM_TIMEOUT); + await warm(playwright, [`/articles/${ARTICLE}`, `/api/articles/iterations?article=${ARTICLE}`, "/api/articles/policy"]); +}); + +// Ask for the task on iteration n, and follow its step to its end on the tab. +async function draft(page: Page, task: string, n: number, status = "done") { + const r = await page.request.post("/api/articles/generate", { data: { task, article: ARTICLE, iteration: n, model: "qwen3:8b" } }); + expect(r.status(), await r.text()).toBe(200); + expect(await r.json()).toMatchObject({ ok: true, iteration: n }); + expect(lastAsked()).toMatchObject({ task, article: ARTICLE, iteration: n, model: "qwen3:8b", authorization: "Bearer umtool-e2e-token" }); + // The job runs in the stub (a child under tsx); its step is the iteration's. + await expect + .poll( + async () => { + const list = (await (await page.request.get(`/api/articles/iterations?article=${ARTICLE}`)).json()) as { + iterations: { n: number; steps: { task: string; status: string }[] }[]; + }; + return list.iterations.find((i) => i.n === n)?.steps.find((s) => s.task === task)?.status ?? "none"; + }, + { timeout: 60_000, intervals: [1000] }, + ) + .toBe(status); + await page.goto(`/articles/${ARTICLE}?tab=iterations`); + await expect(page.locator(`[data-iteration='${n}'] [data-step='${task}']`)).toHaveAttribute("data-step-status", status); +} + +test("cut: the clips and their order drafted from the report's citations, the timeline built from the entries it had", async ({ page }) => { + test.setTimeout(120_000); + const before = manifestOf(1); + expect(before.drafted.timeline).toMatchObject({ task: "convert", model: "code" }); + await draft(page, "cut", 1); + const m = manifestOf(1); + expect(ids(m)).toEqual(["title", "the-contest", "c04", "c06", "the-bakery", "c03", "c01"]); + expect(entry(m, "c04")).toEqual(entry(before, "c04")); + expect(m.drafted.timeline).toMatchObject({ task: "cut", model: "qwen3:8b", iteration: 1, attempt: 2 }); + expect(draftFileOf(1, "cut").units.cut.applied).toBe("applied"); +}); + +test("onscreen: each clip's title and subtitle, several to an ask; a clip with no clean draft left as it was", async ({ page }) => { + test.setTimeout(120_000); + await draft(page, "onscreen", 2); + const m = manifestOf(2); + expect(entry(m, "c01").onscreen).toEqual({ title: "She will not sell to a chain", subtitle: '"I would never sell the bakery to a chain"' }); + expect(entry(m, "c01").drafted.onscreen).toMatchObject({ task: "onscreen", model: "qwen3:8b", iteration: 2, attempt: 1 }); + expect(entry(m, "c04").drafted.onscreen.attempt).toBe(2); + expect(entry(m, "c06").onscreen).toBeUndefined(); + expect(draftFileOf(2, "onscreen").units.c06.attempts).toHaveLength(2); +}); + +test("teaser: a cut with none gets one after its last clip, its lines drafted and checked by the build's validator", async ({ page }) => { + test.setTimeout(120_000); + await draft(page, "teaser", 3); + const m = manifestOf(3); + expect(ids(m).slice(-2)).toEqual(["c06", "teaser"]); + expect(entry(m, "teaser")).toMatchObject({ type: "teaser", lines: ["Synth Kitchen", "The bakery", "The contest", "What the baker says"] }); + expect(entry(m, "teaser").drafted.lines).toMatchObject({ task: "teaser", attempt: 2 }); +}); diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts @@ -216,7 +216,7 @@ export async function cancelDraftJob(id: string): Promise<void> { // The body umtool sends to `report-draft`: the action's own keys, nothing else // (the editor refuses an unknown key; this refuses it first, by name). -const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "force", "autonomy"]; +const DRAFT_KEYS = ["task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "cards", "entries", "force", "autonomy"]; export async function enqueueDraft(body: Record<string, unknown>): Promise<{ jobId: string; iteration: number }> { const out: Record<string, unknown> = {}; diff --git a/umtool/report-to-video/drafts-review.mjs b/umtool/report-to-video/drafts-review.mjs @@ -43,7 +43,7 @@ import { readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; -import { draftedFields, fieldKey, parseReviewAddress, reviewAddress } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; +import { draftedFields, fieldKey, isCodeDraft, parseReviewAddress, reviewAddress } from "yt-dlp-transcript-common/lib/report/drafted.mjs"; import { narrationsOf } from "./narration.mjs"; export const DRAFTS_REVIEW_FILE = "drafts.review.json"; @@ -216,7 +216,9 @@ export function draftsReviewRows(manifest, review) { const row = review?.rows?.[address] ?? null; out.push({ address, entry, field, provenance, key, text: judgedText(field, value), row, state: draftReviewState(key, row) }); }; - const drafted = draftedFields(manifest); + // A field a CODE path made (the converter's timeline, release 28 M1) needs + // no approval: no row, so no badge and no gate. + const drafted = draftedFields(manifest).filter((d) => !isCodeDraft(d.provenance)); const byAddress = new Map(drafted.map((d) => [reviewAddress(d), d])); // Narration rows in timeline order, interleaved with the other entry fields. const narrated = new Map(narrationsOf(manifest).map((n) => [n.id, n])); diff --git a/umtool/report-to-video/drafts-review.test.mjs b/umtool/report-to-video/drafts-review.test.mjs @@ -211,3 +211,17 @@ test("the build: --final refuses an unapproved draft before anything is fetched; const ok = await quietly(() => buildVideo({ manifestPath, opts: { final: true, skipFetch: true } })); assert.doesNotMatch(String(ok.result?.err?.message ?? ""), /is not approved/); }); + +test("a field a code path made (release 28 M1: the converter's timeline) needs no review: no row, no gate", () => { + const m = full(); + m.drafted = { timeline: { task: "convert", model: "code", at: "2026-10-13T00:00:00.000Z", attempt: 1 } }; + const timelineRows = () => draftsReviewRows(m, null).filter((r) => r.field === "timeline"); + assert.deepEqual(timelineRows(), []); + // (The full kit's hand narration keeps release 25's rule; nothing else is said.) + const ok = review({}, { narration: true, rows: { "narrate/the-contest/narration": approve(m, "the-contest", "narration") } }); + assert.deepEqual(draftsReviewProblems(m, ok, { final: true }).errors, []); + // The cut task's own order is a draft like any other. + m.drafted = { timeline: P("cut") }; + assert.deepEqual(timelineRows().map((r) => r.address), ["cut/*/timeline"]); + assert.equal(draftsReviewProblems(m, ok, { final: true }).errors.length, 1); +});