Archilyzer · Source

archilyzer

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

commit 6e5558c6a79ee2ee2a2c26c2f0d83cbf0d781a5d
parent 7b841a8270c43467a13259a5f7e5026878ae64c8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 10:10:33 -0500

sweep-pipeline: selection reads the subject, not the speaker (D2 item 1)

The local sweep's search terms led with the subject's own name and generic
words ("jeremy", "show", "say"), were weighted 1/(position+1), and the 40
recordings read of 3,000-6,800 matches held nothing from the years asked
about (D0 baseline, 11 Nov). Now:

- terms: the model also names the topic; code drops the subject's names
  (the channels' slugs and names, the person the question asks about, any
  host names given), generic words, possessives and plural repeats, keeps a
  phrase a phrase, and asks once more, naming what it dropped, when fewer
  than two usable terms remain;
- rarity: a term in more than 25% of the scope (scope >= 40) is dropped; a
  capped (partial) list never nominates -- it is a sample in page order -- and
  is counted again inside the candidates by id;
- ranking: idf x log2(1 + hits) (raw hits let 30 "star wars" outrank 5
  "acolyte": 19 of the top 40 held the subject's word; saturated, 35), x1.5
  when two terms hit within 90 s (read off the windows the read uses);
- the reading set: the top N (a time budget over seconds a call, default 40)
  plus the best recording of each year-quarter a rare term hits;
- a `select` trace event: scope, term stats, every recording read and why.

Measured on the D0 questions (qwen2.5:7b terms, selection only): the Acolyte
read set holds 25 recordings from 2024 (D0: 0), Musk/Twitter 38 from 2022
(D0: 0).

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Acommon/lib/report/draft/tasks/selection.test.ts | 121+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/selection.ts | 248+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/sweep-pipeline.ts | 243++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/lib/report/draft/tasks/trace.ts | 13+++++++++++--
Mmcp/src/draftTasks.test.ts | 26++++++++++++++++++++++++++
5 files changed, 603 insertions(+), 48 deletions(-)

diff --git a/common/lib/report/draft/tasks/selection.test.ts b/common/lib/report/draft/tasks/selection.test.ts @@ -0,0 +1,121 @@ +// What a local sweep reads (demo epic D2, item 1), on the D0 baseline's own +// cases: the Acolyte question's terms led with "jeremy" and "show"/"say", and +// its 40 read held nothing from 2024. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + cleanTerms, + normalizeTerm, + quarterOf, + rareTermsOf, + readingSet, + readingSize, + scoreOf, + subjectNames, + termStats, + termsNear, + usableTerms, +} from "./selection"; + +const QUARTERING = [{ slug: "the-quartering", name: "TheQuartering" }]; + +test("subjectNames: the person the question asks about and the channel's own words", () => { + const n = subjectNames({ question: "What has Jeremy said about the Star Wars show The Acolyte?", channels: QUARTERING }); + for (const w of ["jeremy", "quartering", "thequartering"]) assert.ok(n.has(w), w); + for (const w of ["acolyte", "star", "wars", "the", "show"]) assert.ok(!n.has(w), w); + assert.ok(subjectNames({ question: "What does Jeremy Hambly think of Disney?", channels: [] }).has("hambly")); + assert.ok(subjectNames({ question: "Jeremy's views on Disney", channels: [] }).has("jeremy")); + assert.ok(subjectNames({ question: "anything", channels: [], hosts: ["Chrissie Mayr"] }).has("mayr")); +}); + +test("cleanTerms: D0's Acolyte terms lose the subject's name and the generic words; phrases stay phrases", () => { + const names = subjectNames({ question: "What has Jeremy said about the Star Wars show The Acolyte?", channels: QUARTERING }); + const c = cleanTerms(["jeremy", "star wars", "acolyte", "show", "comment", "say"], { names }); + assert.deepEqual(c.kept, ["star wars", "acolyte"]); + assert.deepEqual( + c.dropped.map((d) => [d.term, d.why]), + [ + ["jeremy", "the subject's own name"], + ["show", "a generic word"], + ["comment", "a generic word"], + ["say", "a generic word"], + ], + ); + // The coffee question's phrases: the name and the possessive come off. + const a = cleanTerms(["jeremy's coffee company", "company's performance", "the quartering"], { names }); + assert.deepEqual(a.kept, ["coffee company", "company performance"]); + assert.equal(a.dropped[0]!.why, "the subject's own name"); + assert.equal(normalizeTerm('"Wizards of the Coast"'), "wizards of the coast"); + assert.equal(normalizeTerm("the acolyte"), "acolyte"); + assert.deepEqual(cleanTerms(["contest", "contests"], { names }).kept, ["contest"]); +}); + +test("termStats: rarity over the scope; a term in > 25% is common; a capped list scores but never nominates", () => { + const s = termStats( + [ + { term: "acolyte", videos: 48, partial: false }, + { term: "star wars", videos: 755, partial: false }, + { term: "twitter", videos: 2000, partial: true }, + { term: "people", videos: 4000, partial: false }, + { term: "nothing", videos: 0, partial: false }, + ], + 11712, + ); + const by = Object.fromEntries(s.map((x) => [x.term, x])); + assert.ok(by.acolyte!.idf > by["star wars"]!.idf); + assert.equal(by.people!.common, true); + assert.deepEqual([by.twitter!.common, by.twitter!.nominates], [false, false]); + assert.deepEqual(usableTerms(s).map((x) => x.term), ["acolyte", "star wars", "twitter"]); + assert.deepEqual(rareTermsOf(s), ["acolyte"]); + // A scope too small to say anything: nothing is common. + assert.equal(termStats([{ term: "contest", videos: 1, partial: false }], 3)[0]!.common, false); + // No term under 5%: the rarest nominating one is still the gate's. + assert.deepEqual(rareTermsOf(termStats([{ term: "elon musk", videos: 966, partial: false }, { term: "buy", videos: 1500, partial: false }], 11712)), ["elon musk"]); +}); + +test("scoreOf: rarity × saturated hits — 30 'star wars' no longer outrank 5 'acolyte'; two terms near = a bonus", () => { + const stats = new Map(termStats([{ term: "acolyte", videos: 48, partial: false }, { term: "star wars", videos: 755, partial: false }], 11712).map((x) => [x.term, x])); + assert.ok(scoreOf({ acolyte: 5, "star wars": 1 }, stats) > scoreOf({ "star wars": 30 }, stats)); + assert.ok(scoreOf({ acolyte: 2 }, stats, true) > scoreOf({ acolyte: 2 }, stats)); + assert.equal(scoreOf({ unknown: 9 }, stats), 0); +}); + +test("termsNear: two different terms within 90 s", () => { + const lines: ([number, string] | null)[] = [ + [10, "the new star wars show"], + [70, "the acolyte is out"], + [400, "acolyte again"], + ]; + assert.equal(termsNear(lines, ["acolyte", "star wars"]), true); + assert.equal(termsNear(lines.slice(1), ["acolyte", "star wars"]), false); + assert.equal(termsNear([[10, "star wars"], [200, "acolyte"]], ["acolyte", "star wars"]), false); +}); + +test("readingSet: the top n by score, plus the best of each quarter a rare term hits", () => { + const c = (id: string, date: string, score: number, rareHit = true) => ({ id, date, score, rareHit }); + const ranked = [ + c("sw2019a", "2019-12-01", 30, false), + c("sw2019b", "2019-12-02", 29, false), + c("aco2024a", "2024-06-05", 20), + c("aco2024b", "2024-06-06", 19), + c("aco2020", "2020-12-11", 3), + c("sw2018", "2018-01-01", 2, false), + ]; + const s = readingSet(ranked, { n: 3, spreadable: (x) => x.rareHit }); + assert.deepEqual( + s.read.map((x) => x.id), + ["sw2019a", "sw2019b", "aco2024a", "aco2020"], + ); + assert.deepEqual(s.spread, ["aco2020"]); + assert.equal(quarterOf("2024-06-11"), "2024Q2"); + assert.equal(quarterOf("20240611"), "2024Q2"); + assert.equal(quarterOf(""), null); +}); + +test("readingSize: a time budget over the measured seconds a call; 40 by default", () => { + assert.equal(readingSize(), 40); + assert.equal(readingSize({ budgetMinutes: 20, secondsPerCall: 4.3 }), 121); + assert.equal(readingSize({ budgetMinutes: 20, secondsPerCall: 10.4 }), 50); + assert.equal(readingSize({ budgetMinutes: 1, secondsPerCall: 60 }), 5); +}); diff --git a/common/lib/report/draft/tasks/selection.ts b/common/lib/report/draft/tasks/selection.ts @@ -0,0 +1,248 @@ +// 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<string> { + const out = new Set<string>(); + 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<string> = 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<string>; 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); + } + 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. +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 rarest = [...nom].sort((a, b) => a.videos - b.videos)[0]; + if (rarest && !rare.includes(rarest.term)) rare.push(rarest.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<Record<string, number>>, stats: ReadonlyMap<string, TermStat>, 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<C extends Candidate>( + 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<string, C>(); + 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<Record<string, number>> = { "qwen2.5:7b": 4.3, "qwen3:8b": 10.4 }; diff --git a/common/lib/report/draft/tasks/sweep-pipeline.ts b/common/lib/report/draft/tasks/sweep-pipeline.ts @@ -26,6 +26,20 @@ 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 { + cleanTerms, + 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) @@ -48,14 +62,19 @@ const NEGATIONS = /\b(never|not|no|nobody|nothing|none|neither|nor|cannot|withou 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. Mostly SINGLE " + - "words (a name, a noun, a distinctive verb); a two-word phrase only for a fixed name. Lowercase, no quotation marks, " + - "no boolean operators, no plural and singular of the same word. Prefer distinctive words over common ones. Return " + - "between three and six."; + "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 } }, - required: ["terms"], + properties: { + terms: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 6 }, + topic: { type: "string" }, + }, + required: ["terms", "topic"], }; export const EXTRACT_SYSTEM = @@ -127,6 +146,12 @@ export type SweepPipelineInput = { 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[]; // 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. @@ -308,7 +333,6 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const since = input.from ?? iteration.scope?.from; const until = input.to ?? iteration.scope?.to; const origin = input.origin.replace(/\/+$/, ""); - const maxVideos = input.maxVideos ?? 40; const maxClaims = input.maxClaims ?? 40; const only = input.ids ?? iteration.scope?.ids; if (!question) throw new TaskInputError("a sweep needs its question"); @@ -319,25 +343,31 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T 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) + // 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 = ""; + const proposeTerms = async (user: string, what: string) => { + const ans = await ask<{ terms?: unknown; topic?: unknown }>(h, model, TERMS_SYSTEM, user, TERMS_SCHEMA, what, true); + if (!topic && typeof ans.topic === "string") topic = ans.topic.replace(/["“”]/g, "").trim().slice(0, 60); + const c = cleanTerms(Array.isArray(ans.terms) ? ans.terms : [], { names }); + droppedTerms.push(...c.dropped); + return c.kept; + }; let terms: string[] = []; if (input.terms?.length) terms = input.terms.map((t) => t.trim()).filter(Boolean); - else { - const ans = await ask<{ terms?: unknown }>(h, model, TERMS_SYSTEM, `Research question: ${question}`, TERMS_SCHEMA, "terms", true); - const names = new Set(channels.flatMap((c) => [c.toLowerCase(), c.toLowerCase().replace(/-/g, " ")])); - for (const t of Array.isArray(ans.terms) ? ans.terms : []) { - const v = String(t).replace(/["“”]/g, "").trim().toLowerCase(); - if (v && v.length <= 40 && !terms.includes(v) && !names.has(v)) terms.push(v); - } - terms = terms.slice(0, 6); - } - if (!terms.length) return { status: "failed", summary: "no search terms" }; - h.log(`terms: ${terms.join(", ")}`); - h.trace({ t: "terms", terms }); + 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", { @@ -349,6 +379,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T 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, @@ -371,26 +402,57 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T 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)`); + 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. - const hit = new Set([...found.values()].flatMap((v) => Object.keys(v.hits))); - const extra: string[] = []; - for (const t of terms) { - if (hit.has(t) || !t.includes(" ")) continue; - for (const w of t.split(/\s+/)) if (w.length >= 4 && !STOP.has(w) && !terms.includes(w) && !extra.includes(w)) extra.push(w); - } + // 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); - const hitNow = new Set([...found.values()].flatMap((v) => Object.keys(v.hits))); - terms = [...terms.filter((t) => hit.has(t)), ...extra.filter((w) => hitNow.has(w))].slice(0, 8); + 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])); + const rare = rareTermsOf(usable); + 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). @@ -401,16 +463,58 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T h.trace({ t: "note", text: `restricted to ${only.length} recording(s): ${only.slice(0, 20).join(", ")}` }); } const nEnum = found.size; - const weight = new Map(terms.map((t, i) => [t, 1 / (i + 1)])); - const order = [...found.values()].sort((a, b) => { - const wa = Object.keys(a.hits).reduce((s, t) => s + (weight.get(t) ?? 0.2), 0); - const wb = Object.keys(b.hits).reduce((s, t) => s + (weight.get(t) ?? 0.2), 0); - const ha = Object.values(a.hits).reduce((s, x) => s + x, 0); - const hb = Object.values(b.hits).reduce((s, x) => s + x, 0); - return wb - wa || hb - ha || a.date.localeCompare(b.date); + // 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" })), }); - const todo = order.slice(0, maxVideos); - h.log(`${nEnum} video(s) matched; reading ${todo.length}`); + 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[] = []; @@ -428,13 +532,8 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T // The batch's trace: what the model returned, kept or dropped. const batchLines: string[] = []; const batchUsd = h.meter.usd; - const text = await deps.corpus.call("get_transcripts", { - video_ids: batch.map((v) => v.id), - queries: terms.slice(0, 8), - link_style: "base", - channels, - }); - const parsed = parseTranscripts(text); + 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) { @@ -753,3 +852,55 @@ function writeMarkdown( ); 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(" "); +} diff --git a/common/lib/report/draft/tasks/trace.ts b/common/lib/report/draft/tasks/trace.ts @@ -6,13 +6,14 @@ // // {t: "run", phase: "start", task, model, extractor?} // {t: "scope", source, channels, from?, to?, question, seed?: {chars}} -// {t: "terms", terms} the pipeline's search terms +// {t: "terms", terms, topic?, dropped?} the pipeline's search terms (and the ones code dropped) // {t: "enumerate", query, n, ids, partial, unreached, total?} // {t: "read", tool, ids} text read outside a batch // {t: "batch", k, of, ids, lines, model, usd} the extractor's own lines // {t: "cost", step, usd, model, total, turn?, calls?} // {t: "check", quote, cite, ok, reason?, stage, dropped?} // {t: "finding", section, claim, cites} +// {t: "select", scope, terms, rare, candidates, read} what the pipeline reads and why (demo D2) // {t: "note", text} // {t: "run", phase: "end", status, summary, usd, minutes, coverage?} // @@ -90,7 +91,15 @@ export type TraceInput = // A sweep restricted to these recordings (umtool R4). ids?: string[]; } - | { t: "terms"; terms: string[]; extra?: boolean } + | { t: "terms"; terms: string[]; extra?: boolean; topic?: string; dropped?: { term: string; why: string }[]; asked?: "again" } + | { + t: "select"; + scope: number; + terms: { term: string; videos: number; partial: boolean; idf: number; nominates: boolean }[]; + rare: string[]; + candidates: number; + read: { id: string; date: string; score: number; hits: Record<string, number>; why: "top" | "spread" }[]; + } | { t: "enumerate"; query: string; n: number; ids: string[]; partial: boolean; unreached: string[]; total?: number; posts?: number; counts?: Record<string, number>; turn?: number; phase?: string; error?: string } | { t: "read"; tool: string; ids: string[]; turn?: number; phase?: string } | { t: "batch"; k: number; of: number; ids: string[]; lines: string[]; model: string; usd: number; cut?: boolean; turn?: number; phase?: string } diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts @@ -353,6 +353,32 @@ test("sweep-pipeline: terms, enumerate, windows, extract (a non-verbatim quote d assert.deepEqual(after.coverage, { matched: 1, read: 1, partial: false, unreached: [] }); }); +test("sweep-pipeline selection (D2 item 1): the subject's own name and generic words are never searched; the read is traced with its reasons", async () => { + const r = await run("sweep-pipeline"); + const turns = structuredClone(r.turns); + turns[0].message.content = JSON.stringify({ terms: ["kitchen", "say", "contest", "judges"], topic: "the pie contest" }); + ol.push(...turns); + const it = await createIteration("synth-select", { kind: "sweep", model: r.model, question: "What has the baker said about the pie contest?", scope: { channels: r.channels } }, paths); + const d = deps(); + const out = await runTask({ task: "sweep-pipeline", article: "synth-select", n: it.n, origin: ORIGIN }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const trace = await traceOf("synth-select", it.n); + const t = trace.find((e) => e.t === "terms")!; + assert.deepEqual(t.terms, ["contest", "judges"]); + assert.equal(t.topic, "the pie contest"); + assert.deepEqual( + t.dropped.map((x: { term: string; why: string }) => [x.term, x.why]), + [ + ["kitchen", "the subject's own name"], + ["say", "a generic word"], + ], + ); + assert.deepEqual(trace.filter((e) => e.t === "enumerate").map((e) => e.query).sort(), ["contest", "judges"]); + const sel = trace.find((e) => e.t === "select")!; + assert.deepEqual(sel.read.map((x: { id: string; why: string }) => [x.id, x.why]), [["pie-stream-02", "top"]]); + assert.ok(sel.read[0].score > 0); +}); + test("revise-report: ops over the parent's sweep.md — applied, refused with reasons; quotes untouched; a new quote checked", async () => { await drainFake(); const r = await run("revise-report");