Archilyzer · Source

archilyzer

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

commit 60c2da845da38acd54e33f8556a6de6b988ef98b
parent 6ba140ee558532148ea445e7e61f30f02e1763f6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 22:50:58 -0400

Merge r28/media-e: release 28 media step wiring, M4 flips, M5 threads, M6 YouTube text

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

# Conflicts:
#	COMMANDS.md
#	editor/CHANGELOG.md
#	plans/FACTS.md
#	plans/release-28.md

Diffstat:
MCOMMANDS.md | 2+-
MSETTINGS.md | 18+++++++++++++++---
Mcommon/bin/gen.test.ts | 8+++++---
Mcommon/controller/reportDraft.ts | 93++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------
Mcommon/lib/generationSettings.test.ts | 30++++++++++++++++++++++++++++++
Mcommon/lib/generationSettings.ts | 48++++++++++++++++++++++++++++++++++++------------
Acommon/lib/report/draft/tasks/clipEvidence.ts | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/flips.ts | 363+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/index.ts | 35++++++++++++++++++++++++++++++++++-
Acommon/lib/report/draft/tasks/panelTasks.test.ts | 365+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/threads.ts | 280+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/types.ts | 6+++++-
Acommon/lib/report/draft/tasks/youtube.ts | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/panels.d.mts | 20++++++++++++++++++++
Acommon/lib/report/panels.mjs | 180+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Mcommon/testing/README.md | 2+-
Acommon/testing/draft/runs/flips.json | 21+++++++++++++++++++++
Acommon/testing/draft/runs/threads.json | 21+++++++++++++++++++++
Acommon/testing/draft/runs/youtube.json | 21+++++++++++++++++++++
Meditor/CHANGELOG.md | 2++
Meditor/app/api/ops/_reportDraft.test.ts | 39+++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/report-draft/route.ts | 8++++++--
Mmcp/src/draftTasks.test.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mmcp/src/generation.test.ts | 38++++++++++++++++++++++++++------------
Mmcp/src/generation.ts | 10++++++----
Mplans/FACTS.md | 30++++++++++++++++++++++++++++++
Mplans/release-28.md | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 14+++++++++-----
Msettings.json.example | 8+++++++-
Mumtool/components/projects/ReportProject.tsx | 4++++
Aumtool/components/projects/YoutubeSection.tsx | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 4++++
Aumtool/e2e/fixtures/youtube-fixture.mjs | 32++++++++++++++++++++++++++++++++
Aumtool/e2e/media-draft-e.spec.ts | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/README.md | 33+++++++++++++++++++++++++++++++++
Mumtool/report-to-video/build-video.mjs | 57++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/report-to-video/flips.mjs | 80++++---------------------------------------------------------------------------
Mumtool/report-to-video/package.json | 3++-
Mumtool/report-to-video/threads.mjs | 87+++++--------------------------------------------------------------------------
Aumtool/report-to-video/youtube.mjs | 147+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/youtube.test.mjs | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
42 files changed, 2598 insertions(+), 248 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -145,7 +145,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -&gt; {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'` | | `archive-item` | archive-item answers one archive.org item's files from its metadata: {"item"} -&gt; {item: {identifier, url, title?, date?, mediatype?, creator?, collections, restricted, mediaFiles, mediaBytes, files: \[{name, format?, source?, size?, seconds?, media, restricted, original?}\]}}. media marks the originals an import takes (one record each); restricted, what archive.org will not hand out. Read only; nothing is downloaded. | `pnpm ops archive-item --json '{"item":"example-item"}'` | | `import-post` | import-post imports ONE post by its URL into a posts channel of its platform: {"slug", "url"} — an X status (x.com/&lt;handle&gt;/status/&lt;id&gt;) or a Bluesky post (bsky.app/profile/&lt;handle&gt;/post/&lt;id&gt;, or its at:// URI). Read through the channel's own fetcher (gallery-dl for X, with the channel's login; the public AppView for Bluesky) as an import-post job on the platform's queue. Refused, before any job: a URL that is not a post, a channel that is not a posts channel of that platform or whose fetcher cannot read one post, a post the URL names as another account's, the platform held or cooling down. A post already archived is not read again; one the platform says is another account's is not written. The log ends with @@import-post {ok, slug, url, id, written, already?, post?, error?}. | `pnpm ops import-post --json '{"slug":"demo-x","url":"https://x.com/example/status/1700000000000000001"}' --wait` | -| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "narrate" \| "research", "article", ...} -&gt; {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration; a narration takes "iteration" (a done one; "cards"?, "force"?) and is a step on it. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'` | +| `report-draft` | report-draft runs a generation over an article's iteration as a report-draft job: {"task": "sweep" \| "revise-report" \| "revise-video" \| "research" \| a media draft, "article", ...} -&gt; {jobId, iteration, warnings?}. A sweep takes "question" and "channels" (and "from"/"to"): a new iteration; a revision takes "iteration" (the one it revises) and "feedback": a new iteration. A media draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube" — takes "iteration" (a done one; "entries"? entry ids, "force"? re-drafts a field that is a draft already; narrate "cards"?) and is a step on it: it drafts fields of the iteration's video manifest, never one the operator wrote. "copyOf" N runs iteration N again on "model". "extractorModel" is an API sweep's extractor (a Claude model id; default settings.generation.models.extractor). "model" defaults to settings.generation's route for the task (one routed to code needs a model named). A Claude model runs on draft:api, capped at "maxUsd" (default by task, never above caps.max), and is refused when the day's API total has reached caps.daily; a local model runs on draft:local, through the GPU arbiter, and is unloaded when it ends. The corpus is "source" (a handle), "build" (a composed build), or the newest build holding the channels. `job cancel <id>` stops it. The log ends with @@report-draft {article, iteration, task, status, summary, usd, minutes}; --wait prints it. A research run takes "question" ("channels"? "from"/"to"?) and "autonomy" (propose \| limits \| auto; default settings.generation.research): it searches the corpus, the web and archive.org and proposes acquisitions (archive.org imports, videos, new channels — always on no site —, posts, transcription, persisting), each with its reason and evidence, enqueuing what its autonomy and the settings' caps allow through the editor's own actions; the rest waits in the iteration's proposals.json. A sweep with "iteration" N CONTINUES research run N: its question, over its channels and every channel a done acquisition wrote into, the sweep's parent N; refused while N still waits, unless "force" (what is done so far). | `pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","question":"What does she say about the shop?","channels":["demo-channel"]}' --wait`<br>`pnpm ops report-draft --json '{"task":"revise-report","article":"demo-article","iteration":1,"feedback":"Drop the second finding."}'`<br>`pnpm ops report-draft --json '{"task":"research","article":"demo-article","question":"Where did the shop story start?","autonomy":"propose"}' --wait`<br>`pnpm ops report-draft --json '{"task":"sweep","article":"demo-article","iteration":1}'` | | `research-approve` | research-approve settles a research run's acquisitions: {"article", "iteration", "ids"?: \["p01", …\], "approve"?: true \| false, "note"?} -&gt; {outcomes: \[{id, status?, jobId?, note?, error?}\], research: {phase, autonomy, limits, spent, proposals, waitingOn: {approval, jobs}, continuedBy, autoContinue?}}. It first refreshes every enqueued acquisition from its jobs (all done: done; one failed: failed, naming it). approve: true runs each proposal through the editor's own action (past the run's autonomy and caps, never past a standing rule); false rejects it, note saying why. No ids: the run's state now. The phase is wait (approvals or jobs pending), ready (nothing pending: continue with report-draft {"task": "sweep", "iteration": N}) or continued. An `auto` run is continued by the editor itself once ready; autoContinue says how (continued by, held for a build, refused by a cap, and why). Refused while the run's job is going. | `pnpm ops research-approve --json '{"article":"demo-article","iteration":1,"ids":["p01","p03"],"approve":true}'` | | `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["&lt;article&gt;"\], "window"? (seconds, default 60), "maxUsd"? (default 5), "limit"?} -&gt; {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the claim, its quotes, the transcript within the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues (answered pairs are skipped). Results stay local, in .generation/bench/verdicts/&lt;run&gt;/ (umtool's /bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` | diff --git a/SETTINGS.md b/SETTINGS.md @@ -954,7 +954,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | Key | Default | Description | |---|---|---| -| `preset` | `"balanced"` | The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions and narration on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes. | +| `preset` | `"balanced"` | The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes. | | `routes` | object — see below | Where each task runs: `code`, `api` or `local` (below). | | `models` | object — see below | The model each route runs (below). | | `caps` | object — see below | The spend caps in USD (below). | @@ -977,6 +977,12 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `revise-video` | `"local"` | A video-cut iteration from feedback, through checked ops. | | `narrate` | `"local"` | Card narration for an iteration's cut, under the narration rules and the grounding checks. | | `research` | `"api"` | A research run: find what the corpus lacks (the web, archive.org) and propose acquisitions — archive.org imports, new channels, posts, transcription — through the editor, then continue into a sweep. `code` = Claude Code over the MCP. | +| `cut` | `"local"` | A media draft (a step on a done iteration, as narration): the cut's clips and their order, chosen from the report's citations. | +| `onscreen` | `"local"` | A media draft: each clip's on-screen title and subtitle. | +| `teaser` | `"local"` | A media draft: the teaser's lines. | +| `flips` | `"local"` | A media draft: THEN/NOW pairs over the cut's clips. | +| `threads` | `"local"` | A media draft: the cut's threads and each clip's thread. | +| `youtube` | `"local"` | A media draft: the YouTube title and description. | #### `generation.models` @@ -992,7 +998,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude |---|---|---| | `sweep` | `5` | A sweep or research job's cap when it names none. The agent wraps up at 85% and stops at the cap. | | `revision` | `2` | A report or video revision job's cap when it names none. | -| `narration` | `1` | A narration job's cap when it names none. | +| `narration` | `1` | A narration (or other media draft) job's cap when it names none. | | `daily` | `20` | The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap. | | `max` | `10` | The most a job may ask for: a larger `maxUsd` is refused. | @@ -1039,7 +1045,13 @@ Default: "revise-report": "api", "revise-video": "local", "narrate": "local", - "research": "api" + "research": "api", + "cut": "local", + "onscreen": "local", + "teaser": "local", + "flips": "local", + "threads": "local", + "youtube": "local" }, "models": { "api": "claude-sonnet-5-5", diff --git a/common/bin/gen.test.ts b/common/bin/gen.test.ts @@ -3,6 +3,7 @@ import assert from "node:assert/strict"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { GENERATION_PRESETS } from "../lib/generationSettings"; // `archilyzer gen` (release 27 S9). settings.json and the ledger are pinned to // a temp dir BEFORE anything reads getPaths() (it caches), so the offline @@ -73,11 +74,12 @@ test("gen preset writes the preset's routes; gen set writes one; nonsense is a u const m = memoryStore(); const deps = { store: async () => m.store, runOps: async () => 0, out: c.out }; assert.equal(await gen.setMain({ preset: "local" }, deps), 0); - assert.deepEqual(m.written[0], { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" }); + // Every task, the media drafts (release 28) included. + assert.deepEqual(m.written[0], { ...GENERATION_PRESETS.local }); assert.equal(await gen.setMain({ task: "sweep", route: "api" }, deps), 0); - assert.deepEqual(m.written[1], { sweep: "api", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" }); + assert.deepEqual(m.written[1], { ...GENERATION_PRESETS.local, sweep: "api" }); assert.ok(c.lines.includes("(written to the editor at http://editor.test)")); - for (const o of [{ preset: "cheap" }, { task: "sweep", route: "cloud" }, { task: "sweep" }, { task: "teaser", route: "api" }]) { + for (const o of [{ preset: "cheap" }, { task: "sweep", route: "cloud" }, { task: "sweep" }, { task: "nope", route: "api" }]) { assert.equal(await gen.setMain(o, deps), 2, JSON.stringify(o)); } assert.equal(m.written.length, 2); diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -2,7 +2,9 @@ // (release 27, S6; D6). `pnpm ops report-draft` → POST /api/ops/report-draft → // here. // -// task sweep | revise-report | revise-video | narrate | research +// task sweep | revise-report | revise-video | research, or a media +// draft: narrate | cut | onscreen | teaser | flips | threads | +// youtube (a STEP on a done iteration, MEDIA_STEP_TASKS) // article the article id (an article in the making is fine for a sweep) // iteration a revision's parent; the iteration a narration voices; for a // sweep, the research run it CONTINUES (S11: its question, and its @@ -18,6 +20,9 @@ // source / build the corpus (default: the newest build holding the channels) // cards / force a narration's (force: a continuation over a research // run that still waits, with what is done so far) +// entries a media draft's (cut, onscreen, teaser, flips, threads, +// youtube; narrate too): only these entry ids; `force` re-drafts +// a field that is a draft already (release 28) // autonomy a research run's: propose | limits | auto (default: // settings.generation.research.autonomy; the limits are the // settings') @@ -40,7 +45,7 @@ import type { JobProgress } from "../jobs/registry"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import type { Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; -import { capFor, type GenerationSettings, type GenerationTask } from "../lib/generationSettings"; +import { GENERATION_TASKS, capFor, isStepTask, type GenerationSettings, type GenerationTask } from "../lib/generationSettings"; import { PROJECT_URL } from "../lib/project"; import { PRICES, providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; import { webTools } from "../lib/web/tools"; @@ -87,6 +92,7 @@ export const REPORT_DRAFT_BODY_KEYS = [ "source", "build", "cards", + "entries", "force", "autonomy", ] as const; @@ -109,6 +115,7 @@ export type ReportDraftBody = { source?: string; build?: string; cards?: string[]; + entries?: string[]; force?: boolean; autonomy?: Autonomy; }; @@ -119,7 +126,7 @@ export function isKnownApiModel(model: string): boolean { return model.startsWith("claude-") && Object.keys(PRICES).some((p) => model === p || model.startsWith(`${p}-`)); } -const TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate", "research"]; +const TASKS: readonly GenerationTask[] = GENERATION_TASKS; const ymd = /^\d{4}-\d{2}-\d{2}$/; function fail(msg: string): never { @@ -170,6 +177,7 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod set("question", text("question")); set("channels", list("channels")); set("cards", list("cards")); + set("entries", list("entries")); set("source", text("source")); set("build", text("build")); for (const k of ["from", "to"] as const) { @@ -207,26 +215,24 @@ export function parseReportDraftBody(b: Record<string, unknown>): ReportDraftBod if (out.iteration === undefined) fail(`a ${out.task} names the iteration it revises ("iteration")`); if (!out.feedback) fail(`a ${out.task} needs feedback: say what to change`); } + // A media draft (narrate, cut, …) is a step on the iteration it names. if (out.task === "narrate" && out.iteration === undefined) fail('a narration names the iteration it voices ("iteration")'); if (out.task === "narrate" && out.copyOf !== undefined) fail("a narration is a step, not an iteration: it has no copy"); + if (isStepTask(out.task) && out.iteration === undefined) fail(`a ${out.task} draft names the iteration it drafts on ("iteration")`); + if (isStepTask(out.task) && out.copyOf !== undefined) fail(`a ${out.task} draft is a step, not an iteration: it has no copy`); + if (out.entries && !isStepTask(out.task)) fail('"entries" is a media draft\'s (narrate, cut, onscreen, teaser, flips, threads, youtube)'); return out; } -const KIND_OF: Record<GenerationTask, Iteration["kind"]> = { - sweep: "sweep", - "revise-report": "revise-report", - "revise-video": "revise-video", - narrate: "sweep", // (a step: no iteration of its own) - research: "research", -}; +// A step task (narrate, cut, …) has no iteration of its own, so no kind; its +// cap is a narration's. +function kindOf(task: GenerationTask): Iteration["kind"] { + if (isStepTask(task)) throw new ReportDraftInputError(`a ${task} draft is a step: it makes no iteration`); + return task === "revise-report" || task === "revise-video" || task === "research" ? task : "sweep"; +} -const CAP_OF: Record<GenerationTask, "sweep" | "revision" | "narration"> = { - sweep: "sweep", - "revise-report": "revision", - "revise-video": "revision", - narrate: "narration", - research: "sweep", -}; +const capOf = (task: GenerationTask): "sweep" | "revision" | "narration" => + isStepTask(task) ? "narration" : task === "revise-report" || task === "revise-video" ? "revision" : "sweep"; export function expandHome(p: string): string { return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p; @@ -324,7 +330,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep const src = body.copyOf !== undefined ? await readIteration(body.article, body.copyOf, paths) : null; if (body.copyOf !== undefined) { if (!src) return refuse(`"${body.article}" has no iteration i${body.copyOf} to copy`); - if (src.kind !== KIND_OF[body.task]) return refuse(`i${body.copyOf} is a ${src.kind} iteration, not a ${body.task}`); + if (src.kind !== kindOf(body.task)) return refuse(`i${body.copyOf} is a ${src.kind} iteration, not a ${body.task}`); } if (body.task === "research" && !deps.researchEditor) { return refuse("a research run runs in the editor (its reads and acquisitions are the editor's actions)"); @@ -359,16 +365,17 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep } let maxUsd: number | undefined; if (provider === "api") { - maxUsd = capFor(gen.caps, CAP_OF[body.task], body.maxUsd); + maxUsd = capFor(gen.caps, capOf(body.task), body.maxUsd); const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) return refuse(refusal); } - // The iteration: a new one (or a copy), queued; a narration's is the one named. + // The iteration: a new one (or a copy), queued; a step's is the one named. let n: number; - if (body.task === "narrate") { + if (isStepTask(body.task)) { const it = await readIteration(body.article, body.iteration!, paths); if (!it) return refuse(`"${body.article}" has no iteration i${body.iteration}`); - if (it.status !== "done") return refuse(`"${body.article}" i${it.n} is ${it.status}: a narration runs over a done iteration`); + const what = body.task === "narrate" ? "a narration" : `a ${body.task} draft`; + if (it.status !== "done") return refuse(`"${body.article}" i${it.n} is ${it.status}: ${what} runs over a done iteration`); n = it.n; } else if (src) { n = (await copyIteration(body.article, src.n, { model }, paths)).n; @@ -391,7 +398,7 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep await createIteration( body.article, { - kind: KIND_OF[body.task], + kind: kindOf(body.task), model, ...(body.task === "sweep" || body.task === "research" ? { question: body.question, scope: { ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}) } } @@ -408,14 +415,14 @@ export async function enqueueReportDraft(raw: Record<string, unknown>, deps: Rep fn: (onLog, signal, setProgress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal, setProgress }, deps), }); if (!result.ok) { - if (body.task !== "narrate") await updateIteration(body.article, n, { status: "failed", error: result.error }, paths).catch(() => {}); + if (!isStepTask(body.task)) await updateIteration(body.article, n, { status: "failed", error: result.error }, paths).catch(() => {}); return { result }; } - if (body.task !== "narrate") await updateIteration(body.article, n, { jobId: result.jobId }, paths).catch(() => {}); + if (!isStepTask(body.task)) await updateIteration(body.article, n, { jobId: result.jobId }, paths).catch(() => {}); if (cont) await markContinued(body.article, cont.research.n, n, paths).catch(() => {}); // A job cancelled (or refused) before it ran leaves its iteration queued: end it. void result.done.then(async (d) => { - if (body.task === "narrate") return; + if (isStepTask(body.task)) return; const it = await readIteration(body.article, n, paths).catch(() => null); if (it?.status === "queued") { await updateIteration(body.article, n, { status: d.status === "cancelled" ? "cancelled" : "failed", error: `the job ended ${d.status} before it ran` }, paths).catch(() => {}); @@ -449,12 +456,12 @@ async function runReportDraft( // Again at the job's turn: jobs ahead in the queue may have spent the day. const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) { - if (body.task !== "narrate") await updateIteration(body.article, n, { status: "failed", error: refusal }, paths).catch(() => {}); + if (!isStepTask(body.task)) await updateIteration(body.article, n, { status: "failed", error: refusal }, paths).catch(() => {}); throw new Error(refusal); } } const it = (await readIteration(body.article, n, paths))!; - const channels = body.task === "sweep" || body.task === "research" ? (it.scope?.channels ?? []) : await channelsOfReport(body.article, body.task === "narrate" ? n : (it.parent ?? n), paths); + const channels = body.task === "sweep" || body.task === "research" ? (it.scope?.channels ?? []) : await channelsOfReport(body.article, isStepTask(body.task) ? n : (it.parent ?? n), paths); let corpus: (CorpusToolsLike & { close(): Promise<void> }) | null = null; let result: TaskResult | null = null; try { @@ -526,12 +533,30 @@ async function runReportDraft( break; } case "narrate": - input = { task: "narrate", article: body.article, n, model, projectsRoot, ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}), jobId: o.jobId, ...(body.cards ? { cards: body.cards } : {}), ...(body.force ? { force: true } : {}) }; + case "cut": + case "onscreen": + case "teaser": + case "flips": + case "threads": + case "youtube": { + // A media draft: a step on the done iteration n (./tasks/media.ts). + const step = { + article: body.article, + n, + model, + projectsRoot, + ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}), + jobId: o.jobId, + ...(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 }; break; + } } result = await runTask(input, taskDeps); } catch (e) { - if (body.task !== "narrate") { + if (!isStepTask(body.task)) { const cur = await readIteration(body.article, n, paths).catch(() => null); if (cur && (cur.status === "queued" || cur.status === "running")) { await updateIteration(body.article, n, { status: signal.aborted ? "cancelled" : "failed", error: (e as Error).message }, paths).catch(() => {}); @@ -556,16 +581,16 @@ async function runReportDraft( if (result.status === "failed") throw new Error(result.summary); } -// The job's spend, per model, from the iteration's usage (a narration: the -// step's cost, on its model). +// The job's spend, per model, from the iteration's usage (a step — a +// narration, any media draft: the step's cost, on its model). async function recordUsage(body: ReportDraftBody, n: number, model: string, jobId: string, paths: Paths, now: Date) { const it = await readIteration(body.article, n, paths); if (!it) return; const day = utcDay(now); const base = { at: now.toISOString(), day, jobId, article: body.article, iteration: n, task: body.task }; let rows: GenerationUsageRow[]; - if (body.task === "narrate") { - const step = [...it.steps].reverse().find((s) => s.task === "narrate" && s.jobId === jobId); + if (isStepTask(body.task)) { + const step = [...it.steps].reverse().find((s) => s.task === body.task && s.jobId === jobId); rows = step?.cost ? [{ ...base, model, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: step.cost }] : []; } else { rows = Object.entries(it.usage) diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -3,7 +3,10 @@ import assert from "node:assert/strict"; import { DEFAULT_GENERATION_SETTINGS, GENERATION_PRESETS, + GENERATION_TASKS, + MEDIA_STEP_TASKS, capFor, + isStepTask, looksLikeApiKey, presetOf, sanitizeGeneration, @@ -75,6 +78,33 @@ test("research (S11): a route of its own, a file from before it keeps its preset assert.equal(sanitizeGeneration({ research: { autonomy: "yolo" } }).research.autonomy, "propose"); }); +test("the media drafts (release 28): steps, each with narrate's route in every preset; a file from before keeps its preset", () => { + assert.deepEqual([...MEDIA_STEP_TASKS], ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube"]); + for (const t of MEDIA_STEP_TASKS) { + assert.ok(isStepTask(t)); + assert.ok((GENERATION_TASKS as readonly string[]).includes(t)); + for (const p of Object.values(GENERATION_PRESETS)) assert.equal(p[t], p.narrate, `${t} routes as narrate`); + } + for (const t of ["sweep", "revise-report", "revise-video", "research", "nope", undefined]) assert.equal(isStepTask(t), false); + assert.equal(sanitizeGeneration(undefined).routes.cut, "local", "balanced drafts media on the local model"); + // routes written before the media tasks had any (release 27's five). + const five = (p: keyof typeof GENERATION_PRESETS) => + Object.fromEntries(["sweep", "revise-report", "revise-video", "narrate", "research"].map((t) => [t, GENERATION_PRESETS[p][t as "sweep"]])); + for (const p of ["code", "balanced", "api", "local"] as const) { + const old = sanitizeGeneration({ routes: five(p) }); + assert.equal(old.preset, p); + assert.deepEqual(old.routes, GENERATION_PRESETS[p]); + } + // A custom five keep their own routes; the media tasks take the default's. + const custom = sanitizeGeneration({ routes: { ...five("api"), narrate: "local" } }); + assert.equal(custom.preset, "custom"); + assert.equal(custom.routes.youtube, "local"); + // A partial patch names no preset. + assert.equal(sanitizeGeneration({ routes: { narrate: "api" } }).routes.cut, "local"); + // One media task routed on its own is custom. + assert.equal(sanitizeGeneration({ routes: { ...GENERATION_PRESETS.api, teaser: "local" } }).preset, "custom"); +}); + 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 @@ -10,17 +10,30 @@ import type { FieldDocs } from "./fieldDocs"; import { AUTONOMIES, DEFAULT_RESEARCH_LIMITS, type Autonomy } from "./report/draft/research/decide"; -export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research"] as const; +// The media tasks (release 28): each drafts fields of a done iteration's video +// manifest, and runs as a STEP on that iteration (recorded in its `steps`, +// never an iteration of its own), as narrate did first. THE one list: the +// controller, the job, the MCP and umtool ask `isStepTask`. +export const MEDIA_STEP_TASKS = ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube"] as const; +export type MediaStepTask = (typeof MEDIA_STEP_TASKS)[number]; +export const isStepTask = (t: unknown): t is MediaStepTask => typeof t === "string" && (MEDIA_STEP_TASKS as readonly string[]).includes(t); + +export const GENERATION_TASKS = ["sweep", "revise-report", "revise-video", "narrate", "research", "cut", "onscreen", "teaser", "flips", "threads", "youtube"] as const; export type GenerationTask = (typeof GENERATION_TASKS)[number]; +// The tasks every settings file since release 27 S6 routes. +const FIRST_TASKS: readonly GenerationTask[] = ["sweep", "revise-report", "revise-video", "narrate"]; export const GENERATION_ROUTES = ["code", "api", "local"] as const; export type GenerationRoute = (typeof GENERATION_ROUTES)[number]; +// The media tasks other than narrate take narrate's route in every preset. +const mediaRoutes = <R extends GenerationRoute>(r: R) => ({ cut: r, onscreen: r, teaser: r, flips: r, threads: r, youtube: r }) as const; + export const GENERATION_PRESETS = { - code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code" }, - balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api" }, - api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" }, - local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local" }, + code: { sweep: "code", "revise-report": "code", "revise-video": "code", narrate: "code", research: "code", ...mediaRoutes("code") }, + balanced: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api", ...mediaRoutes("local") }, + api: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", ...mediaRoutes("api") }, + local: { sweep: "local", "revise-report": "local", "revise-video": "local", narrate: "local", research: "local", ...mediaRoutes("local") }, } as const satisfies Record<string, Record<GenerationTask, GenerationRoute>>; export type GenerationPreset = keyof typeof GENERATION_PRESETS; export const GENERATION_PRESET_NAMES = Object.keys(GENERATION_PRESETS) as GenerationPreset[]; @@ -89,7 +102,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = { export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { preset: - "The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions and narration on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.", + "The balance knob: `code` (Claude Code does every task), `balanced` (sweeps in Claude Code, report revisions and research runs on the API, video revisions, narration and the other media drafts on the local model), `api`, `local`. Named by `routes`: the preset whose routes they are, else `custom` — choosing a preset is writing its routes.", routes: "Where each task runs: `code`, `api` or `local` (below).", models: "The model each route runs (below).", caps: "The spend caps in USD (below).", @@ -126,6 +139,12 @@ export const GENERATION_ROUTES_FIELD_DOCS: FieldDocs<GenerationRoutes> = { narrate: "Card narration for an iteration's cut, under the narration rules and the grounding checks.", research: "A research run: find what the corpus lacks (the web, archive.org) and propose acquisitions — archive.org imports, new channels, posts, transcription — through the editor, then continue into a sweep. `code` = Claude Code over the MCP.", + cut: "A media draft (a step on a done iteration, as narration): the cut's clips and their order, chosen from the report's citations.", + onscreen: "A media draft: each clip's on-screen title and subtitle.", + teaser: "A media draft: the teaser's lines.", + flips: "A media draft: THEN/NOW pairs over the cut's clips.", + threads: "A media draft: the cut's threads and each clip's thread.", + youtube: "A media draft: the YouTube title and description.", }; export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = { @@ -137,7 +156,7 @@ export const GENERATION_MODELS_FIELD_DOCS: FieldDocs<GenerationModels> = { export const GENERATION_CAPS_FIELD_DOCS: FieldDocs<GenerationCaps> = { sweep: "A sweep or research job's cap when it names none. The agent wraps up at 85% and stops at the cap.", revision: "A report or video revision job's cap when it names none.", - narration: "A narration job's cap when it names none.", + narration: "A narration (or other media draft) job's cap when it names none.", daily: "The API spend a day (UTC) may reach: a job that would start past it is refused, naming the day's total. 0 = no daily cap.", max: "The most a job may ask for: a larger `maxUsd` is refused.", }; @@ -185,11 +204,16 @@ export function sanitizeGeneration(value: unknown): GenerationSettings { const v = rr[t]; routes[t] = typeof v === "string" && (GENERATION_ROUTES as readonly string[]).includes(v) ? (v as GenerationRoute) : d.routes[t]; } - // A file from before research had a route (S11) keeps its preset: research - // takes the route of the preset the other tasks' routes are. - if (!(typeof rr.research === "string" && (GENERATION_ROUTES as readonly string[]).includes(rr.research))) { - const was = GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => t === "research" || routes[t] === GENERATION_PRESETS[p][t])); - if (was) routes.research = GENERATION_PRESETS[was].research; + // A file from before a task had a route (research, S11; the media tasks, + // release 28) keeps its preset: a task it does not name takes the route of + // the preset the tasks it names are routed by. + // (Only a file that routes release 27's first four names a preset this way; + // a partial patch is not one.) + const named = (t: GenerationTask) => typeof rr[t] === "string" && (GENERATION_ROUTES as readonly string[]).includes(rr[t] as string); + const unnamed = GENERATION_TASKS.filter((t) => !named(t)); + if (unnamed.length && FIRST_TASKS.every(named)) { + const was = GENERATION_PRESET_NAMES.find((p) => GENERATION_TASKS.every((t) => !named(t) || routes[t] === GENERATION_PRESETS[p][t])); + if (was) for (const t of unnamed) routes[t] = GENERATION_PRESETS[was][t]; } // The ROUTES are the truth; the preset names them (the preset whose routes // they are, else `custom`). Choosing a preset is writing its routes. diff --git a/common/lib/report/draft/tasks/clipEvidence.ts b/common/lib/report/draft/tasks/clipEvidence.ts @@ -0,0 +1,171 @@ +// What the flips, threads and youtube drafts read (release 28, M4–M6): the +// cut's clips as facts code can check against — each clip's quote, the claim +// it stands for (and that claim's verdict), the chapter it sits under, and +// the date its recording was made — and the one check of a short line of +// text (a topic, a label, a title) against the report. +// +// THE DATE is code's, never the model's: the entry's own `date` (the +// operator's, what the clip's header shows), else the recording's upload date +// from the corpus record (`get_video_metadata`, the reader the other tasks +// use), else the citation's `date`. A clip with none is in no pair. + +import { strictNormalize } from "../../../citations/verify"; +import { extractJsonObject } from "../../../parseStdoutJson"; +import { checkNarration, type GroundingInput, type GroundingResult } from "../grounding"; +import type { ManifestEntry, VideoManifest } from "../videoOps"; +import type { MediaReport } from "./media"; +import type { CorpusToolsLike } from "./types"; + +export type ClipClaim = { id?: string; text: string; verdict?: string }; + +/** One clip of the cut, as the media drafts read it. */ +export type ClipFact = { + id: string; + // The clip's first place in the timeline. + index: number; + quote: string; + claim: ClipClaim | null; + // The chapter card it sits under (its heading), if any. + section: string | null; + // YYYY-MM-DD, or null when nothing says. + date: string | null; + dateFrom: "entry" | "record" | "citation" | null; +}; + +const stripCites = (s: string) => s.replace(/\[([^\]]*)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); + +/** `20260105`, `2026-01-05` or an ISO stamp → `2026-01-05`; else null. */ +export function isoDay(v: unknown): string | null { + if (typeof v !== "string") return null; + const t = v.trim(); + let m = /^(\d{4})(\d{2})(\d{2})$/.exec(t); + if (m) return `${m[1]}-${m[2]}-${m[3]}`; + m = /^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(t); + return m ? `${m[1]}-${m[2]}-${m[3]}` : null; +} + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +/** A side's `when`, written by code from its date: `Jan 2026`. */ +export const whenOf = (day: string) => `${MONTHS[Number(day.slice(5, 7)) - 1] ?? ""} ${day.slice(0, 4)}`.trim(); + +// Every claim of the report by id, and by the citations it cites. +function claimIndex(report: MediaReport) { + const byId = new Map<string, ClipClaim>(); + const byCite = new Map<string, ClipClaim>(); + for (const s of (report.sections ?? []) as { claims?: { id?: string; text?: string; citations?: string[]; verdict?: string }[] }[]) { + for (const c of s.claims ?? []) { + const claim: ClipClaim = { ...(c.id ? { id: c.id } : {}), text: stripCites(c.text ?? ""), ...(c.verdict ? { verdict: c.verdict } : {}) }; + if (c.id) byId.set(c.id, claim); + for (const cid of c.citations ?? []) if (!byCite.has(cid)) byCite.set(cid, claim); + } + } + return { byId, byCite }; +} + +/** + * The cut's clips (every clip of the timeline once, in timeline order), with + * their claims, chapters and dates. `corpus` is asked for the dates the + * entries do not carry; a failed read leaves the date to the citation's. + */ +export async function clipFacts( + manifest: VideoManifest, + report: MediaReport, + corpus: Pick<CorpusToolsLike, "call"> | null, + { dates = true }: { dates?: boolean } = {}, +): Promise<ClipFact[]> { + const { byId, byCite } = claimIndex(report); + const cites = (report.citations ?? {}) as Record<string, { date?: string } | undefined>; + const prov = (manifest.provenance ?? {}) as { channelSlug?: string }; + const recordDates = new Map<string, Promise<string | null>>(); + const recordDate = (channel: string, video: string) => { + const key = `${channel}/${video}`; + let p = recordDates.get(key); + if (!p) { + p = (corpus ? corpus.call("get_video_metadata", { channel, video_id: video }) : Promise.resolve("")) + .then((t) => isoDay((extractJsonObject(t) as { uploadDate?: unknown } | null)?.uploadDate)) + .catch(() => null); + recordDates.set(key, p); + } + return p; + }; + const out: ClipFact[] = []; + const seen = new Set<string>(); + let section: string | null = null; + for (const [index, e] of manifest.timeline.entries()) { + if (e.type === "card" && e.style === "chapter") section = e.heading ?? null; + if (e.type !== "clip" || seen.has(e.id)) continue; + seen.add(e.id); + const claimRef = (e.claim ?? null) as { id?: string; verdict?: string } | null; + const base = (claimRef?.id ? byId.get(claimRef.id) : undefined) ?? byCite.get(e.id) ?? null; + const claim = base || claimRef?.verdict ? { ...(base ?? { text: "" }), ...(claimRef?.verdict ? { verdict: claimRef.verdict } : {}) } : null; + const channel = String(e.siteChannel ?? e.channel ?? prov.channelSlug ?? ""); + const video = String(e.siteVideo ?? e.video ?? ""); + let date = dates ? isoDay(e.date) : null; + let dateFrom: ClipFact["dateFrom"] = date ? "entry" : null; + if (dates && !date && channel && video) { + date = await recordDate(channel, video); + if (date) dateFrom = "record"; + } + if (dates && !date) { + date = isoDay(cites[e.id]?.date); + if (date) dateFrom = "citation"; + } + out.push({ id: e.id, index, quote: String(e.quote ?? "").trim(), claim, section, date, dateFrom }); + } + return out; +} + +/** A clip's evidence line for a prompt (its quote and claim cut to `max` characters each). */ +export function clipLine(c: ClipFact, { max = 160, date = true }: { max?: number; date?: boolean } = {}): string { + const cut = (s: string) => (s.length > max ? `${s.slice(0, max - 1)}…` : s); + return ( + `- ${c.id}` + + (date ? ` [${c.date ?? "date unknown"}]` : "") + + (c.section ? ` (chapter: ${c.section})` : "") + + (c.quote ? `: "${cut(c.quote)}"` : "") + + (c.claim?.text ? ` — claim: ${cut(c.claim.text)}` : "") + ); +} + +/** Lines that fit a character budget, in order; the rest counted. */ +export function fitLines(lines: string[], budget: number): { text: string; omitted: number } { + const kept: string[] = []; + let used = 0; + for (const l of lines) { + if (used + l.length + 1 > budget) break; + kept.push(l); + used += l.length + 1; + } + return { text: kept.join("\n"), omitted: lines.length - kept.length }; +} + +const QUOTED = /“([^”]+)”|"([^"]+)"/g; + +/** + * A short line's problems (a topic, a label, a title or a summary), by the + * narration's grounding (./grounding.ts): every name and number in the + * report, no stock phrase, no first person, no tag. With `quotes`, words in + * quotation marks are allowed only when a cited quote says them verbatim + * (they are then left out of the other checks); without, any quotation marks + * or a run of a quote's words is refused, as in narration. + */ +export function checkLine(text: string, g: GroundingInput, { quotes = false }: { quotes?: boolean } = {}): GroundingResult { + if (!quotes) return checkNarration(text, g); + const hard: string[] = []; + const said = g.quotes.map((q) => ` ${strictNormalize(q)} `); + const stripped = text.replace(QUOTED, (_m, a: string | undefined, b: string | undefined) => { + const words = strictNormalize(a ?? b ?? ""); + if (!words || !said.some((q) => q.includes(` ${words} `))) hard.push(`“${(a ?? b ?? "").slice(0, 80)}” is not what a cited clip says, word for word`); + return " "; + }); + const r = checkNarration(stripped, { ...g, quotes: [] }); + return { hard: [...new Set([...hard, ...r.hard])].sort(), soft: r.soft }; +} + +/** The clips in a manifest by id (the first entry with each id). */ +export function clipsById(manifest: VideoManifest): Map<string, ManifestEntry> { + const m = new Map<string, ManifestEntry>(); + for (const e of manifest.timeline) if (e.type === "clip" && !m.has(e.id)) m.set(e.id, e); + return m; +} diff --git a/common/lib/report/draft/tasks/flips.ts b/common/lib/report/draft/tasks/flips.ts @@ -0,0 +1,363 @@ +// TASK flips — THEN/NOW pairs over the cut's clips (release 28, M4): the +// `render.chrome.flips` panel (umtool/report-to-video/flips.mjs). A STEP on a +// done iteration, on the media task scaffold (./media.ts): one unit, the +// whole field. +// +// The model proposes pairs — a topic and two clip ids, and optionally a part +// of each clip's quote. CODE does the rest and checks it all: +// - the ids name clips of the cut, no clip is in two pairs, 1 to +// FLIPS_LIMITS.pairs[1] pairs (and no more than the dated clips allow); +// - the dates are the recordings' (./clipEvidence.ts), never the model's: +// the earlier clip is THEN, the later NOW, and two clips of one day are +// no pair; each side's `when` is written from its date ("Jan 2026"); +// - a side's `words` are its clip's quote, verbatim — the model's part of +// it only when the quote says exactly that — cut to the limit by code; +// - the topic is one line of at most FLIPS_LIMITS.topic characters, its +// names and numbers the report's (grounding); +// - THEN plays before NOW: a pair the other way round is refused, unless +// the cut's order is a draft itself (`drafted.timeline`) and the flips +// will be applied — then code swaps the two clips' places in the +// timeline, written through applyDraft with this task's provenance; +// - the result passes the build's own validateFlips and validateFlipEntries +// (common's panels.mjs). +// A pair failing a check is dropped when the others stand (the repair); the +// better of two attempts is kept. +// +// ONE LEFT PANEL: flips and threads share it. A cut with threads is refused — +// unless `force` and the threads are a draft: then the flips replace them +// (the list, each clip's `thread` and their mark go) and the log says so. +// A cut with no on-screen deck (`render.chrome`) has no panel: refused. + +import { applyDraft, clearDrafted, entriesWithId, ownerOf } from "../../drafted.mjs"; +import { FLIPS_LIMITS, threadsOn, validateFlipEntries, validateFlips } from "../../panels.mjs"; +import type { GroundingInput } from "../grounding"; +import type { ManifestEntry, VideoManifest } from "../videoOps"; +import { checkLine, clipFacts, clipLine, fitLines, whenOf, type ClipFact } from "./clipEvidence"; +import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import { TaskInputError } from "./run"; +import type { TaskDeps, TaskResult } from "./types"; + +export type FlipsInput = MediaTaskInput; + +/** A pair as the model proposes it. */ +export type ProposedPair = { topic: string; then: string; now: string; thenWords?: string; nowWords?: string }; +export type FlipsValue = { pairs: ProposedPair[] }; + +type Side = { entry: string; when: string; words: string }; +export type FlipPair = { id: string; topic: string; then: Side; now: Side }; + +/** What code makes of a proposal: the field, the swaps it needs, and what is wrong (per pair, and overall). */ +export type FlipsPlan = { + flips: { pairs: FlipPair[] }; + swaps: [string, string][]; + pairProblems: string[][]; + problems: string[]; + soft: string[]; +}; + +type FlipsUnit = MediaUnit & { + // The cut as read (what every plan is made over). + manifest: VideoManifest; + clips: ClipFact[]; + g: GroundingInput; + // The cut's order is a draft and the flips will be applied: a pair may swap its clips. + reorderable: boolean; + // The threads are a draft and `force` is set: the flips replace them. + dropThreads: boolean; + maxPairs: number; + // The kept value's plan (set by toField, read by apply). + chosen?: FlipsPlan; +}; + +// The evidence's share of a prompt (characters), well under the local 8k tokens. +const EVIDENCE_BUDGET = 14_000; + +const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim(); + +/** A pair id from its topic: letters, digits and `-`; unique among `taken`. */ +export function pairId(topic: string, i: number, taken: Set<string>): string { + let base = topic.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, ""); + if (!/^[a-z0-9]/.test(base)) base = `pair-${i + 1}`; + let id = base; + for (let k = 2; taken.has(id); k++) id = `${base}-${k}`; + taken.add(id); + return id; +} + +/** + * A side's words: the clip's quote, verbatim — or the part of it the model + * named, when the quote says exactly that — cut to `max` characters at a word + * (with `…`). `soft` when the model's part was not the quote's. + */ +export function sideWords(quote: string, part: string | undefined, max: number = FLIPS_LIMITS.words): { words: string; soft?: string } { + const q = oneLine(quote); + let w = q; + let soft: string | undefined; + const p = oneLine(part).replace(/^["“'…\s]+|["”'…\s]+$/g, ""); + if (p) { + const at = q.toLowerCase().indexOf(p.toLowerCase()); + if (at >= 0) w = q.slice(at, at + p.length); + else soft = "its words are not the clip's quote: the quote is used"; + } + if (w.length > max) { + const cut = w.slice(0, max - 1); + const sp = cut.lastIndexOf(" "); + w = `${(sp > max / 2 ? cut.slice(0, sp) : cut).replace(/[\s,;:.]+$/, "")}…`; + } + return { words: w, ...(soft ? { soft } : {}) }; +} + +/** The timeline with each pair of ids' places swapped. */ +export function swapEntries(timeline: ManifestEntry[], swaps: readonly [string, string][]): ManifestEntry[] { + const out = [...timeline]; + for (const [a, b] of swaps) { + const i = out.findIndex((e) => e.id === a); + const j = out.findIndex((e) => e.id === b); + if (i < 0 || j < 0) continue; + [out[i], out[j]] = [out[j]!, out[i]!]; + } + return out; +} + +const twins = (m: VideoManifest, id: string) => entriesWithId(m, id).length > 1; + +/** Code's reading of a proposal over this cut (pure). */ +export function planFlips(value: FlipsValue, unit: Pick<FlipsUnit, "clips" | "g" | "reorderable" | "dropThreads" | "maxPairs">, manifest: VideoManifest): FlipsPlan { + const byId = new Map(unit.clips.map((c) => [c.id, c])); + const problems: string[] = []; + const soft: string[] = []; + const [lo] = FLIPS_LIMITS.pairs; + const n = value.pairs.length; + if (n < lo) problems.push("no pair: propose at least one"); + if (n > unit.maxPairs) problems.push(`${n} pairs: at most ${unit.maxPairs}`); + const used = new Set<string>(); + const taken = new Set<string>(); + const pairs: FlipPair[] = []; + const pairProblems: string[][] = []; + const swaps: [string, string][] = []; + value.pairs.forEach((p, i) => { + const bad: string[] = []; + const w = `pair ${i + 1}`; + const topic = oneLine(p.topic); + if (!topic) bad.push(`${w}: no topic`); + else if (topic.length > FLIPS_LIMITS.topic) bad.push(`${w}: the topic is ${topic.length} characters (at most ${FLIPS_LIMITS.topic})`); + else for (const h of checkLine(topic, unit.g).hard) bad.push(`${w}: the topic: ${h}`); + let a = byId.get(p.then); + let b = byId.get(p.now); + if (!a) bad.push(`${w}: ${p.then || "(none)"} is not a clip of the cut`); + if (!b) bad.push(`${w}: ${p.now || "(none)"} is not a clip of the cut`); + let side = { then: p.thenWords, now: p.nowWords }; + if (a && b) { + if (a.id === b.id) bad.push(`${w}: THEN and NOW are the same clip`); + for (const c of [a, b]) { + if (used.has(c.id)) bad.push(`${w}: ${c.id} is already in a pair`); + if (!c.date) bad.push(`${w}: ${c.id}'s recording has no date`); + if (!c.quote) bad.push(`${w}: ${c.id} has no quote`); + } + if (a.date && b.date) { + if (a.date === b.date) bad.push(`${w}: ${a.id} and ${b.id} are of the same day (${a.date})`); + else if (a.date > b.date) { + // THEN is the earlier recording: the dates are code's. + [a, b] = [b, a]; + side = { then: p.nowWords, now: p.thenWords }; + } + } + if (a.id !== b.id && a.index > b.index) { + if (!unit.reorderable) bad.push(`${w}: THEN ${a.id} (${a.date}) plays after NOW ${b.id} (${b.date}) and the cut's order is not a draft — pick another pair, or reorder the cut by hand`); + else if (twins(manifest, a.id) || twins(manifest, b.id)) bad.push(`${w}: ${a.id} or ${b.id} has variant twins — reorder the cut by hand`); + } + } + if (a && b && !bad.length) { + const tw = sideWords(a.quote, side.then); + const nw = sideWords(b.quote, side.now); + if (tw.soft) soft.push(`${w}: ${a.id} ${tw.soft}`); + if (nw.soft) soft.push(`${w}: ${b.id} ${nw.soft}`); + if (a.index > b.index) swaps.push([a.id, b.id]); + pairs.push({ + id: pairId(topic, i, taken), + topic, + then: { entry: a.id, when: whenOf(a.date!), words: tw.words }, + now: { entry: b.id, when: whenOf(b.date!), words: nw.words }, + }); + } + // Only a pair that stands takes its clips: a refused one leaves them free. + if (a && b && !bad.length) for (const c of [a, b]) used.add(c.id); + pairProblems.push(bad); + }); + const flips = { pairs }; + if (pairs.length && !pairProblems.some((x) => x.length) && !problems.length) { + // The build's own checks, on the cut as it will be. + const after = JSON.parse(JSON.stringify(manifest)) as VideoManifest & { render?: { chrome?: Record<string, unknown> } }; + after.timeline = swapEntries(after.timeline, swaps); + if (after.render?.chrome) { + if (unit.dropThreads) delete after.render.chrome.threads; + after.render.chrome.flips = flips; + } + problems.push(...validateFlips(flips), ...validateFlipEntries(after)); + } + return { flips, swaps, pairProblems, problems, soft }; +} + +const allProblems = (p: FlipsPlan) => [...p.problems, ...p.pairProblems.flat()]; + +export function flipsSystem(maxPairs: number): string { + return ( + "You pick THEN/NOW pairs for a short evidence video: two clips of the same speaker on one topic, where what was said " + + "at the earlier date is reversed or contradicted by what was said at the later one. Rules: (1) use only clip ids from " + + "the list; (2) a clip is in one pair at most; (3) propose only pairs that really reverse, at most " + + `${maxPairs}, best first; (4) the topic names what the pair is about in plain words, at most ${FLIPS_LIMITS.topic} ` + + "characters, no quotation marks, no first person, nothing the evidence does not say; (5) the dates are given and " + + "decide which clip is THEN — you never write a date; (6) thenWords and nowWords are optional: a part of that clip's " + + `quote copied word for word, when the whole quote is longer than ${FLIPS_LIMITS.words} characters; leave them out ` + + "otherwise." + ); +} + +export const FLIPS_SPEC: MediaTaskSpec<FlipsUnit, FlipsValue, FlipsInput> = { + task: "flips", + noun: "flips panel", + async units(ctx: MediaContext<FlipsInput>) { + const m = ctx.manifest as VideoManifest & { render?: { chrome?: unknown } }; + const chrome = m.render?.chrome; + if (!chrome || typeof chrome !== "object") { + throw new TaskInputError("flips are drawn by the on-screen deck (render.chrome), and this cut has none — turn the deck on first"); + } + let dropThreads = false; + if (threadsOn(m.render)) { + const owner = ownerOf(m, { field: "render.chrome.threads" }); + if (!ctx.input.force || owner === "operator") { + throw new TaskInputError( + "this cut has threads (render.chrome.threads), and flips and threads share the left panel" + + (owner === "operator" ? ": the threads are the operator's — remove them first" : ": force replaces drafted threads"), + ); + } + dropThreads = true; + } + const clips = await clipFacts(m, ctx.report, ctx.handle.deps.corpus ?? null); + const dated = clips.filter((c) => c.date && c.quote); + const days = new Set(dated.map((c) => c.date)); + if (dated.length < 2 || days.size < 2) { + return [{ id: "flips", skipped: `a pair needs two clips of different dates: ${dated.length} dated clip(s), ${days.size} date(s)` }]; + } + const flipsOwner = ownerOf(m, { field: "render.chrome.flips" }); + return [ + { + id: "flips", + target: { field: "render.chrome.flips" }, + label: "THEN/NOW pairs", + manifest: m, + clips, + g: ctx.grounding, + reorderable: ownerOf(m, { field: "timeline" }) === "drafted" && flipsOwner !== "operator", + dropThreads, + maxPairs: Math.min(FLIPS_LIMITS.pairs[1], Math.floor(dated.length / 2)), + }, + ]; + }, + schema: () => ({ + type: "object", + properties: { + pairs: { + type: "array", + items: { + type: "object", + properties: { + topic: { type: "string" }, + then: { type: "string" }, + now: { type: "string" }, + thenWords: { type: "string" }, + nowWords: { type: "string" }, + }, + required: ["topic", "then", "now"], + }, + }, + }, + required: ["pairs"], + }), + system: (u) => flipsSystem(u.maxPairs), + user(u, ctx) { + const r = ctx.report as { title?: string; summary?: string | null }; + const ev = fitLines(u.clips.map((c) => clipLine(c)), EVIDENCE_BUDGET); + return ( + `Report: ${r.title ?? ""}` + + (r.summary ? `\n${String(r.summary).slice(0, 600)}` : "") + + `\n\nThe cut's clips (id [recording date] (chapter): "quote" — the claim it stands for):\n${ev.text}` + + (ev.omitted ? `\n(${ev.omitted} more clip(s) not shown)` : "") + + "\n\nPropose the pairs." + ); + }, + parse(answer) { + const list = (answer as { pairs?: unknown } | null)?.pairs; + if (!Array.isArray(list)) throw new Error("no pairs list in the answer"); + return { + pairs: list + .filter((p): p is Record<string, unknown> => !!p && typeof p === "object") + .map((p) => ({ + topic: oneLine(p.topic), + then: oneLine(p.then), + now: oneLine(p.now), + ...(typeof p.thenWords === "string" && p.thenWords.trim() ? { thenWords: p.thenWords } : {}), + ...(typeof p.nowWords === "string" && p.nowWords.trim() ? { nowWords: p.nowWords } : {}), + })), + }; + }, + check(value, u) { + const plan = planFlips(value, u, u.manifest); + return { hard: allProblems(plan), soft: plan.soft }; + }, + // The best attempt's pairs that pass, when there is one (never a new pair). + repair(attempts, u) { + let best: MediaAttempt<FlipsValue> | null = null; + for (const a of attempts) { + if (!a.value) continue; + const plan = planFlips(a.value, u, u.manifest); + const good = a.value.pairs.filter((_, i) => !plan.pairProblems[i]?.length).slice(0, u.maxPairs); + if (!good.length) continue; + const v = { pairs: good }; + const again = planFlips(v, u, u.manifest); + const hard = allProblems(again); + if (hard.length) continue; + if (!best || good.length > best.value!.pairs.length) { + best = { value: v, hard: [], soft: [...again.soft, `${a.value.pairs.length - good.length} refused pair(s) dropped`] }; + } + } + return best; + }, + toField(value, u) { + u.chosen = planFlips(value, u, u.manifest); + return u.chosen.flips; + }, + apply(manifest, u, value, provenance, force, ctx) { + const res = applyDraft(manifest, { field: "render.chrome.flips", value, provenance, force }); + if (!res.applied) return res; + const m = manifest as VideoManifest & { render?: { chrome?: Record<string, unknown> } }; + if (u.dropThreads && m.render?.chrome) { + delete m.render.chrome.threads; + for (const e of m.timeline) delete e.thread; + clearDrafted(m, { field: "render.chrome.threads" }); + ctx.handle.log(" the drafted threads were removed: flips and threads share the left panel"); + } + const swaps = u.chosen?.swaps ?? []; + if (swaps.length) { + const t = applyDraft(m, { field: "timeline", value: swapEntries(m.timeline, swaps), provenance, force: true }); + ctx.handle.log( + t.applied + ? ` the cut's order changed so THEN plays first: ${swaps.map(([a, b]) => `${a} ⇄ ${b}`).join(", ")}` + : ` the cut's order could not be changed (${t.reason}): THEN plays after NOW`, + ); + } + return res; + }, + describe: (v, u) => { + const pairs = planFlips(v, u, u.manifest).flips.pairs; + return ( + `${pairs.length} pair(s): ` + + pairs.map((p) => `${p.topic} (${p.then.entry} ${p.then.when} → ${p.now.entry} ${p.now.when})`).join("; ") + + (u.dropThreads ? " — replaces the drafted threads" : "") + ); + }, +}; + +export async function flips(input: FlipsInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(FLIPS_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts @@ -1,13 +1,19 @@ // The generation tasks (release 27, S5), and one dispatcher the editor's // `report-draft` job runs (S6). +import type { MediaStepTask } from "../../../generationSettings"; +import type { MediaTaskInput } from "./media"; +import { flips } from "./flips"; import { narrate, type NarrateInput } from "./narrate"; import { research, type ResearchInput } from "./research"; import { reviseReport, type ReviseReportInput } from "./revise-report"; import { reviseVideo, type ReviseVideoInput } from "./revise-video"; import { sweepAgent, type SweepAgentInput } from "./sweep-agent"; import { sweepPipeline, type SweepPipelineInput } from "./sweep-pipeline"; +import { TaskInputError, runOnIteration } from "./run"; +import { threads } from "./threads"; import { TASK_NAMES, type TaskDeps, type TaskName, type TaskResult } from "./types"; +import { youtube } from "./youtube"; export * from "./types"; export { TaskInputError, runOnIteration, usageOf } from "./run"; @@ -37,6 +43,11 @@ export { type MediaTaskSpec, type MediaUnit, } from "./media"; +// Release 28 M4–M6: the left panel (flips or threads) and the upload's text. +export { flips, FLIPS_SPEC, planFlips, sideWords, swapEntries, type FlipsInput, type FlipsPlan, type FlipsValue } from "./flips"; +export { threads, THREADS_SPEC, THREADS_TASK_COUNT, planThreads, type ThreadsInput, type ThreadsPlan, type ThreadsValue } from "./threads"; +export { youtube, YOUTUBE_SPEC, YOUTUBE_SUMMARY_MAX, type YoutubeInput, type YoutubeValue } from "./youtube"; +export { checkLine, clipFacts, whenOf, type ClipFact } from "./clipEvidence"; export { research, RESEARCH_READ_TOOLS, type ResearchInput } from "./research"; export { pickCorpusBuild, listCorpusBuilds, siteOriginOf, NoCorpusBuildError, type CorpusBuild } from "./corpusSource"; export { momentHref, rewriteLinks, rewriteMomentBases, slugResolver } from "./links"; @@ -49,7 +60,19 @@ export type TaskInput = | ({ task: "revise-report" } & ReviseReportInput) | ({ task: "revise-video" } & ReviseVideoInput) | ({ task: "narrate" } & NarrateInput) - | ({ task: "research" } & ResearchInput); + | ({ 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`); + }, + ); +} export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { switch (input.task) { @@ -65,6 +88,16 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { return narrate(input, deps); case "research": return research(input, deps); + case "flips": + return flips(input, deps); + case "threads": + return threads(input, deps); + case "youtube": + return youtube(input, deps); + case "cut": + case "onscreen": + case "teaser": + return notImplementedTask(input, deps); } } diff --git a/common/lib/report/draft/tasks/panelTasks.test.ts b/common/lib/report/draft/tasks/panelTasks.test.ts @@ -0,0 +1,365 @@ +// The flips, threads and youtube drafts (release 28, M4–M6): every code check +// refuses what it should — dates, order, counts, lengths, ids, grounding — the +// better of two attempts, the repair, the one left panel, and the operator's +// field kept with the draft as an alternative. The fake ollama answers; the +// corpus is the synthetic one's records (their upload dates). + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { recordOf } from "../../../../testing/draft/corpus.mjs"; +import { createIteration, projectOf, updateIteration, writeIterationFile } from "../../iterations"; +import { groundingInputOf } from "../grounding"; +import { validateFlipEntries, validateFlips, validateThreadEntries, validateThreads } from "../../panels.mjs"; +import type { VideoManifest } from "../videoOps"; +import { isoDay, whenOf, type ClipFact } from "./clipEvidence"; +import { flips, planFlips, sideWords, swapEntries } from "./flips"; +import { planThreads, threads } from "./threads"; +import { summaryProblems, titleProblems, youtube, YOUTUBE_SUMMARY_MAX } from "./youtube"; +import type { DraftFile } from "./media"; +import type { TaskDeps } from "./types"; + +const DRAFT = new URL("../../../../testing/draft/", import.meta.url); +const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); + +let tmp: string; +let ol: FakeOllama; +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "panel-tasks-")); + ol = await startFakeOllama(); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +// The full manifest with no left panel (its threads taken off). +async function deckManifest() { + const m = await kit("manifests/full.video.manifest.json"); + delete m.render.chrome.threads; + for (const e of m.timeline) delete e.thread; + return m; +} + +// The corpus as the tasks read it: get_video_metadata answers a record (no cues). +const corpus = { + source: "fake", + tools: [], + call: async (name: string, args: Record<string, unknown> = {}) => { + if (name !== "get_video_metadata") return ""; + const r = recordOf(String(args.channel), String(args.video_id)); + if (!r) throw new Error("video not found"); + const { cues: _c, ...meta } = r; + return JSON.stringify(meta); + }, +}; + +let caseN = 0; +async function project(manifest: unknown) { + caseN++; + const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) }; + const projectsRoot = path.join(tmp, `projects-${caseN}`); + await mkdir(paths.articlesDir, { recursive: true }); + await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const report = await kit("reports/basic.report.json"); + await writeIterationFile("synth-basic", 1, "report.json", report, paths); + const dir = projectOf(projectsRoot, "synth-basic", 1); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`); + await writeFile(path.join(dir, "report.json"), JSON.stringify(report)); + await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths); + const lines: string[] = []; + const deps: TaskDeps = { + llm: { ollama: { baseUrl: ol.url } }, + corpus, + cuesOf: async () => null, + paths, + log: (l) => lines.push(l), + now: () => new Date("2026-10-13T12:00:00.000Z"), + }; + const input = (o: { force?: boolean } = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o }); + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const draftNow = async (task: string) => JSON.parse(await readFile(path.join(dir, `${task}-draft.json`), "utf8")) as DraftFile; + return { dir, deps, lines, input, manifestNow, draftNow, report }; +} + +const P = { task: "cut", model: "qwen3:8b", at: "2026-10-13T11:00:00.000Z", iteration: 1, attempt: 1 }; + +// ─── pure ─── + +test("dates and words are code's: isoDay, whenOf, sideWords verbatim and cut at a word", () => { + assert.equal(isoDay("20260105"), "2026-01-05"); + assert.equal(isoDay("2026-03-01T10:00:00Z"), "2026-03-01"); + assert.equal(isoDay("March"), null); + assert.equal(whenOf("2026-01-05"), "Jan 2026"); + assert.deepEqual(sideWords("I would never sell the bakery to a chain", "Never sell the BAKERY"), { words: "never sell the bakery" }); + assert.deepEqual(sideWords("I would never sell the bakery to a chain", "I'd never sell it"), { + words: "I would never sell the bakery to a chain", + soft: "its words are not the clip's quote: the quote is used", + }); + const long = Array.from({ length: 40 }, (_, i) => `word${i}`).join(" "); + const cut = sideWords(long, undefined).words; + assert.ok(cut.length <= 110 && cut.endsWith("…") && long.startsWith(cut.slice(0, -1)), cut); + assert.deepEqual( + swapEntries([{ type: "clip", id: "a" }, { type: "card", id: "x" }, { type: "clip", id: "b" }], [["a", "b"]]).map((e) => e.id), + ["b", "x", "a"], + ); +}); + +const clip = (id: string, index: number, date: string | null, quote = `the words of ${id}`, verdict?: string): ClipFact => ({ + id, + index, + quote, + claim: verdict ? { text: "", verdict } : null, + section: null, + date, + dateFrom: date ? "record" : null, +}); + +test("planFlips: ids, one pair per clip, dates (the earlier is THEN; one day is no pair), order, the topic's length and grounding", async () => { + const m = (await deckManifest()) as VideoManifest; + const g = groundingInputOf(await kit("reports/basic.report.json")); + const clips = [clip("c01", 2, "2026-01-05"), clip("c02", 3, "2026-01-05"), clip("c04", 6, "2026-02-10"), clip("c07", 9, "2026-03-01"), clip("c05", 7, null)]; + const unit = { clips, g, reorderable: false, dropThreads: false, maxPairs: 2 }; + // The model's THEN is the later recording: code turns it round. + const ok = planFlips({ pairs: [{ topic: "The bakery", then: "c07", now: "c01" }] }, unit, m); + assert.deepEqual(ok.problems, []); + assert.deepEqual(ok.flips.pairs[0], { + id: "the-bakery", + topic: "The bakery", + then: { entry: "c01", when: "Jan 2026", words: "the words of c01" }, + now: { entry: "c07", when: "Mar 2026", words: "the words of c07" }, + }); + const bad = planFlips( + { + pairs: [ + { topic: "The oven", then: "c01", now: "c02" }, + { topic: "The contest", then: "c99", now: "c04" }, + { topic: "The contest", then: "c05", now: "c04" }, + { topic: "A topic that is far too long for the panel", then: "c04", now: "c07" }, + ], + }, + unit, + m, + ); + const all = [...bad.problems, ...bad.pairProblems.flat()].join(" | "); + assert.match(all, /4 pairs: at most 2/); + assert.match(all, /c01 and c02 are of the same day \(2026-01-05\)/); + assert.match(all, /c99 is not a clip of the cut/); + assert.match(all, /c05's recording has no date/); + assert.match(all, /the topic is 42 characters \(at most 32\)/); + // A name the report does not have; a clip in two pairs. + const two = planFlips({ pairs: [{ topic: "The bakery of Gordon", then: "c01", now: "c07" }, { topic: "The oven", then: "c04", now: "c07" }] }, unit, m); + assert.match(two.pairProblems[0]!.join(" "), /name “Gordon” is not in the report/); + assert.equal(two.pairProblems[1]!.length, 0, "a refused pair leaves its clips free"); + const three = planFlips({ pairs: [{ topic: "The bakery", then: "c01", now: "c07" }, { topic: "The oven", then: "c04", now: "c07" }] }, unit, m); + assert.match(three.pairProblems[1]!.join(" "), /c07 is already in a pair/); +}); + +test("planFlips: THEN after NOW in the cut is refused when the order is the operator's, swapped when it is a draft; the build's validators pass", async () => { + const m = (await deckManifest()) as VideoManifest; + // c07 (Mar) before c01 (Jan) in the cut. + m.timeline = swapEntries(m.timeline, [["c01", "c07"]]); + const g = groundingInputOf(await kit("reports/basic.report.json")); + const at = (id: string) => m.timeline.findIndex((e) => e.id === id); + const clips = [clip("c01", at("c01"), "2026-01-05"), clip("c07", at("c07"), "2026-03-01")]; + const v = { pairs: [{ topic: "The bakery", then: "c01", now: "c07" }] }; + const refused = planFlips(v, { clips, g, reorderable: false, dropThreads: false, maxPairs: 1 }, m); + assert.match(refused.pairProblems[0]!.join(" "), /THEN c01 \(2026-01-05\) plays after NOW c07 \(2026-03-01\) and the cut's order is not a draft/); + const swapped = planFlips(v, { clips, g, reorderable: true, dropThreads: false, maxPairs: 1 }, m); + assert.deepEqual([...swapped.problems, ...swapped.pairProblems.flat()], []); + assert.deepEqual(swapped.swaps, [["c01", "c07"]]); + const after = JSON.parse(JSON.stringify(m)); + after.timeline = swapEntries(after.timeline, swapped.swaps); + after.render.chrome.flips = swapped.flips; + assert.deepEqual([...validateFlips(swapped.flips), ...validateFlipEntries(after)], []); +}); + +test("planThreads: 2 to 4, labels, ids, assignments, every thread a clip; the outcome is the last clip's verdict in the manifest", async () => { + const m = (await deckManifest()) as VideoManifest; + const g = groundingInputOf(await kit("reports/basic.report.json")); + const at = (id: string) => m.timeline.findIndex((e) => e.id === id); + const clips = ["c01", "c02", "c03", "c04", "c05", "c06", "c07"].map((id) => clip(id, at(id), null)); + const unit = { clips, g, dropFlips: false }; + const one = planThreads({ threads: [{ id: "a", label: "The bakery" }], assign: [{ clip: "c01", thread: "a" }] }, unit, m); + assert.match(one.problems.join(" "), /1 thread\(s\): 2 to 4/); + const bad = planThreads( + { + threads: [ + { id: "bakery", label: "The bakery" }, + { id: "bakery", label: "The bakery again" }, + { id: "x y!", label: "A label that is much too long for the rail" }, + ], + assign: [ + { clip: "c01", thread: "bakery" }, + { clip: "c99", thread: "bakery" }, + { clip: "c02", thread: "nowhere" }, + { clip: "c03", thread: "bakery" }, + { clip: "c03", thread: "x y!" }, + ], + }, + unit, + m, + ); + const all = [...bad.problems, ...bad.threadProblems.flat()].join(" | "); + assert.match(all, /the id bakery is listed twice/); + assert.match(all, /the label is 42 characters \(at most 32\)/); + assert.match(all, /c99 is not a clip of the cut/); + assert.match(all, /c02 is put in nowhere, which is not a listed thread/); + assert.match(all, /c03 is put in two threads \(bakery, x-y\)/); + // The outcome: code's, from the manifest — c07 (CONTRADICTED) is the bakery's last clip; c06 (NOT_FOUND) the contest's. + const good = planThreads( + { + threads: [{ id: "bakery", label: "The bakery" }, { id: "contest", label: "The contest" }], + assign: ["c01", "c02", "c03", "c07"].map((c) => ({ clip: c, thread: "bakery" })).concat(["c04", "c05"].map((c) => ({ clip: c, thread: "contest" }))), + }, + unit, + m, + ); + assert.deepEqual(good.problems, []); + assert.deepEqual(good.list, [ + { id: "bakery", label: "The bakery", outcome: { verdict: "CONTRADICTED" } }, + { id: "contest", label: "The contest", outcome: { verdict: "PARTLY" } }, + ]); + const after = JSON.parse(JSON.stringify(m)); + after.render.chrome.threads = { list: good.list }; + for (const e of after.timeline) if (good.clips[e.id]) e.thread = good.clips[e.id]; + assert.deepEqual([...validateThreads({ list: good.list }), ...validateThreadEntries(after)], []); +}); + +test("youtube's checks: lengths, one line, links, third person, names and numbers, quotes word for word", async () => { + const g = groundingInputOf(await kit("reports/basic.report.json")); + assert.deepEqual(titleProblems("What the baker of Synth Kitchen says about the bakery", g).hard, []); + assert.match(titleProblems("x".repeat(101), g).hard.join(" "), /101 characters \(at most 100\)/); + assert.match(titleProblems("Synth Kitchen in 2027", g).hard.join(" "), /number 2027 is not in the report/); + assert.match(titleProblems("What Gordon says about the bakery", g).hard.join(" "), /name “Gordon” is not in the report/); + assert.match(summaryProblems("I would never sell it, she says.", g).hard.join(" "), /the narrator is third person/); + assert.deepEqual(summaryProblems('She says "I would never sell the bakery to a chain" on the bread day.', g).hard, []); + assert.match(summaryProblems('She says "I will sell the bakery".', g).hard.join(" "), /is not what a cited clip says, word for word/); + assert.match(summaryProblems("See 0:15 for the bakery.", g).hard.join(" "), /no links, timestamps/); + assert.match(summaryProblems("a ".repeat(YOUTUBE_SUMMARY_MAX), g).hard.join(" "), /at most 900/); +}); + +// ─── the tasks, over the fake ollama ─── + +test("flips refuses a cut with no deck, and one with threads unless forced over drafted threads — which it then replaces, and says so", async () => { + const basic = await project(await kit("manifests/basic.video.manifest.json")); + const none = await flips(basic.input(), basic.deps); + assert.equal(none.status, "failed"); + assert.match(none.summary, /drawn by the on-screen deck \(render\.chrome\), and this cut has none/); + + // The full manifest's threads are hand-written: the operator's, refused even forced. + const full = await project(await kit("manifests/full.video.manifest.json")); + assert.match((await flips(full.input(), full.deps)).summary, /share the left panel: the threads are the operator's/); + assert.match((await flips(full.input({ force: true }), full.deps)).summary, /the threads are the operator's — remove them first/); + + // Drafted threads: refused unforced, replaced forced. + const m = await kit("manifests/full.video.manifest.json"); + m.drafted = { "render.chrome.threads": P }; + const drafted = await project(m); + assert.match((await flips(drafted.input(), drafted.deps)).summary, /force replaces drafted threads/); + ol.push(jsonReply({ pairs: [{ topic: "The bakery's size", then: "c01", now: "c07" }] })); + const out = await flips(drafted.input({ force: true }), drafted.deps); + assert.equal(out.status, "done", `${out.summary}\n${drafted.lines.join("\n")}`); + const now = await drafted.manifestNow(); + assert.equal(now.render.chrome.threads, undefined); + assert.ok(now.timeline.every((e: { thread?: string }) => e.thread === undefined), "every clip's thread goes with the list"); + assert.equal(now.drafted["render.chrome.threads"], undefined); + assert.equal(now.drafted["render.chrome.flips"].task, "flips"); + assert.ok(drafted.lines.some((l) => /the drafted threads were removed/.test(l))); +}); + +test("flips: a pair the other way round in a drafted cut swaps the clips (the timeline re-marked); a refused pair dropped when the rest stand", async () => { + const m = await deckManifest(); + m.timeline = swapEntries(m.timeline, [["c01", "c07"]]); + m.drafted = { timeline: { ...P, model: "code" } }; + const p = await project(m); + const bad = { pairs: [{ topic: "The bakery's size", then: "c01", now: "c07" }, { topic: "The lease and Gordon", then: "c04", now: "c02" }] }; + ol.push(jsonReply(bad), jsonReply(bad)); + const out = await flips(p.input(), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(ol.remaining(), 0, "both attempts asked"); + const now = await p.manifestNow(); + assert.deepEqual(now.render.chrome.flips.pairs.map((x: { then: { entry: string }; now: { entry: string } }) => [x.then.entry, x.now.entry]), [["c01", "c07"]]); + assert.ok(now.timeline.findIndex((e: { id: string }) => e.id === "c01") < now.timeline.findIndex((e: { id: string }) => e.id === "c07")); + assert.equal(now.drafted.timeline.task, "flips", "the order is this draft's now"); + assert.deepEqual([...validateFlips(now.render.chrome.flips), ...validateFlipEntries(now)], []); + const file = await p.draftNow("flips"); + assert.match(JSON.stringify(file.units.flips!.chosen), /1 refused pair\(s\) dropped/); + assert.ok(p.lines.some((l) => /the cut's order changed so THEN plays first: c01 ⇄ c07/.test(l))); +}); + +test("flips: the operator's flips stand, forced or not; a forced draft is kept as an alternative", async () => { + const p = await project(await kit("manifests/flips.video.manifest.json")); + const skipped = await flips(p.input(), p.deps); + assert.equal(skipped.status, "failed"); + assert.match(String((await p.draftNow("flips")).units.flips!.skipped), /the operator's/); + ol.push(jsonReply({ pairs: [{ topic: "The contest", then: "c04", now: "c07" }] })); + const out = await flips(p.input({ force: true }), p.deps); + assert.equal(out.status, "done", out.summary); + const now = await p.manifestNow(); + assert.equal(now.render.chrome.flips.pairs[0].id, "chain", "the operator's pairs stand"); + const alt = (await p.draftNow("flips")).alternatives; + assert.equal(alt.length, 1); + assert.equal(alt[0]!.reason, "operator"); + assert.deepEqual((alt[0]!.value as { pairs: { topic: string }[] }).pairs.map((x) => x.topic), ["The contest"]); +}); + +test("threads: refused with operator's flips; forced over drafted flips replaces them; a refused thread dropped when two stand", async () => { + const op = await project(await kit("manifests/flips.video.manifest.json")); + assert.match((await threads(op.input({ force: true }), op.deps)).summary, /the flips are the operator's — remove them first/); + const m = await kit("manifests/flips.video.manifest.json"); + m.drafted = { "render.chrome.flips": { ...P, task: "flips" } }; + const p = await project(m); + const answer = { + threads: [{ id: "bakery", label: "The bakery" }, { id: "contest", label: "The contest" }, { id: "lease", label: "The lease and Gordon" }], + clips: [ + { clip: "c01", thread: "bakery" }, + { clip: "c02", thread: "bakery" }, + { clip: "c04", thread: "contest" }, + { clip: "c06", thread: "lease" }, + { clip: "c07", thread: "bakery" }, + ], + }; + ol.push(jsonReply(answer), jsonReply(answer)); + const out = await threads(p.input({ force: true }), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + const now = await p.manifestNow(); + assert.equal(now.render.chrome.flips, undefined); + assert.equal(now.drafted["render.chrome.flips"], undefined); + assert.deepEqual(now.render.chrome.threads.list.map((t: { id: string }) => t.id), ["bakery", "contest"]); + const thread = (id: string) => now.timeline.find((e: { id: string }) => e.id === id).thread; + assert.equal(thread("c06"), undefined, "the dropped thread's clip is in none"); + assert.equal(thread("c07"), "bakery"); + assert.deepEqual([...validateThreads(now.render.chrome.threads), ...validateThreadEntries(now)], []); + assert.ok(p.lines.some((l) => /the drafted flips were removed/.test(l))); +}); + +test("youtube: the better of two attempts, the summary's failing sentence removed; the operator's field kept and the draft an alternative", async () => { + const p = await project(await kit("manifests/basic.video.manifest.json")); + const title = "What the baker of Synth Kitchen says about the bakery"; + ol.push( + jsonReply({ title, description: "Synth Kitchen's baker will not sell the bakery. We think she is right." }), + jsonReply({ title: `${title} in 2027`, description: "She will not sell." }), + ); + const out = await youtube(p.input(), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + const now = await p.manifestNow(); + assert.deepEqual(now.publish.youtube, { title, description: "Synth Kitchen's baker will not sell the bakery." }); + assert.equal(now.drafted["publish.youtube"].attempt, 2); + + // The operator edits it (the mark goes): a forced re-draft is an alternative. + now.publish.youtube.title = "The baker on the bakery"; + delete now.drafted; + await writeFile(path.join(p.dir, "video.manifest.json"), JSON.stringify(now)); + ol.push(jsonReply({ title, description: "Synth Kitchen's baker will not sell the bakery." })); + const again = await youtube(p.input({ force: true }), p.deps); + assert.equal(again.status, "done", again.summary); + assert.equal((await p.manifestNow()).publish.youtube.title, "The baker on the bakery"); + const alt = (await p.draftNow("youtube")).alternatives; + assert.equal(alt.at(-1)!.reason, "operator"); + assert.equal((alt.at(-1)!.value as { title: string }).title, title); +}); diff --git a/common/lib/report/draft/tasks/threads.ts b/common/lib/report/draft/tasks/threads.ts @@ -0,0 +1,280 @@ +// TASK threads — the cut's clips grouped into the few lines of argument they +// make (release 28, M5): `render.chrome.threads.list` and each clip's +// `thread` key, drawn as the rail down the frame's left +// (umtool/report-to-video/threads.mjs). A STEP on a done iteration, on the +// media task scaffold (./media.ts): one unit, the whole field. +// +// The model names the threads (an id and a label) and puts each clip in one, +// or in none. CODE checks it all: +// - 2 to 4 threads (THREADS_TASK_COUNT; the rail takes up to +// THREADS_LIMITS.threads[1]), ids that are ids and not listed twice, +// labels of one line of at most THREADS_LIMITS.label characters whose +// names and numbers are the report's (grounding); +// - every assignment names a clip of the cut and a listed thread, a clip +// is in one thread at most, every thread has a clip; +// - a thread's OUTCOME is code's: the claim verdict its last clip carries in +// the manifest (`claim.verdict`), when it carries one — the model never +// sets a verdict; +// - the result passes the build's own validateThreads and +// validateThreadEntries (common's panels.mjs). +// A thread failing a check is dropped with its clips when at least two stand +// (the repair); the better of two attempts is kept. Applied: the list through +// applyDraft, then every clip's `thread` set (or removed: a clip in no thread +// has none) — the mark covers both. +// +// ONE LEFT PANEL: flips and threads share it. A cut with flips is refused — +// unless `force` and the flips are a draft: then the threads replace them and +// the log says so. A cut with no on-screen deck (`render.chrome`) is refused. + +import { applyDraft, clearDrafted, ownerOf } from "../../drafted.mjs"; +import { THREADS_LIMITS, flipsOn, validateThreadEntries, validateThreads } from "../../panels.mjs"; +import { VERDICTS } from "../../verdicts.mjs"; +import type { GroundingInput } from "../grounding"; +import type { VideoManifest } from "../videoOps"; +import { checkLine, clipFacts, clipLine, fitLines, type ClipFact } from "./clipEvidence"; +import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import { TaskInputError } from "./run"; +import type { TaskDeps, TaskResult } from "./types"; + +export type ThreadsInput = MediaTaskInput; + +/** How many threads a draft makes. */ +export const THREADS_TASK_COUNT = Object.freeze([2, 4] as const); + +export type ProposedThread = { id: string; label: string }; +export type ThreadsValue = { threads: ProposedThread[]; assign: { clip: string; thread: string }[] }; + +export type Thread = { id: string; label: string; outcome?: { verdict: string } }; +export type ThreadsPlan = { + list: Thread[]; + // clip id → thread id, for every clip in a thread. + clips: Record<string, string>; + threadProblems: string[][]; + problems: string[]; + soft: string[]; +}; + +type ThreadsUnit = MediaUnit & { + manifest: VideoManifest; + clips: ClipFact[]; + g: GroundingInput; + dropFlips: boolean; + chosen?: ThreadsPlan; +}; + +const EVIDENCE_BUDGET = 14_000; +const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; +const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim(); + +/** A thread id as code keeps it: the model's, else made from its label. */ +export function threadId(raw: string, label: string, i: number): string { + const id = oneLine(raw); + if (ID_RE.test(id)) return id; + const base = (id || label).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, ""); + return /^[a-z0-9]/.test(base) ? base : `thread-${i + 1}`; +} + +/** A clip's verdict as the manifest has it (`claim.verdict`), or null. */ +const manifestVerdict = (m: VideoManifest, id: string): string | null => { + const v = (m.timeline.find((e) => e.type === "clip" && e.id === id)?.claim as { verdict?: unknown } | undefined)?.verdict; + return typeof v === "string" && (VERDICTS as readonly string[]).includes(v) ? v : null; +}; + +/** Code's reading of a proposal over this cut (pure). */ +export function planThreads(value: ThreadsValue, unit: Pick<ThreadsUnit, "clips" | "g" | "dropFlips">, manifest: VideoManifest): ThreadsPlan { + const [lo, hi] = THREADS_TASK_COUNT; + const problems: string[] = []; + const soft: string[] = []; + const n = value.threads.length; + if (n < lo || n > hi) problems.push(`${n} thread(s): ${lo} to ${hi}`); + const byClip = new Map(unit.clips.map((c) => [c.id, c])); + // The model's id → code's, and each thread's problems. + const ids = new Map<string, string>(); + const seen = new Set<string>(); + const threadProblems: string[][] = value.threads.map((t, i) => { + const bad: string[] = []; + const label = oneLine(t.label); + const id = threadId(t.id, label, i); + const w = `thread ${i + 1} (${id})`; + if (seen.has(id)) bad.push(`${w}: the id ${id} is listed twice`); + seen.add(id); + if (!ids.has(oneLine(t.id))) ids.set(oneLine(t.id), id); + if (!label) bad.push(`${w}: no label`); + else if (label.length > THREADS_LIMITS.label) bad.push(`${w}: the label is ${label.length} characters (at most ${THREADS_LIMITS.label})`); + else for (const h of checkLine(label, unit.g).hard) bad.push(`${w}: the label: ${h}`); + return bad; + }); + const listed = value.threads.map((t, i) => threadId(t.id, oneLine(t.label), i)); + const clips: Record<string, string> = {}; + for (const a of value.assign) { + const clip = oneLine(a.clip); + const raw = oneLine(a.thread); + if (!raw) continue; // in no thread + const t = ids.get(raw) ?? (listed.includes(raw) ? raw : null); + if (!byClip.has(clip)) problems.push(`${clip || "(none)"} is not a clip of the cut`); + else if (!t) problems.push(`${clip} is put in ${raw}, which is not a listed thread`); + else if (clips[clip] !== undefined && clips[clip] !== t) problems.push(`${clip} is put in two threads (${clips[clip]}, ${t})`); + else clips[clip] = t; + } + listed.forEach((id, i) => { + if (!Object.values(clips).includes(id)) threadProblems[i]!.push(`thread ${i + 1} (${id}) has no clip`); + }); + // The outcome: the verdict its last clip (in the cut's order) carries. + const list: Thread[] = value.threads.map((t, i) => { + const id = listed[i]!; + const mine = unit.clips.filter((c) => clips[c.id] === id).sort((a, b) => a.index - b.index); + const verdict = mine.length ? manifestVerdict(manifest, mine.at(-1)!.id) : null; + return { id, label: oneLine(t.label), ...(verdict ? { outcome: { verdict } } : {}) }; + }); + if (!problems.length && !threadProblems.some((x) => x.length)) { + // The build's own checks, on the cut as it will be. + const after = JSON.parse(JSON.stringify(manifest)) as VideoManifest & { render?: { chrome?: Record<string, unknown> } }; + if (after.render?.chrome) { + if (unit.dropFlips) delete after.render.chrome.flips; + after.render.chrome.threads = { list }; + } + setClipThreads(after, clips); + problems.push(...validateThreads({ list }), ...validateThreadEntries(after)); + } + return { list, clips, threadProblems, problems, soft }; +} + +/** Every clip's `thread`: the one it is in, or none. */ +export function setClipThreads(m: VideoManifest, clips: Record<string, string>) { + for (const e of m.timeline) { + if (e.type !== "clip") continue; + if (clips[e.id]) e.thread = clips[e.id]; + else delete e.thread; + } +} + +const allProblems = (p: ThreadsPlan) => [...p.problems, ...p.threadProblems.flat()]; + +export function threadsSystem(): string { + const [lo, hi] = THREADS_TASK_COUNT; + return ( + "You group the clips of a short evidence video into threads: the few lines of argument the clips make, drawn as a " + + `rail of cards beside the footage. Rules: (1) ${lo} to ${hi} threads; (2) each thread has an id (letters, digits ` + + `and -) and a label of at most ${THREADS_LIMITS.label} characters in plain words, no quotation marks, no first ` + + "person, nothing the evidence does not say; (3) put each clip in at most one thread, by its id from the list; a " + + "clip that fits none is left out; (4) every thread has at least one clip; (5) you never write a verdict or an " + + "outcome." + ); +} + +export const THREADS_SPEC: MediaTaskSpec<ThreadsUnit, ThreadsValue, ThreadsInput> = { + task: "threads", + noun: "thread rail", + async units(ctx: MediaContext<ThreadsInput>) { + const m = ctx.manifest as VideoManifest & { render?: { chrome?: unknown } }; + if (!m.render?.chrome || typeof m.render.chrome !== "object") { + throw new TaskInputError("threads are drawn by the on-screen deck (render.chrome), and this cut has none — turn the deck on first"); + } + let dropFlips = false; + if (flipsOn(m.render)) { + const owner = ownerOf(m, { field: "render.chrome.flips" }); + if (!ctx.input.force || owner === "operator") { + throw new TaskInputError( + "this cut has flips (render.chrome.flips), and flips and threads share the left panel" + + (owner === "operator" ? ": the flips are the operator's — remove them first" : ": force replaces drafted flips"), + ); + } + dropFlips = true; + } + const clips = await clipFacts(m, ctx.report, null, { dates: false }); + if (clips.length < THREADS_TASK_COUNT[0]) { + return [{ id: "threads", skipped: `${clips.length} clip(s): ${THREADS_TASK_COUNT[0]} threads need at least ${THREADS_TASK_COUNT[0]}` }]; + } + return [{ id: "threads", target: { field: "render.chrome.threads" }, label: "Threads", manifest: m, clips, g: ctx.grounding, dropFlips }]; + }, + schema: () => ({ + type: "object", + properties: { + threads: { + type: "array", + items: { type: "object", properties: { id: { type: "string" }, label: { type: "string" } }, required: ["id", "label"] }, + }, + clips: { + type: "array", + items: { type: "object", properties: { clip: { type: "string" }, thread: { type: "string" } }, required: ["clip", "thread"] }, + }, + }, + required: ["threads", "clips"], + }), + system: () => threadsSystem(), + user(u, ctx) { + const r = ctx.report as { title?: string; summary?: string | null }; + const ev = fitLines(u.clips.map((c) => clipLine(c, { date: false })), EVIDENCE_BUDGET); + return ( + `Report: ${r.title ?? ""}` + + (r.summary ? `\n${String(r.summary).slice(0, 600)}` : "") + + `\n\nThe cut's clips, in order (id (chapter): "quote" — the claim it stands for):\n${ev.text}` + + (ev.omitted ? `\n(${ev.omitted} more clip(s) not shown)` : "") + + '\n\nName the threads, then give every clip its thread ("" for none).' + ); + }, + parse(answer) { + const a = answer as { threads?: unknown; clips?: unknown } | null; + if (!Array.isArray(a?.threads)) throw new Error("no threads list in the answer"); + const objs = (v: unknown) => (Array.isArray(v) ? v : []).filter((x): x is Record<string, unknown> => !!x && typeof x === "object"); + return { + threads: objs(a.threads).map((t) => ({ id: oneLine(t.id), label: oneLine(t.label) })), + assign: objs(a.clips).map((c) => ({ clip: oneLine(c.clip), thread: oneLine(c.thread) })), + }; + }, + check(value, u) { + const plan = planThreads(value, u, u.manifest); + return { hard: allProblems(plan), soft: plan.soft }; + }, + // The best attempt's threads that pass, with their clips, when at least two stand. + repair(attempts, u) { + let best: MediaAttempt<ThreadsValue> | null = null; + for (const a of attempts) { + if (!a.value) continue; + const plan = planThreads(a.value, u, u.manifest); + const keepIdx = plan.list.map((_, i) => i).filter((i) => !plan.threadProblems[i]?.length).slice(0, THREADS_TASK_COUNT[1]); + const keep = new Set(keepIdx.map((i) => plan.list[i]!.id)); + const v: ThreadsValue = { + threads: keepIdx.map((i) => ({ id: plan.list[i]!.id, label: plan.list[i]!.label })), + assign: Object.entries(plan.clips) + .filter(([, t]) => keep.has(t)) + .map(([clip, thread]) => ({ clip, thread })), + }; + if (v.threads.length < THREADS_TASK_COUNT[0]) continue; + const again = planThreads(v, u, u.manifest); + if (allProblems(again).length) continue; + if (!best || v.threads.length > best.value!.threads.length) { + best = { value: v, hard: [], soft: [...again.soft, `${a.value.threads.length - v.threads.length} refused thread(s) dropped`] }; + } + } + return best; + }, + toField(value, u) { + u.chosen = planThreads(value, u, u.manifest); + return { list: u.chosen.list }; + }, + apply(manifest, u, value, provenance, force, ctx) { + const res = applyDraft(manifest, { field: "render.chrome.threads", value, provenance, force }); + if (!res.applied) return res; + setClipThreads(manifest, u.chosen?.clips ?? {}); + const m = manifest as VideoManifest & { render?: { chrome?: Record<string, unknown> } }; + if (u.dropFlips && m.render?.chrome) { + delete m.render.chrome.flips; + clearDrafted(m, { field: "render.chrome.flips" }); + ctx.handle.log(" the drafted flips were removed: flips and threads share the left panel"); + } + return res; + }, + describe(v, u) { + const plan = planThreads(v, u, u.manifest); + const count = (id: string) => Object.values(plan.clips).filter((t) => t === id).length; + return ( + plan.list.map((t) => `${t.label} (${count(t.id)} clip(s)${t.outcome ? `, ${t.outcome.verdict}` : ""})`).join("; ") + + (u.dropFlips ? " — replaces the drafted flips" : "") + ); + }, +}; + +export async function threads(input: ThreadsInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(THREADS_SPEC, input, deps); +} diff --git a/common/lib/report/draft/tasks/types.ts b/common/lib/report/draft/tasks/types.ts @@ -8,6 +8,7 @@ // log and the job's AbortSignal. Nothing here reads settings: the editor job // (S6) builds the deps from `settings.generation`. +import { MEDIA_STEP_TASKS } from "../../../generationSettings"; import type { AgentTool, LlmConfig } from "../../../llm"; import type { CuesOf, PostChannelOf } from "../../convertShared"; import type { readIteration } from "../../iterations"; @@ -79,5 +80,8 @@ export type TaskResult = { minutes: number; }; -export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "narrate", "research"] as const; +// The media tasks (narrate first; release 28's cut, onscreen, teaser, flips, +// threads and youtube) are generationSettings' MEDIA_STEP_TASKS: each a step +// on a done iteration (./media.ts). +export const TASK_NAMES = ["sweep-agent", "sweep-pipeline", "revise-report", "revise-video", "research", ...MEDIA_STEP_TASKS] as const; export type TaskName = (typeof TASK_NAMES)[number]; diff --git a/common/lib/report/draft/tasks/youtube.ts b/common/lib/report/draft/tasks/youtube.ts @@ -0,0 +1,160 @@ +// TASK youtube — the upload's title and summary (release 28, M6): +// `publish.youtube { title, description }`. A STEP on a done iteration, on the +// media task scaffold (./media.ts): one unit, the whole field. +// +// The model writes the title and ONE summary paragraph; the build composes +// out/youtube.txt from them (umtool/report-to-video/youtube.mjs: the chapters +// from its own chapter list, a moment link per cited clip), so the summary +// leaves room for those under YouTube's 5000. CODE checks: +// - the title is one line of at most PUBLISH_YOUTUBE_LIMITS.title +// characters; the summary one paragraph of at most YOUTUBE_SUMMARY_MAX; +// - grounded (./grounding.ts, ./clipEvidence.ts checkLine): every name and +// number is the evidence's (the report's title, summary, sections, claims +// and quotes, the cut's title and subtitle); no stock phrase; third person +// (Q1: a first-person word outside quotation marks is refused); words in +// quotation marks only when a cited quote says them word for word; +// - no links, timestamps or chapter list: those are code's. +// A summary failing a check loses its failing sentences when what is left +// stands (the repair); the better of two attempts is kept. + +import { PUBLISH_YOUTUBE_LIMITS } from "../../drafted.mjs"; +import { sentencesOf, type GroundingInput } from "../grounding"; +import type { VideoManifest } from "../videoOps"; +import { checkLine, fitLines } from "./clipEvidence"; +import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import type { TaskDeps, TaskResult } from "./types"; + +export type YoutubeInput = MediaTaskInput; +export type YoutubeValue = { title: string; description: string }; + +/** The summary's limit: room under YouTube's 5000 for the chapters and the sources. */ +export const YOUTUBE_SUMMARY_MAX = 900; + +type YoutubeUnit = MediaUnit & { g: GroundingInput; evidence: string }; + +const EVIDENCE_BUDGET = 12_000; +const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim(); +const stripCites = (s: string) => s.replace(/\[([^\]]*)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, ""); + +const LINK = /https?:\/\/|www\.|\b\d{1,2}:\d{2}\b|#\w/; + +/** The title's problems. */ +export function titleProblems(title: string, g: GroundingInput): { hard: string[]; soft: string[] } { + const hard: string[] = []; + if (!title) hard.push("the title: empty"); + else if (title.length > PUBLISH_YOUTUBE_LIMITS.title) hard.push(`the title is ${title.length} characters (at most ${PUBLISH_YOUTUBE_LIMITS.title})`); + if (LINK.test(title)) hard.push("the title: no links, timestamps or hashtags"); + const r = title ? checkLine(title, g, { quotes: true }) : { hard: [], soft: [] }; + return { hard: [...hard, ...r.hard.map((h) => `the title: ${h}`)], soft: r.soft.map((s) => `the title: ${s}`) }; +} + +/** The summary's problems. */ +export function summaryProblems(text: string, g: GroundingInput): { hard: string[]; soft: string[] } { + const hard: string[] = []; + if (!text) hard.push("the summary: empty"); + else if (text.length > YOUTUBE_SUMMARY_MAX) hard.push(`the summary is ${text.length} characters (at most ${YOUTUBE_SUMMARY_MAX})`); + if (LINK.test(text)) hard.push("the summary: no links, timestamps, chapters or hashtags — the build adds the chapters and the sources"); + const r = text ? checkLine(text, g, { quotes: true }) : { hard: [], soft: [] }; + return { hard: [...hard, ...r.hard.map((h) => `the summary: ${h}`)], soft: r.soft.map((s) => `the summary: ${s}`) }; +} + +export function youtubeSystem(): string { + return ( + "You write the YouTube title and the summary paragraph of the description for a short evidence video made from a " + + `cited report. Rules: (1) the title is one line of at most ${PUBLISH_YOUTUBE_LIMITS.title} characters: plain and ` + + "specific, no clickbait, no all-caps, no emoji; (2) the summary is one paragraph of at most " + + `${YOUTUBE_SUMMARY_MAX} characters saying what the video shows and what the evidence found; (3) third person: you ` + + "describe what the speaker said, never as the speaker (no I, me, my, we, us or our outside quotation marks); (4) every " + + "name and number comes from the evidence, and nothing goes beyond it; (5) words in quotation marks only when a quote " + + "below says them word for word; (6) no links, timestamps, chapter list or hashtags: the chapters and the sources are " + + "added after it." + ); +} + +/** The evidence a title and summary may draw on, and its grounding (the cut's title and subtitle added). */ +function evidenceOf(ctx: MediaContext<YoutubeInput>): { text: string; g: GroundingInput } { + const r = ctx.report as { + title?: string; + summary?: string | null; + sections?: { title?: string; claims?: { text?: string; verdict?: string }[] | null }[]; + citations?: Record<string, { quote?: string; label?: string; date?: string } | undefined> | null; + }; + const m = ctx.manifest as VideoManifest; + const head = [`Report title: ${r.title ?? ""}`]; + if (m.title && m.title !== r.title) head.push(`Video title: ${m.title}`); + if (m.subtitle) head.push(`Video subtitle: ${m.subtitle}`); + if (r.summary) head.push(`Report summary: ${oneLine(r.summary).slice(0, 1200)}`); + const lines: string[] = []; + for (const s of r.sections ?? []) { + const claims = (s.claims ?? []).map((c) => ` - ${oneLine(stripCites(c.text ?? "")).slice(0, 220)}${c.verdict ? ` [${c.verdict}]` : ""}`); + if (!claims.length) continue; + lines.push(`Section: ${s.title ?? ""}`, ...claims); + } + const ev = fitLines(lines, EVIDENCE_BUDGET); + const quotes = [...new Set(Object.values(r.citations ?? {}).map((c) => oneLine(c?.quote)).filter(Boolean))]; + const q = fitLines(quotes.map((x) => `- "${x.slice(0, 200)}"`), 4000); + return { + text: + `${head.join("\n")}\n\nWhat it found:\n${ev.text}` + + (ev.omitted ? `\n(${ev.omitted} more line(s) not shown)` : "") + + (q.text ? `\n\nQuotes (the only words you may put in quotation marks):\n${q.text}` : ""), + g: { ...ctx.grounding, reference: [ctx.grounding.reference, m.title ?? "", m.subtitle ?? ""].join("\n") }, + }; +} + +export const YOUTUBE_SPEC: MediaTaskSpec<YoutubeUnit, YoutubeValue, YoutubeInput> = { + task: "youtube", + noun: "YouTube text", + units(ctx) { + const { text, g } = evidenceOf(ctx); + return [{ id: "youtube", target: { field: "publish.youtube" }, label: "YouTube title and summary", g, evidence: text }]; + }, + schema: () => ({ + type: "object", + properties: { title: { type: "string" }, description: { type: "string" } }, + required: ["title", "description"], + }), + system: () => youtubeSystem(), + user: (u) => `${u.evidence}\n\nWrite the title and the summary.`, + parse(answer) { + const a = answer as { title?: unknown; description?: unknown } | null; + return { + title: oneLine(a?.title).replace(/^["“]+|["”]+$/g, ""), + // One paragraph: line breaks are spaces. + description: oneLine(a?.description), + }; + }, + check(v, u) { + const t = titleProblems(v.title, u.g); + const d = summaryProblems(v.description, u.g); + return { hard: [...t.hard, ...d.hard], soft: [...t.soft, ...d.soft] }; + }, + // A clean title, with the summary's failing sentences removed (never + // rewritten) and cut to the limit at a sentence. + repair(attempts, u) { + let best: MediaAttempt<YoutubeValue> | null = null; + for (const a of attempts) { + if (!a.value || titleProblems(a.value.title, u.g).hard.length) continue; + const kept: string[] = []; + for (const s of sentencesOf(a.value.description)) { + if (summaryProblems(s, u.g).hard.length) continue; + if ([...kept, s].join(" ").length > YOUTUBE_SUMMARY_MAX) break; + kept.push(s); + } + const description = kept.join(" "); + if (!description) continue; + const v = { title: a.value.title, description }; + const again = summaryProblems(description, u.g); + if (again.hard.length) continue; + if (!best || description.length > best.value!.description.length) { + best = { value: v, hard: [], soft: [...titleProblems(v.title, u.g).soft, ...again.soft, "trimmed: failing or overlong sentences removed"] }; + } + } + return best; + }, + describe: (v) => `${v.title} — ${v.description.slice(0, 120)}${v.description.length > 120 ? "…" : ""}`, +}; + +export async function youtube(input: YoutubeInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(YOUTUBE_SPEC, input, deps); +} diff --git a/common/lib/report/panels.d.mts b/common/lib/report/panels.d.mts @@ -0,0 +1,20 @@ +// Types for ./panels.mjs (release 28, M4/M5): the flips' and the threads' +// limits and validators. See the module's header. + +export type FlipSide = { entry: string; when: string; words: string }; +export type FlipPair = { id: string; topic: string; then: FlipSide; now: FlipSide }; +export type Flips = { pairs: FlipPair[] }; +export type ThreadOutcome = { verdict: string; label?: string }; +export type Thread = { id: string; label: string; outcome?: ThreadOutcome }; +export type Threads = { list: Thread[] }; + +export const FLIPS_LIMITS: Readonly<{ pairs: readonly [number, number]; topic: number; when: number; words: number }>; +export const THREADS_LIMITS: Readonly<{ threads: readonly [number, number]; label: number; outcome: number }>; + +export function flipsOn(render: unknown): boolean; +export function validateFlips(f: unknown, where?: string): string[]; +export function validateFlipEntries(manifest: unknown): string[]; +export function threadsOn(render: unknown): boolean; +export function validateThreads(t: unknown, where?: string): string[]; +export function threadOf(entry: unknown): string | null; +export function validateThreadEntries(manifest: unknown): string[]; diff --git a/common/lib/report/panels.mjs b/common/lib/report/panels.mjs @@ -0,0 +1,180 @@ +// THE LEFT PANEL'S RULES — THE one copy of what a cut's flips +// (`render.chrome.flips`) and threads (`render.chrome.threads`, each clip's +// `thread`) may be: their limits and their validators (release 28, M4/M5: +// moved here from umtool/report-to-video/flips.mjs and threads.mjs, which +// re-export them unchanged, so the flips and threads draft tasks check +// exactly what the build refuses). +// +// Plain JS (with ./panels.d.mts for TypeScript) for the reason +// ./verdicts.mjs is: umtool's report-to-video scripts are `.mjs` run by bare +// `node`, and the draft tasks are TypeScript. PURE: no fs. +// +// The two share the frame's left side: a cut has one or the other +// (umtool's deck.mjs validateChrome refuses both). + +import { VERDICTS } from "./verdicts.mjs"; + +const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); + +// ─── flips ─── + +/** The limits: pairs, a topic's, a `when`'s and a side's words' characters. */ +export const FLIPS_LIMITS = Object.freeze({ pairs: Object.freeze([1, 24]), topic: 32, when: 18, words: 110 }); + +const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; +const oneLineMax = (v, max) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v) && v.length <= max; + +/** Is the flips panel on: a `render.chrome.flips` with at least one pair. */ +export function flipsOn(render) { + const f = render?.chrome?.flips; + return isObj(f) && Array.isArray(f.pairs) && f.pairs.length > 0; +} + +/** + * Every reason `render.chrome.flips` cannot be built, as sentences. Shape + * only; `validateFlipEntries` checks the pairs against the timeline. + * + * @returns {string[]} + */ +export function validateFlips(f, where = "render.chrome.flips") { + if (f === undefined) return []; + if (!isObj(f)) return [`${where} must be an object`]; + const errors = []; + for (const k of Object.keys(f)) if (k !== "pairs") errors.push(`${where}.${k} is not a flips setting`); + const [lo, hi] = FLIPS_LIMITS.pairs; + if (!Array.isArray(f.pairs) || f.pairs.length < lo || f.pairs.length > hi) return [...errors, `${where}.pairs must be ${lo} to ${hi} pairs`]; + const ids = new Set(); + f.pairs.forEach((p, i) => { + const w = `${where}.pairs[${i}]`; + if (!isObj(p)) { errors.push(`${w} must be an object`); return; } + for (const k of Object.keys(p)) if (!["id", "topic", "then", "now"].includes(k)) errors.push(`${w}.${k} is not a pair key`); + if (typeof p.id !== "string" || !ID_RE.test(p.id)) errors.push(`${w}.id must be letters, digits, _ or -`); + else if (ids.has(p.id)) errors.push(`${w}.id ${p.id} is listed twice`); + else ids.add(p.id); + if (!oneLineMax(p.topic, FLIPS_LIMITS.topic)) errors.push(`${w}.topic must be one line of at most ${FLIPS_LIMITS.topic} characters`); + for (const side of ["then", "now"]) { + const s = p[side]; + const ws = `${w}.${side}`; + if (!isObj(s)) { errors.push(`${ws} must be an object`); continue; } + for (const k of Object.keys(s)) if (!["entry", "when", "words"].includes(k)) errors.push(`${ws}.${k} is not a side key`); + if (typeof s.entry !== "string" || !s.entry) errors.push(`${ws}.entry must name a timeline entry`); + if (!oneLineMax(s.when, FLIPS_LIMITS.when)) errors.push(`${ws}.when must be one line of at most ${FLIPS_LIMITS.when} characters`); + if (!oneLineMax(s.words, FLIPS_LIMITS.words)) errors.push(`${ws}.words must be one line of at most ${FLIPS_LIMITS.words} characters`); + } + }); + return errors; +} + +/** + * The pairs against the timeline: each side names an entry of the cut, a clip + * (not a teaser), the THEN side before the NOW side, and no entry in two pairs. + * + * @returns {string[]} + */ +export function validateFlipEntries(manifest) { + const render = manifest?.render ?? {}; + if (!flipsOn(render)) return []; + const errors = []; + const at = new Map((manifest.timeline ?? []).map((e, i) => [e?.id, { e, i }])); + const used = new Map(); + render.chrome.flips.pairs.forEach((p, i) => { + const w = `render.chrome.flips.pairs[${i}] (${p?.id ?? "?"})`; + const idx = {}; + for (const side of ["then", "now"]) { + const id = p?.[side]?.entry; + const hit = at.get(id); + if (!hit) { errors.push(`${w}.${side}.entry ${id} is not in the timeline`); continue; } + if (hit.e.type === "teaser") errors.push(`${w}.${side}.entry ${id} is a teaser, not a clip`); + if (used.has(id)) errors.push(`${w}.${side}.entry ${id} is already in pair ${used.get(id)}`); + used.set(id, p.id); + idx[side] = hit.i; + } + if (idx.then !== undefined && idx.now !== undefined && idx.then >= idx.now) errors.push(`${w}: its THEN entry must come before its NOW entry`); + }); + return errors; +} + +// ─── threads ─── + +/** The limits: how many threads, a label's and an outcome label's characters. */ +export const THREADS_LIMITS = Object.freeze({ threads: Object.freeze([1, 8]), label: 32, outcome: 24 }); + +/** A thread id: letters, digits and `_ -`. */ +const THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; + +const oneLine = (v) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v); + +/** Is the rail on: a `render.chrome.threads` with at least one thread. */ +export function threadsOn(render) { + const t = render?.chrome?.threads; + return isObj(t) && Array.isArray(t.list) && t.list.length > 0; +} + +/** + * Every reason `render.chrome.threads` cannot be built, as sentences (empty: + * it can). validateChrome calls this, so umtool's writer and the build refuse + * the same things. + * + * @returns {string[]} + */ +export function validateThreads(t, where = "render.chrome.threads") { + if (t === undefined) return []; + if (!isObj(t)) return [`${where} must be an object`]; + const errors = []; + for (const k of Object.keys(t)) if (k !== "list") errors.push(`${where}.${k} is not a threads setting`); + const [lo, hi] = THREADS_LIMITS.threads; + if (!Array.isArray(t.list) || t.list.length < lo || t.list.length > hi) { + return [...errors, `${where}.list must be ${lo} to ${hi} threads`]; + } + const seen = new Set(); + t.list.forEach((th, i) => { + const w = `${where}.list[${i}]`; + if (!isObj(th)) { errors.push(`${w} must be an object`); return; } + for (const k of Object.keys(th)) if (!["id", "label", "outcome"].includes(k)) errors.push(`${w}.${k} is not a thread key`); + if (typeof th.id !== "string" || !THREAD_ID_RE.test(th.id)) errors.push(`${w}.id must be letters, digits, _ or -`); + else if (seen.has(th.id)) errors.push(`${w}.id ${th.id} is listed twice`); + else seen.add(th.id); + if (!oneLine(th.label) || th.label.length > THREADS_LIMITS.label) { + errors.push(`${w}.label must be one line of at most ${THREADS_LIMITS.label} characters`); + } + if (th.outcome !== undefined) { + const o = th.outcome; + if (!isObj(o)) { errors.push(`${w}.outcome must be an object`); return; } + for (const k of Object.keys(o)) if (!["verdict", "label"].includes(k)) errors.push(`${w}.outcome.${k} is not an outcome key`); + if (!VERDICTS.includes(o.verdict)) errors.push(`${w}.outcome.verdict must be one of ${VERDICTS.join(", ")}`); + if (o.label !== undefined && (!oneLine(o.label) || o.label.length > THREADS_LIMITS.outcome)) { + errors.push(`${w}.outcome.label must be one line of at most ${THREADS_LIMITS.outcome} characters`); + } + } + }); + return errors; +} + +/** The thread an entry belongs to, or null. */ +export function threadOf(entry) { + return typeof entry?.thread === "string" && entry.thread ? entry.thread : null; +} + +/** + * Every `thread` in the timeline, checked against the list: it names a listed + * thread, it is not on a teaser, and every listed thread has a clip. The + * build refuses with these before it fetches. + * + * @returns {string[]} + */ +export function validateThreadEntries(manifest) { + const errors = []; + const render = manifest?.render ?? {}; + const listed = threadsOn(render) ? new Set(render.chrome.threads.list.map((t) => t?.id)) : new Set(); + const used = new Set(); + (manifest?.timeline ?? []).forEach((e, i) => { + if (e?.thread === undefined || e?.thread === null) return; + const where = `timeline[${i}] (${e.id ?? "?"}).thread`; + if (typeof e.thread !== "string" || !e.thread) { errors.push(`${where} must be a thread id`); return; } + if (e.type === "teaser") { errors.push(`${where}: a teaser belongs to no thread`); return; } + if (!listed.has(e.thread)) { errors.push(`${where} ${e.thread} is not in render.chrome.threads.list`); return; } + used.add(e.thread); + }); + for (const id of listed) if (!used.has(id)) errors.push(`render.chrome.threads: thread ${id} has no clip`); + return errors; +} diff --git a/common/package.json b/common/package.json @@ -36,6 +36,7 @@ "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", "./lib/ports.mjs": "./lib/ports.mjs", "./lib/report/drafted.mjs": "./lib/report/drafted.mjs", + "./lib/report/panels.mjs": "./lib/report/panels.mjs", "./lib/report/verdicts.mjs": "./lib/report/verdicts.mjs", "./lib/toolProbe.mjs": "./lib/toolProbe.mjs", "./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs", diff --git a/common/testing/README.md b/common/testing/README.md @@ -20,7 +20,7 @@ transcript, channel or person goes in these fixtures, ever. | `archiveOrg/fakeArchiveOrg.mjs` | A fake archive.org on loopback: `/advancedsearch.php` (every word of `q` in an item's identifier, title or subject; `*` all) and `/metadata/<id>` over invented items (`ITEMS`: a show's episodes with an original, a derivative and a JSON file, a restricted item, an audio tape). `ia.fetch` sends `https://archive.org/…` to it, for `new ArchiveOrgClient({ fetch: ia.fetch })`; `busyTimes` answers 429 first. | | `draft/manifests/full`, `flips` | Release 28: every media field a draft task writes, as the build accepts it today — per-entry `onscreen`, a narrated card, a teaser, `claim` verdicts, `render.chrome.threads` with a `thread` per clip (`full`), or `render.chrome.flips` (`flips`: one THEN/NOW pair over clips of different dates). Hand-written, not derived; `umtool/report-to-video/fixtures-r28.test.mjs` keeps them lint-clean. | | `draft/reports/ruled.report.json` | Release 28: a synthetic fact-check whose claims carry verdicts standing for operator rulings — every verdict at least once, each cited quote a cue of the corpus. The verdict bench's tests read it. | -| `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. | +| `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`; release 28's `flips`, `threads` and `youtube`, each with a `note` saying what it is run over and why its first answer is refused), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. | | `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. | As committed at S0, the `paragraphs` manifest showed two owed bugs: the title card had no `foot`, and diff --git a/common/testing/draft/runs/flips.json b/common/testing/draft/runs/flips.json @@ -0,0 +1,21 @@ +{ + "task": "flips", + "model": "qwen3:8b", + "note": "Over the full manifest with its threads taken off (a deck, no left panel) and the basic report. The first answer is refused (a pair of one day; a number the report does not have) and re-asked; the second is the S0 flips manifest's pair.", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"pairs\": [{\"topic\": \"The bakery's size\", \"then\": \"c07\", \"now\": \"c01\"}, {\"topic\": \"The contest in 2027\", \"then\": \"c04\", \"now\": \"c05\"}]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"pairs\": [{\"topic\": \"The bakery's size\", \"then\": \"c01\", \"now\": \"c07\"}]}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/runs/threads.json b/common/testing/draft/runs/threads.json @@ -0,0 +1,21 @@ +{ + "task": "threads", + "model": "qwen3:8b", + "note": "Over the full manifest with its threads taken off and the basic report. The first answer is refused (a label naming someone the report does not; a thread with no clip) and re-asked; the second groups the clips as the S0 full manifest does, the lease clip in the contest thread.", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"threads\": [{\"id\": \"bakery\", \"label\": \"The bakery\"}, {\"id\": \"contest\", \"label\": \"The contest\"}, {\"id\": \"gordon\", \"label\": \"Talks with Gordon\"}], \"clips\": [{\"clip\": \"c01\", \"thread\": \"bakery\"}, {\"clip\": \"c02\", \"thread\": \"bakery\"}, {\"clip\": \"c03\", \"thread\": \"bakery\"}, {\"clip\": \"c04\", \"thread\": \"contest\"}, {\"clip\": \"c05\", \"thread\": \"contest\"}, {\"clip\": \"c06\", \"thread\": \"\"}, {\"clip\": \"c07\", \"thread\": \"bakery\"}]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"threads\": [{\"id\": \"bakery\", \"label\": \"The bakery\"}, {\"id\": \"contest\", \"label\": \"The contest\"}], \"clips\": [{\"clip\": \"c01\", \"thread\": \"bakery\"}, {\"clip\": \"c02\", \"thread\": \"bakery\"}, {\"clip\": \"c03\", \"thread\": \"bakery\"}, {\"clip\": \"c04\", \"thread\": \"contest\"}, {\"clip\": \"c05\", \"thread\": \"contest\"}, {\"clip\": \"c06\", \"thread\": \"contest\"}, {\"clip\": \"c07\", \"thread\": \"bakery\"}]}" + }, + "done": true + } + ] +} diff --git a/common/testing/draft/runs/youtube.json b/common/testing/draft/runs/youtube.json @@ -0,0 +1,21 @@ +{ + "task": "youtube", + "model": "qwen3:8b", + "note": "Over the basic manifest and report. The first answer is refused (the summary speaks as the speaker; a link) and re-asked; the second is kept.", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"title\": \"What the baker of Synth Kitchen says about the bakery\", \"description\": \"She told us the bakery is not for sale. Watch it at https://synth.example.\"}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"title\": \"What the baker of Synth Kitchen says about the bakery\", \"description\": \"Synth Kitchen's baker says \\\"I would never sell the bakery to a chain\\\" and that she paid for the new mixer herself. In a later stream she says she did not enter the contest this year, and she will not talk about the lease.\"}" + }, + "done": true + } + ] +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] - **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. - **A drafted field of a report video says it was drafted, and a final build refuses it until it is approved.** A field a generation task writes (a card's narration today; on-screen text, a teaser's lines, the cut's order, the flips, the threads and the YouTube text as their tasks land) carries `drafted` — who drafted it, on which model, when — in the manifest. umtool shows **drafted by <model>** and its review state beside the field (the On-screen table, the teaser editor, the narration page) with **Approve** and **Reject** (with a note), and `/browse/<project>/review` (**Review drafts — N** on the project page) lists every drafted field of the cut and what a final build would refuse. Verdicts are kept in `drafts.review.json` beside the manifest, each on the value it was given on, so a re-draft or an edit needs approving again. A **final** build refuses a drafted field not approved (`--drafts-unreviewed` builds the unapproved anyway, never a rejected one); preview and fast builds only warn. A narration written by hand keeps the rule it had, and existing `narration.review.json` verdicts read as they were (new ones are written to `drafts.review.json`). - **A draft never overwrites what you wrote.** A field with words in it and no `drafted` mark is yours: no generation task replaces it, even when asked to redraft. Its draft is kept aside in `<task>-draft.json` and shown under the field in umtool with **Use this**, which writes it as your own edit. Editing a drafted field in umtool makes it yours (its mark goes). - **A report video manifest may carry `publish.youtube { title, description }`** — two strings, a title of at most 100 characters — for the YouTube text a later task drafts. diff --git a/editor/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts @@ -81,6 +81,23 @@ test("the body: each task's needs, and the refusals in words", () => { assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", question: " q ", channels: "x, y" }), { task: "sweep", article: "a", question: "q", channels: ["x", "y"] }); }); +test("a media draft (release 28): a step body as narrate's — its iteration, no copy; entries a step's; an unknown task refused", () => { + for (const task of ["narrate", "cut", "onscreen", "teaser", "flips", "threads", "youtube"]) { + assert.throws(() => parseReportDraftBody({ task, article: "a" }), task === "narrate" ? /names the iteration it voices/ : new RegExp(`a ${task} draft names the iteration it drafts on`)); + assert.throws(() => parseReportDraftBody({ task, article: "a", iteration: 1, copyOf: 1 }), /is a step, not an iteration: it has no copy/); + assert.deepEqual(parseReportDraftBody({ task, article: "a", iteration: 2, model: "qwen3:8b", entries: "c01, c02", force: true }), { + task, + article: "a", + iteration: 2, + model: "qwen3:8b", + entries: ["c01", "c02"], + force: true, + }); + } + assert.throws(() => parseReportDraftBody({ task: "revise-video", article: "a", iteration: 1, feedback: "f", entries: ["c01"] }), /"entries" is a media draft's/); + assert.throws(() => parseReportDraftBody({ task: "cuts", article: "a", iteration: 1 }), /"task" is one of .*cut, onscreen, teaser, flips, threads, youtube/); +}); + test("extractorModel (release 28 F2): a sweep's, a Claude model the price table knows", () => { const sweep = { task: "sweep", article: "a", question: "q", channels: ["x"] }; assert.equal(parseReportDraftBody({ ...sweep, extractorModel: "claude-haiku-5-5" }).extractorModel, "claude-haiku-5-5"); @@ -217,3 +234,25 @@ test("a local narration: draft:local, a step on the iteration, ollama unloaded w const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); assert.ok(m.timeline.find((e: { id: string }) => e.id === "the-bakery").narration.text); }); + +test("a media draft (youtube, release 28 M6): a step on the done iteration, through the job, its field written", async () => { + // synth-basic i1 is done (the narration test above). + const r = await run("youtube"); + ol.push(...r.turns); + const out = await enqueueReportDraft({ task: "youtube", article: "synth-basic", iteration: 1, model: r.model, source }, deps()); + assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); + assert.equal(out.iteration, 1); + assert.equal(getRegistry().get(out.result.jobId)!.queueKey, "draft:local"); + void out.result.stream.cancel(); + const done = await out.result.done; + assert.equal(done.status, "done", await readFile(getRegistry().get(out.result.jobId)!.logPath, "utf8")); + const it = (await readIteration("synth-basic", 1, paths))!; + assert.equal(it.status, "done", "the iteration is left as it was"); + const step = it.steps.find((s) => s.task === "youtube")!; + assert.equal(step.status, "done"); + const m = JSON.parse(await readFile(path.join(projectOf(gen.projectsRoot, "synth-basic", 1), "video.manifest.json"), "utf8")); + assert.equal(m.publish.youtube.title, "What the baker of Synth Kitchen says about the bakery"); + assert.equal(m.drafted["publish.youtube"].task, "youtube"); + const notDone = await enqueueReportDraft({ task: "cut", article: "synth-basic", iteration: 9, model: "qwen3:8b", source }, deps()); + assert.match((notDone.result as { error: string }).error, /has no iteration i9/); +}); diff --git a/editor/app/api/ops/report-draft/route.ts b/editor/app/api/ops/report-draft/route.ts @@ -9,7 +9,7 @@ export const dynamic = "force-dynamic"; // POST { task, article, iteration?, model?, extractorModel?, feedback?, // question?, channels?, from?, to?, copyOf?, maxUsd?, source?, build?, -// cards?, force?, autonomy? } +// cards?, entries?, force?, autonomy? } // -> { ok: true, jobId, iteration, warnings? } // // A generation over an article's iteration (release 27 S6), as a @@ -18,7 +18,11 @@ export const dynamic = "force-dynamic"; // `from`/`to`); the API model runs the agent, a local model the pipeline; // - "revise-report" / "revise-video": a new iteration revising `iteration` // from `feedback`; -// - "narrate": a step on the done iteration `iteration` (`cards`, `force`); +// - a media draft — "narrate", "cut", "onscreen", "teaser", "flips", +// "threads", "youtube" (release 28): a step on the done iteration +// `iteration` that drafts fields of its video manifest (`entries`: only +// these entry ids; `force`: re-draft a field that is a draft already — +// never one the operator wrote; narrate's `cards`); // - "research" (S11): a new research run from `question` (`channels` // optional, `autonomy` propose | limits | auto, default the settings'): // it discovers, proposes, and enqueues what its autonomy allows through diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts @@ -456,3 +456,84 @@ test("revise-video on a local model: one ops batch over the trimmed cut", async const m = JSON.parse(await readFile(path.join(projectOf(projectsRoot, "synth-basic", it.n), "video.manifest.json"), "utf8")); assert.equal(m.timeline.find((e: { id: string }) => e.id === "the-bakery").heading, "About the bakery"); }); + +// ─── release 28 M4–M6: flips, threads, youtube (lane E) ─── + +// i1 done with the basic report and the FULL manifest with its threads taken +// off: an on-screen deck with no left panel, seven clips over three recordings. +async function deckCut(article = "synth-basic") { + const { projectDir } = await doneSweep(article, "basic", { manifest: true }); + const m = JSON.parse(await readFile(path.join(DRAFT, "manifests", "full.video.manifest.json"), "utf8")); + delete m.render.chrome.threads; + for (const e of m.timeline) delete e.thread; + await writeFile(path.join(projectDir!, "video.manifest.json"), `${JSON.stringify(m, null, 2)}\n`); + return projectDir!; +} + +const manifestOf = async (dir: string) => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + +test("flips: the pairs are code's — dates from the records, THEN before NOW, the quotes verbatim; the S0 flips shape (release 28 M4)", async () => { + await drainFake(); + const r = await run("flips"); + ol.push(...r.turns); + const dir = await deckCut(); + const d = deps(); + const out = await runTask({ task: "flips", article: "synth-basic", n: 1, model: r.model, projectsRoot }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const m = await manifestOf(dir); + const expected = JSON.parse(await readFile(path.join(DRAFT, "manifests", "flips.video.manifest.json"), "utf8")).render.chrome.flips; + const strip = (f: { pairs: { id: string }[] }) => f.pairs.map(({ id: _id, ...p }) => p); + assert.deepEqual(strip(m.render.chrome.flips), strip(expected), "one pair, c01 Jan 2026 → c07 Mar 2026, the quotes word for word"); + assert.equal(m.drafted["render.chrome.flips"].task, "flips"); + assert.equal(m.drafted["render.chrome.flips"].attempt, 2); + const draft = JSON.parse(await readFile(path.join(dir, "flips-draft.json"), "utf8")); + const first = draft.units.flips.attempts[0].hard.join(" | "); + assert.match(first, /c04 and c05 are of the same day \(2026-02-10\)/); + assert.match(first, /number 2027 is not in the report/); + // The dates came from the corpus records: the prompt shows them, the clips carry none. + const user = ol.requests.at(-1).messages[1].content as string; + assert.match(user, /- c01 \[2026-01-05\] \(chapter: The bakery\): "I would never sell the bakery to a chain"/); + assert.match(user, /- c07 \[2026-03-01\]/); + const step = (await readIteration("synth-basic", 1, paths))!.steps.find((s) => s.task === "flips")!; + assert.equal(step.status, "done"); +}); + +test("threads: 2 to 4 threads, every clip's thread set, the outcomes from the manifest's verdicts (release 28 M5)", async () => { + await drainFake(); + const r = await run("threads"); + ol.push(...r.turns); + const dir = await deckCut(); + const d = deps(); + const out = await runTask({ task: "threads", article: "synth-basic", n: 1, model: r.model, projectsRoot }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const m = await manifestOf(dir); + assert.deepEqual(m.render.chrome.threads.list, [ + { id: "bakery", label: "The bakery", outcome: { verdict: "CONTRADICTED" } }, + { id: "contest", label: "The contest", outcome: { verdict: "NOT_FOUND" } }, + ]); + const byId = Object.fromEntries(m.timeline.filter((e: { type: string }) => e.type === "clip").map((e: { id: string; thread?: string }) => [e.id, e.thread])); + assert.deepEqual(byId, { c01: "bakery", c02: "bakery", c03: "bakery", c04: "contest", c05: "contest", c06: "contest", c07: "bakery" }); + assert.equal(m.drafted["render.chrome.threads"].task, "threads"); + const draft = JSON.parse(await readFile(path.join(dir, "threads-draft.json"), "utf8")); + const first = draft.units.threads.attempts[0].hard.join(" | "); + assert.match(first, /name “Gordon” is not in the report/); + assert.match(first, /thread 3 \(gordon\) has no clip/); +}); + +test("youtube: the title and one summary paragraph, grounded and third person (release 28 M6)", async () => { + await drainFake(); + const r = await run("youtube"); + ol.push(...r.turns); + const { projectDir } = await doneSweep("synth-basic", "basic", { manifest: true }); + const d = deps(); + const out = await runTask({ task: "youtube", article: "synth-basic", n: 1, model: r.model, projectsRoot }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const m = await manifestOf(projectDir!); + assert.equal(m.publish.youtube.title, "What the baker of Synth Kitchen says about the bakery"); + assert.match(m.publish.youtube.description, /^Synth Kitchen's baker says "I would never sell the bakery to a chain"/); + assert.equal(m.drafted["publish.youtube"].task, "youtube"); + const draft = JSON.parse(await readFile(path.join(projectDir!, "youtube-draft.json"), "utf8")); + const first = draft.units.youtube.attempts[0].hard.join(" | "); + assert.match(first, /the summary: the narrator is third person \(“us”\)/); + assert.match(first, /no links, timestamps, chapters or hashtags/); +}); diff --git a/mcp/src/generation.test.ts b/mcp/src/generation.test.ts @@ -1,6 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { connectWith, fakeEditor, isError, textOf } from "./editorOps.testkit"; +import { GENERATION_PRESETS, sanitizeGeneration } from "yt-dlp-transcript-common/lib/generationSettings"; import { GENERATE_POLL_MS, GENERATE_TASKS, @@ -61,13 +62,8 @@ function editor(opts: { policy?: Record<string, unknown>; runPolls?: number; end if (u.pathname === "/api/ops/settings" && s.method === "GET") return { status: 200, body: { ok: true, key: "generation", value: policy } }; if (u.pathname === "/api/ops/settings" && s.method === "POST") { const routes = (s.body as { patch: { generation: { routes: Record<string, string> } } }).patch.generation.routes; - const presets: Record<string, string> = { - "code,code,code,code,code": "code", - "api,api,api,api,api": "api", - "local,local,local,local,local": "local", - "code,api,local,local,api": "balanced", - }; - policy = { ...policy, routes: routes as typeof policy.routes, preset: presets[Object.values(routes).join(",")] ?? "custom" }; + // The editor's own sanitizer names the preset the routes are. + policy = { ...policy, routes: routes as typeof policy.routes, preset: sanitizeGeneration({ routes }).preset }; return { status: 200, body: { ok: true, changed: ["generation"], value: { generation: policy } } }; } if (u.pathname === "/api/ops/generation-usage") return { status: 200, body: { ok: true, day: "2026-10-13", usd: 1.75, jobs: 2, daily: 20 } }; @@ -130,7 +126,24 @@ test("generation_policy sets a preset as its routes, and one route alone", async assert.equal(a.isError, undefined, a.text); const post = e.sentOf("/api/ops/settings").find((s) => s.method === "POST")!; assert.deepEqual(post.body, { - patch: { generation: { routes: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" } } }, + patch: { + generation: { + routes: { + sweep: "api", + "revise-report": "api", + "revise-video": "api", + narrate: "api", + research: "api", + // The media drafts (release 28) take narrate's route in every preset. + cut: "api", + onscreen: "api", + teaser: "api", + flips: "api", + threads: "api", + youtube: "api", + }, + }, + }, }); assert.match(a.text, /^Set preset api\./); assert.match(a.text, /preset \*\*api\*\*/); @@ -139,7 +152,7 @@ test("generation_policy sets a preset as its routes, and one route alone", async const post2 = e.sentOf("/api/ops/settings").filter((s) => s.method === "POST")[1]; // The whole routes object (the writer merges one level; a nested object replaces). assert.deepEqual(post2.body, { - patch: { generation: { routes: { sweep: "local", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api" } } }, + patch: { generation: { routes: { ...GENERATION_PRESETS.api, sweep: "local" } } }, }); assert.match(one.text, /^Routed sweep to local\./); assert.match(one.text, /preset \*\*custom\*\*/); @@ -158,8 +171,8 @@ test("generation_policy refuses a muddle before it asks the editor", async () => assert.match(a.text, re); } assert.equal(e.sent.length, 0); - const unknown = await generationPolicyTool({ task: "teaser", route: "api" }, e.deps as never); - assert.match(unknown.text, /no task "teaser" — the policy routes sweep, revise-report, revise-video, narrate, research/); + const unknown = await generationPolicyTool({ task: "nope", route: "api" }, e.deps as never); + assert.match(unknown.text, /no task "nope" — the policy routes sweep, revise-report, revise-video, narrate, research/); assert.equal(e.sent.filter((s) => s.method === "POST").length, 0); const none = await generationPolicyTool({}, fakeEditor(() => ({ status: 200, body: {} }), {}).deps as never); assert.equal(none.isError, true); @@ -263,7 +276,8 @@ test("generate: the arguments are checked before any request; research is a task assert.ok(ex.ok && ex.request.kind === "start"); if (ex.ok && ex.request.kind === "start") assert.equal(ex.request.body.extractorModel, "claude-haiku-5-5"); for (const [args, re] of [ - [{ task: "teaser", article: "a" }, /task is one of sweep, revise-report, revise-video, narrate, research/], + [{ task: "nope", article: "a" }, /task is one of sweep, revise-report, revise-video, narrate, research, cut, onscreen, teaser, flips, threads, youtube/], + [{ task: "cut", article: "a", iteration: 1, entries: [] }, /entries is a non-empty list/], [{ task: "sweep", article: "Not An Id" }, /article is an article id/], [{ task: "sweep", article: "a", channels: [] }, /channels is a non-empty list/], [{ task: "sweep", article: "a", iteration: 0 }, /iteration is an iteration number/], diff --git a/mcp/src/generation.ts b/mcp/src/generation.ts @@ -3,6 +3,7 @@ import { GENERATION_PRESET_NAMES, GENERATION_ROUTES, GENERATION_TASKS, + isStepTask, type GenerationPreset, } from "yt-dlp-transcript-common/lib/generationSettings"; import { AUTONOMIES } from "yt-dlp-transcript-common/lib/report/draft/research/decide"; @@ -252,7 +253,7 @@ export function validateGenerateArgs(args: Record<string, unknown>): { ok: true; if (task !== "sweep") return bad("extractorModel is a sweep's (the extractor an API sweep reads batches with)"); if (!String(body.extractorModel).startsWith("claude-")) return bad("extractorModel is a Claude model id: an API sweep's extractor runs on the API"); } - for (const k of ["channels", "cards"] as const) { + for (const k of ["channels", "cards", "entries"] as const) { if (args[k] === undefined) continue; const v = args[k]; if (!Array.isArray(v) || v.length === 0 || v.some((x) => typeof x !== "string" || !x.trim())) { @@ -381,13 +382,13 @@ export function renderIterationSummary( o: { task: string; article: string; jobId: string; marker: Marker | null; iteration: IterationView; dir?: string; files?: Record<string, string | null> }, ): string { const it = o.iteration; - const step = o.task === "narrate" ? [...(it.steps ?? [])].reverse().find((s) => s.task === "narrate" && s.jobId === o.jobId) : undefined; + const step = isStepTask(o.task) ? [...(it.steps ?? [])].reverse().find((s) => s.task === o.task && s.jobId === o.jobId) : undefined; const status = step?.status ?? o.marker?.status ?? it.status; const lines: string[] = []; lines.push(`generate: ${o.task} of ${o.article} i${it.n} — **${status}** on ${step?.model ?? it.model} (job ${o.jobId})`); if (o.marker?.summary) lines.push(o.marker.summary); if (it.error && status !== "done") lines.push(`error: ${it.error}`); - if (step?.detail) lines.push(`narration: ${step.detail}`); + if (step?.detail) lines.push(`${o.task === "narrate" ? "narration" : o.task}: ${step.detail}`); const per = Object.entries(it.usage ?? {}).filter(([, u]) => u.usd > 0); const total = step ? (step.cost ?? 0) : per.reduce((s, [, u]) => s + u.usd, 0); const minutes = o.marker?.minutes ?? it.minutes; @@ -546,7 +547,7 @@ export async function generateTool( const warnings = Array.isArray(a.body.warnings) ? (a.body.warnings as unknown[]).map(String) : []; const head = `generate ${task}: queued as job ${jobId}` + - (n ? `, ${task === "narrate" ? "narrating" : "making"} ${article} i${n}` : ` for ${article}`) + + (n ? `, ${task === "narrate" ? "narrating" : isStepTask(task) ? `drafting its ${task} on` : "making"} ${article} i${n}` : ` for ${article}`) + (body.model ? ` on ${String(body.model)}` : " on the policy's model") + "." + warnings.map((w) => `\n⚠ ${w}`).join(""); @@ -631,6 +632,7 @@ export const GENERATION_TOOLS = [ via: { type: "string", enum: ["api", "local"], description: "Run on this route's model instead of the policy's route — only when the operator asks." }, maxUsd: { type: "number", description: "An API job's cap in USD (else the task's default; never above the settings' max)." }, cards: { type: "array", items: { type: "string" }, description: "narrate: only these card ids." }, + entries: { type: "array", items: { type: "string" }, description: "A media draft (narrate, cut, onscreen, teaser, flips, threads, youtube): only these entry ids." }, force: { type: "boolean", description: "narrate: redraft cards that already have narration; a sweep continuing a research run: continue while proposals still wait.", diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9295,3 +9295,33 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri 2026-10-14): live, the job-end listener and the boot scan are the triggers, and a `refused` or `held` run is retried only at the next end of a report-draft job or a site build, the next boot, or a heartbeat if one is configured. + +## Release 28 lane E: flips, threads, the YouTube text (verified 2026-10-14, branch `r28/media-e`) + +- **The left panel's rules are common's** — `common/lib/report/panels.mjs` (+ `.d.mts`, exported as + `yt-dlp-transcript-common/lib/report/panels.mjs`): `FLIPS_LIMITS`, `flipsOn`, `validateFlips`, + `validateFlipEntries`, `THREADS_LIMITS`, `threadsOn`, `threadOf`, `validateThreads`, `validateThreadEntries`. + umtool's `report-to-video/flips.mjs` and `threads.mjs` re-export them unchanged; never copy them back. +- **A flips pair is code's but for its clips and topic.** The `flips` task (`tasks/flips.ts`) dates each clip + (`tasks/clipEvidence.ts` `clipFacts`): the entry's `date`, else the corpus record's `uploadDate` + (`get_video_metadata` through `deps.corpus`), else the report citation's `date`. The earlier is THEN; one day is + no pair; `when` is `Mon YYYY`; `words` is the clip's quote (or the model's part of it, when the quote says exactly + that), cut at a word to `FLIPS_LIMITS.words` with `…`; the pair id is the topic slugged. A THEN that plays after its + NOW swaps the two clips' places only when `ownerOf(timeline)` is `"drafted"` and the flips will be applied (the + timeline is rewritten through `applyDraft` with the flips provenance), else the pair is refused. +- **A thread's outcome is its last clip's `claim.verdict` in the manifest** (by timeline order), when it has one; the + `threads` task (`tasks/threads.ts`) makes 2 to 4 threads (`THREADS_TASK_COUNT`) and, once the list is applied, sets + every clip's `thread` (a clip in none has the key removed). +- **One left panel:** `flips` refuses a cut with threads and `threads` one with flips, unless `force` and the other is + a draft: then the other's field, its clips' `thread` keys (for threads) and its mark are removed, and the log says + so. Both refuse a cut with no `render.chrome`. +- **`publish.youtube` is drafted by `youtube`** (`tasks/youtube.ts`): title ≤ 100, one summary paragraph ≤ + `YOUTUBE_SUMMARY_MAX` (900), `checkLine(…, {quotes: true})` grounding (words in quotation marks must be a cited + quote's, word for word), no links, timestamps or hashtags. **`checkLine` does not check a line's FIRST word as a + name** (it is the narration grounding, which skips each sentence's first word), so a topic, label or title that + starts with an unknown name passes that check. +- **`out/youtube.txt`** (`youtube-<variant>.txt` for a variant other than `sourced`) is written by build-video after + every chapter mux (the full build, the deck build, `--rail-only`, `--chapters-only`; also under `--no-chapters`, + without chapters) when the manifest has a `publish.youtube` title. `muxChapters` returns `{chapters: [{start, end, + title}], total}`. The composition is `report-to-video/youtube.mjs` (`composeYoutubeText`, `youtubeChapters`, + `youtubeSources`, `momentLinkOf`, `youtubePreview`, `youtubeTextName`), exported as `umtool-report-to-video/youtube`. diff --git a/plans/release-28.md b/plans/release-28.md @@ -578,6 +578,117 @@ Gates (from the worktree root; counts at the branch start → the tip): - umtool `article-research.spec.ts` 3/3 (31.2 s; its prebuild's capped build 29 s), the new auto-continue test included; - umtool `article-iterations.spec.ts` + `article-new.spec.ts` 7/7 (40.6 s); - editor `report-draft.spec.ts` 3/3 (19.2 s; its prebuild's capped build 48 s), with the new boot arming in its server. +### M4, as shipped (2026-10-14, lane E, `r28/media-e`) + +The flips draft (`flips`): THEN/NOW pairs over the cut's clips, `render.chrome.flips`. A step on a done iteration on +M0's scaffold, one unit (the whole field), replacing step 0's "not implemented" refusal. +- **The model** proposes pairs: a topic, two clip ids, and optionally a part of each clip's quote. Rules, no example. +- **Code** does the rest. It dates each clip: the entry's `date` (the operator's, what the header shows), else the + corpus record's `uploadDate` (`get_video_metadata`), else the citation's `date`. The earlier is THEN, whichever + way the model named them, and a pair of one day is refused. Each `when` is written from the date (`Jan 2026`). + A side's `words` is the clip's quote verbatim, or the model's part of it only when the quote says exactly that, + cut at a word to 110 with `…`. The pair id is the topic slugged. Code refuses unknown ids, a clip in two pairs, and + more pairs than `min(24, dated clips / 2)`. The topic is one line of at most 32 characters, grounded by + `checkLine`. +- **Order:** a THEN that plays after its NOW is refused, unless `ownerOf(timeline)` is `"drafted"` and the flips + will be applied. In that case the two clips swap places, and the timeline is written through `applyDraft` with the + flips provenance. A twin id refuses the swap. +- **The build's validators:** `validateFlips` and `validateFlipEntries` run on the cut as it will be, swaps + included. To make that possible they moved to common, as `common/lib/report/panels.mjs` (see M5). The repair keeps + the attempt's pairs that pass when one fails. +- **One left panel (the simplest correct rule):** a cut with threads is refused, unless `force` and the threads are + a draft. In that case the flips replace them: the list, every clip's `thread` and the mark are removed, and the log + says so. Operator's threads are refused even with `force`. A cut with no `render.chrome` is refused. +- Test kit: `draft/runs/flips.json`. Run over the full manifest with its threads taken off: the first answer is + refused (a pair of one day, a number the report lacks) and re-asked. The kept answer reproduces S0's flips manifest + pair, id aside. + +### M5, as shipped (2026-10-14, lane E, `r28/media-e`) + +The threads draft (`threads`): `render.chrome.threads.list` and each clip's `thread`. +- **The model** names the threads (`{id, label}`) and gives each clip a thread or `""`. +- **Code** checks the result: + - 2 to 4 threads (`THREADS_TASK_COUNT`); + - ids are slugged when invalid, and none is listed twice; + - labels are one line of at most 32 characters, grounded; + - every assignment names a clip of the cut and a listed thread, and no clip is in two threads; + - every thread has a clip; + - `validateThreads` and `validateThreadEntries` pass on the cut as it will be. +- **The outcome is code's:** the `claim.verdict` that the thread's last clip (in timeline order) carries in the + manifest, when it has one. The model never writes a verdict. +- **Applied:** `applyDraft(render.chrome.threads, {list})`, then every clip's `thread` is set, and removed from a + clip in no thread. The repair drops failing threads with their clips when two still stand. +- **Mirror of M4:** a cut with flips is refused unless `force` and the flips are a draft, which the threads then + replace. +- **`common/lib/report/panels.mjs`** is now the one copy of the flips' and the threads' limits and validators. + umtool's `flips.mjs` and `threads.mjs` re-export them unchanged (their tests, deck, lint and fixtures-r28 pass + unchanged). +- Test kit: `draft/runs/threads.json`. The first answer is refused (a label naming someone the report does not, a + thread with no clip). The kept answer: bakery CONTRADICTED (c07), contest NOT_FOUND (c06). + +### M6, as shipped (2026-10-14, lane E, `r28/media-e`) + +The YouTube draft (`youtube`), `out/youtube.txt`, and umtool's panel. +- **The task** writes `publish.youtube {title, description}`: a title of one line, at most 100 characters, and one + summary paragraph of at most 900 (`YOUTUBE_SUMMARY_MAX`, room under `validatePublish`'s 5000). Both are grounded + by `checkLine(…, {quotes: true})`: + - names and numbers come from the report and the cut's title and subtitle; + - no stock phrase; + - third person (Q1's `firstPersonProblems`); + - words in quotation marks only when a cited quote says them word for word; + - no links, timestamps or hashtags. + The repair drops a failing sentence of the summary when the title is clean and something is left. +- **`out/youtube.txt`** is composed by code (`umtool/report-to-video/youtube.mjs`, pure; exported + `umtool-report-to-video/youtube`): + - the title, a blank line, the summary; + - `Chapters` from the build's own chapter list: `muxChapters` now returns `{chapters, total}`, the list it muxed; + - `Sources`: a moment link per cited clip, in cut order, each once — `citeUrl`, else the archive's page at + `cite`. +- **Chapters follow YouTube's rules** (ruled here): the first at 0:00, at least three, each at least ten seconds. A + shorter one is folded into the one before it. A list that still falls short, or does not start at 0:00, is left + out, and the build's `youtube` event names why. +- **When it is written:** after every chapter mux (the full build, the deck build, `--rail-only`, + `--chapters-only`), and under `--no-chapters` without the block, whenever the manifest has a `publish.youtube` + title. The file is `youtube-<variant>.txt` for a variant other than `sourced`, as the mp4 is named. +- **umtool:** `YoutubeSection` on the project page shows `out/youtube.txt` (its age; a note when `publish.youtube` + changed since), else the same text composed without chapters (`youtubePreview`), with **Copy** and "drafted by + <model>". Nothing when neither exists. M9 does "Draft with". +- Test kit: `draft/runs/youtube.json`. The first answer is refused (speaks as the speaker, a link). The editor's + `_reportDraft.test.ts` runs a youtube step through the job (step 0's "not implemented" case is now this). + +| Commit | What | +| --- | --- | +| `e4dff898` | `common/lib/report/panels.mjs` (+ `.d.mts`, package export), flips.mjs and threads.mjs re-export it; `report-to-video/youtube.mjs` + `youtube.test.mjs` (6); `muxChapters` returns its list; `writeYoutubeText` after every chapter mux; the `youtube` event | +| `2d97a52c` | `tasks/clipEvidence.ts` (`clipFacts`, `isoDay`, `whenOf`, `checkLine`), `tasks/flips.ts`, `tasks/threads.ts`, `tasks/youtube.ts`, the dispatcher; `panelTasks.test.ts` (10); runs `flips` / `threads` / `youtube`; the MCP's end-to-end tests (3); the editor's report-draft youtube step; the kit README | +| `f4884f7f` | umtool `YoutubeSection` on the project page; e2e `media-draft-e.spec.ts`, `fixtures/youtube-fixture.mjs` | +| `45355fb8` | report-to-video README: the drafted panels, `publish.youtube` and `out/youtube.txt` | +| (this commit) | these records, FACTS "Release 28 lane E", CHANGELOG | + +Lane E's gates (from the worktree root, at `45355fb8`; counts at the branch's start `381156ae` → its tip): +- tsc clean (all packages) before every commit. +- common 4059 → 4069 (+10, `panelTasks.test.ts`); 4068 passed, 1 failed: `fetchPosts.test.ts` "a drain mid-page + waits for the page's cursor…", the phase-1 flake candidate, 8/8 alone. +- mcp 346 → 349/349 (+3); editor 295/295 (one test rewritten, none added); `test:scripts` 874 + 3 skipped → + 880 + 3 skipped (+6, `youtube.test.mjs`). +- `docs env|files|cli --check`, `settings example --check`: clean (nothing regenerated). +- umtool e2e, single specs in the foreground: + - `media-draft-e.spec.ts` 1/1 (5.0 s; a real offline fast build: three chapters, two folded, and the sources); + - `draft-review.spec.ts` + `report-narration.spec.ts` 6/6; + - `projects.spec.ts` + `build.spec.ts` 29/29. + - Each run's prebuild was umtool's capped `next build`, 29 s. +- umtool capped build, corpus linked, through the heavy slot (5 GB): ok, 29 s with 8.5 GB available; the link removed. + +Found and left: +- `checkLine` does not check a line's FIRST word as a name. It is the narration grounding, which skips each + sentence's first word, so a topic, label or title starting with an unknown name passes that check. The tests use a + name mid-line. +- "Use this" on a threads alternative writes the list alone (M0's `writeDraftedField`), not the clips' `thread` + keys the draft assigned. A threads alternative arises only when the operator's threads are forced over, and its + Use this may then leave clips naming the operator's old ids, which the build refuses. +- The media tasks report no progress in this branch. Lane D's scaffold change (`h.progress` per unit, + `progressMetric`) covers these three once merged; they set no `progressMetric` (default `entries`). +- umtool's editor stub answers a media step only for `narrate` (any other task makes a new iteration in the stub). + That is M9's to extend with its buttons. ## Not in this release diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1215,12 +1215,16 @@ export function usage() { "", 'report-draft runs a generation over an article\'s iteration as a', ' report-draft job: {"task": "sweep" | "revise-report" | "revise-video" |', - ' "narrate" | "research", "article", ...} -> {jobId, iteration, warnings?}.', - ' A sweep takes "question"', + ' "research" | a media draft, "article", ...} -> {jobId, iteration,', + ' warnings?}. A sweep takes "question"', ' and "channels" (and "from"/"to"): a new iteration; a revision takes', - ' "iteration" (the one it revises) and "feedback": a new iteration; a', - ' narration takes "iteration" (a done one; "cards"?, "force"?) and is a step', - ' on it. "copyOf" N runs iteration N again on "model". "extractorModel" is', + ' "iteration" (the one it revises) and "feedback": a new iteration. A media', + ' draft — "narrate", "cut", "onscreen", "teaser", "flips", "threads",', + ' "youtube" — takes "iteration" (a done one; "entries"? entry ids,', + ' "force"? re-drafts a field that is a draft already; narrate "cards"?) and', + " is a step on it: it drafts fields of the iteration's video manifest, never", + ' one the operator wrote. "copyOf" N runs iteration N again on "model".', + ' "extractorModel" is', " an API sweep's extractor (a Claude model id; default", ' settings.generation.models.extractor). "model" defaults to', " settings.generation's route for the task (one routed to code needs a model", diff --git a/settings.json.example b/settings.json.example @@ -244,7 +244,13 @@ "revise-report": "api", "revise-video": "local", "narrate": "local", - "research": "api" + "research": "api", + "cut": "local", + "onscreen": "local", + "teaser": "local", + "flips": "local", + "threads": "local", + "youtube": "local" }, "models": { "api": "claude-sonnet-5-5", diff --git a/umtool/components/projects/ReportProject.tsx b/umtool/components/projects/ReportProject.tsx @@ -30,6 +30,7 @@ import ReportBuildChain from "./ReportBuildChain"; import SnapshotButton from "./SnapshotButton"; import DeleteProject from "./DeleteProject"; import TagCitedButton from "./TagCitedButton"; +import YoutubeSection from "./YoutubeSection"; import { RowControls, RowNotes, TimelineList } from "./TimelineEditor"; import GeneratedBanner from "@/components/notes/GeneratedBanner"; import { NotesProvider } from "@/components/notes/NotesProvider"; @@ -759,6 +760,9 @@ export default async function ReportProject({ )} </section> + {/* --- the upload's text (out/youtube.txt, or its preview) --------- */} + <YoutubeSection dir={project.dir} manifest={m as Record<string, unknown>} /> + {/* --- exports --------------------------------------------------- */} <section data-exports="" className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2"> <h2 className="micro mb-1">export</h2> diff --git a/umtool/components/projects/YoutubeSection.tsx b/umtool/components/projects/YoutubeSection.tsx @@ -0,0 +1,53 @@ +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import CopyButton from "@/components/CopyButton"; +import { fmtAgo } from "@/lib/format"; +import { youtubePreview, youtubeTextName } from "umtool-report-to-video/youtube"; + +// The upload's text (release 28 M6): what the build wrote to +// out/youtube.txt — the title, the summary, the chapters and the sources — +// or, before a build, the same text composed from the manifest without the +// chapters. Shown with Copy. Nothing when the cut has no publish.youtube and +// no built text. + +type Props = { dir: string; manifest: Record<string, unknown> }; + +export default async function YoutubeSection({ dir, manifest }: Props) { + const file = path.join(dir, "out", youtubeTextName("sourced")); + const built = await readFile(file, "utf8").catch(() => null); + const mtimeMs = built === null ? null : await stat(file).then((s) => s.mtimeMs, () => null); + const preview = youtubePreview(manifest); + const text = built ?? preview.text; + if (!text) return null; + const yt = (manifest.publish as { youtube?: { title?: string; description?: string } } | undefined)?.youtube; + // The built text starts with the title and the summary as they were then. + const head = [yt?.title?.trim(), yt?.description?.trim()].filter(Boolean).join("\n\n"); + const stale = built !== null && !!head && !built.startsWith(head); + const drafted = (manifest.drafted as Record<string, { model?: string }> | undefined)?.["publish.youtube"]; + return ( + <section + data-youtube={built !== null ? "built" : "preview"} + aria-label="YouTube text" + className="rounded border border-[var(--color-line)] bg-[var(--color-panel)] px-3 py-2" + > + <div className="mb-1 flex flex-wrap items-baseline gap-3"> + <h2 className="micro">youtube</h2> + <span className="num text-[11px] text-[var(--color-dim)]" data-youtube-status=""> + {built !== null + ? `out/${youtubeTextName("sourced")}${mtimeMs ? `, built ${fmtAgo(mtimeMs)}` : ""}${stale ? " — the title or summary has changed since: rebuild" : ""}` + : `preview — ${preview.note}`} + {drafted ? ` · drafted by ${drafted.model ?? "a model"}` : ""} + </span> + <span className="ml-auto"> + <CopyButton text={text} label="Copy" title="copy the YouTube title and description" /> + </span> + </div> + <pre + data-youtube-text="" + className="max-h-[40vh] overflow-y-auto whitespace-pre-wrap break-words font-mono text-[11px] text-[var(--color-text)]" + > + {text} + </pre> + </section> + ); +} diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -26,6 +26,7 @@ import { makeSitesFixture } from "./sites-fixture.mjs"; import { makeIterationsFixture } from "./iterations-fixture.mjs"; import { makeDeleteFixture } from "./delete-fixture.mjs"; import { makeDraftReviewFixture } from "./draft-review-fixture.mjs"; +import { makeYoutubeFixture } from "./youtube-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -1656,6 +1657,8 @@ for (const dir of [BENCH, BUILD, ONSCREEN, ONSCREEN_BUILD, ONSCREEN_POSTS, ONSCR // Release 28: drafted fields to review, and a final build they hold // (draft-review.spec.ts). makeDraftReviewFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); +// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts). +makeYoutubeFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") }); // TWO MORE cached windows for vid1, and they are the regression rather than // decoration. @@ -1958,4 +1961,5 @@ console.log(` takes-fixture (writable: takes/ with 4 takes over 2 gro console.log(` narration-fixture (writable: a narrated card, voiced by the editor stub's tone)`); console.log(` narration-review-fixture (writable: two narrated cards, nothing judged)`); console.log(` draft-review-fixture (writable: drafted on-screen, narration, teaser; an alternative), draft-review-build-fixture`); +console.log(` youtube-fixture (writable: a drafted publish.youtube, built fast to out/youtube.txt)`); console.log(` ${taken} candidate files copied, 2 mix tracks synthesised`); diff --git a/umtool/e2e/fixtures/youtube-fixture.mjs b/umtool/e2e/fixtures/youtube-fixture.mjs @@ -0,0 +1,32 @@ +// What media-draft-e.spec.ts reads (release 28, M6): a cut whose +// publish.youtube was drafted, three cards long enough to make YouTube +// chapters, and two clips over the cached window the build fixtures share — +// so the project page previews the YouTube text, and a fast build writes +// out/youtube.txt with its chapters and sources. Its own, so the other specs' +// projects are never touched. Synthetic, like every fixture. +import { copyFileSync, mkdirSync, writeFileSync } from "node:fs"; +import path from "node:path"; + +const P = (task, model = "qwen3:8b") => ({ task, model, at: "2026-10-13T10:00:00.000Z", iteration: 1, attempt: 1 }); + +/** + * @param {{ reports: string, manifest: Function, cachedWindow: string }} o + * `manifest` is make-fixture's manifest(slug, title, provenance, timeline); + * `cachedWindow` the vid1 0-9 s window the build fixtures share. + */ +export function makeYoutubeFixture({ reports, manifest, cachedWindow }) { + const dir = path.join(reports, "youtube-fixture"); + mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); + const m = manifest("youtube-fixture", "The YouTube Fixture", { siteOrigin: "https://archive.example" }, [ + { type: "card", id: "title", style: "title", seconds: 10, heading: "The YouTube Fixture" }, + { type: "clip", id: "c01", video: "vid1", start: 3.0, end: 6.0, cite: 3, section: 0, lock: true, quote: "and because" }, + { type: "card", id: "k01", style: "chapter", seconds: 10, heading: "The county" }, + { type: "clip", id: "c02", video: "vid1", start: 9.0, end: 12.0, cite: 9, section: 0, lock: true, quote: "another whole sentence" }, + { type: "card", id: "k02", style: "chapter", seconds: 10, heading: "Then" }, + ]); + m.publish = { youtube: { title: "The county said yes", description: "Half a year on, the county said yes, and the fixture says so." } }; + m.drafted = { "publish.youtube": P("youtube") }; + writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); + copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", path.basename(cachedWindow))); + return { dir }; +} diff --git a/umtool/e2e/media-draft-e.spec.ts b/umtool/e2e/media-draft-e.spec.ts @@ -0,0 +1,69 @@ +import { test, expect } from "@playwright/test"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// --------------------------------------------------------------------------- +// Release 28 lane E's media drafts, as umtool shows them (M6): the project +// page's YouTube text — previewed from publish.youtube before a build (the +// sources, no chapters), copied with Copy, then as a fast build writes it to +// out/youtube.txt with the build's own chapters (YouTube's rules) and a moment +// link per cited clip. The flips, threads and youtube tasks themselves run +// over the fake LLM in common's and the MCP's suites; umtool's "Draft with" +// buttons are M9's. Fixture: e2e/fixtures/youtube-fixture.mjs. +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const FIXTURE = path.join(HERE, "..", ".e2e-song"); +const PROJECT = "reports/youtube-fixture"; +const DIR = path.join(FIXTURE, "reports", "youtube-fixture"); +const TITLE = "The county said yes"; +const SUMMARY = "Half a year on, the county said yes, and the fixture says so."; +const SOURCES = ["https://archive.example/?v=testchan%2Fvid1&t=3", "https://archive.example/?v=testchan%2Fvid1&t=9"]; + +test("the YouTube text: a preview before the build, Copy, then out/youtube.txt with chapters and sources", async ({ page, request, context }) => { + test.setTimeout(300_000); + await context.grantPermissions(["clipboard-read", "clipboard-write"]); + await page.goto(`/browse/${PROJECT}`); + const section = page.locator("[data-youtube]"); + await expect(section).toHaveAttribute("data-youtube", "preview"); + await expect(section.locator("[data-youtube-status]")).toContainText("chapters are added by the build"); + await expect(section.locator("[data-youtube-status]")).toContainText("drafted by qwen3:8b"); + const preview = await section.locator("[data-youtube-text]").textContent(); + expect(preview).toBe(`${TITLE}\n\n${SUMMARY}\n\nSources\n${SOURCES.join("\n")}\n`); + await section.getByRole("button", { name: "Copy" }).click(); + await expect(section.locator("[data-copy]")).toHaveAttribute("data-state", "done"); + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(preview); + + // A fast build (hard cuts) writes the text with the build's chapters. + const start = await request.post("/api/report/build", { data: { project: PROJECT, preset: "fast" } }); + expect(start.ok(), await start.text()).toBeTruthy(); + const { job } = (await start.json()) as { job: { id: string } }; + let done: { state: string; error: string | null } = { state: "running", error: null }; + const until = Date.now() + 240_000; + while (Date.now() < until) { + done = (await (await request.get(`/api/report/build?job=${job.id}`)).json()) as typeof done; + if (done.state !== "running") break; + await new Promise((r) => setTimeout(r, 400)); + } + expect(done.state, done.error ?? "").toBe("done"); + const file = path.join(DIR, "out", "youtube.txt"); + expect(existsSync(file)).toBe(true); + const text = readFileSync(file, "utf8"); + const [title, , summary, , chaptersHead, ...rest] = text.split("\n"); + expect([title, summary, chaptersHead]).toEqual([TITLE, SUMMARY, "Chapters"]); + // Five entries; the two under ten seconds after a chapter are folded: three + // chapters, the first at 0:00 (the title card), the clips' at 0:10 and 0:2x. + const chapters = rest.slice(0, rest.indexOf("")); + expect(chapters.length).toBe(3); + expect(chapters[0]).toBe("0:00 The YouTube Fixture"); + expect(chapters[1]).toMatch(/^0:1\d /); + expect(chapters[2]).toMatch(/^0:2\d /); + expect(text.endsWith(`\n\nSources\n${SOURCES.join("\n")}\n`)).toBe(true); + + // The page shows the built text now. + await page.reload(); + await expect(section).toHaveAttribute("data-youtube", "built"); + await expect(section.locator("[data-youtube-status]")).toContainText("out/youtube.txt, built"); + expect(await section.locator("[data-youtube-text]").textContent()).toBe(text); +}); diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md @@ -675,6 +675,39 @@ holds one pair while it plays. - **Punch.** The panel is built for short clips — the line and nothing else — and near-hard cuts (`transition` 0.12); a smaller `footageScale` gives it room. +The flips and the threads can be drafted (release 28): the `flips` and +`threads` tasks (`common/lib/report/draft/tasks/`) write these fields with a +`drafted` mark, through the checks this section describes — the limits and +validators are one copy, `common/lib/report/panels.mjs`, which `flips.mjs` and +`threads.mjs` re-export. A pair's dates, `when`s and words are code's (the +recordings' dates; the quote, verbatim); a thread's outcome is its last clip's +`claim.verdict`. Each task refuses a cut that has the other panel, unless +forced over a draft of it, which it then replaces. + +### `publish.youtube` — the upload's text (`out/youtube.txt`) + +```jsonc +"publish": { "youtube": { "title": "…", // one line, ≤ 100 characters + "description": "…" } } // the summary paragraph (≤ 5000; the youtube task keeps it ≤ 900) +``` + +Every build that muxes chapters (or would have, under `--no-chapters`) writes +`out/youtube.txt` (`youtube-<variant>.txt` for another variant) when the +manifest has `publish.youtube`, composed by code (`youtube.mjs`): + +- the title, a blank line, the description; +- `Chapters`: the build's own chapter list as `m:ss Title`, on YouTube's rules — + the first at 0:00, at least three, each at least ten seconds (a shorter one is + folded into the one before it). A list that still falls short is left out, + and the build's `youtube` event says why; +- `Sources`: a moment link per cited clip, in cut order, each once — its + `citeUrl`, else the archive's page at its `cite` second (a `src` clip without + a `citeUrl` has none). + +umtool's project page shows the text with **Copy** — the built file, or before +a build the same text without the chapters. The `youtube` task drafts the title +and the summary (grounded, third person, quotes only word for word). + ### The `image` entry type A still: the receipts a clip cannot say out loud — a post, a thread, a DM, a diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -143,6 +143,8 @@ import { import { validateClaims } from "./factcheck.mjs"; import { validateThreadEntries } from "./threads.mjs"; import { validateFlipEntries } from "./flips.mjs"; +// The upload's text (release 28 M6): composed by code, written beside the cut. +import { composeYoutubeText, youtubeChapters, youtubeSources, youtubeTextName } from "./youtube.mjs"; // A card's `narration` (release 25): validated, resolved and levelled in // narration.mjs (pure); its synthesized sound is kept in out/narration/ // (narration-store.mjs) by asking the editor (narrate-via-editor.mjs). @@ -408,7 +410,7 @@ export function variantPaths(outRoot, slug, variant) { // printed -- this is a formatting switch, not new instrumentation. // // Events: start, card, clip, fetch, snap, segment, entry-failed, concat, -// chapters, chrome, narrate, note, done. +// chapters, youtube, chrome, narrate, note, done. const HUMAN = { start: (e) => `${e.title} — ${e.entries} entr(ies)`, card: (e) => `card ${e.id}`, @@ -432,6 +434,7 @@ const HUMAN = { "entry-failed": (e) => ` ** ${e.id} failed: ${e.message}`, concat: (e) => `${e.mode === "xfade" ? "crossfading" : "hard-cutting"} ${e.n} segments…`, chapters: (e) => `chapters: ${e.n} marker(s) -> ${e.file}`, + youtube: (e) => `youtube: ${e.file}${e.chapters ? ` (${e.chapters} chapter(s))` : ""}${e.note ? ` — ${e.note}` : ""}`, // The deck's steps. `phase` is schedule | compose | render | cached | overlay. chrome: (e) => `chrome ${e.phase}` + @@ -3947,23 +3950,29 @@ export async function measureChromeSchedule({ manifest, entries, segments, D }) return deckSchedule({ entries, durs, D, render, provenance, metas, posts: manifest.posts ?? [] }); } +// Returns the chapters it muxed (`{ chapters: [{ start, end, title }], total }`, +// seconds) -- the list out/youtube.txt's Chapters are made from -- or null +// when the cut is one segment and gets none. async function muxChapters(finalPath, entries, segments, D, outDir, provenance, fps, deck = false, joins = null, { disclosure = null } = {}) { - if (segments.length < 2) return; + if (segments.length < 2) return null; // The cut's own offsets: under the deck a held clip is longer in the cut // than its file, and every chapter after it starts that much later. const { starts, total } = await cutOffsets(segments, D, fps, joins); const lines = [";FFMETADATA1", ""]; + const chapters = []; for (let i = 0; i < entries.length; i += 1) { // Land just PAST the crossfade, so the marker opens on the incoming clip // rather than on the outgoing one mid-dissolve. const start = i === 0 ? 0 : starts[i] + D; const end = i === entries.length - 1 ? total : starts[i + 1] + D; + const title = await chapterTitle(entries[i], i, provenance, { deck }); + chapters.push({ start, end, title }); lines.push( "[CHAPTER]", "TIMEBASE=1/1000", `START=${Math.round(start * 1000)}`, `END=${Math.round(end * 1000)}`, - `title=${ffmetaEscape(await chapterTitle(entries[i], i, provenance, { deck }))}`, + `title=${ffmetaEscape(title)}`, "", ); } @@ -3984,6 +3993,28 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance, ); await rename(tmp, finalPath); EMIT("chapters", { n: entries.length, file: path.basename(metaPath) }); + return { chapters, total }; +} + +/** + * `out/youtube.txt` (youtube.mjs): the cut's `publish.youtube` title and + * description, the chapters the build just muxed (YouTube's rules, else left + * out with a note) and a moment link per cited clip. Written by every build + * that muxes chapters -- or would have, under --no-chapters -- when the + * manifest has `publish.youtube`; nothing otherwise. + * + * @param {{ chapters: Array<{ start: number, end: number, title: string }>, total: number } | null} muxed + * @param {string | null} [why] why there are no chapters (`--no-chapters`) + */ +async function writeYoutubeText(manifest, entries, outRoot, variant, muxed, why = null) { + const youtube = manifest.publish?.youtube; + if (!youtube?.title) return null; + const { chapters, note } = muxed ? youtubeChapters(muxed.chapters, muxed.total) : { chapters: null, note: `no chapters: ${why ?? "the cut is one segment"}` }; + const text = composeYoutubeText({ youtube, chapters, sources: youtubeSources(entries, manifest.provenance) }); + const file = path.join(outRoot, youtubeTextName(variant)); + await writeFile(file, text, "utf8"); + EMIT("youtube", { file: path.basename(file), chapters: chapters?.length ?? 0, note }); + return file; } /** @@ -4452,7 +4483,8 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } // Under the deck the cut's offsets include the holds: measured, not written. const joins = deck ? segmentJoins(await measureChromeSchedule({ manifest, entries, segments: segs, D })) : null; - await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + const muxed = await muxChapters(finalPath, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + await writeYoutubeText(manifest, entries, outRoot, variant, muxed); return { out: finalPath, failures: [] }; } @@ -4486,9 +4518,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly await assertConcatLength(out, railPlan.total, render.fps, "rail build"); // applyRail re-encodes, so the chapters muxed onto the previous final are // gone. Put them back, or --rail-only quietly ships a chapterless cut. - if (!opts.noChapters) { - await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render), null, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); - } + const muxed = opts.noChapters + ? null + : await muxChapters(out, entries, segs, D, outDir, provenance, render.fps, deckOn(render), null, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null); } EMIT("done", { out, failures: [] }); return { out, failures: [] }; @@ -4594,7 +4627,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } await assertConcatLength(dirs.final, schedule.total, render.fps, "deck build"); // The overlay re-encodes, so the chapters on the previous final are gone. - if (!opts.noChapters) await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + const muxed = opts.noChapters + ? null + : await muxChapters(dirs.final, entries, segs, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null); await pruneFrames(); EMIT("done", { out: dirs.final, failures: [] }); return { out: dirs.final, failures: [] }; @@ -4717,7 +4753,10 @@ export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly // shortest=1), and a hang means an unbounded -loop 1. if (railPlan) await assertConcatLength(final, railPlan.total, render.fps, "rail build"); - if (!opts.noChapters) await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + const muxed = opts.noChapters + ? null + : await muxChapters(final, entries, segments, D, outDir, provenance, render.fps, deckOn(render), joins, { disclosure: await readCutDisclosure(narrationStore, manifest, " ") }); + await writeYoutubeText(manifest, entries, outRoot, variant, muxed, opts.noChapters ? "--no-chapters" : null); // A branded cut with a `thumbnail` gets one beside it. The cut is already // done, so a thumbnail that cannot be made is said, not thrown. diff --git a/umtool/report-to-video/flips.mjs b/umtool/report-to-video/flips.mjs @@ -15,10 +15,12 @@ // threadsGeometry); the two are one region and a cut has one or the other. // // PURE, like threads.mjs. chrome-flips.mjs draws the panel. +// The limits and the validators are common's (lib/report/panels.mjs, release +// 28): the flips draft task checks exactly what the build refuses. +import { FLIPS_LIMITS, flipsOn, validateFlipEntries, validateFlips } from "yt-dlp-transcript-common/lib/report/panels.mjs"; import { planCues } from "./threads.mjs"; -/** The limits: pairs, a topic's, a `when`'s and a side's words' characters. */ -export const FLIPS_LIMITS = Object.freeze({ pairs: Object.freeze([1, 24]), topic: 32, when: 18, words: 110 }); +export { FLIPS_LIMITS, flipsOn, validateFlipEntries, validateFlips }; /** * The panel's motion, in seconds: a pair rises in over `enter`, its NOW card @@ -32,80 +34,6 @@ export const FLIP_MOTION = Object.freeze({ /** How bright the THEN card rests once NOW has landed. */ export const THEN_DIM = 0.5; -const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; -const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); -const oneLine = (v, max) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v) && v.length <= max; - -/** Is the flips panel on: a `render.chrome.flips` with at least one pair. */ -export function flipsOn(render) { - const f = render?.chrome?.flips; - return isObj(f) && Array.isArray(f.pairs) && f.pairs.length > 0; -} - -/** - * Every reason `render.chrome.flips` cannot be built, as sentences. Shape - * only; `validateFlipEntries` checks the pairs against the timeline. - * - * @returns {string[]} - */ -export function validateFlips(f, where = "render.chrome.flips") { - if (f === undefined) return []; - if (!isObj(f)) return [`${where} must be an object`]; - const errors = []; - for (const k of Object.keys(f)) if (k !== "pairs") errors.push(`${where}.${k} is not a flips setting`); - const [lo, hi] = FLIPS_LIMITS.pairs; - if (!Array.isArray(f.pairs) || f.pairs.length < lo || f.pairs.length > hi) return [...errors, `${where}.pairs must be ${lo} to ${hi} pairs`]; - const ids = new Set(); - f.pairs.forEach((p, i) => { - const w = `${where}.pairs[${i}]`; - if (!isObj(p)) { errors.push(`${w} must be an object`); return; } - for (const k of Object.keys(p)) if (!["id", "topic", "then", "now"].includes(k)) errors.push(`${w}.${k} is not a pair key`); - if (typeof p.id !== "string" || !ID_RE.test(p.id)) errors.push(`${w}.id must be letters, digits, _ or -`); - else if (ids.has(p.id)) errors.push(`${w}.id ${p.id} is listed twice`); - else ids.add(p.id); - if (!oneLine(p.topic, FLIPS_LIMITS.topic)) errors.push(`${w}.topic must be one line of at most ${FLIPS_LIMITS.topic} characters`); - for (const side of ["then", "now"]) { - const s = p[side]; - const ws = `${w}.${side}`; - if (!isObj(s)) { errors.push(`${ws} must be an object`); continue; } - for (const k of Object.keys(s)) if (!["entry", "when", "words"].includes(k)) errors.push(`${ws}.${k} is not a side key`); - if (typeof s.entry !== "string" || !s.entry) errors.push(`${ws}.entry must name a timeline entry`); - if (!oneLine(s.when, FLIPS_LIMITS.when)) errors.push(`${ws}.when must be one line of at most ${FLIPS_LIMITS.when} characters`); - if (!oneLine(s.words, FLIPS_LIMITS.words)) errors.push(`${ws}.words must be one line of at most ${FLIPS_LIMITS.words} characters`); - } - }); - return errors; -} - -/** - * The pairs against the timeline: each side names an entry of the cut, a clip - * (not a teaser), the THEN side before the NOW side, and no entry in two pairs. - * - * @returns {string[]} - */ -export function validateFlipEntries(manifest) { - const render = manifest?.render ?? {}; - if (!flipsOn(render)) return []; - const errors = []; - const at = new Map((manifest.timeline ?? []).map((e, i) => [e?.id, { e, i }])); - const used = new Map(); - render.chrome.flips.pairs.forEach((p, i) => { - const w = `render.chrome.flips.pairs[${i}] (${p?.id ?? "?"})`; - const idx = {}; - for (const side of ["then", "now"]) { - const id = p?.[side]?.entry; - const hit = at.get(id); - if (!hit) { errors.push(`${w}.${side}.entry ${id} is not in the timeline`); continue; } - if (hit.e.type === "teaser") errors.push(`${w}.${side}.entry ${id} is a teaser, not a clip`); - if (used.has(id)) errors.push(`${w}.${side}.entry ${id} is already in pair ${used.get(id)}`); - used.set(id, p.id); - idx[side] = hit.i; - } - if (idx.then !== undefined && idx.now !== undefined && idx.then >= idx.now) errors.push(`${w}: its THEN entry must come before its NOW entry`); - }); - return errors; -} - /** The years between two `when`s, when both carry one (`2019`, `May 2019`): else null. */ export function yearsBetween(a, b) { const y = (s) => { diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -40,6 +40,7 @@ "./resolve-windows": "./resolve-windows.mjs", "./shoot-page": "./shoot-page.mjs", "./sources": "./sources.mjs", - "./verify-build": "./verify-build.mjs" + "./verify-build": "./verify-build.mjs", + "./youtube": "./youtube.mjs" } } diff --git a/umtool/report-to-video/threads.mjs b/umtool/report-to-video/threads.mjs @@ -19,10 +19,12 @@ // PURE, like factcheck.mjs: the settings, their validation, the schedule and // the cues. No fs. deck.mjs imports this file -- never the other way round. // chrome-threads.mjs draws the rail. -import { resolveFactcheck, VERDICTS } from "./factcheck.mjs"; +import { resolveFactcheck } from "./factcheck.mjs"; +// The limits and the validators are common's (lib/report/panels.mjs, release +// 28): the threads draft task checks exactly what the build refuses. +import { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads } from "yt-dlp-transcript-common/lib/report/panels.mjs"; -/** The limits: how many threads, a label's and an outcome label's characters. */ -export const THREADS_LIMITS = Object.freeze({ threads: Object.freeze([1, 8]), label: 32, outcome: 24 }); +export { THREADS_LIMITS, threadOf, threadsOn, validateThreadEntries, validateThreads }; /** * The rail's motion, in seconds: a card lights over `light` and its string @@ -37,17 +39,7 @@ export const THREAD_MOTION = Object.freeze({ /** How long before its thread's last clip ends the outcome lands, at most. */ export const OUTCOME_LEAD = 1.8; -/** A thread id: letters, digits and `_ -`. */ -const THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; - const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v); -const oneLine = (v) => typeof v === "string" && v.trim() !== "" && !/[\n\r]/.test(v); - -/** Is the rail on: a `render.chrome.threads` with at least one thread. */ -export function threadsOn(render) { - const t = render?.chrome?.threads; - return isObj(t) && Array.isArray(t.list) && t.list.length > 0; -} /** * The threads with their outcomes resolved: `[{ id, label, outcome: { verdict, @@ -68,75 +60,6 @@ export function resolveThreads(render) { } /** - * Every reason `render.chrome.threads` cannot be built, as sentences (empty: - * it can). validateChrome calls this, so umtool's writer and the build refuse - * the same things. - * - * @returns {string[]} - */ -export function validateThreads(t, where = "render.chrome.threads") { - if (t === undefined) return []; - if (!isObj(t)) return [`${where} must be an object`]; - const errors = []; - for (const k of Object.keys(t)) if (k !== "list") errors.push(`${where}.${k} is not a threads setting`); - const [lo, hi] = THREADS_LIMITS.threads; - if (!Array.isArray(t.list) || t.list.length < lo || t.list.length > hi) { - return [...errors, `${where}.list must be ${lo} to ${hi} threads`]; - } - const seen = new Set(); - t.list.forEach((th, i) => { - const w = `${where}.list[${i}]`; - if (!isObj(th)) { errors.push(`${w} must be an object`); return; } - for (const k of Object.keys(th)) if (!["id", "label", "outcome"].includes(k)) errors.push(`${w}.${k} is not a thread key`); - if (typeof th.id !== "string" || !THREAD_ID_RE.test(th.id)) errors.push(`${w}.id must be letters, digits, _ or -`); - else if (seen.has(th.id)) errors.push(`${w}.id ${th.id} is listed twice`); - else seen.add(th.id); - if (!oneLine(th.label) || th.label.length > THREADS_LIMITS.label) { - errors.push(`${w}.label must be one line of at most ${THREADS_LIMITS.label} characters`); - } - if (th.outcome !== undefined) { - const o = th.outcome; - if (!isObj(o)) { errors.push(`${w}.outcome must be an object`); return; } - for (const k of Object.keys(o)) if (!["verdict", "label"].includes(k)) errors.push(`${w}.outcome.${k} is not an outcome key`); - if (!VERDICTS.includes(o.verdict)) errors.push(`${w}.outcome.verdict must be one of ${VERDICTS.join(", ")}`); - if (o.label !== undefined && (!oneLine(o.label) || o.label.length > THREADS_LIMITS.outcome)) { - errors.push(`${w}.outcome.label must be one line of at most ${THREADS_LIMITS.outcome} characters`); - } - } - }); - return errors; -} - -/** The thread an entry belongs to, or null. */ -export function threadOf(entry) { - return typeof entry?.thread === "string" && entry.thread ? entry.thread : null; -} - -/** - * Every `thread` in the timeline, checked against the list: it names a listed - * thread, it is not on a teaser, and every listed thread has a clip. The - * build refuses with these before it fetches. - * - * @returns {string[]} - */ -export function validateThreadEntries(manifest) { - const errors = []; - const render = manifest?.render ?? {}; - const listed = threadsOn(render) ? new Set(render.chrome.threads.list.map((t) => t?.id)) : new Set(); - const used = new Set(); - (manifest?.timeline ?? []).forEach((e, i) => { - if (e?.thread === undefined || e?.thread === null) return; - const where = `timeline[${i}] (${e.id ?? "?"}).thread`; - if (typeof e.thread !== "string" || !e.thread) { errors.push(`${where} must be a thread id`); return; } - if (e.type === "teaser") { errors.push(`${where}: a teaser belongs to no thread`); return; } - if (!listed.has(e.thread)) { errors.push(`${where} ${e.thread} is not in render.chrome.threads.list`); return; } - used.add(e.thread); - }); - for (const id of listed) if (!used.has(id)) errors.push(`render.chrome.threads: thread ${id} has no clip`); - return errors; -} - -/** * The rail's schedule, in the cut's clock. `segments` are the schedule's, in * order, each `{ id, start, duration, thread }`; `moves` are the footage's * moves for popup posts (deck.mjs footageMoves). diff --git a/umtool/report-to-video/youtube.mjs b/umtool/report-to-video/youtube.mjs @@ -0,0 +1,147 @@ +// THE YOUTUBE TEXT (release 28, M6): what a cut's upload says, composed by +// CODE from `publish.youtube { title, description }` (drafted by the youtube +// task or written by hand), the build's own chapter list and the cut's +// citations. The build writes it to `out/youtube.txt` (`out/youtube-<variant>.txt` +// for a variant other than `sourced`, as the cut's mp4 is named); umtool shows +// and copies it, and previews it the same way, without chapters, before a build. +// +// <title> +// +// <description> +// +// Chapters +// 0:00 <chapter> +// … +// +// Sources +// <a moment link per cited clip, in cut order, each once> +// +// The chapters are YouTube's: the first at 0:00, at least three, each at +// least ten seconds. A chapter shorter than that is folded into the one +// before it (a first one shorter than that takes the next one's span). A list +// that is still too short, or does not start at 0:00, is left out -- and the +// result's `notes` say why. +// +// PURE: no fs. build-video.mjs writes the file. + +/** YouTube's rules for a description's chapters. */ +export const YOUTUBE_CHAPTERS = Object.freeze({ min: 3, minSeconds: 10 }); + +/** `m:ss`, or `h:mm:ss` from an hour. */ +export function chapterStamp(seconds) { + const s = Math.max(0, Math.floor(seconds)); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const ss = String(s % 60).padStart(2, "0"); + return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; +} + +const oneLine = (s) => String(s ?? "").replace(/\s+/g, " ").trim(); + +/** + * The chapters as YouTube takes them, from the build's list (`{ start, end?, + * title }`, seconds, in order; `total` the cut's length for the last one's + * span): `{ chapters, note }` -- `chapters` null when the block is left out, + * `note` saying what was folded or why the block is left out. + * + * @param {Array<{ start: number, end?: number, title: string }> | null | undefined} list + * @param {number | null} [total] + */ +export function youtubeChapters(list, total = null) { + if (!Array.isArray(list) || !list.length) return { chapters: null, note: "no chapters: the build made none" }; + const all = list.map((c) => ({ start: Math.floor(Number(c.start)), title: oneLine(c.title) || "Chapter" })); + if (all[0].start !== 0) return { chapters: null, note: `no chapters: the first starts at ${chapterStamp(all[0].start)}, not 0:00` }; + const end = Number.isFinite(Number(total)) && total !== null + ? Math.floor(Number(total)) + : Math.floor(Number(list.at(-1).end ?? all.at(-1).start + YOUTUBE_CHAPTERS.minSeconds)); + const kept = [all[0]]; + let folded = 0; + for (const c of all.slice(1)) { + if (c.start - kept.at(-1).start < YOUTUBE_CHAPTERS.minSeconds) { + folded++; + // A first chapter too short to stand takes the next one's span under its own 0:00. + continue; + } + kept.push(c); + } + // The last must run ten seconds too. + while (kept.length > 1 && end - kept.at(-1).start < YOUTUBE_CHAPTERS.minSeconds) { + kept.pop(); + folded++; + } + const foldNote = folded ? `${folded} chapter(s) under ${YOUTUBE_CHAPTERS.minSeconds} s folded into the one before` : ""; + if (kept.length < YOUTUBE_CHAPTERS.min) { + return { + chapters: null, + note: `no chapters: ${kept.length} of at least ${YOUTUBE_CHAPTERS.min}` + (foldNote ? ` (${foldNote})` : ""), + }; + } + return { chapters: kept, note: foldNote }; +} + +/** + * A clip's moment link: its `citeUrl` when it has one, else the archive's page + * at the cited second (`cite`, else `start`) -- the link the citation makes + * (`<origin>/?v=<channel>%2F<video>&t=<s>`). A clip from a file beside the + * manifest (`src`) with no `citeUrl` has none; nor has any other entry. + */ +export function momentLinkOf(entry, provenance = {}) { + if (entry?.type !== "clip") return null; + if (entry.citeUrl) return entry.citeUrl; + if (entry.src != null) return null; + const origin = String(provenance?.siteOrigin ?? "").replace(/\/+$/, ""); + const channel = entry.channel ?? provenance?.channelSlug; + if (!origin || !channel || !entry.video) return null; + const at = Number.isFinite(Number(entry.cite)) ? Number(entry.cite) : Number(entry.start); + return `${origin}/?v=${encodeURIComponent(`${channel}/${entry.video}`)}&t=${Math.floor(Number.isFinite(at) ? at : 0)}`; +} + +/** The cut's moment links, in cut order, each once. */ +export function youtubeSources(entries, provenance = {}) { + const out = []; + const seen = new Set(); + for (const e of entries ?? []) { + const href = momentLinkOf(e, provenance); + if (!href || seen.has(href)) continue; + seen.add(href); + out.push(href); + } + return out; +} + +/** + * The text. `chapters` is youtubeChapters' (null: no block); `sources` the + * links. Null when the manifest has no `publish.youtube` title. + * + * @param {{ youtube?: { title?: string, description?: string } | null, chapters?: Array<{ start: number, title: string }> | null, sources?: string[] }} o + * @returns {string | null} + */ +export function composeYoutubeText({ youtube, chapters = null, sources = [] }) { + const title = oneLine(youtube?.title); + if (!title) return null; + const parts = [title]; + const description = String(youtube?.description ?? "").trim(); + if (description) parts.push(description); + if (chapters?.length) parts.push(["Chapters", ...chapters.map((c) => `${chapterStamp(c.start)} ${oneLine(c.title)}`)].join("\n")); + if (sources.length) parts.push(["Sources", ...sources].join("\n")); + return `${parts.join("\n\n")}\n`; +} + +/** The file a variant's text is written to, in the project's `out/`. */ +export function youtubeTextName(variant = "sourced") { + return variant === "sourced" ? "youtube.txt" : `youtube-${variant}.txt`; +} + +/** + * The preview umtool shows before a build: composed the same way, without + * chapters (the build makes them), over the default cut's entries -- an entry + * tagged with another `variant` is left out, as build-video's selectVariant + * leaves it out of `sourced`. + * + * @returns {{ text: string | null, note: string }} + */ +export function youtubePreview(manifest) { + const entries = (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => !e?.variant || e.variant === "sourced"); + const text = composeYoutubeText({ youtube: manifest?.publish?.youtube, chapters: null, sources: youtubeSources(entries, manifest?.provenance) }); + return { text, note: "chapters are added by the build" }; +} diff --git a/umtool/report-to-video/youtube.test.mjs b/umtool/report-to-video/youtube.test.mjs @@ -0,0 +1,91 @@ +// out/youtube.txt's composition (release 28 M6): the title, the summary, the +// chapters on YouTube's rules (0:00 first, at least three, ten seconds each), +// the sources in cut order, each once. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { + chapterStamp, composeYoutubeText, momentLinkOf, youtubeChapters, youtubePreview, youtubeSources, youtubeTextName, YOUTUBE_CHAPTERS, +} from "./youtube.mjs"; + +const FULL = new URL("../../common/testing/draft/manifests/full.video.manifest.json", import.meta.url); +const YT = { title: "What the baker says about the bakery", description: "Synth Kitchen on the bakery and the contest." }; + +test("stamps: m:ss, h:mm:ss from an hour", () => { + assert.equal(chapterStamp(0), "0:00"); + assert.equal(chapterStamp(65.9), "1:05"); + assert.equal(chapterStamp(3725), "1:02:05"); +}); + +test("chapters: 0:00 first, at least three, each ten seconds — short ones folded into the one before", () => { + const list = [ + { start: 0, title: "Title" }, + { start: 4, title: "The bakery" }, // 4 s after the first: folded + { start: 12.4, title: "Not for sale" }, + { start: 30, title: "The contest" }, + { start: 55, title: "Last" }, // 5 s before the end: folded + ]; + const r = youtubeChapters(list, 60); + assert.deepEqual(r.chapters.map((c) => [c.start, c.title]), [[0, "Title"], [12, "Not for sale"], [30, "The contest"]]); + assert.match(r.note, /2 chapter\(s\) under 10 s folded/); + assert.equal(YOUTUBE_CHAPTERS.min, 3); +}); + +test("chapters: fewer than three, or not starting at 0:00, are left out — and the note says why", () => { + const two = youtubeChapters([{ start: 0, title: "A" }, { start: 20, title: "B" }], 40); + assert.equal(two.chapters, null); + assert.match(two.note, /^no chapters: 2 of at least 3/); + const late = youtubeChapters([{ start: 2, title: "A" }, { start: 20, title: "B" }, { start: 40, title: "C" }], 60); + assert.equal(late.chapters, null); + assert.match(late.note, /first starts at 0:02, not 0:00/); + assert.match(youtubeChapters(null).note, /made none/); +}); + +test("sources: a moment link per cited clip in cut order, each once; citeUrl wins; a src clip and a card have none", () => { + const prov = { siteOrigin: "https://synth.example/", channelSlug: "synth-kitchen" }; + const entries = [ + { type: "card", id: "t" }, + { type: "clip", id: "c02", video: "bread-day-01", start: 24.2, cite: 25 }, + { type: "clip", id: "c01", channel: "synth-kitchen", video: "bread-day-01", start: 15 }, + { type: "clip", id: "c02b", video: "bread-day-01", start: 25, cite: 25.9 }, // the same moment again + { type: "clip", id: "x", citeUrl: "https://x.example/post/1" }, + { type: "clip", id: "local", src: "a.mp4", start: 0 }, + ]; + assert.deepEqual(youtubeSources(entries, prov), [ + "https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=25", + "https://synth.example/?v=synth-kitchen%2Fbread-day-01&t=15", + "https://x.example/post/1", + ]); + assert.equal(momentLinkOf({ type: "clip", video: "v" }, {}), null, "no origin: no link"); +}); + +test("the text: title, a blank, the summary, Chapters, Sources; nothing without a title", () => { + const text = composeYoutubeText({ + youtube: YT, + chapters: [{ start: 0, title: "Title" }, { start: 12, title: "Not for sale" }, { start: 75, title: "The contest" }], + sources: ["https://a.example/1", "https://a.example/2"], + }); + assert.equal( + text, + "What the baker says about the bakery\n\nSynth Kitchen on the bakery and the contest.\n\nChapters\n0:00 Title\n0:12 Not for sale\n1:15 The contest\n\nSources\nhttps://a.example/1\nhttps://a.example/2\n", + ); + assert.equal(composeYoutubeText({ youtube: { title: " ", description: "x" } }), null); + assert.equal(composeYoutubeText({ youtube: { title: "T" } }), "T\n"); + assert.equal(youtubeTextName(), "youtube.txt"); + assert.equal(youtubeTextName("full"), "youtube-full.txt"); +}); + +test("the preview: the default cut's sources, no chapters", async () => { + const m = JSON.parse(await readFile(FULL, "utf8")); + m.publish = { youtube: YT }; + m.timeline.push({ type: "clip", id: "only-full", variant: "full", channel: "synth-kitchen", video: "qa-long-03", start: 5, cite: 5 }); + const p = youtubePreview(m); + const lines = p.text.split("\n"); + assert.equal(lines[0], YT.title); + assert.ok(!p.text.includes("Chapters")); + const sources = lines.slice(lines.indexOf("Sources") + 1).filter(Boolean); + assert.equal(sources.length, 7, "seven clips, seven moments"); + assert.ok(!p.text.includes("qa-long-03&t=5"), "an entry of another variant is not in the default cut"); + assert.equal(youtubePreview({ timeline: [] }).text, null); +});