Archilyzer · Source

archilyzer

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

commit 0b1bcdfe8a6c09ce15221e8ba7a3a3803ed74775
parent faf41080eba24893b9dc3ff1e4afbd15d8e4be4e
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 22:32:33 -0400

report-draft: the cut task — selection and order from the report's citations (r28 M1)

tasks/cut.ts: one unit, the timeline's order. The model answers citation ids
grouped under the section headings; code refuses an id not in the cut, one
twice, more than settings.generation.cut.maxClips (new, default 20) or fewer
than 3, a pinned clip dropped (a post rides on it, a flip names it), a
heading not the cut's or heading two groups, and a cut the build's own
validators would refuse; then code BUILDS the timeline from the entries it
had (chapter cards kept for sections with entries, dropped when empty; head,
teaser and tail in place; twins together; nothing invented).

Who owns the order (the M1 ruling): the converter marks its timeline
drafted.timeline {task: convert, model: code}; an unmarked timeline in the
converter's clip order counts as code's too; a code mark needs no review
(drafts-review rows, the final gate and umtool's count leave it out). The
test kit's derived manifests regenerated. SETTINGS.md regenerated.

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

Diffstat:
MSETTINGS.md | 10++++++++++
Mcommon/controller/reportDraft.ts | 14++++++++++++--
Mcommon/lib/generationSettings.test.ts | 6++++++
Mcommon/lib/generationSettings.ts | 17+++++++++++++++++
Mcommon/lib/report/convertManifest.ts | 10++++++++++
Acommon/lib/report/draft/tasks/cut.test.ts | 209+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/cut.ts | 419+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/index.ts | 7++++++-
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/runs/cut.json | 20++++++++++++++++++++
Msettings.json.example | 3+++
Mumtool/components/projects/ReportProject.tsx | 5+++--
Mumtool/report-to-video/drafts-review.mjs | 6++++--
Mumtool/report-to-video/drafts-review.test.mjs | 14++++++++++++++
20 files changed, 774 insertions(+), 10 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). | #### `generation.routes` @@ -1019,6 +1020,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). | + Default: ```json @@ -1059,6 +1066,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 @@ -104,3 +104,9 @@ test("the media drafts (release 28): steps, each with narrate's route in every p // One media task routed on its own is custom. 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)); +}); diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -55,6 +55,9 @@ export type GenerationResearch = { postWalksNeedApproval: boolean; }; +// The cut task's limits (release 28 M1). +export type GenerationCut = { maxClips: number }; + export type GenerationSettings = { preset: GenerationPreset | "custom"; routes: GenerationRoutes; @@ -68,6 +71,7 @@ export type GenerationSettings = { web: GenerationWeb; citationOrigin: string; research: GenerationResearch; + cut: GenerationCut; }; export const DEFAULT_GENERATION_RESEARCH: GenerationResearch = { autonomy: "propose", ...DEFAULT_RESEARCH_LIMITS }; @@ -87,6 +91,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = { web: { provider: "duckduckgo", searchUrl: "" }, citationOrigin: "", research: { ...DEFAULT_GENERATION_RESEARCH }, + cut: { maxClips: 20 }, }; export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { @@ -106,6 +111,12 @@ 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).", +}; + +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> = { @@ -224,6 +235,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/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/index.ts b/common/lib/report/draft/tasks/index.ts @@ -3,6 +3,7 @@ import type { MediaStepTask } from "../../../generationSettings"; import type { MediaTaskInput } from "./media"; +import { cut, type CutInput } from "./cut"; import { narrate, type NarrateInput } from "./narrate"; import { research, type ResearchInput } from "./research"; import { reviseReport, type ReviseReportInput } from "./revise-report"; @@ -19,6 +20,8 @@ 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"; // The media task scaffold (release 28, M0): what every media task is. export { ALTERNATIVES_PER_FIELD, @@ -53,7 +56,8 @@ export type TaskInput = | ({ task: "revise-video" } & ReviseVideoInput) | ({ task: "narrate" } & NarrateInput) | ({ task: "research" } & ResearchInput) - | ({ task: Exclude<MediaStepTask, "narrate"> } & MediaTaskInput); + | ({ task: "cut" } & CutInput) + | ({ task: Exclude<MediaStepTask, "narrate" | "cut"> } & 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). @@ -81,6 +85,7 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { case "research": return research(input, deps); case "cut": + return cut(input, deps); case "onscreen": case "teaser": case "flips": 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, SOCIAL_LINK_FIELD_DOCS, @@ -287,6 +288,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) }, ], }; } 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/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/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/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"; @@ -152,7 +152,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/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); +});