// TRIAGE, TIER 1 — the window judge, on its own (umtool R6): the sweep // pipeline's judge (sweep-pipeline.ts EXTRACT_SYSTEM: relevant, items {quote, // claim, on_topic, strength}) over the candidates' MATCHING windows only — // get_transcripts' windows around the terms and topics (a caller's own windows // when it names them; a recording no word matched, put forward by a digest tag, // is read from its opening). Each window is cut to model-sized chunks, at most // a few per recording. // // What the model says is never taken on trust: // - its line must be VERBATIM in the window it read (the pipeline's `locate`) // and in the transcript's cues around that second (R2's word check, // lib/report/quoteWords.ts) — else it is dismissed as "not verbatim", the // invented line kept beside its reason // - strength 3 on topic is a STRONG flag, 2 a WEAK one; 1, or off topic, is // dismissed with the model's own claim as the reason // - a window it judges not relevant is dismissed as a window // // Pure over the corpus tools, the model (`ask`) and the cue reader it is handed. import { checkWordsInWindow, windowAround, type WordCue } from "../../quoteWords"; import { mmss } from "../reportOps"; import { chunksOf, EXTRACT_SCHEMA, EXTRACT_SYSTEM, locate, parseTranscripts, windowsOf, type ParsedTranscript } from "../tasks/sweep-pipeline"; import { momentHref } from "../tasks/links"; import type { CorpusToolsLike } from "../tasks/types"; import { heardRule, holdsSpelling, normSpelling, spellingKey, withHeard, type TriageHeard, type TriageHeardDropped } from "./learned"; import { STRONG_SCORE, type TriageCandidate, type TriageDismissal, type TriageFlag, type TriageScore, type TriageWindow } from "./types"; export const TRIAGE_READ_BATCH = 8; export const TRIAGE_CHUNKS_PER_RECORDING = 3; export const TRIAGE_FLAGS_PER_RECORDING = 3; export const TRIAGE_MIN_LINE_WORDS = 4; export type JudgeInput = { question: string; candidates: TriageCandidate[]; terms: string | null; regex?: boolean; topics: string[]; channels: string[]; // A caller's own windows per recording (seconds): only these are read. windows?: Record; origin?: string | null; maxChunksPerRecording?: number; maxFlagsPerRecording?: number; // R6.3: the watched names. The judge also reports a span it takes for a // mis-hearing of one (`heard`), checked verbatim here; `known` (spelling // keys: the names, the learned and removed spellings) are not reported. names?: string[]; known?: ReadonlySet; // A span the terms' own query already finds is not reported (coveredByTerms). covered?: (span: string) => boolean; }; export type JudgeTrace = (e: { t: "batch"; k: number; of: number; ids: string[]; lines: string[]; model: string; usd: number } | { t: "check"; quote: string; cite: { channel?: string; video?: string; start?: number; url?: string }; ok: boolean; reason: string; stage: "triage"; dropped?: boolean; claim?: string }) => void; export type JudgeDeps = { corpus: Pick; // The model: a structured answer to the judge's prompt. ask: (system: string, user: string, schema: object, what: string) => Promise; model: string; // A recording's cues (the verbatim check); null: unread, the window decides. cuesOf?: (channel: string, id: string) => Promise; // The spend so far (USD), for each batch's line. usd?: () => number; signal?: AbortSignal; log?: (line: string) => void; progress?: (done: number, total: number) => void; trace?: JudgeTrace; // Why the judge must stop now (the job's cap reached), else null. stop?: () => string | null; }; export type JudgeResult = { flags: TriageFlag[]; dismissed: TriageDismissal[]; read: number; windows: number; chunks: number; // Why it stopped before every candidate was judged, and the ids not judged. stopped?: { reason: string; ids: string[] }; // R6.3: the spans it heard as a watched name, verbatim (code-checked), and the ones put aside. heard: TriageHeard[]; heardDropped: TriageHeardDropped[]; }; type Line = [number, string]; const clean = (s: unknown) => String(s ?? "") .replace(/["“”]/g, "") .replace(/\s+/g, " ") .trim() .replace(/^\[[\d:]+\]\s*/, ""); const oneLine = (s: unknown, max = 240) => String(s ?? "").replace(/\s+/g, " ").trim().slice(0, max); /** The window a chunk spans (its first line's second to its last's, plus one cue). */ const spanOf = (ch: readonly Line[]): TriageWindow => ({ start: ch[0]![0], end: ch[ch.length - 1]![0] + 5 }); // The channel slug of a recording: off a moment_base in the archive's form, // else the one channel, else the channel whose metadata names it. async function slugOf(p: ParsedTranscript | undefined, id: string, channels: string[], corpus: JudgeDeps["corpus"]): Promise { const m = p?.momentBase ? /[?&]v=([^&%/]+)(?:%2F|\/)/i.exec(p.momentBase) : null; if (m) return decodeURIComponent(m[1]!); if (channels.length === 1) return channels[0]!; for (const c of channels) { try { await corpus.call("get_video_metadata", { video_id: id, channel: c }); return c; } catch { // not this channel's } } return channels[0] ?? null; } /** The judge over the candidates' windows. */ export async function judgeCandidates(i: JudgeInput, d: JudgeDeps): Promise { const flags: TriageFlag[] = []; const dismissed: TriageDismissal[] = []; const maxChunks = i.maxChunksPerRecording ?? TRIAGE_CHUNKS_PER_RECORDING; const maxFlags = i.maxFlagsPerRecording ?? TRIAGE_FLAGS_PER_RECORDING; const terms = i.terms?.trim() || null; const words = [...(terms && !i.regex ? [terms] : []), ...i.topics].map((t) => t.trim()).filter(Boolean).slice(0, 8); const queryArgs: Record = terms && i.regex ? { query: terms, regex: true, ...(words.length ? { queries: words } : {}) } : words.length ? { queries: words } : {}; const names = (i.names ?? []).map((n) => n.trim()).filter(Boolean); const system = names.length ? `${EXTRACT_SYSTEM}${heardRule(names)}` : EXTRACT_SYSTEM; const schema = names.length ? withHeard(EXTRACT_SCHEMA) : EXTRACT_SCHEMA; const heard: TriageHeard[] = []; const heardDropped: TriageHeardDropped[] = []; const cueCache = new Map>(); const cues = (slug: string, id: string) => { const key = `${slug}/${id}`; let p = cueCache.get(key); if (!p) { p = d.cuesOf ? d.cuesOf(slug, id).catch(() => null) : Promise.resolve(null); cueCache.set(key, p); } return p; }; let read = 0; let nWindows = 0; let nChunks = 0; let done = 0; const total = i.candidates.length; d.progress?.(0, total); const batches = Math.ceil(total / TRIAGE_READ_BATCH); let stopped: JudgeResult["stopped"]; for (let b = 0; b < total && !stopped; b += TRIAGE_READ_BATCH) { d.signal?.throwIfAborted(); const halt = d.stop?.() ?? null; if (halt) { stopped = { reason: halt, ids: i.candidates.slice(b).map((c) => c.id) }; break; } const batch = i.candidates.slice(b, b + TRIAGE_READ_BATCH); const before = d.usd?.() ?? 0; const lines: string[] = []; const windowed = batch.filter((c) => !i.windows?.[c.id]?.length); const parsed = windowed.length ? parseTranscripts(await d.corpus.call("get_transcripts", { video_ids: windowed.map((c) => c.id), ...queryArgs, link_style: "base", channels: i.channels })) : new Map(); for (const c of batch) { d.signal?.throwIfAborted(); let p = parsed.get(c.id); let wins: Line[][] = p ? windowsOf(p.lines) : []; let opening = false; const own = i.windows?.[c.id]; if (own?.length || (!wins.length && (c.by.includes("topics") || !Object.keys(queryArgs).length))) { // The caller's windows, or (no word matched: a digest tag put it forward) its opening. const full = parseTranscripts(await d.corpus.call("get_transcripts", { video_ids: [c.id], link_style: "base", channels: i.channels })).get(c.id); p = full ?? p; const all = (full?.lines ?? []).filter((l): l is Line => l !== null); if (own?.length) { wins = own.map((w) => all.filter(([s]) => s >= w.start - 5 && s <= w.end + 5)).filter((w) => w.length); } else if (all.length) { wins = [all]; opening = true; } } const title = c.title ?? p?.title ?? c.id; if (!wins.length) { dismissed.push({ id: c.id, title, channel: c.channel, stage: "read", reason: p ? "no window matched the terms or topics" : "no transcript text returned" }); lines.push(`${c.id}: ${p ? "no window matched" : "no transcript text returned"}`); d.progress?.(++done, total); continue; } read++; const slug = await slugOf(p, c.id, i.channels, d.corpus); let kept = 0; let chunksHere = 0; outer: for (const win of wins) { nWindows++; for (const ch of chunksOf(win)) { if (chunksHere >= maxChunks || kept >= maxFlags) break outer; d.signal?.throwIfAborted(); if (d.stop?.()) break outer; chunksHere++; nChunks++; const span = spanOf(ch); const excerpt = ch.map(([s, t]) => `[${mmss(s)}] ${t}`).join("\n"); const user = `Research question: ${i.question}\n\nVideo: ${title}${c.channel ? ` (${c.channel}${c.date ? `, ${c.date}` : ""})` : ""}\n\nTranscript excerpt:\n${excerpt}`; let ans: { relevant?: unknown; items?: unknown; heard?: unknown }; try { ans = await d.ask(system, user, schema, `triage ${c.id}@${ch[0]![0]}`); } catch (e) { if (d.signal?.aborted) throw e; dismissed.push({ id: c.id, title, channel: slug, window: span, stage: "judge", reason: `the model's answer failed: ${oneLine((e as Error).message, 160)}` }); lines.push(`${c.id} @ ${mmss(span.start)}: the model's answer failed — ${oneLine((e as Error).message, 160)}`); continue; } if (names.length && Array.isArray(ans.heard)) { for (const h of await checkHeard(ans.heard, { id: c.id, title, slug, chunk: ch, names, known: i.known, ...(i.covered ? { covered: i.covered } : {}), cues, already: heard })) { if ("reason" in h) { heardDropped.push(h); lines.push(`${c.id}: heard “${h.span}” as ${h.means} [put aside: ${h.reason}]`); } else { heard.push(h); lines.push(`${c.id} @ ${mmss(h.at)}: heard “${h.span}” as ${h.means} [verbatim${h.checked === "cues" ? " in the cues" : " in its window"}]`); } } } const items = Array.isArray(ans.items) ? (ans.items as { quote?: unknown; claim?: unknown; on_topic?: unknown; strength?: unknown }[]) : []; if (!ans.relevant || !items.length) { dismissed.push({ id: c.id, title, channel: slug, window: span, stage: "judge", reason: opening ? "not relevant to the question (its opening read: no word matched)" : "not relevant to the question" }); lines.push(`${c.id} @ ${mmss(span.start)}–${mmss(span.end)}: not relevant`); continue; } for (const raw of items.slice(0, 3)) { const line = clean(raw.quote); const reason = oneLine(raw.claim) || "(no reason given)"; const strength = Math.min(3, Math.max(1, Math.round(Number(raw.strength) || 2))) as TriageScore; const sec = line ? locate(line, ch) : null; const base = { id: c.id, title, channel: slug, window: span, line, score: strength }; let why: { stage: TriageDismissal["stage"]; reason: string } | null = null; let at = sec ?? span.start; let checked: TriageFlag["checked"] = "window"; if (!line) why = { stage: "verbatim", reason: "no line given" }; else if (sec === null) why = { stage: "verbatim", reason: "not verbatim in its window" }; else if (line.split(" ").filter(Boolean).length < TRIAGE_MIN_LINE_WORDS) why = { stage: "verbatim", reason: `too short to check (${line.split(" ").filter(Boolean).length} words)` }; else if (slug) { const all = await cues(slug, c.id); if (all?.length) { const v = checkWordsInWindow(line, { t: sec, end: sec }, windowAround(all, sec, 30)); if (v.status === "ok") { checked = "cues"; if (v.nowAt !== undefined) at = v.nowAt; } else { why = { stage: "verbatim", reason: `not in the transcript's cues near ${mmss(sec)}` }; } } } if (!why && raw.on_topic === false) why = { stage: "score", reason: `off topic — ${reason}` }; if (!why && strength < 2) why = { stage: "score", reason: `a mention only — ${reason}` }; if (!why && flags.some((f) => f.id === c.id && f.line === line)) why = { stage: "score", reason: "the same line twice" }; const url = slug && p?.momentBase ? `${p.momentBase}${Math.floor(at)}` : slug && i.origin ? momentHref(i.origin.replace(/\/+$/, ""), slug, c.id, at) : undefined; if (why) { dismissed.push({ ...base, at, ...why }); lines.push(`${c.id} @ ${mmss(at)} “${line}” — ${reason} [dismissed: ${why.reason}]`); d.trace?.({ t: "check", quote: line, cite: { ...(slug ? { channel: slug } : {}), video: c.id, start: at, ...(url ? { url } : {}) }, ok: false, reason: why.reason, stage: "triage", dropped: true, claim: reason }); continue; } if (kept >= maxFlags) break; kept++; const f: TriageFlag = { f: `f${flags.length + 1}`, id: c.id, channel: slug, title, date: c.date, window: span, line, at, score: strength, strength: strength >= STRONG_SCORE ? "strong" : "weak", reason, checked, ...(url ? { url } : {}), }; flags.push(f); lines.push(`${c.id} @ ${mmss(at)} “${line}” — ${reason} [${f.strength} flag ${f.f}]`); d.trace?.({ t: "check", quote: line, cite: { ...(slug ? { channel: slug } : {}), video: c.id, start: at, ...(url ? { url } : {}) }, ok: true, reason: `${f.strength} flag (score ${strength}), verbatim${checked === "cues" ? " in the cues" : " in its window"}`, stage: "triage", claim: reason }); } } } d.log?.(` ${c.id}: ${kept} flag(s), ${chunksHere} chunk(s) judged`); d.progress?.(++done, total); } const k = b / TRIAGE_READ_BATCH + 1; d.trace?.({ t: "batch", k, of: batches, ids: batch.map((c) => c.id), lines, model: d.model, usd: (d.usd?.() ?? 0) - before }); } return { flags, dismissed, read, windows: nWindows, chunks: nChunks, ...(stopped ? { stopped } : {}), heard, heardDropped }; } /** * R6.3: the spans the judge says it heard as a watched name, checked by code — * the name one of the watched ones, the span not the name itself nor a * spelling already known, at most four words, VERBATIM in the chunk it read * (`locate`, whole words) and in the transcript's cues near that second * (when they read). Answers each kept span, or the span with why it was put * aside. */ export async function checkHeard( raw: unknown[], o: { id: string; title: string | null; slug: string | null; chunk: readonly Line[]; names: readonly string[]; known?: ReadonlySet; covered?: (span: string) => boolean; cues: (slug: string, id: string) => Promise; already?: readonly TriageHeard[]; }, ): Promise<(TriageHeard | TriageHeardDropped)[]> { const out: (TriageHeard | TriageHeardDropped)[] = []; const byKey = new Map(o.names.map((n) => [spellingKey(n), n])); const done = new Set((o.already ?? []).map((h) => spellingKey(h.span))); for (const r of raw.slice(0, 3)) { const span = normSpelling((r as { span?: unknown })?.span); const meansRaw = String((r as { means?: unknown })?.means ?? "").trim(); const means = byKey.get(spellingKey(meansRaw)); const key = spellingKey(span); if (!span || !key) continue; if (!means) { out.push({ span, means: meansRaw, id: o.id, reason: "not a watched name" }); continue; } if (byKey.has(key) || o.known?.has(key) || done.has(key) || o.covered?.(span)) continue; if (key.split(" ").length > 4) { out.push({ span, means, id: o.id, reason: "too long (at most 4 words)" }); continue; } const sec = locate(span, o.chunk); if (sec === null) { out.push({ span, means, id: o.id, reason: "not verbatim in its window" }); continue; } const line = o.chunk.find(([s, t]) => s === sec && holdsSpelling(t, span))?.[1] ?? o.chunk.find(([s]) => s === sec)?.[1] ?? ""; let checked: TriageHeard["checked"] = "window"; let at = sec; if (o.slug) { const all = await o.cues(o.slug, o.id); if (all?.length) { const v = checkWordsInWindow(span, { t: sec, end: sec }, windowAround(all, sec, 30)); if (v.status !== "ok") { out.push({ span, means, id: o.id, reason: `not in the transcript's cues near ${mmss(sec)}` }); continue; } checked = "cues"; if (v.nowAt !== undefined) at = v.nowAt; } } done.add(key); out.push({ span, means, id: o.id, channel: o.slug, title: o.title, at, line, checked }); } return out; }