// What a local sweep reads (demo epic D2, item 1): the search terms the model // proposes, cleaned by code; their rarity over the scope; each recording's // score; and the reading set — the best by score plus one recording per // year-quarter that has hits, so a 2024 subject is never answered from 2017. // // Pure: the pipeline (./sweep-pipeline.ts) does the calls and hands the // numbers in. Measured on the D0 baseline (11 Nov 2026): the model's terms led // with the subject's own name and generic words ("jeremy", "show", "say"), // were weighted by their position, and the 40 read of 3,000-6,800 matches held // nothing from the years asked about. import { strictNormalize } from "../../../citations/verify"; // Words that never make a search term on their own: function words, and the // words a question ABOUT someone's talk is made of. export const GENERIC_WORDS = new Set( ( "a an the and or but of to in on at by for from with without into onto over under about after before between " + "is are was were be been being am do does did done has have had having will would shall should can could may might must " + "i me my we us our you your he him his she her they them their it its this that these those there here " + "what when where which who whom whose why how whether if then than so such also just like very really " + "not no yes all any some more most many much other others own same each every both few " + "say says said saying tell tells told talk talks talked talking speak speaks spoke discuss discussed discussion " + "think thinks thought thoughts feel feels felt opinion opinions view views comment comments commented commentary " + "statement statements mention mentions mentioned remark remarks claim claims claimed argue argued react reaction reacts " + "show shows video videos channel channels stream streams streamer episode content " + "thing things stuff people person someone something anything everything way ways time times year years day days " + "get gets got make makes made making go goes went going come came take took give gave start started starting " + "reason reasons why because issue issues topic topics subject question questions answer news story stories " + "good bad new old big great best worst lot lots" ).split(/\s+/), ); export type ChannelName = { slug: string; name?: string | null }; // "TheQuartering" → "the quartering"; "the-quartering" → "the quartering". function nameWords(s: string): string[] { return s .replace(/\(.*?\)/g, " ") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/[-_]+/g, " ") .toLowerCase() .split(/[^a-z0-9']+/) .filter(Boolean); } // The person a question is about ("What has Jeremy said about …", "What does // Jeremy Hambly think of …", "Jeremy's views on …"): their name words. const ASKED_ABOUT = /\b(?:what|how|why|when|where|has|have|does|do|did|is|was)\s+((?:[A-Z][\w'’.-]*\s+){0,2}[A-Z][\w'’.-]*?)(?:['’]s)?\s+(?:ever\s+|really\s+|publicly\s+)?(?:said|say|says|think|thinks|thought|felt|feel|feels|talked|talk|talks|claimed|claim|claims|argued|argue|revealed|reveal|told|tell|admitted|admit|stated|state|reacted|react|commented|comment|done|do)\b/; const POSSESSIVE = /\b([A-Z][\w-]*(?:\s+[A-Z][\w-]*){0,2})['’]s\s+(?:views?|take|takes|opinions?|thoughts|comments|words|stance|position|reaction)\b/; // The subject's own names: the channels' slugs and names, the person the // question asks about, and any host names the caller knows (a channel's // context note). A term that is one of these finds the speaker everywhere. export function subjectNames(o: { question: string; channels: readonly ChannelName[]; hosts?: readonly string[] }): Set { const out = new Set(); const add = (s: string) => { const words = nameWords(s).filter((w) => !GENERIC_WORDS.has(w)); for (const w of words) out.add(w); const joined = words.join(" "); if (joined) out.add(joined); const solid = s.toLowerCase().replace(/[^a-z0-9]+/g, ""); if (solid.length >= 4) out.add(solid); }; for (const c of o.channels) { add(c.slug); if (c.name) add(c.name); } for (const h of o.hosts ?? []) add(h); for (const re of [ASKED_ABOUT, POSSESSIVE]) { const m = re.exec(o.question); if (m) add(m[1]!); } return out; } export type DroppedTerm = { term: string; why: string }; // A proposed term as a search phrase: lowercase, no quotes or operators, the // generic words trimmed from its ends (a phrase stays a phrase). // A possessive is its noun ("company's" → "company"); `names`' words come // off a phrase's ends too ("jeremy's coffee company" → "coffee company"). export function normalizeTerm(raw: unknown, names: ReadonlySet = new Set()): string { let words = String(raw ?? "") .toLowerCase() .replace(/[’‘`]/g, "'") .replace(/["“”]/g, "") .replace(/[^a-z0-9'\- ]+/g, " ") .split(/\s+/) .map((w) => w.replace(/'s$|s'$|^'+|'+$/g, (m) => (m === "s'" ? "s" : ""))) .filter(Boolean); const edge = (w: string) => GENERIC_WORDS.has(w) || names.has(w); while (words.length > 1 && edge(words[0]!)) words = words.slice(1); while (words.length > 1 && edge(words.at(-1)!)) words = words.slice(0, -1); return words.join(" "); } // The model's terms, cleaned: the subject's own names, generic words, too // long and repeats dropped, each with its reason. Phrases are kept whole. export function cleanTerms(proposed: readonly unknown[], o: { names: ReadonlySet; max?: number }): { kept: string[]; dropped: DroppedTerm[] } { const kept: string[] = []; const dropped: DroppedTerm[] = []; for (const raw of proposed) { const t = normalizeTerm(raw, o.names); if (!t) continue; const words = t.split(" "); if (t.length > 40) dropped.push({ term: t, why: "too long" }); else if (words.every((w) => GENERIC_WORDS.has(w))) dropped.push({ term: t, why: "a generic word" }); else if (o.names.has(t) || words.every((w) => o.names.has(w) || GENERIC_WORDS.has(w))) dropped.push({ term: t, why: "the subject's own name" }); else if (t.length < 3) dropped.push({ term: t, why: "too short" }); else if (kept.includes(t)) continue; else if (kept.some((k) => k === `${t}s` || `${k}s` === t)) dropped.push({ term: t, why: "a plural of another term" }); else kept.push(t); } // A phrase that holds another term ("star wars the acolyte" and "star // wars"): its remainder is a term too ("acolyte"; qwen3:8b on the Acolyte // question proposed only the two, and "acolyte" alone was never searched). for (const t of [...kept]) { for (const k of kept) { if (k === t || !t.startsWith(`${k} `) && !t.endsWith(` ${k}`)) continue; const rest = normalizeTerm(t.startsWith(`${k} `) ? t.slice(k.length + 1) : t.slice(0, t.length - k.length - 1), o.names); const rw = rest.split(" "); if (rest.length >= 4 && !kept.includes(rest) && !rw.every((w) => GENERIC_WORDS.has(w) || o.names.has(w))) kept.push(rest); } } const max = o.max ?? 6; for (const t of kept.slice(max)) dropped.push({ term: t, why: `more than ${max} terms` }); return { kept: kept.slice(0, max), dropped }; } // A term's enumeration as the pipeline saw it. export type TermCount = { term: string; videos: number; partial: boolean }; export type TermStat = TermCount & { // Of the scope's recordings (a partial count is a lower bound). share: number; // ln(scope / videos): an upper bound for a partial count. idf: number; // Matches more than COMMON_SHARE of the scope: dropped. common: boolean; // Its list nominates recordings. A capped (partial) list is a sample in the // corpus's page order, not by relevance: it only scores the nominated. nominates: boolean; }; export const COMMON_SHARE = 0.25; // Below this many recordings a share says nothing (one of three is 33%). export const MIN_SCOPE_FOR_SHARE = 40; // The gate's rare terms (item 2): at most this share of the scope. export const RARE_SHARE = 0.05; export function termStats(counts: readonly TermCount[], scopeSize: number): TermStat[] { const n = Math.max(1, scopeSize, ...counts.map((c) => c.videos)); return counts.map((c) => { const share = c.videos / n; const common = share > COMMON_SHARE && n >= MIN_SCOPE_FOR_SHARE; return { ...c, share, idf: c.videos > 0 ? Math.log(n / c.videos) : 0, common, nominates: c.videos > 0 && !common && !c.partial }; }); } // The usable terms: matched something and not common. export const usableTerms = (stats: readonly TermStat[]) => stats.filter((s) => s.videos > 0 && !s.common); // The terms a kept item must show (item 2's gate): the nominating terms at // most RARE_SHARE of the scope, and always the rarest nominating one(s). export function rareTermsOf(stats: readonly TermStat[]): string[] { const nom = stats.filter((s) => s.nominates); const rare = nom.filter((s) => s.share <= RARE_SHARE).map((s) => s.term); const least = Math.min(...nom.map((s) => s.videos)); for (const s of nom) if (s.videos === least && !rare.includes(s.term)) rare.push(s.term); return rare; } // Two different terms within `seconds` of each other in a recording's lines. export function termsNear(lines: readonly ([number, string] | null)[], terms: readonly string[], seconds = 90): boolean { const keys = terms.map((t) => ` ${strictNormalize(t)} `).filter((k) => k.trim()); const hits: [number, number][] = []; for (const l of lines) { if (!l) continue; const text = ` ${strictNormalize(l[1])} `; keys.forEach((k, i) => { if (text.includes(k)) hits.push([l[0], i]); }); } hits.sort((a, b) => a[0] - b[0]); for (let i = 0; i < hits.length; i++) { for (let j = i + 1; j < hits.length && hits[j]![0] - hits[i]![0] <= seconds; j++) if (hits[j]![1] !== hits[i]![1]) return true; } return false; } export const NEAR_BONUS = 1.5; // A recording's score: Σ rarity × hits over the usable terms, × NEAR_BONUS // when two terms hit within 90 s. Hits count saturated (log2(1 + hits), as // BM25 does): on D0's Acolyte question raw hits let 30 "star wars" outrank 5 // "acolyte" (19 of the top 40 held the subject's word); saturated, 35 of 40. export function scoreOf(hits: Readonly>, stats: ReadonlyMap, near = false): number { let s = 0; for (const [t, h] of Object.entries(hits)) { const st = stats.get(t); if (!st || st.common) continue; s += st.idf * Math.log2(1 + Math.max(0, h)); } return near ? s * NEAR_BONUS : s; } // "2024-06-11" → "2024Q2"; null when the date does not read. export function quarterOf(date: string | null | undefined): string | null { const m = /^(\d{4})-?(\d{2})/.exec(date ?? ""); if (!m) return null; const q = Math.floor((Number(m[2]) - 1) / 3) + 1; return q >= 1 && q <= 4 ? `${m[1]}Q${q}` : null; } export type Candidate = { id: string; date: string; score: number }; // The reading set: the top `n` by score, plus the best of every year-quarter // that has a (spreadable) candidate (at most `spreadMax` of them, the quarters whose best // scores highest), in score order. `spread` names the ones the date spread // added. // Only a candidate `spreadable` passes (one a rare term hits: a quarter where // only a common word hits has nothing on the subject). export function readingSet( ranked: readonly C[], o: { n: number; spreadMax?: number; spreadable?: (c: C) => boolean }, ): { read: C[]; spread: string[]; quarters: number } { const byScore = [...ranked].sort((a, b) => b.score - a.score || a.date.localeCompare(b.date) || a.id.localeCompare(b.id)); const top = byScore.slice(0, o.n); const inTop = new Set(top.map((c) => c.id)); const covered = new Set(top.map((c) => quarterOf(c.date)).filter(Boolean)); const best = new Map(); for (const c of byScore) { const q = quarterOf(c.date); if (!q || best.has(q) || (o.spreadable && !o.spreadable(c))) continue; best.set(q, c); } const extra = [...best.entries()] .filter(([q, c]) => !covered.has(q) && !inTop.has(c.id)) .map(([, c]) => c) .sort((a, b) => b.score - a.score) .slice(0, Math.max(0, o.spreadMax ?? Math.ceil(o.n / 2))); const read = [...top, ...extra].sort((a, b) => b.score - a.score || a.date.localeCompare(b.date)); return { read, spread: extra.map((c) => c.id), quarters: best.size }; } // How many recordings a time budget reads: calls a recording (measured on D0: // 2.3 extract calls per recording read) × seconds a call. Default 40. export const DEFAULT_READ = 40; export const CALLS_PER_RECORDING = 2.3; export function readingSize(o: { budgetMinutes?: number; secondsPerCall?: number } = {}): number { if (!o.budgetMinutes || !o.secondsPerCall || o.budgetMinutes <= 0 || o.secondsPerCall <= 0) return DEFAULT_READ; return Math.max(5, Math.min(150, Math.floor((o.budgetMinutes * 60) / (o.secondsPerCall * CALLS_PER_RECORDING)))); } // Measured seconds a call on this machine (D0, 11 Nov 2026: an extract call // on the RX 6600 XT); the plan's estimate when the settings name none. export const MEASURED_SECONDS_PER_CALL: Readonly> = { "qwen2.5:7b": 4.3, "qwen3:8b": 10.4 };