// A LOOKOUT RUN'S MODEL STAGES, the pure half (lane/lookout slice 2, stages // 3–5): the prompts and schemas, and the code that checks every answer. No // I/O — controller/lookoutRun.ts reads the cues, asks the model and writes. // // THE MODEL NEVER PUTS WORDS IN ANYONE'S MOUTH: // - stage 3 (read): every quote the model gives is LOCATED in the chunk it // was shown (its words verbatim and contiguous after normalising case and // punctuation, sweep-pipeline's `norm`, as its `locate` matches); one that // is not there — a paraphrase — is dropped and counted. What is STORED is // the transcript's own text for the located span, byte for byte as the // cues say it, never the model's string; its words are counted after // normalising, so punctuation is no word. Start and end come from the // cues, never from the model. // - stage 4 (group): the model sees the located items as numbered lines and // answers with item ids only; // - stage 5 (check): an idea keeps only ids that exist (an invented one is // dropped and counted), takes its moments' quotes from the items — it can // add none of its own — and needs at least two moments; one with none has // no story key and is no finding (lookoutStore `ideaKey`). // // The reading prompt is FIXED and generic, so every lookout (and later the // digest) can share one notes file per video; a lookout's own prompt steers // only the grouping. import { CHUNK_CHARS, MAX_QUOTE_WORDS, MIN_QUOTE_WORDS, norm } from "./report/draft/tasks/sweep-pipeline"; import { momentHref } from "./report/draft/tasks/links"; import { platformMomentUrl } from "./momentUrl"; import type { Platform } from "./platform"; import type { Cue } from "./vtt"; import { ideaKey, type LookoutIdea, type LookoutMoment } from "./lookoutStore"; import { READING_VOICES, type ReadingChunk, type ReadingItem, type ReadingVoice } from "./readingNotes-server"; export { CHUNK_CHARS }; /** Bumped when the reading prompt or schema changes: every video's notes go stale with it. */ export const READING_PROMPT_VERSION = 1; export const READING_MAX_ITEMS = 3; /** A grouping call's numbered lines, at most. */ export const GROUP_CHARS = 6000; /** A quote cut to this many words on a grouping line. */ export const GROUP_QUOTE_WORDS = 40; /** An idea is a story: at least this many moments. */ export const MIN_IDEA_MOMENTS = 2; export const MAX_IDEA_CAVEATS = 8; export const READING_KINDS = ["announcement", "claim", "feud", "reversal", "admission", "prediction", "running-story"] as const; export type ReadingKind = (typeof READING_KINDS)[number]; // ─── Stage 3: read ─── export const READ_SYSTEM = "You read one stretch of a video's transcript for material a short news-style video could be built from. " + "Wanted, by kind: announcement (a change in the speaker's business, channels, schedule, health or plans); " + "claim (a new claim or accusation about a named person or company); feud (a reply to, or fight with, someone named); " + "reversal (contradicting or walking back something said earlier); admission (a personal disclosure or a mistake owned); " + "prediction (a forecast with stakes); running-story (a story the speaker keeps returning to). " + "Not wanted: plain reaction to a news story with nothing of the speaker's own, sponsor reads, chat banter, isolated one-liners. " + `Give at most ${READING_MAX_ITEMS} items, none when nothing qualifies. Each quote is copied WORD FOR WORD from the transcript, ` + `${MIN_QUOTE_WORDS} to ${MAX_QUOTE_WORDS} words in one contiguous run — never a paraphrase, never joined from two places. ` + "voice says whose words the quote is: own (the speaker's), reading (a tweet, headline, article or message read aloud), " + "clip (a clip being played), unsure. covers is one line on what this stretch is about."; export const READ_SCHEMA = { type: "object", properties: { covers: { type: "string" }, items: { type: "array", maxItems: READING_MAX_ITEMS, items: { type: "object", properties: { kind: { type: "string", enum: [...READING_KINDS] }, quote: { type: "string" }, why: { type: "string" }, voice: { type: "string", enum: [...READING_VOICES] }, people: { type: "array", items: { type: "string" } }, }, required: ["kind", "quote", "why", "voice", "people"], }, }, }, required: ["covers", "items"], } as const; /** `m:ss` / `h:mm:ss`. */ export function clockOf(seconds: number): string { const s = Math.max(0, Math.floor(seconds)); const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); const ss = String(s % 60).padStart(2, "0"); return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; } export function readPrompt( v: { title: string; airDate: string }, chunk: readonly [number, string][], index: number, total: number, ): string { const lines = chunk.map(([sec, text]) => `[${clockOf(sec)}] ${text}`).join("\n"); return `Video: ${v.title || "(untitled)"}, aired ${v.airDate}. Part ${index + 1} of ${total}.\n\nTranscript:\n${lines}`; } export type ReadDropReason = "not-in-transcript" | "too-short" | "too-long" | "not-a-kind" | "repeated" | "over-limit" | "malformed"; const words = (s: string) => s.trim().split(/\s+/).filter(Boolean); const str = (v: unknown, max = 400) => (typeof v === "string" ? v.trim().slice(0, max) : ""); /** A text's words after normalising (case, punctuation): what the quote limits count. */ const normWords = (s: string) => norm(s).split(" ").filter(Boolean); /** Where a quote is in a chunk: its first and last line, and the TRANSCRIPT's text for it. */ export type QuoteSpan = { startLine: number; endLine: number; text: string }; /** * The quote found in the chunk, word for word after normalising — and the * transcript's own text for those words: from the first word's token in its * line to the last word's token in its line, the lines between whole, joined * by a space (the cue break). A token is the transcript's, whole (its * punctuation and case kept). Null when the words are not there, contiguous. */ export function quoteSpan(quote: string, chunk: readonly [number, string][]): QuoteSpan | null { const q = normWords(quote); if (!q.length) return null; const toks: { w: string; line: number; from: number; to: number }[] = []; chunk.forEach(([, text], line) => { for (const m of text.matchAll(/\S+/g)) { for (const w of normWords(m[0])) toks.push({ w, line, from: m.index!, to: m.index! + m[0].length }); } }); outer: for (let i = 0; i + q.length <= toks.length; i++) { for (let k = 0; k < q.length; k++) if (toks[i + k]!.w !== q[k]) continue outer; const a = toks[i]!; const b = toks[i + q.length - 1]!; const parts: string[] = []; for (let l = a.line; l <= b.line; l++) { const t = chunk[l]![1]; parts.push(t.slice(l === a.line ? a.from : 0, l === b.line ? b.to : t.length)); } return { startLine: a.line, endLine: b.line, text: parts.join(" ") }; } return null; } // Each chunk line's cue end: the cue at that whole second with that text, // found in order (a chunk's lines are cueLines of the cues, in order). function lineEnds(chunk: readonly [number, string][], cues: readonly Cue[]): number[] { let p = 0; return chunk.map(([sec, text]) => { for (let j = p; j < cues.length; j++) { const c = cues[j]!; if (Math.floor(c.start) === sec && c.text.trim() === text) { p = j + 1; return Math.round(c.end * 100) / 100; } } return sec; }); } /** * One reading answer, checked against the chunk it was asked about: each item * kept only when its quote is in the chunk verbatim and of the right length, * its kind one of the list; start and end from the cues. Never throws: a * malformed answer is an empty chunk with what it held counted as dropped. */ export function checkReading( answer: unknown, chunk: readonly [number, string][], cues: readonly Cue[], index: number, ): { chunk: ReadingChunk; dropped: { quote: string; reason: ReadDropReason }[] } { const a = (answer && typeof answer === "object" ? answer : {}) as Record; const rawItems = Array.isArray(a.items) ? a.items : []; const items: ReadingItem[] = []; const dropped: { quote: string; reason: ReadDropReason }[] = []; const seen = new Set(); let ends: number[] | null = null; for (const raw of rawItems) { const r = (raw && typeof raw === "object" ? raw : null) as Record | null; const quote = r ? str(r.quote, 2000) : ""; if (!r || !quote) { dropped.push({ quote, reason: "malformed" }); continue; } if (items.length >= READING_MAX_ITEMS) { dropped.push({ quote, reason: "over-limit" }); continue; } if (!(READING_KINDS as readonly string[]).includes(str(r.kind))) { dropped.push({ quote, reason: "not-a-kind" }); continue; } const n = normWords(quote).length; if (n < MIN_QUOTE_WORDS) { dropped.push({ quote, reason: "too-short" }); continue; } if (n > MAX_QUOTE_WORDS) { dropped.push({ quote, reason: "too-long" }); continue; } const span = quoteSpan(quote, chunk); if (span === null) { dropped.push({ quote, reason: "not-in-transcript" }); continue; } const start = chunk[span.startLine]![0]; const key = `${start}\n${norm(span.text)}`; if (seen.has(key)) { dropped.push({ quote, reason: "repeated" }); continue; } seen.add(key); ends ??= lineEnds(chunk, cues); const voice = (READING_VOICES as readonly string[]).includes(str(r.voice)) ? (str(r.voice) as ReadingVoice) : "unsure"; items.push({ kind: str(r.kind), // The transcript's words, never the model's string. quote: span.text, start, end: ends[span.endLine]!, why: str(r.why), voice, people: Array.isArray(r.people) ? r.people.map((p) => str(p, 80)).filter(Boolean).slice(0, 8) : [], }); } return { chunk: { index, from: chunk[0]?.[0] ?? 0, to: chunk[chunk.length - 1]?.[0] ?? 0, covers: str(a.covers), items, dropped: dropped.length, }, dropped, }; } // ─── Stage 4: group ─── /** A located item as the grouping sees it, with what its moment needs. */ export type GroupItem = ReadingItem & { /** `i`: what the model answers with. */ id: string; channel: string; video: string; /** The record's id and platform (a moment link on a site needs them). */ recordId: string; platform: string; url: string | null; title: string; date: string; }; export const GROUP_SYSTEM = "You are given numbered moments found in a creator's recent videos: id | date | channel | kind | quote | why. " + "Group them into video ideas. An idea is ONE STORY told by several moments — the same subject across days or videos, " + "a claim and its reversal, an announcement and its follow-up — never one moment alone. Answer with the moments' ids only " + "(itemIds); never write a quote. workingTitle: a short title. angle: two sentences. whyNow: one line. kind: the story's kind. " + "confidence: high, medium or low that this is a real, self-contained story, and confidenceWhy in one line. caveats: what a " + "reviewer must check. sensitive: true when it touches health, family, a minor, a legal matter or an accusation. " + "Give the strongest ideas first; fewer good ideas beat many weak ones."; export const GROUP_SCHEMA = { type: "object", properties: { ideas: { type: "array", items: { type: "object", properties: { workingTitle: { type: "string" }, angle: { type: "string" }, whyNow: { type: "string" }, kind: { type: "string" }, itemIds: { type: "array", items: { type: "string" } }, confidence: { type: "string", enum: ["high", "medium", "low"] }, confidenceWhy: { type: "string" }, caveats: { type: "array", items: { type: "string" } }, sensitive: { type: "boolean" }, }, required: ["workingTitle", "angle", "whyNow", "kind", "itemIds", "confidence", "confidenceWhy", "caveats", "sensitive"], }, }, }, required: ["ideas"], } as const; export function groupLine(i: GroupItem): string { const q = words(i.quote); const quote = q.length > GROUP_QUOTE_WORDS ? `${q.slice(0, GROUP_QUOTE_WORDS).join(" ")} …` : q.join(" "); return `${i.id} | ${i.date} | ${i.channel} | ${i.kind} | "${quote}" | ${i.why}`.replace(/\s*\n\s*/g, " "); } /** The items as grouping calls' line sets: in date order, each at most `maxChars`. */ export function groupBatches(items: readonly GroupItem[], maxChars = GROUP_CHARS): GroupItem[][] { const sorted = [...items].sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0) || (a.channel < b.channel ? -1 : a.channel > b.channel ? 1 : 0) || a.start - b.start); const out: GroupItem[][] = []; let cur: GroupItem[] = []; let size = 0; for (const i of sorted) { const l = groupLine(i).length + 1; if (cur.length && size + l > maxChars) { out.push(cur); cur = []; size = 0; } cur.push(i); size += l; } if (cur.length) out.push(cur); return out; } export function groupPrompt(batch: readonly GroupItem[], o: { prompt: string; from: string; to: string }): string { const ask = o.prompt.trim() ? `\n\nWhat the operator wants from these ideas: ${o.prompt.trim()}` : ""; return `Moments from ${o.from} to ${o.to}:\n${batch.map(groupLine).join("\n")}${ask}`; } /** A grouping answer's idea, as the model gave it (before stage 5). */ export type RawIdea = Record; export function ideasOf(answer: unknown): RawIdea[] { const a = (answer && typeof answer === "object" ? answer : {}) as Record; return Array.isArray(a.ideas) ? a.ideas.filter((x): x is RawIdea => !!x && typeof x === "object" && !Array.isArray(x)) : []; } // ─── Merging the batches' ideas ─── export const MERGE_SYSTEM = "You are given candidate video ideas, each found in a different stretch of days: id | dates | title | angle. " + "Some may be the same story seen on different days. Answer with the groups of candidate ids that are ONE story " + "(two or more ids each), with a title and a two-sentence angle for the merged story. Leave a candidate out when it " + "stands alone."; export const MERGE_SCHEMA = { type: "object", properties: { merges: { type: "array", items: { type: "object", properties: { ids: { type: "array", items: { type: "string" } }, workingTitle: { type: "string" }, angle: { type: "string" }, }, required: ["ids", "workingTitle", "angle"], }, }, }, required: ["merges"], } as const; export function mergeLine(id: string, idea: RawIdea, dates: string[]): string { return `${id} | ${dates.join(", ")} | ${str(idea.workingTitle, 160)} | ${str(idea.angle, 400)}`.replace(/\s*\n\s*/g, " "); } /** * Candidates merged by a merge answer: each group of two or more KNOWN ids * becomes one idea whose item ids are the union of theirs (and the first's * other fields, its title and angle the merge's); a candidate in no group, or * named twice, is kept as it was. Ids the model invented are ignored. */ export function applyMerges(candidates: ReadonlyMap, answer: unknown): { ideas: RawIdea[]; merged: number } { const a = (answer && typeof answer === "object" ? answer : {}) as Record; const merges = Array.isArray(a.merges) ? a.merges : []; const used = new Set(); const out: RawIdea[] = []; let merged = 0; for (const m of merges) { if (!m || typeof m !== "object") continue; const r = m as Record; const ids = Array.isArray(r.ids) ? [...new Set(r.ids.filter((x): x is string => typeof x === "string" && candidates.has(x) && !used.has(x)))] : []; if (ids.length < 2) continue; for (const id of ids) used.add(id); const parts = ids.map((id) => candidates.get(id)!); const itemIds = [...new Set(parts.flatMap((p) => (Array.isArray(p.itemIds) ? p.itemIds : [])))]; const caveats = [...new Set(parts.flatMap((p) => (Array.isArray(p.caveats) ? p.caveats : [])))]; out.push({ ...parts[0], workingTitle: str(r.workingTitle, 160) || parts[0]!.workingTitle, angle: str(r.angle, 600) || parts[0]!.angle, itemIds, caveats, sensitive: parts.some((p) => p.sensitive === true), }); merged++; } for (const [id, idea] of candidates) if (!used.has(id)) out.push(idea); return { ideas: out, merged }; } // ─── Stage 5: check ─── export type IdeaDropCounts = { /** Item ids the model named that no item has. */ inventedItemIds: number; /** Ideas left with one moment: not a story. */ oneMoment: number; /** Ideas left with no moment: no citation, no key, no finding. */ noCitation: number; /** Ideas whose moments are another idea's (the same story key). */ sameStory: number; }; const CONFIDENCE = ["high", "medium", "low"] as const; const VOICE_WORDS: Record, string> = { reading: "reading something aloud", clip: "playing a clip", unsure: "possibly not speaking in his own voice", }; function linkOf(i: GroupItem, siteOrigin: string): string | undefined { if (siteOrigin) return momentHref(siteOrigin, i.channel, i.recordId || i.video, i.start, i.platform || null); return platformMomentUrl(i.url, (i.platform || null) as Platform | null, i.start) ?? undefined; } /** * Stage 5: the model's ideas made findings. Every idea keeps only item ids that * exist, each at most once; its moments are those items' (quote, times, date — * code's, never the model's); one with fewer than two moments is dropped and * counted (one with none has no key at all); a moment whose voice is not * "own" becomes a caveat; two ideas with the same story key are one (the * first kept). Ordered by confidence, then distinct days, then moments. */ export function checkIdeas( raw: readonly RawIdea[], items: ReadonlyMap, o: { siteOrigin: string }, ): { ideas: LookoutIdea[]; dropped: IdeaDropCounts } { const dropped: IdeaDropCounts = { inventedItemIds: 0, oneMoment: 0, noCitation: 0, sameStory: 0 }; const keyed = new Map(); for (const r of raw) { const ids = Array.isArray(r.itemIds) ? r.itemIds : []; const found: GroupItem[] = []; const seen = new Set(); for (const id of ids) { const it = typeof id === "string" ? items.get(id.trim()) : undefined; if (!it) { dropped.inventedItemIds++; continue; } if (seen.has(it.id)) continue; seen.add(it.id); found.push(it); } found.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : 0) || (a.channel < b.channel ? -1 : a.channel > b.channel ? 1 : 0) || a.start - b.start); const moments: (LookoutMoment & { voice: ReadingVoice })[] = found.map((i) => ({ channel: i.channel, video: i.video, date: i.date, start: i.start, end: i.end, quote: i.quote, ...(linkOf(i, o.siteOrigin) ? { link: linkOf(i, o.siteOrigin) } : {}), ...(i.title ? { title: i.title } : {}), voice: i.voice, })); const key = ideaKey(moments); if (key === null) { dropped.noCitation++; continue; } if (moments.length < MIN_IDEA_MOMENTS) { dropped.oneMoment++; continue; } if (keyed.has(key)) { dropped.sameStory++; continue; } const caveats = (Array.isArray(r.caveats) ? r.caveats : []).map((c) => str(c, 300)).filter(Boolean); moments.forEach((m, n) => { if (m.voice !== "own") caveats.push(`Moment ${n + 1} (${m.date}, ${clockOf(m.start)}): the model thinks he may be ${VOICE_WORDS[m.voice]} — check by ear.`); }); const confidence = (CONFIDENCE as readonly string[]).includes(str(r.confidence)) ? (str(r.confidence) as LookoutIdea["confidence"]) : "low"; keyed.set(key, { id: "", key, workingTitle: str(r.workingTitle, 160) || "(untitled idea)", angle: str(r.angle, 600), whyNow: str(r.whyNow, 300), kind: str(r.kind, 40), estimatedLengthSec: Math.round(moments.reduce((s, m) => s + Math.max(0, m.end - m.start), 0)), confidence, confidenceWhy: str(r.confidenceWhy, 300), moments: moments.map(({ voice: _voice, ...m }) => m), caveats: [...new Set(caveats)].slice(0, MAX_IDEA_CAVEATS + moments.length), sensitive: r.sensitive === true, }); } const rank = (c: LookoutIdea["confidence"]) => CONFIDENCE.indexOf(c); const days = (i: LookoutIdea) => new Set(i.moments.map((m) => m.date)).size; const ideas = [...keyed.values()].sort( (a, b) => rank(a.confidence) - rank(b.confidence) || days(b) - days(a) || b.moments.length - a.moments.length || (a.key < b.key ? -1 : 1), ); ideas.forEach((i, n) => (i.id = `idea-${n + 1}`)); return { ideas, dropped }; }