// A RESEARCH CASE OVER THE LIVE CORPUS (plans/release-38/research-cases-and-assist.md, lane A, stages 1, 2 and 9): // what the case's scope holds per channel × year, the candidate windows its term families find, and the subject's // uploads for the date checks. READ-ONLY on the corpus; the caller writes the case's own files // (lib/research/caseStore-server.ts). // // Why the live corpus and not a published build: a case reads private channels and channels no site carries (the // Oneylyzer case did), and recordings downloaded since the last publish. So it reads `channels//` through the // readers that already exist, never a walk of its own: // - which recordings are held: heldVideoIds (videoCues.ts); // - their dates: the LMDB index's `byChannel` key scan (recencyIndex.ts openUploadDateIndex: the transcribed // videos, for one cheap scan), then a head/tail read of metadata.info.json for the rest (channelCoverage.ts // readDateAndTitle) -- and for a listed video never fetched, the channel's metadata scan; // - their words: readCuesInVideoDir (videoCues.ts) -- a fresh transcript.cues.json, else what normalize would // write: the caption-track rule (en-orig before en, a local transcription above captions), rolling captions // folded by parseVtt; // - transcribed or not, audio or not: readVideoFiles (videoStatus.ts). // A channel whose text cannot be read (a drive not answering, a move in flight) is SKIPPED WITH ITS REASON, never // read as "nothing held" (assertChannelTextReadable); a social channel holds posts, not recordings. import path from "node:path"; import { readFile } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { isSocialChannel } from "../lib/channelConfig"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { mapConcurrent } from "../lib/concurrency"; import { extractVideoId } from "../lib/videoId"; import { isVideoTranscribed, readVideoFiles } from "../lib/videoStatus"; import type { CandidateCounts, CandidateWindow, CaseDefinition, CoverageRow } from "../lib/research/caseTypes"; import { day8, emptyCounts, erasOn, keyYears, recordingWindows, sortWindows, subjectChannels, trackOfFile, type DatedUpload, type ScanOptions, } from "../lib/research/casePipeline"; import { readChannelConfig } from "./channels"; import { readDateAndTitle } from "./channelCoverage"; import { loadMetadataScan } from "./metadataScanStore"; import { openUploadDateIndex } from "./recencyIndex"; import { heldVideoIds, readCuesInVideoDir } from "./videoCues"; export type CaseChannels = { slugs: string[]; problems: string[] }; type SiteJson = { channels?: { slug?: unknown; groupId?: unknown }[]; defaultGroupId?: unknown; groups?: { id?: unknown }[] }; async function readSite(paths: Paths, id: string): Promise { if (!/^[a-z0-9][a-z0-9_-]*$/i.test(id)) return null; try { return JSON.parse(await readFile(path.join(paths.sitesDir, id, "site.json"), "utf8")) as SiteJson; } catch { return null; } } /** * The channels a case reads: its scope's channels, every channel of its scope's sites (a site.json's pool), every * channel of its `:` groups, its reader groups' named channels, and the subjects' own. A site or a * group that cannot be read is a problem, said; never an empty scope. */ export async function caseChannels(paths: Paths, def: CaseDefinition): Promise { const out = new Set(def.scope.channels); const problems: string[] = []; for (const s of def.subjects) for (const c of s.channels ?? []) out.add(c); for (const g of def.groups) if (Array.isArray(g.channels)) for (const c of g.channels) out.add(c); for (const id of def.scope.sites) { const site = await readSite(paths, id); if (!site) { problems.push(`site ${id}: no site.json`); continue; } for (const c of site.channels ?? []) if (typeof c.slug === "string" && c.slug) out.add(c.slug); } for (const sg of def.scope.groups) { const [siteId, groupId] = sg.split(":"); const site = await readSite(paths, siteId); if (!site) { problems.push(`group ${sg}: no site.json for ${siteId}`); continue; } const fallback = typeof site.defaultGroupId === "string" ? site.defaultGroupId : site.groups?.[0]?.id; const members = (site.channels ?? []).filter((c) => typeof c.slug === "string" && (typeof c.groupId === "string" ? c.groupId : fallback) === groupId); if (!members.length) problems.push(`group ${sg}: no channel of ${siteId} is in it`); for (const c of members) out.add(c.slug as string); } return { slugs: [...out].sort(), problems }; } type Opened = { ok: true; slug: string; configName?: string; dataDir: string } | { ok: false; slug: string; reason: string }; async function openChannel(paths: Paths, slug: string): Promise { const config = await readChannelConfig(paths, slug); if (!config) return { ok: false, slug, reason: "not in the corpus" }; if (isSocialChannel(config)) return { ok: false, slug, reason: "a social channel: posts, not recordings" }; try { await assertChannelTextReadable(paths, slug, config); } catch (e) { return { ok: false, slug, reason: (e as Error).message }; } return { ok: true, slug, configName: config.name, dataDir: path.join(paths.channelsDir, slug, "data") }; } /** Held recordings with their dates: the index's first (one key scan), a metadata read for the rest. */ async function datedHeld(dataDir: string, indexDates: Map | undefined): Promise<{ id: string; date: string; title?: string }[]> { const ids = [...(await heldVideoIds(dataDir))].sort(); return mapConcurrent(ids, 16, async (id) => { const fromIndex = indexDates?.get(id); if (fromIndex && /^\d{8}$/.test(fromIndex)) return { id, date: fromIndex }; const r = await readDateAndTitle(path.join(dataDir, id)); return { id, date: r.uploadDate ?? "", ...(r.title ? { title: r.title } : {}) }; }); } /** A channel's listed ids: its playlist's lines, each the canonical id of its URL (or the line, when it is one). */ async function listedIds(paths: Paths, slug: string): Promise> { let raw = ""; try { raw = await readFile(path.join(paths.channelsDir, slug, "playlist"), "utf8"); } catch { return new Set(); } const out = new Set(); for (const line of raw.split("\n")) { const l = line.trim(); if (!l) continue; const id = /^https?:\/\//.test(l) ? extractVideoId(l) : l; if (id) out.add(id); } return out; } // --------------------------------------------------------------------------------------------------------------- // Stage 1: coverage /** * One channel per year: LISTED (its playlist and everything it holds), HELD (a data//), TRANSCRIBED (held with * a transcript or English captions) and UNTRANSCRIBED AUDIO (held with audio and no transcript). A held video is * dated by the index or its metadata; a listed one never fetched by the channel's metadata scan; what nothing * dates is the row of year 0. `key` marks a year one of the case's eras touches. */ export async function channelYearCoverage( paths: Paths, slug: string, def: Pick, indexDates?: Map, ): Promise<{ rows: CoverageRow[]; problem?: string }> { const ch = await openChannel(paths, slug); if (!ch.ok) return { rows: [], problem: ch.reason }; const years = keyYears(def); const by = new Map(); const row = (year: number) => { let r = by.get(year); if (!r) by.set(year, (r = { channel: slug, year, listed: 0, held: 0, transcribed: 0, untranscribedAudio: 0, ...(years.has(year) ? { key: true } : {}) })); return r; }; const held = await datedHeld(ch.dataDir, indexDates); const heldIds = new Set(held.map((h) => h.id)); await mapConcurrent(held, 16, async (h) => { const files = await readVideoFiles(path.join(ch.dataDir, h.id)); const r = row(h.date ? Number(h.date.slice(0, 4)) : 0); r.listed++; r.held++; if (isVideoTranscribed(files)) r.transcribed++; else if (files.audioFiles.length > 0) r.untranscribedAudio++; }); const listed = await listedIds(paths, slug); const scan = await loadMetadataScan(paths, slug).catch(() => null); for (const id of listed) { if (heldIds.has(id)) continue; const d = day8(scan?.entries[id]?.uploadDate); row(d ? Number(d.slice(0, 4)) : 0).listed++; } return { rows: [...by.values()].sort((a, b) => a.year - b.year) }; } /** Every channel of the case, per year; the channels it could not read, with why. */ export async function caseCoverage(paths: Paths, def: CaseDefinition): Promise<{ rows: CoverageRow[]; skipped: { slug: string; reason: string }[]; problems: string[] }> { const { slugs, problems } = await caseChannels(paths, def); const index = openUploadDateIndex(paths, slugs); try { const rows: CoverageRow[] = []; const skipped: { slug: string; reason: string }[] = []; for (const slug of slugs) { const r = await channelYearCoverage(paths, slug, def, index.datesBySlug.get(slug)); if (r.problem) skipped.push({ slug, reason: r.problem }); rows.push(...r.rows); } return { rows, skipped, problems }; } finally { await index.close().catch(() => {}); } } // --------------------------------------------------------------------------------------------------------------- // Stage 2: candidates export type CaseCandidatesOptions = ScanOptions & { onNote?: (line: string) => void }; /** * The candidate windows of every recording in scope dated inside an era (casePipeline.ts recordingWindows: the * families, ±W s windows merged, title hits, the noise filters), in reading order, and the counts -- per family, * year, channel and group -- before anything is read. Deterministic: the same corpus and definition give the same * windows with the same keys. */ export async function caseCandidates(paths: Paths, def: CaseDefinition, o: CaseCandidatesOptions = {}): Promise<{ windows: CandidateWindow[]; counts: CandidateCounts; problems: string[] }> { const counts = emptyCounts(); const { slugs, problems } = await caseChannels(paths, def); if (!def.eras.length) throw new Error("the case has no era: define an era and its term families first"); const index = openUploadDateIndex(paths, slugs); const windows: CandidateWindow[] = []; try { for (const slug of slugs) { const ch = await openChannel(paths, slug); if (!ch.ok) { counts.skipped.push({ slug, reason: ch.reason }); o.onNote?.(`skipped ${slug}: ${ch.reason}`); continue; } counts.scanned.channels++; const held = await datedHeld(ch.dataDir, index.datesBySlug.get(slug)); let found = 0; await mapConcurrent(held, 8, async (h) => { counts.scanned.videos++; if (!h.date) { counts.scanned.undated++; return; } if (!erasOn(def, h.date).length) return; counts.scanned.inEra++; const read = await readCuesInVideoDir({ slug, id: h.id, videoDir: path.join(ch.dataDir, h.id), configName: ch.configName }).catch(() => null); if (!read || !read.cues.length) { counts.scanned.noText++; return; } counts.scanned.withText++; const ws = recordingWindows( def, { slug, id: h.id, date: h.date, title: read.title ?? h.title ?? h.id, ...(read.webpageUrl ? { url: read.webpageUrl } : {}), ...(typeof read.duration === "number" ? { duration: read.duration } : {}), track: trackOfFile(read.file), cues: read.cues, }, counts, o, ); found += ws.length; windows.push(...ws); }); o.onNote?.(`${slug}: ${held.length} held, ${found} ${found === 1 ? "window" : "windows"}`); } } finally { await index.close().catch(() => {}); } return { windows: sortWindows(def, windows), counts, problems }; } // --------------------------------------------------------------------------------------------------------------- // Stage 9: the subject's uploads /** * Every upload of the subjects' own channels, held or only listed: its date, title and whether it has words to * check (a transcript or captions). A listed upload never fetched is dated by the metadata scan, and is not * captioned -- it cannot be checked, and the table says so. */ export async function subjectUploads(paths: Paths, def: CaseDefinition): Promise<{ uploads: DatedUpload[]; skipped: { slug: string; reason: string }[] }> { const slugs = [...subjectChannels(def)].sort(); const index = openUploadDateIndex(paths, slugs); const uploads: DatedUpload[] = []; const skipped: { slug: string; reason: string }[] = []; try { for (const slug of slugs) { const ch = await openChannel(paths, slug); if (!ch.ok) { skipped.push({ slug, reason: ch.reason }); continue; } const held = await datedHeld(ch.dataDir, index.datesBySlug.get(slug)); await mapConcurrent(held, 16, async (h) => { if (!h.date) return; const dir = path.join(ch.dataDir, h.id); const files = await readVideoFiles(dir); const title = h.title ?? (await readDateAndTitle(dir)).title ?? h.id; uploads.push({ slug, id: h.id, date: h.date, title, captioned: isVideoTranscribed(files) }); }); const heldIds = new Set(held.map((h) => h.id)); const scan = await loadMetadataScan(paths, slug).catch(() => null); for (const id of await listedIds(paths, slug)) { if (heldIds.has(id)) continue; const e = scan?.entries[id]; const d = day8(e?.uploadDate); if (d) uploads.push({ slug, id, date: d, title: e?.title || id, captioned: false }); } } } finally { await index.close().catch(() => {}); } uploads.sort((a, b) => a.date.localeCompare(b.date) || a.slug.localeCompare(b.slug) || a.id.localeCompare(b.id)); return { uploads, skipped }; }