// CORPUS GREP — a regex over the LIVE corpus's transcripts, off disk, with no // index and no editor (`archilyzer corpus grep`). // // The published shards and the MCP (TRANSCRIPT_LOCAL_DIR is a composed public // dir) only know what the last publish built. A video downloaded an hour ago, // a private channel, or a channel no site carries is invisible to them. This // reads `transcripts/channels//data//` itself: each video's cues the // way the ops transcript route reads them (readCuesInVideoDir — a fresh // transcript.cues.json, else what normalize would write: the caption-track // rule, en-orig before en, YouTube's rolling-caption repeats collapsed by // parseVtt), dated by metadata.info.json's upload_date. // // A WINDOW is `windowSeconds` (30) of cues starting at a cue, stepped by half a // window; a window is a hit when the pattern matches its text, and the next hit // in the same video starts after that window ends, so one moment is one hit. // Each hit names the start second of the cue the match begins in. // // Read-only. A channel whose text is not readable (its drive is not answering, // a legacy layout, a move in flight — assertChannelTextReadable) is skipped // with its reason, never read as "no videos". A social channel holds posts, // not transcripts, and is left out. // // Reference: an agent's hand-written ~/reports/quartering-huck/search/since.py // (2026-10-25), which this replaces. import path from "node:path"; import { readFile, stat } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import type { Cue } from "../lib/vtt"; import type { ChannelConfig } from "../lib/channelConfig"; import { isSocialChannel } from "../lib/channelConfig"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { mapConcurrent } from "../lib/concurrency"; import { listChannelConfigs, readChannelConfig } from "./channels"; import { heldVideoIds, readCuesInVideoDir } from "./videoCues"; export type CorpusGrepHit = { // YYYY-MM-DD, or "" for an undated video (searched only with no date bound). date: string; slug: string; id: string; // The start second of the cue the match begins in. start: number; title: string; // The whole window's text. text: string; url?: string; }; export type CorpusGrepPending = { date: string; slug: string; id: string; title: string; duration?: number; }; export type CorpusGrepResult = { pattern: string; since: string | null; until: string | null; windowSeconds: number; channels: string[]; skippedChannels: { slug: string; reason: string }[]; // Videos in range (by upload date) and how many of them had a transcript. videosInRange: number; videosSearched: number; // In range with no transcript yet: still to download or transcribe. noTranscript: CorpusGrepPending[]; // No metadata.info.json (so no date): left out when a date bound is set. undated: number; // Every hit, before `limit`. totalHits: number; hits: CorpusGrepHit[]; // Videos whose transcript could not be read, with the error. errors: { slug: string; id: string; error: string }[]; }; export type CorpusGrepOptions = { paths: Paths; pattern: RegExp; // Absent: every channel that is not social. channels?: readonly string[]; // YYYYMMDD, inclusive. since?: string; until?: string; windowSeconds?: number; // Hits returned (all are counted in totalHits). Absent: all. limit?: number; onNote?: (line: string) => void; }; const DAY_MS = 24 * 60 * 60 * 1000; // "2026-10-21" or "20261021" -> "20261021"; anything else null. export function parseGrepDate(raw: string): string | null { const m = /^(\d{4})-?(\d{2})-?(\d{2})$/.exec(raw.trim()); if (!m) return null; const [, y, mo, d] = m; const t = Date.UTC(Number(y), Number(mo) - 1, Number(d)); const back = new Date(t); if (back.getUTCMonth() !== Number(mo) - 1 || back.getUTCDate() !== Number(d)) return null; return `${y}${mo}${d}`; } function dashed(day: string): string { return day.length === 8 ? `${day.slice(0, 4)}-${day.slice(4, 6)}-${day.slice(6)}` : day; } // The windows of one video's cues that the pattern matches (see the header). export function grepCues( cues: readonly Cue[], pattern: RegExp, windowSeconds = 30, ): { start: number; text: string }[] { const re = new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, "")); const half = windowSeconds / 2; const out: { start: number; text: string }[] = []; const n = cues.length; let i = 0; let blockedUntil = -Infinity; while (i < n) { const t0 = cues[i].start; if (t0 >= blockedUntil) { let text = ""; const offsets: { at: number; cue: number }[] = []; for (let j = i; j < n && cues[j].start < t0 + windowSeconds; j++) { const piece = cues[j].text.replace(/\s+/g, " ").trim(); if (!piece) continue; if (text) text += " "; offsets.push({ at: text.length, cue: j }); text += piece; } const m = text ? re.exec(text) : null; if (m) { let cue = offsets[0].cue; for (const o of offsets) { if (o.at <= m.index) cue = o.cue; else break; } out.push({ start: Math.floor(cues[cue].start), text }); blockedUntil = t0 + windowSeconds; } } let k = i + 1; while (k < n && cues[k].start < t0 + half) k++; i = k; } return out; } type Meta = { upload_date?: unknown; release_date?: unknown; timestamp?: unknown; title?: unknown; fulltitle?: unknown; duration?: unknown; webpage_url?: unknown; }; function metaDay(m: Meta): string { for (const v of [m.upload_date, m.release_date]) { if (typeof v === "string" && /^\d{8}$/.test(v)) return v; } if (typeof m.timestamp === "number" && Number.isFinite(m.timestamp)) { return new Date(m.timestamp * 1000).toISOString().slice(0, 10).replace(/-/g, ""); } return ""; } async function grepChannel( opts: CorpusGrepOptions, slug: string, config: ChannelConfig, result: CorpusGrepResult, ): Promise { const dataDir = path.join(opts.paths.channelsDir, slug, "data"); const ids = [...(await heldVideoIds(dataDir))].sort(); const since = opts.since ?? null; const until = opts.until ?? null; const dated = since !== null || until !== null; // A video uploaded on or after `since` cannot have had its metadata written // before that day: an mtime two days earlier (timezone slack) rules it out // with one stat and no parse. Only false positives get through, and the // upload_date check below settles those. const floorMs = since ? Date.UTC(Number(since.slice(0, 4)), Number(since.slice(4, 6)) - 1, Number(since.slice(6))) - 2 * DAY_MS : null; const windowSeconds = opts.windowSeconds ?? 30; await mapConcurrent(ids, 8, async (id) => { const videoDir = path.join(dataDir, id); const metaPath = path.join(videoDir, "metadata.info.json"); const st = await stat(metaPath).catch(() => null); let meta: Meta | null = null; if (st) { if (floorMs !== null && st.mtimeMs < floorMs) return; try { meta = JSON.parse(await readFile(metaPath, "utf8")) as Meta; } catch { meta = null; } } const day = meta ? metaDay(meta) : ""; if (!day) { result.undated++; if (dated) return; } else { if (since && day < since) return; if (until && day > until) return; } result.videosInRange++; const titleOf = (m: Meta | null) => typeof m?.title === "string" ? m.title : typeof m?.fulltitle === "string" ? m.fulltitle : ""; let read; try { read = await readCuesInVideoDir({ slug, id, videoDir, configName: config.name }); } catch (err) { result.errors.push({ slug, id, error: (err as Error).message }); return; } if (!read || read.cues.length === 0) { result.noTranscript.push({ date: dashed(day), slug, id, title: titleOf(meta), ...(typeof meta?.duration === "number" ? { duration: meta.duration } : {}), }); return; } result.videosSearched++; const title = read.title ?? titleOf(meta); const url = read.webpageUrl ?? (typeof meta?.webpage_url === "string" ? meta.webpage_url : undefined); for (const w of grepCues(read.cues, opts.pattern, windowSeconds)) { result.hits.push({ date: dashed(day), slug, id, start: w.start, title, text: w.text, ...(url ? { url } : {}) }); } }); } export async function corpusGrep(opts: CorpusGrepOptions): Promise { const result: CorpusGrepResult = { pattern: opts.pattern.source, since: opts.since ? dashed(opts.since) : null, until: opts.until ? dashed(opts.until) : null, windowSeconds: opts.windowSeconds ?? 30, channels: [], skippedChannels: [], videosInRange: 0, videosSearched: 0, noTranscript: [], undated: 0, totalHits: 0, hits: [], errors: [], }; let targets: { slug: string; config: ChannelConfig }[]; if (opts.channels && opts.channels.length) { targets = []; for (const slug of opts.channels) { const config = await readChannelConfig(opts.paths, slug); if (!config) throw new Error(`Channel "${slug}" not found in ${opts.paths.channelsDir}`); targets.push({ slug, config }); } } else { targets = await listChannelConfigs(opts.paths); } for (const { slug, config } of targets) { if (isSocialChannel(config)) { if (opts.channels?.length) { result.skippedChannels.push({ slug, reason: "a social channel: posts, not transcripts" }); } continue; } try { await assertChannelTextReadable(opts.paths, slug, config); } catch (err) { const reason = (err as Error).message; result.skippedChannels.push({ slug, reason }); opts.onNote?.(`skipped ${slug}: ${reason}`); continue; } result.channels.push(slug); try { await grepChannel(opts, slug, config, result); } catch (err) { // data/ could not be listed (not ENOENT — that is a channel holding // nothing): say so rather than count it as empty. result.channels.pop(); result.skippedChannels.push({ slug, reason: (err as Error).message }); opts.onNote?.(`skipped ${slug}: ${(err as Error).message}`); } } const order = (a: { date: string; slug: string; id: string }, b: typeof a) => a.date.localeCompare(b.date) || a.slug.localeCompare(b.slug) || a.id.localeCompare(b.id); result.hits.sort((a, b) => order(a, b) || a.start - b.start); result.noTranscript.sort(order); result.totalHits = result.hits.length; if (opts.limit !== undefined && result.hits.length > opts.limit) { result.hits = result.hits.slice(0, opts.limit); } return result; }