Archilyzer · Source

archilyzer

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

commit ec96f82abd2838dff4e6eb61e6a9f35691d15163
parent 135fd7b2a80be220b61df0ce4277b7f13b17de1a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 22:37:58 -0400

common: the flips, threads and youtube media drafts (r28 M4, M5, M6)

Three specs on the media task scaffold, each one unit (the whole field),
replacing step 0's "not implemented" refusals in the dispatcher:

- flips: the model proposes pairs (a topic, two clip ids, optionally a part
  of each quote); code dates them from the recordings (the entry's date,
  else the corpus record's upload date, else the citation's), makes the
  earlier THEN, refuses one day, writes each `when` and the verbatim words
  (cut at a word), refuses a THEN that plays after its NOW unless the cut's
  order is a draft (then the two clips swap places, the timeline written
  through applyDraft), and runs the build's validators.
- threads: 2 to 4 threads, labels grounded and at most 32 characters, every
  assignment a clip and a listed thread, every thread a clip; a thread's
  outcome is its last clip's verdict in the manifest, never the model's;
  every clip's thread set after the list is applied.
- youtube: publish.youtube's title (one line, at most 100) and one summary
  paragraph (at most 900), grounded, third person, quotes only word for
  word, no links or timestamps; a failing sentence removed when the rest
  stands.

Flips and threads share the left panel: each refuses a cut with the other,
unless forced over a draft, which it then replaces and says so. clipEvidence.ts
holds the clips' facts and checkLine (a short line's grounding). Recorded
runs for the three in the test kit; the MCP's end-to-end tests run them; the
editor's report-draft test runs a youtube step through the job.

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

Diffstat:
Acommon/lib/report/draft/tasks/clipEvidence.ts | 171+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/flips.ts | 363+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/index.ts | 17++++++++++++++---
Acommon/lib/report/draft/tasks/panelTasks.test.ts | 365+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/threads.ts | 280+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/youtube.ts | 160+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
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/app/api/ops/_reportDraft.test.ts | 15++++++++++-----
Mmcp/src/draftTasks.test.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12 files changed, 1508 insertions(+), 9 deletions(-)

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 @@ -3,6 +3,7 @@ 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"; @@ -10,7 +11,9 @@ 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"; @@ -40,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"; @@ -80,12 +88,15 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { return narrate(input, deps); case "research": return research(input, deps); - case "cut": - case "onscreen": - case "teaser": 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/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/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/app/api/ops/_reportDraft.test.ts b/editor/app/api/ops/_reportDraft.test.ts @@ -235,19 +235,24 @@ test("a local narration: draft:local, a step on the iteration, ollama unloaded w assert.ok(m.timeline.find((e: { id: string }) => e.id === "the-bakery").narration.text); }); -test("a media draft this build does not have: a step on the done iteration, failed at the job, saying so", async () => { +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 out = await enqueueReportDraft({ task: "youtube", article: "synth-basic", iteration: 1, model: "qwen3:8b", source }, deps()); + 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, "failed"); + 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, "failed"); - assert.match(step.detail ?? "", /youtube is not implemented in this build/); + 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/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/); +});