// TASK sweep-pipeline — a cited sweep made by CODE around a small local model // (release 27, S5, D4; the stopgap's local_sweep.py, the only sweep that fits // qwen's 8k context). // // The model only: proposes search terms, judges each transcript window, // copies quotes and writes a one-line claim, groups the claims into sections // and names the report. Code does the rest: enumeration (the MCP's tools), // windowing, the verbatim check (a quote not found in its window is DROPPED // and logged), citation links on the article's origin, coverage, convert and // the strict quote check (a finding that fails it is dropped, never fixed). // Every prompt fits the local cap; one that would not is never sent (the // ollama module refuses it) and that chunk is logged as failed. // // TWO CLAIM FORMS (demo epic D2, round b; `claimForm`): `sentence` — the model // drafts a one-line claim and a meaning check judges it — and `neutral` — the // model only copies the quote and labels its topic, and CODE writes the line: // "In (<date>), on <topic>: "<quote>"" (./neutralClaim.ts; no meaning // check, there is no drafted sentence). And READ-ALOUD CUES (`readAloud`, // ./readAloud.ts): a quote whose transcript says it is being read aloud (a // tweet, a headline, "it says") is dropped, or kept marked "check by ear". // // The run is TRACED (trace.jsonl, ./trace.ts; umtool R3): the scope, the // terms, each term's enumeration, each read batch with the model's lines, // every quote kept or dropped and why, the findings; the iteration's // `coverage` is what was enumerated and read. import { structuredAnswer, type LlmConfig, type Meter } from "../../../llm"; import type { CallItem } from "../../../llm/callLog"; import { CallSlot } from "../../../llm/callLog-server"; import type { Report } from "../../schema"; import { writeIterationFile } from "../../iterations"; import { mmss } from "../reportOps"; import { strictNormalize } from "../../../citations/verify"; import { fragmentOf, fullSentenceFor } from "../../../citations/fragment"; import { momentHref } from "./links"; import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; import { CoverageTally, enumerateOf, traceReport } from "./trace"; import { GATE_CHARS, lintClaim, MIN_KEPT, onTopicBy, quoteContext } from "./claimChecks"; import { CHECK_BY_EAR, decideMeaning, MEANING_SCHEMA, MEANING_SYSTEM, meaningPrompt, readMeaning, type MeaningAnswer, type MeaningDecision } from "./meaning"; import { NEUTRAL_EXTRACT_SYSTEM, NEUTRAL_GROUP_SYSTEM, NEUTRAL_LINES_NOTE, neutralExtractSchema, neutralHeading, neutralSentence, neutralTitle, runTopicOf, topicLabel, type ClaimForm, type TopicLabel } from "./neutralClaim"; import { cuesLine, READ_ALOUD_FLAG, readAloudCues, type ReadAloudCue, type ReadAloudMode } from "./readAloud"; export { lintClaim }; import { cleanTerms, normalizeTerm, readingSet, readingSize, rareTermsOf, scoreOf, subjectNames, termStats, termsNear, usableTerms, type ChannelName, type DroppedTerm, type TermStat, } from "./selection"; import type { TaskDeps, TaskResult } from "./types"; export const CHUNK_CHARS = 7000; // one model call's transcript text (~2k tokens) export const MAX_ITEMS_PER_CHUNK = 3; export const MAX_CLAIMS_PER_SECTION = 12; export const MAX_SECTIONS = 6; export const MAX_CLAIMS_TOTAL = 60; export const MAX_CLAIMS_PER_VIDEO = 6; export const MIN_QUOTE_WORDS = 7; export const MAX_QUOTE_WORDS = 60; export const READ_BATCH = 8; // The meaning check's budget: one call per kept item, at most this many. export const MAX_MEANING_CHECKS = 60; const STOP = new Set( "what when where which about with from that this have said says their there they them were been into over under more most some such than then also just like make made making".split( " ", ), ); export const TERMS_SYSTEM = "You plan keyword searches over automatic speech-recognition transcripts of streams and videos. Given a research " + "question, return search phrases likely to be SPOKEN, word for word, in the recordings that answer it, and the topic: " + "the thing the question is about, in at most five words. Terms name the TOPIC, not the person the question asks " + "about: never the speaker's or the channel's own name, never generic words (say, show, video, comment, think, " + "reason). Prefer the topic's distinctive names and nouns; keep a multi-word name together as one phrase (\"star " + "wars\", \"wizards of the coast\"). Lowercase, no quotation marks, no boolean operators, no plural and singular of " + "the same word. Return between three and six, the most distinctive first."; export const TERMS_SCHEMA = { type: "object", properties: { terms: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 6 }, topic: { type: "string" }, }, required: ["terms", "topic"], }; export const EXTRACT_SYSTEM = "You read excerpts of an automatic transcript and pick out evidence for a research question. Rules: (1) Only use the " + "excerpt; never add facts. (2) Each quote is copied EXACTLY, character for character, from consecutive transcript " + "lines, without the bracketed timestamps; at least 8 and at most 40 words, a whole sentence or clause; do not fix grammar, spelling or names. " + "(3) Each claim is one plain sentence saying what the speaker says in that quote, attributed to the speaker; keep " + "every negation (not, never, no) and every hedge (maybe, I think, allegedly, if) the quote has; do not state motives " + "or feelings; do not exaggerate; paraphrase in the third person in at most 20 words, do not repeat the quote. Set " + "on_topic to true only when the quote itself is about the question's subject. A message or donation the streamer " + "reads aloud from chat is someone else's words: say so in the claim. Strength: 3 = the quote directly answers the " + "question, 2 = it bears on it, 1 = it only mentions a search word. (4) If the excerpt does not bear on the question, " + "set relevant to false and return no items. (5) Return at most three items, the strongest first."; export const EXTRACT_SCHEMA = { type: "object", properties: { relevant: { type: "boolean" }, items: { type: "array", maxItems: MAX_ITEMS_PER_CHUNK, items: { type: "object", properties: { quote: { type: "string" }, claim: { type: "string" }, on_topic: { type: "boolean" }, strength: { type: "integer", minimum: 1, maximum: 3 }, }, required: ["quote", "claim", "on_topic", "strength"], }, }, }, required: ["relevant", "items"], }; export const GROUP_SYSTEM = "You organise numbered findings into a short report. Return a plain, factual title (at most 90 characters, no " + "clickbait, no verdicts) and between one and six sections. Each section has a short heading (at most 60 characters) " + "naming what its findings have in common, and the numbers of the findings it holds, each number in exactly one " + "section. Headings describe; they do not judge, exaggerate or add facts the findings do not state."; export const GROUP_SCHEMA = { type: "object", properties: { title: { type: "string" }, sections: { type: "array", minItems: 1, maxItems: MAX_SECTIONS, items: { type: "object", properties: { heading: { type: "string" }, findings: { type: "array", items: { type: "integer" } } }, required: ["heading", "findings"], }, }, }, required: ["title", "sections"], }; export type SweepPipelineInput = { article: string; n: number; question?: string; channels?: string[]; from?: string; to?: string; model?: string; origin: string; maxUsd?: number; terms?: string[]; maxVideos?: number; maxClaims?: number; // The read budget (item 1): recordings read = minutes × 60 / (seconds a // call × calls a recording), default 40. `maxVideos` wins when given. readMinutes?: number; secondsPerCall?: number; // The subject's host names (a channel's context note): never search terms. hosts?: string[]; // The claim form (round b): `sentence` (the model drafts each claim; the // default here) or `neutral` (code writes "In <title> (<date>), on <topic>:" // around the quote). settings.generation.localSweep.claimForm, passed by // the controller. claimForm?: ClaimForm; // A quote with a read-aloud cue around it: `off` (the default here), `flag` // (kept, marked "check by ear") or `drop`. settings.generation.localSweep.readAloud. readAloud?: ReadAloudMode; // Only these recordings (umtool R4; a general sweep option): the worklist is // the enumeration's rows of these ids, and any of them the terms did not // find is read too. Default: the iteration's scope.ids. ids?: string[]; }; // ─── Pure helpers (exported for the tests) ─── export const norm = (s: string) => strictNormalize(s); type Line = [number, string] | null; // null: an explicit window break export type EnumeratedVideo = { id: string; channel: string; date: string; title: string; hits: Record<string, number> }; const ENUM_LINE = /^- (\S+) \| (\w+) \| (.*?) \| (\d{4}-\d{2}-\d{2}|[^|]*?) \| (\d+) match\(es\) \| (.*)$/; // enumerate_matches' worklist lines. export function parseEnumerate(text: string, term: string): EnumeratedVideo[] { const out: EnumeratedVideo[] = []; for (const raw of text.split("\n")) { const m = ENUM_LINE.exec(raw.trim()); if (!m || m[2] !== "video") continue; out.push({ id: m[1]!, channel: m[3]!, date: m[4]!.trim(), title: m[6]!, hits: { [term]: Number(m[5]) } }); } return out; } const STAMP = /^\[(?:\d+:)?\d+:\d+\|(\d+)\]\s?(.*)$/; export type ParsedTranscript = { title: string; momentBase: string | null; lines: Line[] }; // get_transcripts (link_style base) → per video id: title, moment_base, lines. export function parseTranscripts(text: string): Map<string, ParsedTranscript> { const out = new Map<string, ParsedTranscript>(); for (const block of text.split(/\n---\n/)) { const id = /video_id: (\S+)/.exec(block)?.[1]; if (!id) continue; const title = /^## (.*)$/m.exec(block)?.[1]?.trim() ?? id; const mb = /moment_base: (\S+)/.exec(block)?.[1] ?? null; const lines: Line[] = []; for (const ln of block.split("\n")) { const s = STAMP.exec(ln.trim()); if (s) lines.push([Number(s[1]), s[2]!.trim()]); else if (lines.length && ["…", "...", "⋯"].includes(ln.trim())) lines.push(null); } out.set(id, { title, momentBase: mb, lines }); } return out; } export function windowsOf(lines: readonly Line[], gap = 90): [number, string][][] { const wins: [number, string][][] = []; let cur: [number, string][] = []; let prev: number | null = null; for (const l of lines) { if (l === null) { if (cur.length) wins.push(cur); cur = []; prev = null; continue; } if (prev !== null && l[0] - prev > gap && cur.length) { wins.push(cur); cur = []; } cur.push(l); prev = l[0]; } if (cur.length) wins.push(cur); return wins; } // One window in model-sized chunks, overlapping by three lines. export function chunksOf(win: readonly [number, string][], chunkChars = CHUNK_CHARS): [number, string][][] { const out: [number, string][][] = []; let cur: [number, string][] = []; let size = 0; for (const ln of win) { const l = ln[1].length + 12; if (cur.length && size + l > chunkChars) { out.push(cur); cur = cur.slice(-3); size = cur.reduce((s, x) => s + x[1].length + 12, 0); } cur.push(ln); size += l; } if (cur.length) out.push(cur); return out; } // The second of the line where the verbatim quote starts, or null. export function locate(quote: string, chunk: readonly [number, string][]): number | null { const q = norm(quote); if (!q) return null; let text = ""; const starts: [number, number][] = []; for (const [sec, txt] of chunk) { const n = norm(txt); if (!n) continue; if (text) text += " "; starts.push([text.length, sec]); text += n; } const i = ` ${text} `.indexOf(` ${q} `); if (i < 0) return null; let sec = starts[0]![1]; for (const [off, s] of starts) { if (off <= i) sec = s; else break; } return sec; } // ─── The run ─── type Kept = { video: string; title: string; channel: string; slug: string; date: string; quote: string; claim: string; sec: number; strength: number; flags: string[]; // The transcript around the quote (400 characters before, 150 after) and // the question's term the gate found in it (D2 item 2). before: string; after: string; gate: string; // The meaning check's answer and what code made of it (D2 item 3); `mark`: // kept, "check by ear". meaning?: { answer: MeaningAnswer; decision: MeaningDecision; seconds: number; drafted: string }; mark?: boolean; // The neutral form's topic label (the model's, or the run's topic when code // refused it) and the read-aloud cues found around the quote (round b). label?: TopicLabel; readAloud?: ReadAloudCue[]; }; export async function sweepPipeline(input: SweepPipelineInput, deps: TaskDeps): Promise<TaskResult> { return runOnIteration( { article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["sweep"], trace: { task: "sweep-pipeline", ...(input.model ? { model: input.model } : {}) } }, (h) => pipelineBody(h, input), ); } // The model log's phase of a pipeline step (lib/llm/callLog.ts PHASE_ORDER). export const phaseOfStep = (what: string) => (what.startsWith("terms") ? "terms" : what.startsWith("extract") ? "reading" : what.startsWith("meaning") ? "meaning-check" : what.startsWith("group") ? "grouping" : what); async function ask<T>(h: TaskHandle, model: string, system: string, user: string, schema: object, what: string, traceCost = false, slot?: CallSlot): Promise<T> { const t0 = Date.now(); const before = h.meter.usd; const out = await structuredAnswer<T>({ llm: h.deps.llm as LlmConfig, model, system, user, schema, meter: h.meter as Meter, signal: h.deps.signal, call: { phase: phaseOfStep(what), label: what, ...(slot ? { slot } : {}) }, }); h.turns([{ kind: "model", what, seconds: Math.round((Date.now() - t0) / 100) / 10, answer: out }]); if (traceCost) h.trace({ t: "cost", step: what, usd: h.meter.usd - before, model, total: h.meter.usd }); return out; } // The pipeline's body over a handle (exported: a refresh runs it on its own // iteration, restricted to its new recordings — draft/refresh/task.ts). export async function sweepPipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<TaskOutcome> { return pipelineBody(h, input); } async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<TaskOutcome> { const { deps, iteration } = h; const question = (input.question ?? iteration.question ?? "").trim(); const channels = input.channels ?? iteration.scope?.channels ?? []; const model = input.model ?? iteration.model; const since = input.from ?? iteration.scope?.from; const until = input.to ?? iteration.scope?.to; const origin = input.origin.replace(/\/+$/, ""); const maxClaims = input.maxClaims ?? 40; const only = input.ids ?? iteration.scope?.ids; const form: ClaimForm = input.claimForm ?? "sentence"; const neutral = form === "neutral"; const raMode: ReadAloudMode = input.readAloud ?? "off"; if (!question) throw new TaskInputError("a sweep needs its question"); if (!channels.length) throw new TaskInputError("a sweep needs its channels"); const event = (e: Record<string, unknown>) => h.turns([e]); h.log(`pipeline sweep on ${model}, corpus ${deps.corpus.source}, links on ${origin}${neutral ? "; claims in the speaker-neutral form (written by code)" : ""}${raMode !== "off" ? `; read-aloud cues: ${raMode}` : ""}`); const cov = new CoverageTally(); h.setCoverage(() => cov.value()); h.trace({ t: "scope", source: deps.corpus.source, channels, ...(since ? { from: since } : {}), ...(until ? { to: until } : {}), question, model, origin, ...(only?.length ? { ids: only } : {}) }); // 1. terms (the model, unless given), cleaned by code: never the subject's // own names, never generic words; a phrase stays a phrase. const channelNames = await channelNamesOf(deps.corpus, channels); const names = subjectNames({ question, channels: channelNames, hosts: input.hosts }); const droppedTerms: DroppedTerm[] = []; let topic = ""; // The topic as the model wrote it (the neutral form shows it). let topicShown = ""; // The first terms call's model-log slot: the run's topic is decided on it too. const termsCall: { slot: CallSlot | null } = { slot: null }; const proposeTerms = async (user: string, what: string) => { const slot = new CallSlot(); termsCall.slot ??= slot; const ans = await ask<{ terms?: unknown; topic?: unknown }>(h, model, TERMS_SYSTEM, user, TERMS_SCHEMA, what, true, slot); if (!topic && typeof ans.topic === "string") topic = ans.topic.replace(/["“”]/g, "").trim().slice(0, 60); if (!topicShown) topicShown = topic.replace(/[[\]()<>*_`#|]/g, " ").replace(/\s+/g, " ").trim(); const c = cleanTerms(Array.isArray(ans.terms) ? ans.terms : [], { names }); droppedTerms.push(...c.dropped); const termItems: CallItem[] = [...c.kept.map((t): CallItem => ({ text: t, outcome: "kept", why: "searched" })), ...c.dropped.map((d): CallItem => ({ text: d.term, outcome: "dropped", why: d.why }))]; slot.decide(c.kept.length ? "kept" : "dropped", c.kept.length ? `searched for ${c.kept.join(", ")}` : "no usable term", termItems); return c.kept; }; let terms: string[] = []; if (input.terms?.length) terms = input.terms.map((t) => t.trim()).filter(Boolean); else terms = await proposeTerms(`Research question: ${question}`, "terms"); if (!terms.length && !input.terms?.length) terms = await proposeTerms(retermsPrompt(question, droppedTerms), "terms#2"); if (!terms.length) return { status: "failed", summary: `no search terms${droppedTerms.length ? ` (dropped: ${droppedTerms.map((d) => `${d.term}, ${d.why}`).join("; ")})` : ""}` }; h.log(`terms: ${terms.join(", ")}${topic ? ` (topic: ${topic})` : ""}${droppedTerms.length ? `; dropped ${droppedTerms.map((d) => `${d.term} (${d.why})`).join(", ")}` : ""}`); h.trace({ t: "terms", terms, ...(topic ? { topic } : {}), ...(droppedTerms.length ? { dropped: droppedTerms } : {}) }); // 2. enumerate (code) const found = new Map<string, EnumeratedVideo>(); const partial: string[] = []; const counts = new Map<string, { videos: number; partial: boolean }>(); const enumerate = async (list: string[]) => { for (const term of list) { const text = await deps.corpus.call("enumerate_matches", { query: term, channels, ...(since ? { date_from: since } : {}), ...(until ? { date_to: until } : {}), }); if (text.includes("COVERAGE PARTIAL")) partial.push(term); const vids = parseEnumerate(text, term); const e = enumerateOf(text); counts.set(term, { videos: vids.length, partial: e.partial }); cov.enumerated( vids.map((v) => v.id), e.partial, e.unreached, ); h.trace({ t: "enumerate", query: term, n: vids.length, ids: vids.map((v) => v.id), partial: e.partial, unreached: e.unreached, ...(e.total !== null ? { total: e.total } : {}), ...(e.posts ? { posts: e.posts } : {}), counts: Object.fromEntries(vids.map((v) => [v.id, v.hits[term] ?? 0])), }); for (const v of vids) { const had = found.get(v.id); if (had) Object.assign(had.hits, v.hits); else found.set(v.id, v); } event({ kind: "enumerate", term, videos: vids.length, partial: text.includes("COVERAGE PARTIAL") }); h.log(`term "${term}": ${vids.length} video(s)${e.partial ? " (capped)" : ""}`); } }; await enumerate(terms); if (!input.terms?.length) { // A phrase that matched nothing: its distinctive words alone (cleaned). const extra = cleanTerms( terms.filter((t) => t.includes(" ") && !counts.get(t)?.videos).flatMap((t) => t.split(/\s+/).filter((w) => w.length >= 4 && !STOP.has(w))), { names }, ).kept.filter((w) => !terms.includes(w)); if (extra.length) { h.log(`phrases with no match; trying words: ${extra.join(", ")}`); h.trace({ t: "terms", terms: extra, extra: true }); await enumerate(extra); terms = [...terms, ...extra].slice(0, 8); } } // Rarity over the scope: a term in more than a quarter of it is dropped. const scopeSize = await scopeSizeOf(deps.corpus, channels, since, until, channelNames); const statsOf = () => termStats(terms.map((t) => ({ term: t, ...(counts.get(t) ?? { videos: 0, partial: false }) })), scopeSize); let stats = statsOf(); const noteCommon = (list: TermStat[]) => { for (const st of list) { if (!st.common || droppedTerms.some((d) => d.term === st.term)) continue; droppedTerms.push({ term: st.term, why: `too common: in ${Math.round(st.share * 100)}% of the scope's recordings` }); } for (const st of list) if (!st.videos && !droppedTerms.some((d) => d.term === st.term)) droppedTerms.push({ term: st.term, why: "no match" }); }; noteCommon(stats); if (usableTerms(stats).length < 2 && !input.terms?.length) { // Once more, naming what was dropped and why. const more = (await proposeTerms(retermsPrompt(question, droppedTerms), "terms#2")).filter((t) => !terms.includes(t)); if (more.length) { h.log(`fewer than two usable terms; asked again: ${more.join(", ")}`); h.trace({ t: "terms", terms: more, extra: true, asked: "again" }); await enumerate(more); terms = [...terms, ...more]; stats = statsOf(); noteCommon(stats); } } const usable = usableTerms(stats).sort((a, b) => b.idf - a.idf); terms = usable.map((s) => s.term); if (!terms.length) return { status: "failed", summary: `no usable search terms (${droppedTerms.map((d) => `${d.term}: ${d.why}`).join("; ")})` }; const statMap = new Map(usable.map((st) => [st.term, st])); // The topic the model named, as the gate reads it (the subject's names off). topic = normalizeTerm(topic, names); const rare = rareTermsOf(usable); // The neutral form's fallback label and its report's title: the topic the // model named for the question, else with the subject's names off, else the // rarest term — the first that passes the label rules (never the model's // raw words unchecked: a topic that attributes would be every refused // label's and the title). const hostNames = [...names]; const rt = runTopicOf([topicShown, topic, ...rare, ...terms], { hosts: hostNames, ground: [question, ...terms] }); const runTopic = rt.topic; if (neutral && rt.refused.length) { const line = `the run's topic: ${rt.refused.map((r) => `“${r.candidate}” refused (${r.why})`).join("; ")}; “${runTopic}” used`; h.log(line); h.trace({ t: "note", text: line }); // The model log: on the terms call, whose answer named the topic. termsCall.slot?.items([ ...rt.refused.map((r): CallItem => ({ text: `topic: ${r.candidate}`, outcome: "dropped", why: `label refused: ${r.why}` })), { text: `topic: ${runTopic}`, outcome: "kept", why: "the run's topic (its fallback label and the report's title)" }, ]); } h.trace({ t: "note", text: `scope ${scopeSize} recording(s); terms by rarity: ${usable.map((st) => `${st.term} ${st.videos}${st.partial ? "+" : ""} (${(st.share * 100).toFixed(1)}%, idf ${st.idf.toFixed(2)}${st.nominates ? "" : ", scores only"})`).join("; ")}; rare: ${rare.join(", ")}`, }); h.log(`scope ${scopeSize} recording(s); by rarity: ${usable.map((st) => `${st.term} ${st.videos}${st.partial ? "+" : ""}`).join(", ")}`); if (only?.length) { // A restricted sweep: only these recordings, each read even when the // terms did not find it (its windows are what the terms match in it). const set = new Set(only); for (const id of [...found.keys()]) if (!set.has(id)) found.delete(id); for (const id of only) if (!found.has(id)) found.set(id, { id, channel: channels.length === 1 ? channels[0]! : "", date: "", title: id, hits: {} }); h.log(`restricted to ${only.length} recording(s)`); h.trace({ t: "note", text: `restricted to ${only.length} recording(s): ${only.slice(0, 20).join(", ")}` }); } const nEnum = found.size; // Candidates: what a nominating term found (a capped list is a sample in // page order, never a nomination) — or, when no term nominates, everything. const nominators = usable.filter((st) => st.nominates).map((st) => st.term); let candidates = [...found.values()].filter((v) => only?.length || !nominators.length || nominators.some((t) => (v.hits[t] ?? 0) > 0)); // A capped term counts again inside the candidates, uncapped. const capped = usable.filter((st) => st.partial).map((st) => st.term); if (capped.length && nominators.length && candidates.length) { const ids = candidates.map((v) => v.id); for (const term of capped) { for (const v of candidates) delete v.hits[term]; for (let i = 0; i < ids.length; i += 400) { const text = await deps.corpus.call("enumerate_matches", { query: term, channels, ids: ids.slice(i, i + 400) }); for (const r of parseEnumerate(text, term)) { const v = found.get(r.id); if (v) v.hits[term] = r.hits[term] ?? 0; } } } } const nRead = input.maxVideos ?? readingSize({ budgetMinutes: input.readMinutes, secondsPerCall: input.secondsPerCall }); // Two terms within 90 s: read off the windows of the best by score (the // same windows the read uses, fetched once). const transcripts = new Map<string, ParsedTranscript>(); const windowsFor = async (ids: string[]) => { const missing = ids.filter((id) => !transcripts.has(id)); for (let i = 0; i < missing.length; i += READ_BATCH) { const text = await deps.corpus.call("get_transcripts", { video_ids: missing.slice(i, i + READ_BATCH), queries: terms.slice(0, 8), link_style: "base", channels }); for (const [id, p] of parseTranscripts(text)) transcripts.set(id, p); } }; let ranked = candidates.map((v) => ({ ...v, score: scoreOf(v.hits, statMap) })); ranked.sort((a, b) => b.score - a.score || a.date.localeCompare(b.date)); if (terms.length > 1 && !only?.length) { const head = ranked.slice(0, Math.min(ranked.length, 2 * nRead, 80)); await windowsFor(head.map((v) => v.id)); const near = new Set(head.filter((v) => termsNear(transcripts.get(v.id)?.lines ?? [], terms)).map((v) => v.id)); ranked = ranked.map((v) => (near.has(v.id) ? { ...v, score: scoreOf(v.hits, statMap, true) } : v)); } const sel = only?.length ? { read: ranked, spread: [] as string[], quarters: 0 } : readingSet(ranked, { n: nRead, spreadable: (v) => rare.some((t) => (v.hits[t] ?? 0) > 0) }); const todo = sel.read; const spreadSet = new Set(sel.spread); h.trace({ t: "select", scope: scopeSize, terms: usable.map((st) => ({ term: st.term, videos: st.videos, partial: st.partial, idf: Math.round(st.idf * 1000) / 1000, nominates: st.nominates })), rare, candidates: ranked.length, read: todo.map((v) => ({ id: v.id, date: v.date, score: Math.round(v.score * 100) / 100, hits: v.hits, why: spreadSet.has(v.id) ? "spread" : "top" })), }); candidates = []; h.log(`${nEnum} video(s) matched; reading ${todo.length} (the top ${Math.min(nRead, todo.length)} by score${sel.spread.length ? `, ${sel.spread.length} more for the date spread` : ""})`); h.trace({ t: "note", text: `reading ${todo.length} of ${nEnum}: top ${Math.min(nRead, todo.length)} by rarity × hits${sel.spread.length ? ` + ${sel.spread.length} for the date spread (${sel.quarters} quarter(s) with hits)` : ""}; years ${yearSpread(todo)}` }); // 3. read windows and extract (the model judges, code verifies) const kept: Kept[] = []; const dropped: { video: string; quote: string; why: string }[] = []; let nChunks = 0; let nRelevant = 0; const readIds: string[] = []; // The job's progress: the recordings gone through, of the worklist. let visited = 0; h.progress({ metric: "entries", current: 0, total: todo.length }); const batches = Math.ceil(todo.length / READ_BATCH); for (let b = 0; b < todo.length; b += READ_BATCH) { deps.signal?.throwIfAborted(); const batch = todo.slice(b, b + READ_BATCH); // The batch's trace: what the model returned, kept or dropped. const batchLines: string[] = []; const batchUsd = h.meter.usd; await windowsFor(batch.map((v) => v.id)); const parsed = transcripts; for (const v of batch) { const p = parsed.get(v.id); if (!p || !p.lines.length) { event({ kind: "unread", video: v.id, why: "no windows returned" }); batchLines.push(`${v.id}: no windows returned`); h.progress({ metric: "entries", current: ++visited, total: todo.length }); continue; } readIds.push(v.id); cov.readIds([v.id]); const title = p.title || v.title; // The channel slug: off a moment_base in the archive's form, else asked. let slug: string | null = null; const mbm = p.momentBase ? /[?&]v=([^&%/]+)(?:%2F|\/)/i.exec(p.momentBase) : null; if (mbm) slug = decodeURIComponent(mbm[1]!); if (!slug && channels.length === 1) slug = channels[0]!; if (!slug) { for (const c of channels) { try { await deps.corpus.call("get_video_metadata", { video_id: v.id, channel: c }); slug = c; break; } catch { // not this channel's } } } slug ??= channels[0]!; for (const win of windowsOf(p.lines)) { for (const ch of chunksOf(win)) { deps.signal?.throwIfAborted(); nChunks++; const excerpt = ch.map(([s, t]) => `[${mmss(s)}] ${t}`).join("\n"); const user = `Research question: ${question}\n\nVideo: ${title} (${v.channel}, ${v.date})\n\nTranscript excerpt:\n${excerpt}`; let ans: { relevant?: unknown; items?: unknown }; const slot = new CallSlot(); try { ans = await ask(h, model, neutral ? NEUTRAL_EXTRACT_SYSTEM : EXTRACT_SYSTEM, user, neutral ? neutralExtractSchema(MAX_ITEMS_PER_CHUNK) : EXTRACT_SCHEMA, `extract ${v.id}@${ch[0]![0]}`, false, slot); } catch (e) { if (deps.signal?.aborted) throw e; event({ kind: "chunk-failed", video: v.id, at: ch[0]![0], error: (e as Error).message }); batchLines.push(`${v.id} @ ${mmss(ch[0]![0])}: the model's answer failed — ${(e as Error).message}`); h.log(` chunk failed: ${(e as Error).message}`); continue; } if (!ans.relevant) { slot.decide("dropped", "the model: the excerpt does not bear on the question"); continue; } nRelevant++; const items = Array.isArray(ans.items) ? ans.items.slice(0, MAX_ITEMS_PER_CHUNK) : []; // What code did with each of the model's items (the model log). const fates: CallItem[] = []; for (const raw of items as { quote?: unknown; claim?: unknown; topic?: unknown; on_topic?: unknown; strength?: unknown }[]) { let quote = String(raw.quote ?? "") .replace(/["“”]/g, "") .replace(/\s+/g, " ") .trim() .replace(/^\[[\d:]+\]\s*/, ""); // The neutral form has no drafted claim: code writes the line below. let claim = neutral ? "" : String(raw.claim ?? "").replace(/\s+/g, " ").trim().replace(/"/g, "'").replace(/[“”]/g, "'"); const sec = locate(quote, ch); // A quote that stops mid-thought (Q2) becomes its whole sentence // when the window has one: code copies the words, still verbatim. const frag = sec === null ? null : fragmentOf(quote); if (frag) { const lines = win.map(([s, t], i) => ({ start: s, end: win[i + 1]?.[0] ?? s + 1, text: t })); const whole = fullSentenceFor(quote, lines, sec!, { windowSeconds: Number.MAX_SAFE_INTEGER }); if (whole && whole.split(" ").length <= MAX_QUOTE_WORDS) { event({ kind: "extended", video: v.id, quote, to: whole }); quote = whole; } } const wc = quote.split(" ").filter(Boolean).length; const stillFragment = sec === null ? null : fragmentOf(quote); let why: string | null = null; if (sec === null) why = "not verbatim in its window"; else if (stillFragment) why = `a fragment (${stillFragment.why})`; else if (wc < MIN_QUOTE_WORDS) why = `too short (${wc} words)`; else if (wc > MAX_QUOTE_WORDS) why = `too long (${wc} words)`; else if (!neutral && !claim) why = "no claim"; else if (raw.on_topic === false || (Number(raw.strength) || 2) < 2) why = "model: not on topic"; const key = norm(quote); if (!why && kept.some((k) => k.video === v.id && (norm(k.quote).includes(key) || key.includes(norm(k.quote))))) why = "duplicate"; // The gate (D2 item 2): the question's rare term (or the topic) // in the quote or the 300 characters before it — code's call, // whatever the model's on_topic said. const around = !why ? quoteContext(win, quote, { before: 400, after: 150 }) : null; const gate = around ? onTopicBy({ quote, before: around.before, terms: rare, ...(topic ? { topic } : {}) }) : null; if (!why && !gate) why = `off the question: no ${rare.map((t) => `“${t}”`).join(" or ")}${topic && !rare.includes(topic) ? ` or “${topic}”` : ""} in the quote or the 300 characters before it`; // Read-aloud cues (round b): what the transcript around the quote // says about whose words it is. Dropped, or kept to check by ear. const cues = !why && raMode !== "off" ? readAloudCues({ before: around!.before, quote, after: around!.after, hosts: hostNames }) : []; if (cues.length && raMode === "drop") why = `read aloud: ${cuesLine(cues)}`; // The neutral form: the model's topic label, held down by code, // and the line code writes around the quote. let label: TopicLabel | undefined; if (neutral && !why) { label = topicLabel(raw.topic, { fallback: runTopic, hosts: hostNames, ground: [quote, around!.before.slice(-GATE_CHARS), title, question, runTopic, ...terms] }); claim = neutralSentence({ title, date: v.date, topic: label.label }); } const at = sec ?? ch[0]![0]; batchLines.push(`${v.id} @ ${mmss(at)} “${quote}” — ${claim || "(no claim)"}${why ? ` [dropped: ${why}]` : ""}`); // Kept: and flagged to check by ear, or with its topic label refused (the run's topic used). const keptWhy = `verbatim in its window${cues.length ? `; flagged: check by ear (read-aloud cue: ${cuesLine(cues)})` : ""}${label?.from === "fallback" ? `; label refused: ${label.why} — the run's topic used` : ""}`; fates.push({ text: quote ? `“${quote}” — ${claim || "(no claim)"}` : claim || "(empty)", outcome: why ? "dropped" : "kept", why: why ?? keptWhy }); if (why) { dropped.push({ video: v.id, quote, why }); event({ kind: "dropped", why, video: v.id, quote, claim }); h.trace({ t: "check", quote, cite: { channel: slug, video: v.id, start: at }, ok: false, reason: why, stage: "extract", dropped: true, claim }); continue; } h.trace({ t: "check", quote, cite: { channel: slug, video: v.id, start: at }, ok: true, reason: `verbatim in its window${cues.length ? `; read-aloud cue: ${cuesLine(cues)} — to check by ear` : ""}${label?.from === "fallback" ? `; topic label refused (${label.why}), the run's topic used` : ""}`, stage: "extract", claim, }); if (cues.length) event({ kind: "read-aloud", video: v.id, quote, cues }); kept.push({ video: v.id, title, channel: v.channel, slug, date: v.date, quote, claim, sec: sec!, strength: Math.round(Number(raw.strength) || 2), flags: neutral ? [] : lintClaim(claim, quote), before: around!.before, after: around!.after, gate: gate!, ...(label ? { label } : {}), ...(cues.length ? { readAloud: cues, mark: true } : {}), }); } const nKept = fates.filter((f) => f.outcome === "kept").length; if (fates.length) slot.decide(nKept ? "kept" : "dropped", `${nKept} of ${fates.length} item${fates.length === 1 ? "" : "s"} kept`, fates); else slot.decide("n/a", "relevant, but no items"); } } h.log(` read ${v.id} — kept so far ${kept.length}, dropped ${dropped.length}`); h.progress({ metric: "entries", current: ++visited, total: todo.length }); } const k = b / READ_BATCH + 1; const usd = h.meter.usd - batchUsd; h.trace({ t: "batch", k, of: batches, ids: batch.map((v) => v.id), lines: batchLines, model, usd }); h.trace({ t: "cost", step: `batch ${k}`, usd, model, total: h.meter.usd }); } // Too little on the question is a result, said in one sentence — never a // report padded with what is off it (a restricted sweep, a refresh's, keeps // even one). const minKept = only?.length ? 1 : MIN_KEPT; const nothingFound = async (stage: string) => { const offQuestion = dropped.filter((d) => d.why.startsWith("off the question")).length; const sentence = `Nothing usable found: ${readIds.length} recording(s) read of ${nEnum} matching ${terms.join(", ")}; ` + `${kept.length} passage(s) ${stage}${offQuestion ? ` (${offQuestion} more were verbatim but off it)` : ""}, ` + `fewer than the ${minKept} a report needs.`; h.check({ name: "evidence", ok: true, detail: sentence }); h.trace({ t: "note", text: sentence }); const title = question.replace(/["“”#]/g, "").trim().slice(0, 90); const md = writeNothing(sentence, { question, title, channels, terms, since, until, nEnum, read: readIds.length, nChunks, nRelevant, dropped: dropped.length, partial, todo: todo.length, model, }); await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths); const c = await convertSweepText(md, { id: h.article, title, cuesOf: deps.cuesOf, postChannelOf: deps.postChannelOf }); if (c.ok) await writeIterationFile(h.article, h.n, "report.json", c.report, h.paths); return { status: "done" as const, summary: sentence }; }; if (kept.length < minKept) return nothingFound("were verbatim and on the question"); // 3b. the meaning check (D2 item 3): one call per kept item, with the // transcript around its quote; code decides from the answer. Its answer is // kept beside the item (items.jsonl: the prompt, the answer, the decision, // the seconds). kept.sort((a, b) => b.strength - a.strength || a.date.localeCompare(b.date) || a.video.localeCompare(b.video) || a.sec - b.sec); const host = askedAboutName(question) ?? "the channel's host (its own voice)"; // The neutral form has no drafted sentence to check: no call. Its items // are stored the same way (items.jsonl), with the label and the cues. // A quote kept on a read-aloud cue is checked last: it is shown marked to // check by ear whatever the check says, so it never spends the budget of an // unmarked one. const toCheck = neutral ? [] : [...kept.filter((r) => !r.mark), ...kept.filter((r) => r.mark)].slice(0, MAX_MEANING_CHECKS); const unchecked = neutral ? 0 : kept.length - toCheck.length; const items: Record<string, unknown>[] = []; const tally: Record<string, number> = {}; const passed: Kept[] = []; for (const r of toCheck) { deps.signal?.throwIfAborted(); const user = meaningPrompt({ question, host, before: r.before, quote: r.quote, after: r.after, sentence: r.claim }); const t0 = Date.now(); let answer: MeaningAnswer; const slot = new CallSlot(); try { answer = readMeaning(await ask(h, model, MEANING_SYSTEM, user, MEANING_SCHEMA, `meaning ${r.video}@${r.sec}`, false, slot)); } catch (e) { if (deps.signal?.aborted) throw e; tally["check failed"] = (tally["check failed"] ?? 0) + 1; dropped.push({ video: r.video, quote: r.quote, why: `meaning check failed: ${(e as Error).message}` }); items.push({ video: r.video, sec: r.sec, quote: r.quote, claim: r.claim, gate: r.gate, before: r.before, after: r.after, prompt: user, error: (e as Error).message, decision: { action: "drop", why: "the meaning check failed" } }); continue; } const seconds = Math.round((Date.now() - t0) / 100) / 10; const decision = decideMeaning(answer, { sentence: r.claim, quote: r.quote, before: r.before, after: r.after }); tally[decision.action] = (tally[decision.action] ?? 0) + 1; // The model log: what code made of the answer (a read-aloud mark stays a flag). const ear = r.readAloud?.length ? `; flagged: check by ear (read-aloud cue: ${cuesLine(r.readAloud)})` : ""; if (decision.action === "drop") slot.decide("dropped", `meaning check: ${decision.why}`); else if (decision.action === "rewrite") slot.decide("rewritten", `meaning check: ${decision.why}${ear}`, [{ text: decision.sentence, outcome: "rewritten", why: `from: ${r.claim}` }]); else if (decision.action === "mark") slot.decide("kept", `flagged: check by ear (${decision.why})${ear}`); else slot.decide("kept", `meaning check: ${decision.why}${ear}`); items.push({ video: r.video, sec: r.sec, quote: r.quote, claim: r.claim, gate: r.gate, before: r.before, after: r.after, prompt: user, answer, decision, seconds, ...(r.readAloud ? { readAloud: r.readAloud } : {}) }); h.trace({ t: "meaning", video: r.video, sec: r.sec, quote: r.quote, answer, action: decision.action, why: decision.why, ...(decision.action !== "drop" && decision.sentence !== r.claim ? { from: r.claim, to: decision.sentence } : {}), seconds }); if (decision.action === "drop") { dropped.push({ video: r.video, quote: r.quote, why: `meaning check: ${decision.why}` }); event({ kind: "dropped", why: `meaning check: ${decision.why}`, video: r.video, quote: r.quote, claim: r.claim }); continue; } passed.push({ ...r, claim: decision.sentence.replace(/"/g, "'"), meaning: { answer, decision, seconds, drafted: r.claim }, ...(decision.action === "mark" || r.mark ? { mark: true } : {}) }); } if (neutral) { for (const r of kept) { items.push({ video: r.video, sec: r.sec, quote: r.quote, claim: r.claim, form: "neutral", topic: r.label?.label, ...(r.label?.from === "fallback" ? { topicRefused: r.label.why } : {}), gate: r.gate, before: r.before, after: r.after, ...(r.readAloud ? { readAloud: r.readAloud } : {}), decision: r.mark ? { action: "mark", why: `read-aloud cue: ${cuesLine(r.readAloud ?? [])}` } : { action: "keep", why: "verbatim, on the question, no read-aloud cue" }, }); } } await writeIterationFile(h.article, h.n, "items.jsonl", items.map((x) => JSON.stringify(x)).join("\n") + (items.length ? "\n" : ""), h.paths); if (!neutral) { const tallyLine = Object.entries(tally).map(([k, n]) => `${n} ${k === "mark" ? "marked check by ear" : k === "keep" ? "kept" : k === "rewrite" ? "rewritten" : k === "drop" ? "dropped" : k}`).join(", "); h.log(`meaning check: ${toCheck.length} item(s): ${tallyLine}${unchecked ? `; ${unchecked} past the budget of ${MAX_MEANING_CHECKS} not checked (left out)` : ""}`); h.check({ name: "meaning", ok: !tally["check failed"], detail: `${toCheck.length} checked: ${tallyLine}${unchecked ? `; ${unchecked} not checked` : ""}` }); kept.splice(0, kept.length, ...passed); if (kept.length < minKept) return nothingFound("were verbatim, on the question and passed the meaning check"); } const nReadAloud = dropped.filter((d) => d.why.startsWith("read aloud")).length; const nByEar = kept.filter((r) => r.readAloud?.length).length; if (raMode !== "off") { const line = `read-aloud cues (${raMode}): ${raMode === "drop" ? `${nReadAloud} quote(s) dropped` : `${nByEar} quote(s) kept to check by ear`}`; h.log(line); h.check({ name: "read-aloud", ok: true, detail: line }); } // 4. group and title (the model); counts, balance and caps in code // "Check by ear" items are never grouped (never in the first section): // they are a last section of their own. const marked = kept.filter((r) => r.mark).slice(0, MAX_CLAIMS_PER_SECTION); const perVideo = new Map<string, number>(); const trimmed = kept.filter((r) => !r.mark).filter((r) => { perVideo.set(r.video, (perVideo.get(r.video) ?? 0) + 1); return perVideo.get(r.video)! <= MAX_CLAIMS_PER_VIDEO; }); const pool = trimmed .slice(0, MAX_CLAIMS_TOTAL) .sort((a, b) => a.date.localeCompare(b.date) || a.video.localeCompare(b.video) || a.sec - b.sec); const listing = pool.map((r, i) => (neutral ? `${i + 1}. (${r.date}) ${r.label!.label}: ${r.quote.split(" ").slice(0, 24).join(" ")}` : `${i + 1}. (${r.date}) ${r.claim}`)).join("\n"); let best: { score: number; g: { title?: unknown; sections?: unknown }; slot: CallSlot; why: string } | null = null; const groupSlots: { slot: CallSlot; why: string }[] = []; for (let attempt = 0; attempt < (pool.length ? 2 : 0); attempt++) { let g: { title?: unknown; sections?: unknown }; const slot = new CallSlot(); try { g = await ask(h, model, neutral ? NEUTRAL_GROUP_SYSTEM : GROUP_SYSTEM, `Research question: ${question}\n\n${neutral ? "Quotes" : "Findings"}:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`, true, slot); } catch (e) { if (deps.signal?.aborted) throw e; event({ kind: "group-failed", error: (e as Error).message }); continue; } const secs = (Array.isArray(g.sections) ? g.sections : []).slice(0, MAX_SECTIONS) as { findings?: unknown }[]; const nums = (s: { findings?: unknown }) => (Array.isArray(s.findings) ? s.findings : []).filter((x): x is number => Number.isInteger(x) && x >= 1 && x <= pool.length); const placed = new Set(secs.flatMap(nums)); const biggest = Math.max(0, ...secs.map((s) => new Set(nums(s)).size)); const score = placed.size - (secs.length > 1 && biggest > 0.7 * pool.length ? biggest : 0) * 0.5; const why = `placed ${placed.size} of ${pool.length} findings in ${secs.length} section${secs.length === 1 ? "" : "s"}${secs.length > 1 && biggest > 0.7 * pool.length ? ` (one holds ${biggest})` : ""}`; groupSlots.push({ slot, why }); if (!best || score > best.score) best = { score, g, slot, why }; if (placed.size >= pool.length * 0.8 && biggest <= 0.7 * pool.length) break; } for (const x of groupSlots) if (best && x.slot !== best.slot) x.slot.decide("dropped", `${x.why}; the other grouping was kept`); best?.slot.decide("kept", best.why); const g = best?.g ?? { title: question, sections: [] }; // The neutral form's title is code's too: the topic and whose recordings. const title = neutral ? neutralTitle(runTopic, channelNames.map((c) => c.name || c.slug)) : (String(g.title ?? "") || question).replace(/["“”#]/g, "").trim().slice(0, 90) || question.slice(0, 90); const raw = ((Array.isArray(g.sections) ? g.sections : []) as { heading?: unknown; findings?: unknown }[]) .slice(0, MAX_SECTIONS) .map((s) => ({ heading: String(s.heading ?? "").replace(/[#"“”]/g, "").trim().slice(0, 60) || "Findings", nums: [...new Set((Array.isArray(s.findings) ? s.findings : []).filter((x): x is number => Number.isInteger(x) && x >= 1 && x <= pool.length))].sort((a, b) => a - b), })) .filter((s) => s.nums.length); // A finding in several sections goes to the smallest of them. const home = new Map<number, number>(); raw.forEach((s, i) => { for (const n of s.nums) if (!home.has(n) || raw[home.get(n)!]!.nums.length > s.nums.length) home.set(n, i); }); let sections = raw.map((s, i) => ({ heading: s.heading, nums: s.nums.filter((n) => home.get(n) === i) })); const rest = pool.map((_, i) => i + 1).filter((n) => !home.has(n)); // The neutral form's headings are held down like its labels: a heading that // is not a grounded noun-phrase topic (neutralHeading) is code's, built from // the section's labels. // A code-written heading's base (its ordinal off), to number them again // once the caps have dropped what they drop. const codeBase = new Map<string, string>(); const headingItems: CallItem[] = []; if (neutral) { const used = new Set<string>(); sections = sections.map((s) => { const recs = s.nums.map((n) => pool[n - 1]!); // The labels a code heading is built from are the model's that passed // (a refused one is the run's topic, which is every section's). const own = recs.filter((x) => x.label!.from === "model").map((x) => x.label!.label); const r = neutralHeading(s.heading, { labels: own, ground: [...recs.flatMap((x) => [x.quote, x.title]), question, runTopic], topic: runTopic, hosts: hostNames, used }); if (r.from === "code") { codeBase.set(r.heading, r.heading.replace(/ \(\d+\)$/, "")); const line = `heading “${s.heading}” replaced by “${r.heading}” (${r.why})`; h.log(line); h.trace({ t: "note", text: line }); } headingItems.push( r.from === "model" ? { text: `heading: ${s.heading}`, outcome: "kept", why: "a grounded noun-phrase topic" } : { text: `heading: ${s.heading}`, outcome: "rewritten", why: `heading refused: ${r.why} — replaced by “${codeBase.get(r.heading)}” (written by code)` }, ); return { ...s, heading: r.heading }; }); // The model log: on the grouping call whose headings these were. best?.slot.items(headingItems); } if (rest.length) sections.push({ heading: neutral ? "Other quotes" : "Other findings", nums: rest }); sections = sections.filter((s) => s.nums.length); let leftOut = kept.length - pool.length - marked.length + unchecked; for (const s of sections) { s.nums.sort((a, b) => pool[b - 1]!.strength - pool[a - 1]!.strength || pool[a - 1]!.date.localeCompare(pool[b - 1]!.date) || pool[a - 1]!.sec - pool[b - 1]!.sec); if (s.nums.length > MAX_CLAIMS_PER_SECTION) { leftOut += s.nums.length - MAX_CLAIMS_PER_SECTION; s.nums = s.nums.slice(0, MAX_CLAIMS_PER_SECTION); } } let secs = sections.map((s) => ({ heading: s.heading, recs: s.nums.map((n) => pool[n - 1]!).sort((a, b) => b.strength - a.strength) })); const total = secs.reduce((s, x) => s + x.recs.length, 0); if (total > maxClaims) { // Round-robin across sections, so every section keeps its first ones. const keep = new Set<string>(); for (let i = 0; keep.size < maxClaims; i++) { secs.forEach((s, si) => { if (i < s.recs.length && keep.size < maxClaims) keep.add(`${si}:${i}`); }); } secs = secs.map((s, si) => ({ heading: s.heading, recs: s.recs.filter((_, ri) => keep.has(`${si}:${ri}`)) })).filter((s) => s.recs.length); leftOut += total - maxClaims; } if (codeBase.size) { // Ordinals in the order shown, with no gap: (2) follows the base, or a // model heading of the same words. const k = new Map<string, number>(); for (const s of secs) if (!codeBase.has(s.heading)) k.set(s.heading.toLowerCase(), 1); for (const s of secs) { const base = codeBase.get(s.heading); if (base === undefined) continue; const n = (k.get(base.toLowerCase()) ?? 0) + 1; k.set(base.toLowerCase(), n); s.heading = n === 1 ? base : `${base} (${n})`; } } if (marked.length) secs.push({ heading: "To check by ear", recs: marked }); for (const s of secs) s.recs.sort((a, b) => a.date.localeCompare(b.date) || a.sec - b.sec); // 5. the markdown, convert, the strict check (a failing finding is dropped) const ctx = { question, title, channels, origin, terms, source: deps.corpus.source, model, since, until, nEnum, read: readIds.length, nChunks, nRelevant, kept: kept.length, leftOut, partial, todo: todo.length, neutral, readAloud: raMode, nReadAloud, }; let md = writeMarkdown(secs, { ...ctx, dropped: dropped.length }); await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths); let report = null; let lastProblems: string[] = []; for (let round = 0; round < 3; round++) { const c = await convertSweepText(md, { id: h.article, title, cuesOf: deps.cuesOf, postChannelOf: deps.postChannelOf }); h.check({ name: "convert", ok: c.ok, ...(c.ok ? {} : { detail: c.problems.slice(0, 3).join("; ") }) }); if (!c.ok) return { status: "failed", summary: `the report does not convert: ${c.problems[0]}` }; const problems = await checkQuotes(c.report, deps); for (const p of problems) { h.trace({ t: "check", quote: p.quote, cite: { citation: p.citation, channel: p.channel, video: p.id, ...(p.second !== undefined ? { start: p.second } : {}) }, ok: false, reason: p.why, stage: "strict", round: round + 1 }); } if (!problems.length) { report = c.report; break; } const d = dropFailedFindings(md, problems); lastProblems = problems.map((p) => p.why); for (const why of d.dropped) { dropped.push({ video: "", quote: "", why: `quote check: ${why}` }); event({ kind: "dropped", why: `quote check: ${why}` }); } for (const item of d.items) { const p = item.problem; h.trace({ t: "check", quote: p.quote, cite: { citation: p.citation, channel: p.channel, video: p.id, ...(p.second !== undefined ? { start: p.second } : {}) }, ok: false, reason: `quote check: ${p.why}`, stage: "drop", dropped: true, claim: item.claim }); } if (!d.dropped.length) break; // Re-render from what is left: the coverage counts the drop. const left = new Set( problems.map((p) => `${p.channel}/${p.id}`), ); secs = secs .map((s) => ({ heading: s.heading, recs: s.recs.filter( (r) => !(left.has(`${r.slug}/${r.video}`) && problems.some((p) => norm(r.quote).includes(norm(p.quote)) || norm(p.quote).includes(norm(r.quote)))), ), })) .filter((s) => s.recs.length); if (!secs.length) return { status: "failed", summary: "nothing left after the quote check" }; md = writeMarkdown(secs, { ...ctx, dropped: dropped.length }); await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths); } if (!report) { h.check({ name: "quotes", ok: false, detail: lastProblems.slice(0, 3).join("; ") }); return { status: "failed", summary: "quotes still fail the strict check" }; } const cited = secs.flatMap((s) => s.recs); const flagged = cited.filter((r) => r.flags.length); h.check({ name: "quotes", ok: true, detail: `every quote verbatim (strict); ${dropped.length} dropped` }); h.check({ name: "lint", ok: flagged.length === 0, detail: flagged.length ? `${flagged.length} claim(s) to read against their quote: ${flagged.slice(0, 3).map((r) => `${r.claim.slice(0, 50)} (${r.flags[0]})`).join("; ")}` : "no claim flagged", }); // A quote kept on a read-aloud cue carries the flag in the report's data // (a pill on the claim's card), not only in its words. const byEar = cited.filter((r) => r.readAloud?.length); if (byEar.length) flagReadAloud(report as Report, byEar); await writeIterationFile(h.article, h.n, "report.json", report, h.paths); traceReport(h.trace, report as Report); return { status: "done", summary: `“${title}”: ${cited.length} claim(s) in ${secs.length} section(s) from ${new Set(cited.map((r) => r.video)).size} video(s); ${dropped.length} dropped, ${flagged.length} flagged` + (raMode === "flag" ? `, ${byEar.length} to check by ear (read-aloud cue)` : raMode === "drop" ? `, ${nReadAloud} of the dropped on a read-aloud cue` : ""), }; } // The claims whose citation is one of these records' quotes get the flag. function flagReadAloud(report: Report, recs: readonly Kept[]): void { const keys = new Set(recs.map((r) => `${r.video}|${norm(r.quote)}`)); const hit = new Set<string>(); for (const [cid, c] of Object.entries(report.citations ?? {})) { const q = (c as { quote?: string }).quote; if ((c.kind === "video" || c.kind === "audio") && q && keys.has(`${c.id}|${norm(q)}`)) hit.add(cid); } for (const s of report.sections ?? []) for (const k of s.claims ?? []) if ((k.citations ?? []).some((c) => hit.has(c))) k.flag = READ_ALOUD_FLAG; } function citeLabel(r: Kept): string { return `${r.title.replace(/[[\]()]/g, "").trim().slice(0, 80)} @ ${mmss(r.sec)}`; } function writeMarkdown( secs: { heading: string; recs: Kept[] }[], c: { question: string; title: string; channels: string[]; origin: string; terms: string[]; source: string; model: string; since?: string; until?: string; nEnum: number; read: number; nChunks: number; nRelevant: number; kept: number; dropped: number; leftOut: number; partial: string[]; todo: number; neutral?: boolean; readAloud?: ReadAloudMode; nReadAloud?: number; }, ): string { const cited = secs.flatMap((s) => s.recs); const md = [`# ${c.title}`, "", `Question: ${c.question}`, ""]; const byEar = cited.filter((r) => r.readAloud?.length).length; for (const s of secs) { md.push(`## ${s.heading}`, ""); for (const r of s.recs) md.push(`- ${r.mark ? `${CHECK_BY_EAR} ` : ""}${r.claim} "${r.quote}" — [${citeLabel(r)}](${momentHref(c.origin, r.slug, r.video, r.sec)})`); md.push(""); } const scope = c.channels.join(", ") + (c.since ? `, from ${c.since}` : "") + (c.until ? ` to ${c.until}` : ""); md.push( "## Coverage", "", `Searched ${scope} for ${c.terms.join(", ")}. ${c.nEnum} video(s) matched; ${c.read} read (${c.nChunks} excerpt(s), ` + `${c.nRelevant} judged relevant); ${new Set(cited.map((r) => r.video)).size} cited, ${cited.length} quote(s). Quotes ` + `found ${c.kept}, dropped ${c.dropped} (not verbatim, unusable, or not passing the quote check), ${c.leftOut} left out ` + `by the caps. ` + (c.neutral ? `The quotes were picked and their topics labelled by ${c.model}; ${NEUTRAL_LINES_NOTE}; every quote was checked word for word against its transcript.` : `Drafted by ${c.model}; every quote was checked word for word against its transcript.`) + (c.readAloud === "flag" && byEar ? ` ${byEar} quote(s) are marked to check by ear: the transcript around them has a sign of reading aloud (a tweet, a headline, an article, “it says”), so the words may not be the speaker's own.` : "") + (c.readAloud === "drop" && c.nReadAloud ? ` ${c.nReadAloud} of the dropped quote(s) had a sign of reading aloud around them (a tweet, a headline, an article, “it says”).` : "") + (c.partial.length ? ` COVERAGE PARTIAL for: ${c.partial.join(", ")}.` : "") + (c.nEnum > c.todo ? ` Only ${c.todo} of the ${c.nEnum} matching videos were read.` : ""), "", ); return md.join("\n"); } // The prompt that asks for terms again, naming what was dropped. function retermsPrompt(question: string, dropped: readonly DroppedTerm[]): string { return ( `Research question: ${question}\n\n` + `These terms were dropped: ${dropped.map((d) => `"${d.term}" (${d.why})`).join(", ") || "none"}. ` + "Propose different, more distinctive terms for the topic." ); } // The scope's channels with their names (list_channels' lines). async function channelNamesOf(corpus: TaskDeps["corpus"], channels: readonly string[]): Promise<(ChannelName & { videos?: number })[]> { const out: (ChannelName & { videos?: number })[] = channels.map((slug) => ({ slug })); try { const text = await corpus.call("list_channels", {}); for (const line of text.split("\n")) { const m = /^\s*-\s+(.*?)\s+\(slug:\s*([^,\s)]+)(?:,\s*(\d+)\s+videos?)?/.exec(line); if (!m) continue; const c = out.find((x) => x.slug === m[2]); if (c) { c.name = m[1]!; if (m[3]) c.videos = Number(m[3]); } } } catch { // the slugs alone } return out; } // How many recordings the scope holds: the listing when the corpus has one, // else the channels' counts. async function scopeSizeOf(corpus: TaskDeps["corpus"], channels: string[], since: string | undefined, until: string | undefined, names: readonly { videos?: number }[]): Promise<number> { if (corpus.listRecordings) { try { const l = await corpus.listRecordings({ channels, ...(since ? { date_from: since } : {}), ...(until ? { date_to: until } : {}) }); if (l.rows.length) return l.rows.length; } catch { // the counts below } } return names.reduce((s, c) => s + (c.videos ?? 0), 0); } function yearSpread(vids: readonly { date: string }[]): string { const by = new Map<string, number>(); for (const v of vids) { const y = /^\d{4}/.exec(v.date)?.[0] ?? "?"; by.set(y, (by.get(y) ?? 0) + 1); } return [...by.entries()].sort().map(([y, n]) => `${y}:${n}`).join(" "); } // "Nothing usable found": the question, the one sentence, and what was // searched and read. function writeNothing( sentence: string, c: { question: string; title: string; channels: string[]; terms: string[]; since?: string; until?: string; nEnum: number; read: number; nChunks: number; nRelevant: number; dropped: number; partial: string[]; todo: number; model: string; }, ): string { const scope = c.channels.join(", ") + (c.since ? `, from ${c.since}` : "") + (c.until ? ` to ${c.until}` : ""); return [ `# ${c.title}`, "", `Question: ${c.question}`, "", "## Nothing usable found", "", sentence, "", "## Coverage", "", `Searched ${scope} for ${c.terms.join(", ")}. ${c.nEnum} video(s) matched; ${c.read} read (${c.nChunks} excerpt(s), ` + `${c.nRelevant} judged relevant); ${c.dropped} quote(s) dropped. Drafted by ${c.model}.` + (c.partial.length ? ` COVERAGE PARTIAL for: ${c.partial.join(", ")}.` : "") + (c.nEnum > c.todo ? ` Only ${c.todo} of the ${c.nEnum} matching videos were read.` : ""), "", ].join("\n"); } // The person the question asks about, as written ("Jeremy"), or null. function askedAboutName(question: string): string | null { const m = /\b(?:has|have|does|do|did|is|was)\s+((?:[A-Z][\w'’.-]*\s+){0,2}[A-Z][\w'’.-]*?)(?:['’]s)?\s+(?:ever\s+|really\s+)?(?:said|say|think|thought|felt|feel|talked|talk|claimed|argued|told|stated|reacted|commented)\b/.exec(question); return m ? m[1]!.trim() : null; }