// THE ENUMERATE, AS DATA (umtool redesign R1): the one scan behind // `enumerate_matches`, callable in process. // // `enumerate_matches` renders its result as text for an agent. umtool's // Research page needs the same scan as structured data -- the ids, the // timecodes, the coverage -- and must not parse the text to get it. So the // scan lives here, and the tool is a renderer over it: the scoping, the // filters, the exclusions, the alias expansion, the mirror collapsing and the // caps (MCP_POLICY) are one code path for both by construction. // // The argument parsing for both search tools moved here from server.ts // unchanged (`parseSearchArgs`, `strArray`): it is the half of the contract a // caller passing the tool's own arguments needs. import { normalizeDateArg } from "./dateArg"; import { isTagId } from "yt-dlp-transcript-common/lib/curatedTags"; import { VIDEO_STATES, isVideoState, type VideoState, } from "yt-dlp-transcript-common/lib/availability"; import type { LayerScope } from "yt-dlp-transcript-common/lib/searchQuery"; import type { TranscriptDetail } from "yt-dlp-transcript-common/lib/transcripts"; import { recordHasText, statHasText, type ListArgs, type ListedRecording, type RecordingListing } from "yt-dlp-transcript-common/lib/report/draft/refresh/delta"; import type { CountPhrasesArgs, PhraseCount, PhraseCounts } from "yt-dlp-transcript-common/lib/report/draft/triage/confirm"; import { learnedAlternation, spellingPattern } from "yt-dlp-transcript-common/lib/report/draft/triage/learned"; import type { ChannelRef, ShardSource } from "./source"; import { parseContentTypes, resolveSelectedChannels, searchTranscripts, type SearchFilters, type SearchResult, } from "./search"; // The parsed form of SEARCH_FILTER_ARGS, plus any tokens that were not // understood. Unknown tokens are REPORTED rather than dropped silently: a // typo'd state ("removed" for "deleted") would otherwise widen the search back // to the whole corpus and look like a legitimate empty result. export type ParsedSearchArgs = { filters: SearchFilters | null; exclude?: string[]; scopes?: LayerScope[]; collapseDuplicates: boolean; warnings: string[]; // Set when an argument must stop the call rather than be dropped (a date // bound that is not a date). Callers return it as an error and search nothing. error?: string; }; export const SCOPE_TOKENS: ReadonlyArray = [ "transcripts", "chat", "description", "tags", "metadata", "posts", ]; export function parseSearchArgs(args: Record): ParsedSearchArgs { const warnings: string[] = []; const rawStates = strArray(args.states); let states: VideoState[] | undefined; if (rawStates) { states = rawStates.filter((s): s is VideoState => isVideoState(s)); const bad = rawStates.filter((s) => !isVideoState(s)); if (bad.length > 0) { warnings.push( `unknown state(s) ignored: ${bad.join(", ")} (valid: ${VIDEO_STATES.join(", ")})`, ); } if (states.length === 0) { states = undefined; warnings.push("no valid states given — the state filter was NOT applied"); } } const mediaType = args.media_type === "video" || args.media_type === "livestream" ? args.media_type : undefined; if (args.media_type !== undefined && mediaType === undefined) { warnings.push(`unknown media_type ignored: ${String(args.media_type)}`); } const age = args.age === "all_ages" || args.age === "restricted" ? args.age : undefined; if (args.age !== undefined && age === undefined) { warnings.push(`unknown age ignored: ${String(args.age)}`); } // A date bound the caller cannot have meant is an ERROR, not a warning: an // ignored bound widens the search to the whole corpus and the count reads as // the bounded one (see dateArg.ts). The common spellings are normalised. const from = normalizeDateArg(args.date_from); const to = normalizeDateArg(args.date_to); const badDates = [ ["date_from", args.date_from, from], ["date_to", args.date_to, to], ] .filter(([, , v]) => v === null) .map(([name, raw]) => `${name}=${JSON.stringify(raw)}`); const error = badDates.length ? `not a date: ${badDates.join(", ")} — use YYYYMMDD or YYYY-MM-DD. Nothing was searched.` : undefined; // Curated tags. A malformed id is REPORTED, never silently dropped: dropping // the only tag in the list would widen the search back to the whole corpus // and read as a legitimate result, which is the same failure a typo'd state // would cause. const rawTags = strArray(args.tags); let tags: string[] | undefined; if (rawTags) { const normalized = rawTags.map((t) => t.trim().toLowerCase()); tags = normalized.filter((t) => isTagId(t)); const bad = normalized.filter((t) => !isTagId(t)); if (bad.length > 0) { warnings.push( `not a tag id, ignored: ${bad.join(", ")} (ids are lowercase, ` + `[a-z0-9._-]; call list_tags)`, ); } if (tags.length === 0) { tags = undefined; warnings.push("no valid tags given — the tag filter was NOT applied"); } } const anyFilter = states !== undefined || mediaType !== undefined || age !== undefined || Boolean(from) || Boolean(to) || tags !== undefined; const filters: SearchFilters | null = anyFilter ? { videos: mediaType === undefined || mediaType === "video", livestreams: mediaType === undefined || mediaType === "livestream", allAges: age === undefined || age === "all_ages", restricted: age === undefined || age === "restricted", states: new Set(states ?? VIDEO_STATES), ...(from ? { dateFrom: from } : {}), ...(to ? { dateTo: to } : {}), ...(tags ? { curatedTags: tags } : {}), } : null; const rawScopes = strArray(args.scopes); let scopes: LayerScope[] | undefined; if (rawScopes) { scopes = rawScopes.filter((s): s is LayerScope => (SCOPE_TOKENS as readonly string[]).includes(s), ); const bad = rawScopes.filter( (s) => !(SCOPE_TOKENS as readonly string[]).includes(s), ); if (bad.length > 0) { warnings.push(`unknown scope(s) ignored: ${bad.join(", ")}`); } if (scopes.length === 0) { scopes = undefined; warnings.push("no valid scopes given — searching captions + title"); } } return { filters, exclude: strArray(args.exclude), scopes, collapseDuplicates: args.collapse_duplicates !== false, warnings, ...(error ? { error } : {}), }; } // Coerce a tool arg to a trimmed non-empty string[] (drops non-strings/blanks). export function strArray(v: unknown): string[] | undefined { if (!Array.isArray(v)) return undefined; const out = v .filter((x): x is string => typeof x === "string") .map((x) => x.trim()) .filter((x) => x !== ""); return out.length > 0 ? out : undefined; } // Videos per batch when a call names none: the sweep's own batch. export const DEFAULT_BATCH_SIZE = 8; export type EnumerateOptions = { // The worklist carries no cue text by default, exactly as the tool's. A // caller that shows the hits asks for snippets; WHICH recordings match does // not change (snippets are collected after a record has matched). includeSnippets?: boolean; // Snippets kept per recording when they are included (the engine's default, // 4, otherwise). `matches` still counts every hit. snippetsPerVideo?: number; // Every transcript record the scan reads, before any filter: what a caller // learns about the scope for free (umtool counts transcripts vs captions). onRecord?: (rec: TranscriptDetail, ch: ChannelRef) => void; }; export type Enumerated = { query: string; parsed: ParsedSearchArgs; result: SearchResult; batchSize: number; }; // `enumerate_matches`' scan: the tool's own arguments in, the whole match set // out (never a page of it -- the coverage rule). `{ error }` is the text the // tool answers with as an error, and nothing was searched. export async function enumerate( source: ShardSource, args: Record, opts: EnumerateOptions = {}, ): Promise { const query = String(args.query ?? "").trim(); if (!query) return { error: "query is required" }; const batchSizeArg = typeof args.batch_size === "number" ? Math.floor(args.batch_size) : DEFAULT_BATCH_SIZE; const batchSize = batchSizeArg >= 1 ? batchSizeArg : DEFAULT_BATCH_SIZE; const parsed = parseSearchArgs(args); if (parsed.error) return { error: parsed.error }; const result = await searchTranscripts(source, { query, filters: parsed.filters, exclude: parsed.exclude, scopes: parsed.scopes, collapseDuplicates: parsed.collapseDuplicates, // The singulars stay parsed even though they are no longer advertised. channel: typeof args.channel === "string" ? args.channel : undefined, channels: strArray(args.channels), group: typeof args.group === "string" ? args.group : undefined, groups: strArray(args.groups), regex: args.regex === true, useAliases: args.use_aliases !== false, maxPages: typeof args.max_pages === "number" ? args.max_pages : undefined, contentTypes: parseContentTypes(args.content_types), includeSnippets: opts.includeSnippets === true, ...(opts.snippetsPerVideo !== undefined ? { snippetsPerVideo: opts.snippetsPerVideo } : {}), ...(opts.onRecord ? { onRecord: opts.onRecord } : {}), // R6.1: only these recordings — the pages holding them, nothing else. ...(strArray(args.ids) ? { ids: strArray(args.ids) } : {}), offset: 0, // The whole set: searchTranscripts collects up to HARD_VIDEO_CAP and then // slices, so asking for every collected match costs nothing extra. limit: Number.MAX_SAFE_INTEGER, }); return { query, parsed, result, batchSize }; } // ─── R6.1: every recording in a scope, uncapped ─── const ymd = (d: unknown): string | null => { const m = /^(\d{4})-?(\d{2})-?(\d{2})/.exec(String(d ?? "").trim()); return m ? `${m[1]}-${m[2]}-${m[3]}` : null; }; /** * Every transcript record in a scope, by id: each channel's transcripts * manifest (`slugToPage` lists every record the build ships — no cap) dated * and titled from the summaries index (`videoIndex`). A record the index does * not know is dated from its own page (only those pages are read). With * `date_from`/`date_to`, only the records in the range. Never a capped scan: * a channel whose manifest does not read, a scope token no channel matches, * or a record no page dates is said in `problems` and makes the listing * incomplete — never "nothing there". * * R6.2: each row says whether the build carries transcript text for it * (`hasTranscript`): the stats index's flag, or — for a record whose page was * read anyway — its own cues. A manifest lists a record with no transcript * yet (metadata only); a triage must not count it as seen. null: the build * does not say (no stats shipped, or none for this record). */ export async function listRecordings(source: ShardSource, args: ListArgs): Promise { const from = args.date_from ? ymd(args.date_from) : null; const to = args.date_to ? ymd(args.date_to) : null; const sel = await resolveSelectedChannels(source, { channels: args.channels?.length ? args.channels : undefined }); const problems: string[] = []; const unreached = new Set(); for (const t of sel.unknownChannels) { problems.push(`no channel "${t}" in this corpus`); unreached.add(t); } let index: Awaited>> | null = null; if (typeof source.videoIndex === "function") { try { index = await source.videoIndex(); } catch { index = null; } } // R6.2: transcript presence, from the stats index (one read, cached per // source). Absent or unreadable: unknown, never "untranscribed". let stats: Awaited>> | null = null; if (typeof source.statsIndex === "function") { try { stats = await source.statsIndex(); if (stats.size === 0) stats = null; } catch { stats = null; } } const rows: ListedRecording[] = []; const inRange = (d: string | null) => (!from || (d !== null && d >= from)) && (!to || (d !== null && d <= to)); for (const ch of sel.channels) { let manifest; try { manifest = await source.transcriptsManifest(ch); } catch (e) { // A posts channel ships no transcripts: nothing to list, nothing missed. const posts = await source.postsManifest(ch).catch(() => null); if (posts) continue; problems.push(`${ch.slug}: its transcripts manifest does not read (${(e as Error).message})`); unreached.add(ch.name); continue; } // The ids the index cannot date, by page: read those pages only. const undated = new Map(); for (const [id, page] of Object.entries(manifest.slugToPage)) { const rec = index?.get(`${ch.slug}/${id}`); if (!rec) { const list = undated.get(page) ?? []; list.push(id); undated.set(page, list); continue; } const date = ymd(rec.uploadDate); if (inRange(date)) rows.push({ id, channel: ch.name, channelSlug: ch.slug, date, title: rec.title ?? null, hasTranscript: statHasText(stats?.get(`${ch.slug}/${id}`)) }); } let lost = 0; for (const [page, ids] of undated) { let recs: TranscriptDetail[] | null = null; try { recs = await source.transcriptPage(ch, page); } catch { recs = null; } const byId = new Map((recs ?? []).map((r) => [r.id, r])); for (const id of ids) { const r = byId.get(id); if (!r) { lost++; continue; } const date = ymd(r.uploadDate); // The record is in hand: its own cues say, whatever the stats say. if (inRange(date)) rows.push({ id, channel: ch.name, channelSlug: ch.slug, date, title: r.title ?? null, hasTranscript: recordHasText(r) }); } } if (lost) { problems.push(`${ch.slug}: ${lost} recording(s) its manifest lists could not be read or dated`); unreached.add(ch.name); } } return { rows, complete: problems.length === 0, unreached: [...unreached], problems }; } // ─── R6.3: phrases counted over a scope, uncapped ─── // The ids one restricted scan reads: well under the 2,000-recording cap, so a // batch can never be cut by it. export const COUNT_ID_BATCH = 1000; // Snippets kept per recording while counting: every matching line, in practice. const COUNT_SNIPPETS = 500; /** * Each phrase's count in a scope — the recordings it occurs in, its lines, and * a few examples (newest first) — UNCAPPED and in one scan for all of them: * the scope LISTED (listRecordings: every recording the build ships, by id), * then enumerate's own scan restricted to those ids in batches of * COUNT_ID_BATCH, the phrases as one alternation of escaped literals * (learned.ts spellingPattern — what a triage's query matches them with). Each * matching line is attributed to the phrases it holds. A recording listed * with no transcript yet is not counted. A listing that is not complete, or a * batch the scan could not finish, makes the answer `complete: false`, said in * `problems` — a count from it is "at least". */ export async function countPhrases(source: ShardSource, args: CountPhrasesArgs): Promise { const phrases = [...new Set(args.phrases.filter((p) => typeof p === "string" && p.trim()))]; const counts: Record = Object.fromEntries(phrases.map((p) => [p, { recordings: 0, lines: 0, examples: [] }])); const listing = await listRecordings(source, { ...(args.channels?.length ? { channels: args.channels } : {}), ...(args.date_from ? { date_from: args.date_from } : {}), ...(args.date_to ? { date_to: args.date_to } : {}) }); const rows = listing.rows.filter((r) => r.hasTranscript !== false); const problems = [...listing.problems]; let complete = listing.complete; const combined = learnedAlternation(phrases); if (!combined || !rows.length) return { counts, complete, problems, listed: rows.length }; const res = phrases.map((p) => [p, new RegExp(spellingPattern(p), "i")] as const); const byId = new Map(rows.map((r) => [r.id, r])); const ids = [...byId.keys()]; const keep = Math.max(1, args.examples ?? 10); for (let i = 0; i < ids.length; i += COUNT_ID_BATCH) { const batch = ids.slice(i, i + COUNT_ID_BATCH); const e = await enumerate( source, { query: combined, regex: true, ...(args.channels?.length ? { channels: args.channels } : {}), ids: batch, content_types: ["video"] }, { includeSnippets: true, snippetsPerVideo: COUNT_SNIPPETS }, ); if ("error" in e) { complete = false; problems.push(`ids ${i + 1}–${i + batch.length}: ${e.error}`); continue; } if (e.result.truncated) { complete = false; const c = e.result.coverage; problems.push(`ids ${i + 1}–${i + batch.length}: the scan was capped${c.channelStopped ? ` (stopped in ${c.channelStopped.channel} at page ${c.channelStopped.page} of ${c.channelStopped.pages})` : ""}`); } for (const h of e.result.hits) { if (h.contentType === "post") continue; const listed = byId.get(h.videoId); for (const [p, re] of res) { const lines = h.snippets.filter((s) => !s.scope && re.test(s.text)); if (!lines.length && !re.test(h.title ?? "")) continue; const c = counts[p]!; c.recordings++; c.lines += lines.length; c.examples.push({ id: h.videoId, channel: h.channelName ?? listed?.channel ?? null, channelSlug: h.channelSlug ?? listed?.channelSlug ?? null, date: ymd(h.uploadDate) ?? listed?.date ?? null, title: h.title ?? listed?.title ?? null, start: lines[0]?.seconds ?? null, text: lines[0]?.text ?? null, }); } } } for (const c of Object.values(counts)) { c.examples.sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? ""))); c.examples = c.examples.slice(0, keep); } return { counts, complete, problems, listed: rows.length }; }