commit 53cbdb10126c1100d44e3b41bb297dea407bb451 parent b3d53c78f83fd4f1edaaf8e1ed5fc9e45a950f6f Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Wed, 14 Oct 2026 04:08:32 -0400 Merge branch 'ux/integration' into ux/p3 Diffstat:
16 files changed, 258 insertions(+), 25 deletions(-)
diff --git a/common/controller/researchAutoContinue.test.ts b/common/controller/researchAutoContinue.test.ts @@ -26,6 +26,7 @@ import { researchAutoContinueTick, UNBUILT_CHECK, } from "./researchAutoContinue"; +import { approveResearch } from "./researchRuns"; let tmp: string; let paths: Paths; @@ -198,6 +199,43 @@ test("the heartbeat and job ends racing continue once; a claim held elsewhere is assert.equal((await sweepsOf("synth-auto-stale", stale)).length, 1); }); +test("the operator's last decision settles an auto run, and it continues by itself — no job has to end (release 28 smoke)", async () => { + const article = "synth-auto-decided"; + const n = await makeRun(article, { + channels: ["synth-kitchen"], + proposals: [ + prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/5" }, "done", { doneAt: "2026-10-13T10:00:00.000Z" }), + prop("p02", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/6" }, "proposed", { note: "past the run's caps" }), + ], + }); + assert.ok(armResearchAutoContinue(deps(), { bootScan: false, env: {} })); + const r = await approveResearch({ article, iteration: n, ids: ["p02"], approve: false, note: "too large" }, { paths, editor: {} as never }); + assert.ok(r.ok); + assert.equal(r.view.phase, "ready"); + const rec = await until(async () => { + const x = await recOf(article, n); + return x.autoContinue?.status === "continued" ? x : null; + }, "the continuation"); + const sweeps = await sweepsOf(article, n); + assert.equal(sweeps.length, 1); + assert.deepEqual(rec.continuedBy, [sweeps[0]!.n]); + await ended(sweeps[0]!.jobId!); + // A decision that leaves the run waiting fires nothing. + const other = "synth-auto-still-waiting"; + const m = await makeRun(other, { + channels: ["synth-kitchen"], + proposals: [ + prop("p01", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/7" }, "proposed"), + prop("p02", "import-video", { slug: "synth-kitchen", url: "https://video.example/v/8" }, "proposed"), + ], + }); + const w = await approveResearch({ article: other, iteration: m, ids: ["p01"], approve: false }, { paths, editor: {} as never }); + assert.ok(w.ok); + assert.equal(w.view.phase, "wait"); + await new Promise((res) => setTimeout(res, 100)); + assert.equal((await sweepsOf(other, m)).length, 0); +}); + test("propose and limits never continue by themselves; a proposal waiting for approval holds an auto run", async () => { for (const autonomy of ["propose", "limits"] as const) { const article = `synth-auto-${autonomy}`; diff --git a/common/controller/researchAutoContinue.ts b/common/controller/researchAutoContinue.ts @@ -62,7 +62,7 @@ import { listCorpusBuilds } from "../lib/report/draft/tasks/corpusSource"; import { readResearchState, widenedChannels, type AutoContinueRecord, type ResearchRecord } from "../lib/report/draft/research/state"; import { dailyCapRefusal, dayUsage, utcDay } from "./generationUsage"; import { enqueueReportDraft, REPORT_DRAFT_JOB_KIND, type ReportDraftDeps } from "./reportDraft"; -import { markContinued, researchState, takeWatchedRun } from "./researchRuns"; +import { markContinued, onResearchSettled, researchState, takeWatchedRun } from "./researchRuns"; export const CLAIM_STALE_MS = 10 * 60_000; @@ -334,6 +334,19 @@ export function armResearchAutoContinue(deps: ReportDraftDeps, o: { log?: (line: void scanAutoContinue(state.deps, state.log).catch(() => {}); } }); + // The operator's last decision on a run's proposals (approve-research): the + // run may be ready with no job left to end. + const offJobs = state.off; + const offSettled = onResearchSettled((article, n) => { + void maybeAutoContinue(article, n, state.deps).then( + (r) => report(article, n, r, null, state.log), + (e) => state.log?.(`research auto-continue: ${article} i${n}: ${(e as Error).message}`), + ); + }); + state.off = () => { + offJobs(); + offSettled(); + }; globalThis.__yttResearchAutoContinue__ = state; if (o.bootScan !== false) void scanAutoContinue(deps, o.log).catch(() => {}); return true; diff --git a/common/controller/researchRuns.ts b/common/controller/researchRuns.ts @@ -203,6 +203,25 @@ export function parseResearchApproveBody(b: Record<string, unknown>): ResearchAp export type ResearchOutcome = { id: string; status?: Proposal["status"]; jobId?: string; note?: string; error?: string }; +// SETTLED: the operator's decisions left a run with nothing to wait for. The +// auto-continue (./researchAutoContinue.ts) listens: a decision is the trigger +// a job's end is for an acquisition, and nothing else would notice it while +// the heartbeat is off. On globalThis, as onJobEnd's listeners are, so every +// copy of this module the server bundles shares one set. +type SettledListener = (article: string, n: number) => void; +declare global { + // eslint-disable-next-line no-var + var __yttResearchSettled__: Set<SettledListener> | undefined; +} +const settledListeners = (): Set<SettledListener> => (globalThis.__yttResearchSettled__ ??= new Set()); + +export function onResearchSettled(l: SettledListener): () => void { + settledListeners().add(l); + return () => { + settledListeners().delete(l); + }; +} + // The operator's yes or no on a research run's proposals (no ids: its state). export async function approveResearch( raw: Record<string, unknown>, @@ -216,7 +235,7 @@ export async function approveResearch( } const jobOf = deps.jobOf ?? jobOfPaths(deps.paths); try { - return await serial(`${body.article}/${body.iteration}`, async () => { + const res = await serial(`${body.article}/${body.iteration}`, async () => { const { it, state } = await readRun(body.article, body.iteration, deps.paths); if (body.ids.length && (it.status === "queued" || it.status === "running")) { throw new ResearchInputError(`"${body.article}" i${it.n} is ${it.status}: its proposals are the run's until it ends`); @@ -238,6 +257,17 @@ export async function approveResearch( const now = (await readIteration(body.article, it.n, deps.paths)) ?? it; return { ok: true as const, view: viewOf(body.article, now, state, phase), outcomes }; }); + // Outside the run's lock: a listener may take it. + if (body.ids.length && res.view.phase === "ready") { + for (const l of settledListeners()) { + try { + l(body.article, body.iteration); + } catch { + // a listener's failure is its own + } + } + } + return res; } catch (e) { return { ok: false, error: (e as Error).message }; } diff --git a/common/lib/report/draft/grounding.ts b/common/lib/report/draft/grounding.ts @@ -225,6 +225,8 @@ export function groundedProblems(text: string, reference: string, where = "the r const low = text.toLowerCase(); const refNorm = strictNormalize(reference); const refNums = new Set(reference.replace(/,/g, "").match(/\d+/g) ?? []); + // A number the reference spells out ("about four ferrets") is that number in digits too. + for (const w of refNorm.split(/\s+/)) if (NUM_WORDS[w] !== undefined) refNums.add(String(NUM_WORDS[w])); for (const d of text.match(/\d[\d,]*/g) ?? []) { if (!refNums.has(d.replace(/,/g, ""))) out.add(`number ${d} is not in ${where}`); } diff --git a/common/lib/report/draft/tasks/clipEvidence.ts b/common/lib/report/draft/tasks/clipEvidence.ts @@ -14,6 +14,7 @@ import { extractJsonObject } from "../../../parseStdoutJson"; import { checkNarration, type GroundingInput, type GroundingResult } from "../grounding"; import type { ManifestEntry, VideoManifest } from "../videoOps"; import type { MediaReport } from "./media"; +import { isTitleCase, titleAsSentence } from "./onscreen"; import type { CorpusToolsLike } from "./types"; export type ClipClaim = { id?: string; text: string; verdict?: string }; @@ -140,6 +141,24 @@ export function fitLines(lines: string[], budget: number): { text: string; omitt return { text: kept.join("\n"), omitted: lines.length - kept.length }; } +const FIT_SMALL = new Set(["a", "an", "the", "and", "or", "of", "to", "in", "on", "for", "with", "at", "by", "from", "as", "but"]); + +/** + * A short line (a flip's topic, a thread's label) fitted to `max` characters + * in code, never by asking again: a line over it keeps the part before a colon + * or a dash when that part fits, else drops words from its end — and a small + * word left dangling — until it fits. A line that fits is returned as it is. + */ +export function fitShortLine(text: string, max: number): string { + const t = text.trim(); + if (t.length <= max) return t; + const head = t.split(/\s*[:—–]\s*|\s+-\s+/)[0]!.trim(); + if (head && head.length <= max && head !== t) return head; + const words = t.split(/\s+/); + while (words.length > 1 && (words.join(" ").length > max || FIT_SMALL.has(words.at(-1)!.toLowerCase()))) words.pop(); + return words.join(" ").replace(/[\s,;:.]+$/, ""); +} + const QUOTED = /“([^”]+)”|"([^"]+)"/g; /** @@ -151,6 +170,20 @@ const QUOTED = /“([^”]+)”|"([^"]+)"/g; * 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 { + // A Title Case line is checked in its sentence case, and a capital left over + // that the report lacks is soft (./onscreen.ts titleLineGrounding says why). + if (isTitleCase(text)) { + const r = checkLineAsIs(titleAsSentence(text, g.reference), g, quotes); + const names = r.hard.filter((h) => h.startsWith("name “")); + return { + hard: r.hard.filter((h) => !h.startsWith("name “")), + soft: [...r.soft, ...names.map((h) => `${h} (a Title Case word — check it is not a name)`)], + }; + } + return checkLineAsIs(text, g, quotes); +} + +function checkLineAsIs(text: string, g: GroundingInput, quotes: boolean): GroundingResult { if (!quotes) return checkNarration(text, g); const hard: string[] = []; const said = g.quotes.map((q) => ` ${strictNormalize(q)} `); diff --git a/common/lib/report/draft/tasks/fitShortLine.test.ts b/common/lib/report/draft/tasks/fitShortLine.test.ts @@ -0,0 +1,11 @@ +// fitShortLine (./clipEvidence.ts): a flip topic or a thread label fitted in code. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { fitShortLine } from "./clipEvidence"; + +test("fitShortLine (release 28 smoke): a label past its limit is fitted in code — the part before a colon, else whole words off its end", () => { + assert.equal(fitShortLine("Insulinoma: Disease and Management", 32), "Insulinoma"); + assert.equal(fitShortLine("Rescue growth and staffing and the vets", 32), "Rescue growth and staffing"); + assert.equal(fitShortLine("The bakery", 32), "The bakery"); + assert.equal(fitShortLine("Supercalifragilisticexpialidociousnessness", 32).length > 32, true, "one word is left for the check to refuse"); +}); diff --git a/common/lib/report/draft/tasks/flips.ts b/common/lib/report/draft/tasks/flips.ts @@ -32,7 +32,7 @@ import { applyDraft, clearDrafted, entriesWithId, ownerOf } from "../../drafted. 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 { checkLine, clipFacts, clipLine, fitLines, fitShortLine, 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"; @@ -293,7 +293,7 @@ export const FLIPS_SPEC: MediaTaskSpec<FlipsUnit, FlipsValue, FlipsInput> = { pairs: list .filter((p): p is Record<string, unknown> => !!p && typeof p === "object") .map((p) => ({ - topic: oneLine(p.topic), + topic: fitShortLine(oneLine(p.topic), FLIPS_LIMITS.topic), then: oneLine(p.then), now: oneLine(p.now), ...(typeof p.thenWords === "string" && p.thenWords.trim() ? { thenWords: p.thenWords } : {}), diff --git a/common/lib/report/draft/tasks/onscreen.test.ts b/common/lib/report/draft/tasks/onscreen.test.ts @@ -11,7 +11,8 @@ 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, isTitleCase, isVerbatimOf, onscreen, onscreenBatches, quotedParts, titleAsSentence, ONSCREEN_SPEC } from "./onscreen"; +import { checkOnscreen, isTitleCase, isVerbatimOf, onscreen, onscreenBatches, quotedParts, titleAsSentence, titleLineGrounding, ONSCREEN_SPEC } from "./onscreen"; +import { groundedProblems } from "../grounding"; import type { DraftFile } from "./media"; import type { TaskDeps } from "./types"; @@ -124,9 +125,10 @@ test("onscreen's checks, each alone", () => { assert.equal(isVerbatimOf("sel the", "I would never sell the bakery"), false, "whole words"); }); -test("onscreen: a Title Case title passes as its sentence case; an unknown name in one still fails (release 28 M9 ruling)", () => { +test("onscreen: a Title Case title passes as its sentence case; an unknown name in one is flagged soft (release 28 M9 ruling, smoke)", () => { const u = { quote: "I would never sell the bakery to a chain", evidence: "Report: Synth Kitchen\nSection: The bakery\nClaim: The baker says she will not sell to a chain.\nQuote: \"I would never sell the bakery to a chain\"\nSource: Bread day, 2026-01-05" }; const hard = (title: string) => checkOnscreen({ title }, u).hard; + const soft = (title: string) => checkOnscreen({ title }, u).soft; // Ordinary Title Case: every word capitalised, none a name. assert.deepEqual(hard("The Baker Will Never Sell The Bakery"), []); assert.deepEqual(hard("She Refuses To Sell To A Chain"), []); @@ -134,8 +136,11 @@ test("onscreen: a Title Case title passes as its sentence case; an unknown name // A name the evidence has keeps its capital and passes. assert.deepEqual(hard("Synth Kitchen Will Not Sell"), []); // A name it lacks still fails, Title Case or not. - assert.match(hard("Why Marco Says The Bakery Stays").join(), /name “Marco” is not in the clip's evidence/); - assert.match(hard("The Bakery Stays, Says Marco").join(), /name “Marco” is not in the clip's evidence/); + // In a Title Case title an unknown capital is soft (the review holds it): code + // cannot tell a headline word from a name the evidence lacks. + assert.match(soft("Why Marco Says The Bakery Stays").join(), /name “Marco” is not in the clip's evidence/); + assert.match(soft("The Bakery Stays, Says Marco").join(), /name “Marco” is not in the clip's evidence/); + assert.deepEqual(hard("Why Marco Says The Bakery Stays"), []); assert.match(hard("The bakery stays, says Marco").join(), /name “Marco” is not in the clip's evidence/); assert.equal(isTitleCase("The Baker Will Never Sell"), true); assert.equal(isTitleCase("The baker will never sell"), false); @@ -174,3 +179,15 @@ test("onscreen: the operator's text kept (forced, the draft an alternative); ent 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)); }); + +test("short lines (release 28 smoke): a Title Case word the evidence lacks is soft, numbers stay hard; a spelled-out number matches its digits", () => { + const ev = "The rescue grew from about four ferrets to 56. Loki was found at 55."; + const t = titleLineGrounding("Ferret Rescue Expansion", ev, "the report"); + assert.deepEqual(t.hard, []); + assert.match(t.soft.join(), /name “Expansion”.*Title Case/); + // Not Title Case: an unknown name is hard, as it always was. + assert.match(titleLineGrounding("The rescue hired Gordon", ev, "the report").hard.join(), /name “Gordon”/); + // A number is hard in either case; "four" in the evidence is 4. + assert.match(titleLineGrounding("Ferret Rescue Grows To 70", ev, "the report").hard.join(), /number 70/); + assert.deepEqual(groundedProblems("Did they grow from 4 to 56?", ev), []); +}); diff --git a/common/lib/report/draft/tasks/onscreen.ts b/common/lib/report/draft/tasks/onscreen.ts @@ -115,6 +115,25 @@ export function titleAsSentence(title: string, evidence: string): string { }); } +/** + * The names-and-numbers check of one short line (an on-screen title, a teaser + * line). A Title Case line is checked in its sentence case (titleAsSentence), + * and what is left capitalised and absent from the evidence is SOFT: without a + * lexicon code cannot tell an ordinary headline word ("Expansion") from a name + * the evidence lacks, so it is said to the reviewer (the drafts review holds a + * final build until the line is approved) rather than refused. Numbers, and + * names in a line that is not Title Case, stay hard. + */ +export function titleLineGrounding(text: string, evidence: string, where: string): { hard: string[]; soft: string[] } { + if (!isTitleCase(text)) return { hard: groundedProblems(text, evidence, where), soft: [] }; + const hard: string[] = []; + const soft: string[] = []; + for (const p of groundedProblems(titleAsSentence(text, evidence), evidence, where)) { + (p.startsWith("name ") ? soft : hard).push(p.startsWith("name ") ? `${p} (a Title Case word — check it is not a name)` : p); + } + return { hard, soft }; +} + /** 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[] = []; @@ -135,10 +154,11 @@ export function checkOnscreen(v: OnscreenValue, u: Pick<OnscreenUnit, "quote" | // Title Case title is checked in its sentence case (titleAsSentence): its // capitals are not a name's signal, so an ordinary word is lowercased and an // unknown name still stands out. - const said = `${titleAsSentence(title, u.evidence)}. ${sub.replace(QUOTED_RE, " ")}`; - hard.push(...groundedProblems(said, u.evidence, "the clip's evidence")); + const t = titleLineGrounding(title, u.evidence, "the clip's evidence"); + hard.push(...t.hard); + hard.push(...groundedProblems(sub.replace(QUOTED_RE, " "), u.evidence, "the clip's evidence")); hard.push(...firstPersonProblems(`${title}. ${sub}`)); - return { hard: [...new Set(hard)], soft: [] }; + return { hard: [...new Set(hard)], soft: [...new Set(t.soft)] }; } const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); diff --git a/common/lib/report/draft/tasks/teaser.test.ts b/common/lib/report/draft/tasks/teaser.test.ts @@ -16,7 +16,7 @@ import { promisify } from "node:util"; import { jsonReply, startFakeOllama, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; import { createIteration, projectOf, updateIteration, writeIterationFile } from "../../iterations"; import { loadDeckChecks, type DeckChecks } from "./deckChecks"; -import { checkTeaser, claimGist, parseTeaser, teaser, teaserEvidence } from "./teaser"; +import { checkTeaser, claimGist, fitTeaserLines, parseTeaser, teaser, teaserEvidence } from "./teaser"; import type { DraftFile } from "./media"; import type { TaskDeps } from "./types"; @@ -106,9 +106,13 @@ test("teaser's checks, each alone; the build's validateTeaser is one of them", a assert.match(hard(["Synth Kitchen", "“The bakery”", "The contest"]).join(), /line 2 has quotation marks/); assert.deepEqual(hard(["Synth Kitchen", "The baker's bakery", "The contest"]), [], "an apostrophe is not a quotation"); assert.match(hard(["Synth Kitchen", "The bakery", "In 2025"]).join(), /line 3: number 2025 is not in the report/); - assert.match(hard(["Synth Kitchen", "The bakery", "Ask Marco"]).join(), /line 3: name “Marco” is not in the report/); - // A middle line is a title: past its row's fit the build refuses it. - assert.match(hard(["Synth Kitchen", "The bakery and the contest and the oven", "The contest"]).join(), /it would not build: .*lines\[1\]/); + assert.match(hard(["Synth Kitchen", "The bakery", "Then ask Marco"]).join(), /line 3: name “Marco” is not in the report/); + // A Title Case line's unknown capital is soft (the review holds it). + assert.match(checkTeaser(["Synth Kitchen", "The bakery", "Ask Marco"], u).soft.join(), /line 3: name “Marco”/); + // A middle line is a title: past its row's fit, code sets its end as the + // second tier; a line no split can fit (one long word) the build refuses. + assert.deepEqual(hard(["Synth Kitchen", "The bakery and the contest and the oven", "The contest"]), []); + assert.match(hard(["Synth Kitchen", "Thebakeryandthecontestandtheovenandmore", "The contest"]).join(), /it would not build: .*lines\[1\]/); // Without the build's check nothing is written. assert.match(hard(["Synth Kitchen", "The bakery", "The contest"], { ...u, deck: null as never }).join(), /not available, so the lines are not written/); assert.equal(claimGist('She says she would not sell: "I would never sell the bakery to a chain"'), "She says she would not sell"); @@ -141,3 +145,13 @@ test("teaser: the operator's lines kept (forced, the draft an alternative); a te assert.equal((await q.manifestNow()).timeline.some((e: { type: string }) => e.type === "teaser"), false, "no teaser added"); assert.equal(ol.remaining(), 0); }); + +test("teaser: a line past its role's row gets its end as the second tier; one that fits, or cannot be split, stays as written", () => { + const long = "Why can a glucose crash save a life?"; // 36: a title fits 34 + assert.deepEqual(fitTeaserLines(["Overline", long, "Kicker"]), ["Overline", { text: long, break: "life?" }, "Kicker"]); + assert.deepEqual(fitTeaserLines(["Overline", "Short title", "Kicker"]), ["Overline", "Short title", "Kicker"]); + // Roles follow position: one line is a title, two are an overline and a title. + assert.deepEqual(fitTeaserLines([long]), [{ text: long, break: "life?" }]); + assert.deepEqual(fitTeaserLines([long, long]), [long, { text: long, break: "life?" }]); + assert.deepEqual(fitTeaserLines(["Overline", "x".repeat(40), "Kicker"]), ["Overline", "x".repeat(40), "Kicker"]); +}); diff --git a/common/lib/report/draft/tasks/teaser.ts b/common/lib/report/draft/tasks/teaser.ts @@ -18,7 +18,7 @@ import { strictNormalize } from "../../../citations/verify"; import { applyDraft, entriesWithId } from "../../drafted.mjs"; -import { groundedProblems } from "../grounding"; +import { titleLineGrounding } from "./onscreen"; import type { ManifestEntry, VideoManifest } from "../videoOps"; import type { DeckChecks } from "./deckChecks"; import { runMediaTask, type MediaContext, type MediaReport, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; @@ -32,6 +32,35 @@ export const TEASER_QUOTE_RUN = 5; // The row each role fits (deck.mjs TEASER_LIMITS.fit): the prompt's rule; the // build's validator is the check. const ROLE_FIT = { overline: 64, title: 34, kicker: 56 }; +// A `break` (the line's end, drawn as the smaller second tier) fits this row. +const SUB_FIT = 66; + +export type TeaserLine = string | { text: string; break: string }; + +/** + * The lines as the card draws them: a line longer than its role's row (roles + * follow position: with three or more lines the first is the overline, the + * last the kicker, the rest titles; two are an overline and a title; one is a + * title) becomes `{ text, break }`, its end set as the second tier at the last + * word boundary where the first tier fits the role and the end fits the + * second tier's row. A line that cannot be split so stays as written, and the + * build's check refuses it. Code fits the rows; the model only writes words. + */ +export function fitTeaserLines(lines: string[]): TeaserLine[] { + const roleOf = (i: number): keyof typeof ROLE_FIT => + lines.length >= 3 ? (i === 0 ? "overline" : i === lines.length - 1 ? "kicker" : "title") : lines.length === 2 && i === 0 ? "overline" : "title"; + return lines.map((line, i) => { + const fit = ROLE_FIT[roleOf(i)]; + if (line.length <= fit) return line; + const words = line.split(/\s+/); + for (let k = words.length - 1; k >= 1; k--) { + const head = words.slice(0, k).join(" "); + const tail = words.slice(k).join(" "); + if (head.length <= fit && tail.length <= SUB_FIT) return { text: line, break: tail }; + } + return line; + }); +} export const NEW_TEASER_ID = "teaser"; export type TeaserInput = MediaTaskInput; @@ -96,11 +125,12 @@ export function quoteRunIn(line: string, quotes: readonly string[]): string | nu /** The teaser entry these lines would make. */ export const teaserEntryOf = (u: Pick<TeaserUnit, "entry" | "id">, lines: string[]): ManifestEntry => - ({ ...(u.entry ?? { type: "teaser", id: u.id }), lines }) as ManifestEntry; + ({ ...(u.entry ?? { type: "teaser", id: u.id }), lines: fitTeaserLines(lines) }) as ManifestEntry; /** Every code check of a teaser's lines: `hard` refuses them. */ export function checkTeaser(lines: string[], u: Pick<TeaserUnit, "entry" | "id" | "evidence" | "quotes" | "deck">): { hard: string[]; soft: string[] } { const hard: string[] = []; + const soft: string[] = []; if (lines.length < TEASER_MIN_LINES || lines.length > TEASER_MAX_LINES) hard.push(`${lines.length} lines (${TEASER_MIN_LINES} to ${TEASER_MAX_LINES})`); lines.forEach((l, i) => { const n = `line ${i + 1}`; @@ -110,13 +140,15 @@ export function checkTeaser(lines: string[], u: Pick<TeaserUnit, "entry" | "id" if (QUOTE_MARKS_RE.test(l)) hard.push(`${n} has quotation marks: a teaser reads no quote out`); const run = quoteRunIn(l, u.quotes); if (run) hard.push(`${n} repeats a quote ("${run}"): the clips say it; the teaser does not read it out`); - for (const p of groundedProblems(l, u.evidence, "the report")) hard.push(`${n}: ${p}`); + const g = titleLineGrounding(l, u.evidence, "the report"); + for (const p of g.hard) hard.push(`${n}: ${p}`); + for (const p of g.soft) soft.push(`${n}: ${p}`); }); if (!hard.length) { if (!u.deck) hard.push("the build's teaser check (deck.mjs validateTeaser) is not available, so the lines are not written"); else for (const e of u.deck.validateTeaser(teaserEntryOf(u, lines), `teaser ${u.id}`)) hard.push(`it would not build: ${e}`); } - return { hard, soft: [] }; + return { hard, soft }; } export function teaserSystem(): string { @@ -197,7 +229,7 @@ export const TEASER_SPEC: MediaTaskSpec<TeaserUnit, string[], TeaserInput> = { }); manifest.timeline.splice(at < 0 ? manifest.timeline.length : at + 1, 0, { type: "teaser", id: u.id } as ManifestEntry); } - return applyDraft(manifest, { entry: u.id, field: "lines", value, provenance, force }); + return applyDraft(manifest, { entry: u.id, field: "lines", value: fitTeaserLines(value as string[]), provenance, force }); }, describe: (lines) => lines.join(" / "), }; diff --git a/common/lib/report/draft/tasks/threads.ts b/common/lib/report/draft/tasks/threads.ts @@ -31,7 +31,7 @@ import { THREADS_LIMITS, flipsOn, validateThreadEntries, validateThreads } from 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 { checkLine, clipFacts, clipLine, fitLines, fitShortLine, 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"; @@ -218,7 +218,7 @@ export const THREADS_SPEC: MediaTaskSpec<ThreadsUnit, ThreadsValue, ThreadsInput 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) })), + threads: objs(a.threads).map((t) => ({ id: oneLine(t.id), label: fitShortLine(oneLine(t.label), THREADS_LIMITS.label) })), assign: objs(a.clips).map((c) => ({ clip: oneLine(c.clip), thread: oneLine(c.thread) })), }; }, diff --git a/common/testing/draft/runs/threads.json b/common/testing/draft/runs/threads.json @@ -6,7 +6,7 @@ { "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\"}]}" + "content": "{\"threads\": [{\"id\": \"bakery\", \"label\": \"The bakery\"}, {\"id\": \"contest\", \"label\": \"The contest\"}, {\"id\": \"gordon\", \"label\": \"A talk 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 }, diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -3966,7 +3966,9 @@ async function muxChapters(finalPath, entries, segments, D, outDir, provenance, const start = i === 0 ? 0 : starts[i] + D; const end = i === entries.length - 1 ? total : starts[i + 1] + D; const title = await chapterTitle(entries[i], i, provenance, { deck }); - chapters.push({ start, end, title }); + // `section`: the entry opens one of the cut's sections (a card) -- what + // out/youtube.txt's Chapters keep (youtube.mjs youtubeChapters). + chapters.push({ start, end, title, section: entries[i]?.type === "card" }); lines.push( "[CHAPTER]", "TIMEBASE=1/1000", diff --git a/umtool/report-to-video/youtube.mjs b/umtool/report-to-video/youtube.mjs @@ -44,11 +44,16 @@ const oneLine = (s) => String(s ?? "").replace(/\s+/g, " ").trim(); * span): `{ chapters, note }` -- `chapters` null when the block is left out, * `note` saying what was folded or why the block is left out. * - * @param {Array<{ start: number, end?: number, title: string }> | null | undefined} list + * @param {Array<{ start: number, end?: number, title: string, section?: boolean }> | null | undefined} list * @param {number | null} [total] */ export function youtubeChapters(list, total = null) { if (!Array.isArray(list) || !list.length) return { chapters: null, note: "no chapters: the build made none" }; + // The build's list has a chapter per segment (a player's navigation). A + // description's chapters are the cut's SECTIONS: when the list says which + // entries open one (`section`: a title or chapter card), every other entry + // folds into the section before it. + if (list.some((c) => c?.section === true)) list = list.filter((c, i) => i === 0 || c?.section === true); const all = list.map((c) => ({ start: Math.floor(Number(c.start)), title: oneLine(c.title) || "Chapter" })); if (all[0].start !== 0) return { chapters: null, note: `no chapters: the first starts at ${chapterStamp(all[0].start)}, not 0:00` }; const end = Number.isFinite(Number(total)) && total !== null diff --git a/umtool/report-to-video/youtube.test.mjs b/umtool/report-to-video/youtube.test.mjs @@ -89,3 +89,19 @@ test("the preview: the default cut's sources, no chapters", async () => { assert.ok(!p.text.includes("qa-long-03&t=5"), "an entry of another variant is not in the default cut"); assert.equal(youtubePreview({ timeline: [] }).text, null); }); + +test("youtubeChapters: with sections marked, the clips fold into the section that opens before them", () => { + const list = [ + { start: 0, title: "The title", section: true }, + { start: 14, title: "Size and staffing", section: true }, + { start: 32, title: "clip a", section: false }, + { start: 44, title: "clip a again", section: false }, + { start: 72, title: "Insulinoma", section: true }, + { start: 82, title: "clip b", section: false }, + { start: 110, title: "clip c", section: false }, + ]; + const r = youtubeChapters(list, 130); + assert.deepEqual(r.chapters.map((c) => c.title), ["The title", "Size and staffing", "Insulinoma"]); + // Too few sections: the block is left out rather than listing clips. + assert.equal(youtubeChapters(list.filter((c) => c.title !== "Insulinoma"), 130).chapters, null); +});