Archilyzer · Source

archilyzer

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

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

report-draft: the onscreen task — each clip's title and subtitle, in batches (r28 M2)

tasks/onscreen.ts: one unit per clip entry, asked several to a call (as many
as fit the local prompt cap, at most 8; the re-ask only the refused). The
evidence is the clip's claim (text, verdict), section, quote and source. Code
refuses a title over 60 characters or a subtitle over 90, more than one line,
a title with quotation marks, a subtitle quoting anything but the clip's own
quote word for word (or marks that do not pair up), a name or number the
evidence does not have, and the first person outside a quotation.
grounding.ts: groundedProblems(text, reference, where), the names and numbers
check checkNarration ran inline, now one function both use.

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

Diffstat:
Mcommon/lib/report/draft/grounding.ts | 37+++++++++++++++++++++++++------------
Mcommon/lib/report/draft/tasks/index.ts | 6+++++-
Acommon/lib/report/draft/tasks/onscreen.test.ts | 156+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/onscreen.ts | 207+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/draft/runs/onscreen.json | 20++++++++++++++++++++
5 files changed, 413 insertions(+), 13 deletions(-)

diff --git a/common/lib/report/draft/grounding.ts b/common/lib/report/draft/grounding.ts @@ -213,23 +213,25 @@ export function sentencesOf(text: string): string[] { const hasWord = (normText: string, w: string) => ` ${normText} `.includes(` ${w} `); -export function checkNarration(text: string, input: GroundingInput): GroundingResult { - const hard = new Set<string>(); - const soft = new Set<string>(); +/** + * The numbers (digits or words) and names (a capitalised word past a + * sentence's first that is not a common one) in `text` that `reference` does + * not have, as sentences naming `where` ("the report"; a media task's own + * evidence). What checkNarration grounds; release 28's on-screen and teaser + * drafts ground the same way. + */ +export function groundedProblems(text: string, reference: string, where = "the report"): string[] { + const out = new Set<string>(); const low = text.toLowerCase(); - if (/<[^>]+>/.test(text)) hard.add("has a tag in angle brackets"); - for (const b of BANNED_PHRASES) if (low.includes(b)) hard.add(`stock phrase “${b}”`); - - const ref = input.reference; - const refNorm = strictNormalize(ref); - const refNums = new Set(ref.replace(/,/g, "").match(/\d+/g) ?? []); + const refNorm = strictNormalize(reference); + const refNums = new Set(reference.replace(/,/g, "").match(/\d+/g) ?? []); for (const d of text.match(/\d[\d,]*/g) ?? []) { - if (!refNums.has(d.replace(/,/g, ""))) hard.add(`number ${d} is not in the report`); + if (!refNums.has(d.replace(/,/g, ""))) out.add(`number ${d} is not in ${where}`); } for (const w of low.match(/[a-z]+/g) ?? []) { const n = NUM_WORDS[w]; if (n === undefined) continue; - if (!hasWord(refNorm, w) && !refNums.has(String(n))) hard.add(`number “${w}” is not in the report`); + if (!hasWord(refNorm, w) && !refNums.has(String(n))) out.add(`number “${w}” is not in ${where}`); } for (const sent of sentencesOf(text)) { const toks = sent.match(/[A-Za-z][A-Za-z'’.-]*/g) ?? []; @@ -237,9 +239,20 @@ export function checkNarration(text: string, input: GroundingInput): GroundingRe const t = raw.replace(/^[.\-’']+|[.\-’']+$/g, ""); if (!/^[A-Z]/.test(t) || COMMON_CAPS.has(t)) continue; const n = strictNormalize(t.replace(/['’]s$/, "")); - if (n && !refNorm.includes(n)) hard.add(`name “${t}” is not in the report`); + if (n && !refNorm.includes(n)) out.add(`name “${t}” is not in ${where}`); } } + return [...out]; +} + +export function checkNarration(text: string, input: GroundingInput): GroundingResult { + const hard = new Set<string>(); + const soft = new Set<string>(); + const low = text.toLowerCase(); + if (/<[^>]+>/.test(text)) hard.add("has a tag in angle brackets"); + for (const b of BANNED_PHRASES) if (low.includes(b)) hard.add(`stock phrase “${b}”`); + + for (const p of groundedProblems(text, input.reference)) hard.add(p); if (/(^|\s)'[^']+(\s[^']+){3,}'/.test(text) || /["“”]/.test(text)) { hard.add("text in quotation marks: no quotes in narration"); } diff --git a/common/lib/report/draft/tasks/index.ts b/common/lib/report/draft/tasks/index.ts @@ -5,6 +5,7 @@ import type { MediaStepTask } from "../../../generationSettings"; import type { MediaTaskInput } from "./media"; import { cut, type CutInput } from "./cut"; import { narrate, type NarrateInput } from "./narrate"; +import { onscreen, type OnscreenInput } from "./onscreen"; import { research, type ResearchInput } from "./research"; import { reviseReport, type ReviseReportInput } from "./revise-report"; import { reviseVideo, type ReviseVideoInput } from "./revise-video"; @@ -22,6 +23,7 @@ export { reviseVideo, type ReviseVideoInput } from "./revise-video"; export { narrate, NARRATE_SPEC, type NarrateInput } from "./narrate"; export { cut, CUT_SPEC, CUT_MIN_CLIPS, DEFAULT_MAX_CLIPS, buildCut, cutCandidates, isConverterOrder, type CutInput } from "./cut"; export { loadDeckChecks, type DeckChecks } from "./deckChecks"; +export { onscreen, ONSCREEN_SPEC, ONSCREEN_TITLE_MAX, ONSCREEN_SUBTITLE_MAX, checkOnscreen, type OnscreenInput } from "./onscreen"; // The media task scaffold (release 28, M0): what every media task is. export { ALTERNATIVES_PER_FIELD, @@ -57,7 +59,8 @@ export type TaskInput = | ({ task: "narrate" } & NarrateInput) | ({ task: "research" } & ResearchInput) | ({ task: "cut" } & CutInput) - | ({ task: Exclude<MediaStepTask, "narrate" | "cut"> } & MediaTaskInput); + | ({ task: "onscreen" } & OnscreenInput) + | ({ task: Exclude<MediaStepTask, "narrate" | "cut" | "onscreen"> } & 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). @@ -87,6 +90,7 @@ export function runTask(input: TaskInput, deps: TaskDeps): Promise<TaskResult> { case "cut": return cut(input, deps); case "onscreen": + return onscreen(input, deps); case "teaser": case "flips": case "threads": diff --git a/common/lib/report/draft/tasks/onscreen.test.ts b/common/lib/report/draft/tasks/onscreen.test.ts @@ -0,0 +1,156 @@ +// TASK onscreen (release 28 M2) over the S0 kit's manifests and the basic +// report, against the fake ollama: several clips in one ask, the re-ask only +// for the refused, each code check refusing what it should, the better of two +// kept, a clip with no clean draft not written, the operator's text kept and +// the draft an alternative. Real iterations store and project in a temp dir. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; +import { createIteration, projectOf, readIteration, updateIteration, writeIterationFile } from "../../iterations"; +import { checkOnscreen, isVerbatimOf, onscreen, onscreenBatches, quotedParts, ONSCREEN_SPEC } from "./onscreen"; +import type { DraftFile } from "./media"; +import type { TaskDeps } from "./types"; + +const DRAFT = new URL("../../../../testing/draft/", import.meta.url); +const kit = async (rel: string) => JSON.parse(await readFile(new URL(rel, DRAFT), "utf8")); + +let tmp: string; +let ol: FakeOllama; +before(async () => { + tmp = await mkdtemp(path.join(os.tmpdir(), "onscreen-task-")); + ol = await startFakeOllama(); +}); +after(async () => { + await ol.close(); + await rm(tmp, { recursive: true, force: true }); +}); + +let caseN = 0; +async function project(manifest: unknown) { + caseN++; + const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) }; + const projectsRoot = path.join(tmp, `projects-${caseN}`); + await mkdir(paths.articlesDir, { recursive: true }); + await createIteration("synth-basic", { kind: "sweep", model: "qwen3:8b", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); + const report = await kit("reports/basic.report.json"); + await writeIterationFile("synth-basic", 1, "report.json", report, paths); + const dir = projectOf(projectsRoot, "synth-basic", 1); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`); + await writeFile(path.join(dir, "report.json"), JSON.stringify(report)); + await updateIteration("synth-basic", 1, { status: "done", projectDir: dir }, paths); + const lines: string[] = []; + const progress: unknown[] = []; + const deps: TaskDeps = { + llm: { ollama: { baseUrl: ol.url } }, + corpus: { source: "none", tools: [], call: async () => "" }, + cuesOf: async () => null, + paths, + log: (l) => lines.push(l), + progress: (p) => progress.push(p), + now: () => new Date("2026-10-13T12:00:00.000Z"), + }; + const manifestNow = async () => JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); + const draft = async () => JSON.parse(await readFile(path.join(dir, "onscreen-draft.json"), "utf8")) as DraftFile; + const input = (o: Record<string, unknown> = {}) => ({ article: "synth-basic", n: 1, model: "qwen3:8b", projectsRoot, ...o }); + return { dir, paths, deps, lines, progress, manifestNow, draft, input, report }; +} + +const entry = (m: { timeline: { id: string }[] }, id: string) => m.timeline.find((e) => e.id === id) as Record<string, any>; + +test("onscreen, the recorded run: six clips in one ask, the four refused asked again, the better of two kept, a clip with none clean not written", async () => { + const m = await kit("manifests/basic.video.manifest.json"); + const p = await project(m); + const r = await kit("runs/onscreen.json"); + const asked: string[] = []; + ol.push(...r.turns.map((t: unknown) => (body: { messages: { content: string }[] }) => (asked.push(body.messages.at(-1)!.content), t))); + const out = await onscreen(p.input(), p.deps); + assert.equal(out.status, "done", `${out.summary}\n${p.lines.join("\n")}`); + assert.equal(ol.remaining(), 0); + assert.equal(asked.length, 2, "one ask for six clips, one re-ask"); + assert.match(asked[0]!, /### Clip c01[\s\S]*### Clip c06/); + assert.doesNotMatch(asked[1]!, /### Clip c01|### Clip c05/); + assert.match(asked[1]!, /Your last drafts were refused: c02: the title has quotation marks/); + assert.match(out.summary, /^5 clip\(s\) titled \(undo: /); + const after = await p.manifestNow(); + assert.deepEqual(entry(after, "c01").onscreen, { title: "She will not sell to a chain", subtitle: '"I would never sell the bakery to a chain"' }); + assert.deepEqual(entry(after, "c02").onscreen, { title: "The oven story, denied", subtitle: '"we never said that about the old oven"' }); + assert.deepEqual(entry(after, "c03").onscreen, { title: "Who paid for the mixer", subtitle: '"I paid for the new mixer myself"' }); + assert.equal(entry(after, "c04").onscreen.title, "Out of the contest this year"); + assert.equal(entry(after, "c04").drafted.onscreen.attempt, 2); + assert.equal(entry(after, "c05").drafted.onscreen.attempt, 1); + assert.equal(entry(after, "c06").onscreen, undefined, "no clean draft: not written"); + const file = await p.draft(); + const c06 = file.units.c06 as { attempts: { hard: string[] }[] }; + assert.match(c06.attempts[0]!.hard.join(), /number 2024 is not in the clip's evidence/); + assert.match(c06.attempts[1]!.hard.join(), /name “Marco” is not in the clip's evidence/); + const c04 = file.units.c04 as { attempts: { hard: string[] }[] }; + assert.match(c04.attempts[0]!.hard.join(), /the title is \d+ characters \(at most 60\)/); + const c03 = file.units.c03 as { attempts: { hard: string[] }[] }; + assert.match(c03.attempts[0]!.hard.join(), /the subtitle quotes “I bought the mixer”, which is not the clip's quote word for word/); + assert.deepEqual(p.progress, [ + { metric: "entries", current: 0, total: 6 }, + { metric: "entries", current: 6, total: 6 }, + ]); + const it = (await readIteration("synth-basic", 1, p.paths))!; + assert.equal(it.checks!.find((c) => c.name === "onscreen")!.ok, false, "a clip not written fails the check"); + assert.equal(it.steps.find((s) => s.task === "onscreen")!.status, "done"); +}); + +test("onscreen's checks, each alone", () => { + const u = { quote: "I would never sell the bakery to a chain", evidence: "Report: Synth Kitchen\nSection: The bakery\nQuote: \"I would never sell the bakery to a chain\"\nSource: Bread day, 2026-01-05" }; + const hard = (title: string, subtitle?: string) => checkOnscreen({ title, ...(subtitle ? { subtitle } : {}) }, u).hard; + assert.deepEqual(hard("Not for sale", "The baker on a chain"), []); + assert.deepEqual(hard("Not for sale", '"never sell the bakery"'), [], "a verbatim part of the quote"); + assert.deepEqual(hard("Not for sale", "“Never sell the bakery,” on Bread day"), [], "curly marks, case and punctuation aside"); + assert.match(hard("x".repeat(61)).join(), /the title is 61 characters \(at most 60\)/); + assert.match(hard("Not for sale", "y".repeat(91)).join(), /the subtitle is 91 characters \(at most 90\)/); + assert.match(hard("Not for\nsale").join(), /the title is more than one line/); + assert.match(hard('"Not for sale"').join(), /the title has quotation marks/); + assert.match(hard("The ‘chain’ line").join(), /the title has quotation marks/); + assert.deepEqual(hard("She won't sell"), [], "an apostrophe is not a quotation"); + assert.match(hard("Not for sale", '"never sell it"').join(), /quotes “never sell it”, which is not the clip's quote word for word/); + assert.match(hard("Not for sale", 'She said "never sell').join(), /quotation marks do not pair up/); + assert.match(hard("Not for sale", "Sold in 2025").join(), /number 2025 is not in the clip's evidence/); + assert.deepEqual(hard("Not for sale", "Bread day, 2026"), []); + assert.match(hard("Not for sale", "Her friend Marco agrees").join(), /name “Marco” is not in the clip's evidence/); + assert.match(hard("I will never sell").join(), /the narrator is third person/); + assert.deepEqual(quotedParts('a "b c" d «e»'), { parts: ["b c", "e"], balanced: true }); + assert.equal(isVerbatimOf("sell the", "I would never sell the bakery"), true); + assert.equal(isVerbatimOf("sel the", "I would never sell the bakery"), false, "whole words"); +}); + +test("onscreen: the operator's text kept (forced, the draft an alternative); entries asks only those; batches fit the local cap", async () => { + const full = await kit("manifests/full.video.manifest.json"); + const p = await project(full); + // c01 and c04 hold the operator's text: skipped unforced, so c02 alone is asked. + ol.push(jsonReply({ entries: [{ id: "c02", title: "The oven story, denied", subtitle: "" }] })); + const one = await onscreen(p.input({ entries: ["c01", "c02", "c04"] }), p.deps); + assert.equal(one.status, "done", `${one.summary}\n${p.lines.join("\n")}`); + const f1 = await p.draft(); + assert.deepEqual(Object.keys(f1.units).sort(), ["c01", "c02", "c04"]); + assert.match(String(f1.units.c01!.skipped), /the operator's/); + // Forced over c01: its words stand, the draft is an alternative. + ol.push(jsonReply({ entries: [{ id: "c01", title: "She will not sell to a chain", subtitle: "" }] })); + const forced = await onscreen(p.input({ entries: ["c01"], force: true }), p.deps); + assert.match(forced.summary, /^0 clip\(s\) titled, 1 as alternatives/); + const after = await p.manifestNow(); + assert.deepEqual(entry(after, "c01").onscreen, entry(full, "c01").onscreen); + assert.deepEqual(entry(after, "c02").onscreen, { title: "The oven story, denied" }); + const alt = (await p.draft()).alternatives; + assert.deepEqual(alt.map((a) => [a.target.entry, a.reason, (a.value as { title: string }).title]), [["c01", "operator", "She will not sell to a chain"]]); + assert.equal(ol.remaining(), 0); + + // Batches: at most eight, and as many as fit a small cap. + const ctx = { manifest: full, report: p.report, input: p.input(), handle: { deps: p.deps } } as never; + const units = (await ONSCREEN_SPEC.units(ctx)) as never[]; + const many = Array.from({ length: 20 }, (_, i) => ({ ...(units[i % units.length] as object), id: `x${i}` })) as never[]; + assert.deepEqual(onscreenBatches(many, ctx).map((b) => b.length), [8, 8, 4]); + const small = { ...(ctx as object), handle: { deps: { ...p.deps, llm: { ollama: { baseUrl: ol.url, promptCapTokens: 1100 } } } } } as never; + const sizes = onscreenBatches(many, small).map((b) => b.length); + assert.ok(sizes.every((n) => n >= 1 && n < 8) && sizes.reduce((a, b) => a + b, 0) === 20, String(sizes)); +}); diff --git a/common/lib/report/draft/tasks/onscreen.ts b/common/lib/report/draft/tasks/onscreen.ts @@ -0,0 +1,207 @@ +// TASK onscreen — each clip's on-screen title and subtitle (release 28 M2). +// A STEP on a done iteration (./media.ts): one unit per clip entry (or the +// `entries` asked for), the field `onscreen.{title, subtitle}`. +// +// The evidence of a clip is what the report says of it: the claim it cites +// (its text and verdict), its section, its quote, its source and date. Several +// clips are asked in one call (`batch`), as many as fit the local model's +// prompt cap (at most ONSCREEN_BATCH_MAX); a re-ask carries only the clips +// refused. Code checks every line: the title at most 60 characters, the +// subtitle at most 90, one line each; the title quotes nothing, and the +// subtitle quotes only words of the clip's own quote, verbatim (inside +// quotation marks); no name or number the evidence does not have; and the +// narrator's third person outside a quotation. The better of two attempts is +// kept; a clip whose on-screen text is the operator's is never replaced. + +import { strictNormalize } from "../../../citations/verify"; +import { CHARS_PER_TOKEN, ollamaConfigOf, promptCapOf, providerOf, structuredPromptEstimate } from "../../../llm"; +import { firstPersonProblems, groundedProblems } from "../grounding"; +import type { ManifestEntry } from "../videoOps"; +import { cutCandidates } from "./cut"; +import { runMediaTask, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; +import type { TaskDeps, TaskResult } from "./types"; + +export const ONSCREEN_TITLE_MAX = 60; +export const ONSCREEN_SUBTITLE_MAX = 90; +// The most clips one ask carries (an API model too: a review reads them as a set). +export const ONSCREEN_BATCH_MAX = 8; +// The room a re-ask's words take on top of a batch's prompt. +const RETRY_ROOM_CHARS = 1500; + +export type OnscreenInput = MediaTaskInput; + +export type OnscreenValue = { title: string; subtitle?: string }; + +type OnscreenUnit = MediaUnit & { + entry: ManifestEntry; + // The clip's own words: what the subtitle may quote. + quote: string; + // The evidence block shown to the model; names and numbers are grounded in it. + evidence: string; +}; + +type Obj = Record<string, any>; +const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v); + +// A quotation: double marks (straight or curly), guillemets, or curly singles. +const QUOTED_RE = /"([^"]*)"|“([^”]*)”|«([^»]*)»|‘([^’]*)’/g; +const QUOTE_MARKS_RE = /["“”«»„‟]|‘[^’]*’/; + +/** The quoted parts of a line, and whether its marks pair up. */ +export function quotedParts(text: string): { parts: string[]; balanced: boolean } { + const parts: string[] = []; + for (const m of text.matchAll(QUOTED_RE)) parts.push((m[1] ?? m[2] ?? m[3] ?? m[4] ?? "").trim()); + const rest = text.replace(QUOTED_RE, " "); + return { parts, balanced: !/["“”«»„‟]/.test(rest) && !/‘/.test(rest) }; +} + +/** Is `part` the quote's own words, in order (punctuation and case aside)? */ +export function isVerbatimOf(part: string, quote: string): boolean { + const p = strictNormalize(part); + return !!p && ` ${strictNormalize(quote)} `.includes(` ${p} `); +} + +/** Every code check of one clip's on-screen text: `hard` refuses it. */ +export function checkOnscreen(v: OnscreenValue, u: Pick<OnscreenUnit, "quote" | "evidence">): { hard: string[]; soft: string[] } { + const hard: string[] = []; + const title = v.title; + const sub = v.subtitle ?? ""; + if (!title.trim()) hard.push("no title"); + for (const [name, text, max] of [["title", title, ONSCREEN_TITLE_MAX], ["subtitle", sub, ONSCREEN_SUBTITLE_MAX]] as const) { + if (/[\r\n]/.test(text)) hard.push(`the ${name} is more than one line`); + if (text.trim().length > max) hard.push(`the ${name} is ${text.trim().length} characters (at most ${max})`); + } + if (QUOTE_MARKS_RE.test(title)) hard.push("the title has quotation marks: a title quotes nobody"); + const { parts, balanced } = quotedParts(sub); + if (!balanced) hard.push("the subtitle's quotation marks do not pair up"); + for (const part of parts) { + if (!isVerbatimOf(part, u.quote)) hard.push(`the subtitle quotes “${part}”, which is not the clip's quote word for word`); + } + // Names and numbers: in the evidence (a quoted part is the quote's own). + const said = `${title}. ${sub.replace(QUOTED_RE, " ")}`; + hard.push(...groundedProblems(said, u.evidence, "the clip's evidence")); + hard.push(...firstPersonProblems(`${title}. ${sub}`)); + return { hard: [...new Set(hard)], soft: [] }; +} + +const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); + +function unitsOf(ctx: MediaContext<OnscreenInput>): OnscreenUnit[] { + const { manifest, report } = ctx; + const byEntry = new Map(cutCandidates(manifest, report).map((c) => [c.entry, c])); + const out: OnscreenUnit[] = []; + const seen = new Set<string>(); + let chapter = ""; + for (const e of manifest.timeline) { + if (e.type === "card" && e.style === "chapter") chapter = String(e.heading ?? ""); + if (e.type !== "clip" || seen.has(e.id)) continue; + seen.add(e.id); + const c = byEntry.get(e.id); + const verdict = c?.claim?.verdict ?? (isObj(e.claim) ? e.claim.verdict : undefined); + const quote = String(e.quote ?? c?.quote ?? ""); + const lines = [ + `Report: ${String(report.title ?? "")}`, + chapter ? `Section: ${chapter}` : "", + c?.claim ? `Claim${verdict ? ` [${verdict}]` : ""}: ${stripCites(c.claim.text)}` : verdict ? `Verdict: ${verdict}` : "", + quote ? `Quote: "${quote}"` : "", + [c?.label, c?.date || e.date].filter(Boolean).length ? `Source: ${[c?.label, c?.date || e.date].filter(Boolean).join(", ")}` : "", + ].filter(Boolean); + out.push({ id: e.id, target: { entry: e.id, field: "onscreen" }, label: chapter || undefined, entry: e, quote, evidence: lines.join("\n") }); + } + return out; +} + +export function onscreenSystem(): string { + const rules = [ + "For each clip, write the text shown on screen while it plays: a title that says what the clip shows, in plain words, and a subtitle that adds who, when or what is at stake.", + `The title is one line of at most ${ONSCREEN_TITLE_MAX} characters, and it has no quotation marks.`, + `The subtitle is one line of at most ${ONSCREEN_SUBTITLE_MAX} characters. It may quote the speaker only with words from that clip's quote, exactly as they are, inside double quotation marks.`, + "Use only names and numbers that appear in that clip's evidence.", + "Write in the third person, in sentence case: no I, me, my, we or our outside a quotation.", + "Say what the clip shows; do not add facts, and do not put the verdict in the speaker's mouth.", + ]; + return ( + "You write on-screen text for the clips of a short evidence video. " + + `Rules: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + + 'Answer with "entries": one {"id", "title", "subtitle"} per clip, its id exactly as given.' + ); +} + +const SCHEMA = { + type: "object", + properties: { + entries: { + type: "array", + items: { + type: "object", + properties: { id: { type: "string" }, title: { type: "string" }, subtitle: { type: "string" } }, + required: ["id", "title", "subtitle"], + }, + }, + }, + required: ["entries"], +}; + +const userOf = (units: OnscreenUnit[]) => + `${units.map((u) => `### Clip ${u.id}\n${u.evidence}`).join("\n\n")}\n\nWrite the on-screen title and subtitle of ${units.length === 1 ? "this clip" : `each of these ${units.length} clips`}.`; + +/** The units in asks: as many per ask as fit the local prompt cap, at most ONSCREEN_BATCH_MAX. */ +export function onscreenBatches(units: OnscreenUnit[], ctx: Pick<MediaContext<OnscreenInput>, "input" | "handle">): OnscreenUnit[][] { + const local = providerOf(ctx.input.model) === "local"; + const cap = local ? promptCapOf(ollamaConfigOf(ctx.handle.deps.llm, ctx.input.model)) - Math.ceil(RETRY_ROOM_CHARS / CHARS_PER_TOKEN) : Number.POSITIVE_INFINITY; + const system = onscreenSystem(); + const out: OnscreenUnit[][] = []; + let cur: OnscreenUnit[] = []; + for (const u of units) { + const next = [...cur, u]; + const fits = next.length <= ONSCREEN_BATCH_MAX && (!local || structuredPromptEstimate({ system, user: userOf(next), schema: SCHEMA }) <= cap); + if (fits || !cur.length) cur = next; + else { + out.push(cur); + cur = [u]; + } + } + if (cur.length) out.push(cur); + return out; +} + +/** One clip's answer to its value (a throw is a hard failure). */ +export function parseOnscreen(raw: unknown): OnscreenValue { + const o = isObj(raw) ? raw : {}; + const title = typeof o.title === "string" ? o.title.trim() : ""; + const subtitle = typeof o.subtitle === "string" ? o.subtitle.trim() : ""; + if (!title && !subtitle) throw new Error("no title and no subtitle"); + return { title, ...(subtitle ? { subtitle } : {}) }; +} + +/** On-screen text as a media task (./media.ts): one unit per clip, asked in batches. */ +export const ONSCREEN_SPEC: MediaTaskSpec<OnscreenUnit, OnscreenValue, OnscreenInput> = { + task: "onscreen", + noun: "clip", + verb: "titled", + progressMetric: "entries", + units: (ctx) => unitsOf(ctx), + schema: () => SCHEMA, + system: () => onscreenSystem(), + user: (u) => userOf([u]), + batch: { + group: (units, ctx) => onscreenBatches(units, ctx), + schema: () => SCHEMA, + system: () => onscreenSystem(), + user: (units) => userOf(units), + split(answer) { + const list = isObj(answer) && Array.isArray(answer.entries) ? answer.entries : []; + const out: Record<string, unknown> = {}; + for (const e of list) if (isObj(e) && typeof e.id === "string" && !(e.id.trim() in out)) out[e.id.trim()] = e; + return out; + }, + }, + parse: (raw) => parseOnscreen(raw), + check: (v, u) => checkOnscreen(v, u), + toField: (v) => ({ title: v.title, ...(v.subtitle ? { subtitle: v.subtitle } : {}) }), + describe: (v) => `${v.title}${v.subtitle ? ` — ${v.subtitle}` : ""}`, +}; + +export async function onscreen(input: OnscreenInput, deps: TaskDeps): Promise<TaskResult> { + return runMediaTask(ONSCREEN_SPEC, input, deps); +} diff --git a/common/testing/draft/runs/onscreen.json b/common/testing/draft/runs/onscreen.json @@ -0,0 +1,20 @@ +{ + "task": "onscreen", + "model": "qwen3:8b", + "turns": [ + { + "message": { + "role": "assistant", + "content": "{\"entries\": [{\"id\": \"c01\", \"title\": \"She will not sell to a chain\", \"subtitle\": \"\\\"I would never sell the bakery to a chain\\\"\"}, {\"id\": \"c02\", \"title\": \"\\\"Never said that\\\"\", \"subtitle\": \"On the old oven\"}, {\"id\": \"c03\", \"title\": \"Who paid for the mixer\", \"subtitle\": \"\\\"I bought the mixer\\\"\"}, {\"id\": \"c04\", \"title\": \"She did not enter the contest this year, she says, and explains it\", \"subtitle\": \"Pie stream\"}, {\"id\": \"c05\", \"title\": \"Why she stayed out\", \"subtitle\": \"The judges were her friends\"}, {\"id\": \"c06\", \"title\": \"Lease talks in 2024\", \"subtitle\": \"Her lawyer said to keep quiet\"}]}" + }, + "done": true + }, + { + "message": { + "role": "assistant", + "content": "{\"entries\": [{\"id\": \"c02\", \"title\": \"The oven story, denied\", \"subtitle\": \"\\\"we never said that about the old oven\\\"\"}, {\"id\": \"c03\", \"title\": \"Who paid for the mixer\", \"subtitle\": \"\\\"I paid for the new mixer myself\\\"\"}, {\"id\": \"c04\", \"title\": \"Out of the contest this year\", \"subtitle\": \"From the pie stream\"}, {\"id\": \"c06\", \"title\": \"Lease talks with Marco\", \"subtitle\": \"Her lawyer said to keep quiet\"}]}" + }, + "done": true + } + ] +}