// WHAT A LOOKOUT WOULD READ — stages 1 and 2 of a lookout run, with no model // (lane/lookout slice 1). `pnpm ops lookout-run {"id", "dryRun": true}` answers // this; the run itself (controller/lookoutRun.ts) reads exactly the `read` // list it returns, chunked the same way (`cueLines`). // // Stage 1, select: every video of the lookout's channels whose AIR date // (lib/lookout.ts airDateOf: `release_timestamp`, else `timestamp`, in the // lookout's zone) falls in the window. A video with no transcript yet is listed // and not read; one under `minSeconds` is listed and not read. // Stage 2, fold and cap: duplicate uploads and a stream's cut-downs are folded // into one recording (lib/lookout.ts foldRecordings); then the longest // `maxVideos` recordings are read and every other one is listed as skipped for // the cap — with what was folded into it. // // READS ONLY TEXT, WRITES NOTHING. Per channel: `data/` listed, each video's // transcript.cues.json HEAD (its UTC upload date and duration), and for the // few within two days of the window its metadata.info.json (the timestamps) // and its whole cues (the text the folding compares). Behind the text guard // (lib/channelMedia.ts): a channel whose text cannot be read is refused by // name, never read as empty. No network, no model. // // REFUSED BY NAME in v1: a local media library channel, and a slug this // archive does not hold (a channel only on a remote site). import { open as openFile, readFile, stat } from "node:fs/promises"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { mapConcurrent } from "../lib/concurrency"; import { comparisonText, shingles } from "../lib/duplicates"; import { LOCAL_RECORDING_ID_RE } from "../lib/localMedia"; import { LOOKOUT_SHINGLE_SIZE, addDays, airDateOf, foldRecordings, inWindow, isoOfUploadDate, lookoutWindow, type AirDate, type DedupeVideo, type LookoutPlan, type LookoutPlanFolded, type LookoutPlanRead, type LookoutPlanSkipped, type LookoutPlanVideo, type LookoutWindow, } from "../lib/lookout"; import type { LookoutItem } from "../lib/lookoutSettings"; import { measuredSecondsPerCall } from "../lib/lookoutStore"; import { CHUNK_CHARS, chunksOf } from "../lib/report/draft/tasks/sweep-pipeline"; import type { Cue } from "../lib/vtt"; import { CUES_JSON_FILENAME } from "../lib/videoStatus"; import { readChannelConfig } from "./channels"; import { heldVideoIds } from "./videoCues"; export type LookoutPlanOptions = { /** Override the lookout's `days` for this plan. */ days?: number; /** Override the lookout's `maxVideos` for this plan. */ maxVideos?: number; /** The window's last day (YYYY-MM-DD); default today in the lookout's zone. */ until?: string; now?: Date; /** Files read at once (default 32). */ concurrency?: number; }; export class LookoutPlanRefusal extends Error {} const META_FILENAME = "metadata.info.json"; const CUES_HEAD_BYTES = 16 * 1024; const META_TAIL_BYTES = 16 * 1024; // A video whose UTC upload date is this many days outside the window cannot // air inside it (the zone moves a date by one; a stream's start precedes its // upload by hours) and is not read further. const PREFILTER_SLACK_DAYS = 2; // THE DIRECTORY'S ctime, FIRST. A big channel holds thousands of video // directories and a lookout wants a week of them; opening every one's cues is // ~1 ms a file (23,516 directories: 28 s, measured 11 Nov), a stat is a // seventh of that. A video that aired in the window got its transcript after // it aired, and writing transcript.cues.json — created or renamed into place — // sets its directory's ctime, which no copy or `touch` can set back. So a // directory whose ctime is before the window (less the slack) cannot hold a // video that aired in it with a transcript, and is not opened. A bulk pass that // touches every directory only makes this slower, never wrong. A video with no // transcript yet is listed only if its directory changed in that time too. const CTIME_SLACK_MS = PREFILTER_SLACK_DAYS * 86_400_000 + 14 * 3_600_000; async function readHead(file: string, bytes: number): Promise { let fh; try { fh = await openFile(file, "r"); const buf = Buffer.allocUnsafe(bytes); const { bytesRead } = await fh.read(buf, 0, bytes, 0); return buf.toString("latin1", 0, bytesRead); } catch { return null; } finally { await fh?.close().catch(() => {}); } } async function readTail(file: string, bytes: number): Promise { let fh; try { fh = await openFile(file, "r"); const { size } = await fh.stat(); const len = Math.min(bytes, size); const buf = Buffer.allocUnsafe(len); await fh.read(buf, 0, len, size - len); return buf.toString("latin1"); } catch { return null; } finally { await fh?.close().catch(() => {}); } } const num = (s: string | undefined): number | null => { if (s === undefined) return null; const n = Number(s); return Number.isFinite(n) ? n : null; }; function lastMatch(text: string, re: RegExp): RegExpExecArray | null { let last: RegExpExecArray | null = null; for (const m of text.matchAll(re)) last = m as RegExpExecArray; return last; } export type MetaDates = { releaseTimestamp: number | null; timestamp: number | null; uploadDate: string | null; liveStatus: string | null; duration: number | null; /** The record's title and page URL — what a video with no transcript is listed by. */ title: string | null; webpageUrl: string | null; }; // The JSON string after the first `"":` in `buf`, decoded (escapes and // UTF-8); null when it is absent, not a string, or longer than `max` bytes. function stringOf(buf: Buffer, key: string, max = 4096): string | null { const at = buf.indexOf(`"${key}":`, 0, "latin1"); if (at < 0) return null; let i = at + key.length + 3; while (i < buf.length && (buf[i] === 0x20 || buf[i] === 0x0a || buf[i] === 0x0d || buf[i] === 0x09)) i++; if (buf[i] !== 0x22) return null; const end = Math.min(buf.length, i + 1 + max); for (let j = i + 1; j < end; j++) { if (buf[j] === 0x5c) j++; else if (buf[j] === 0x22) { try { const v: unknown = JSON.parse(buf.toString("utf8", i, j + 1)); return typeof v === "string" && v.trim() ? v : null; } catch { return null; } } } return null; } // The value after `"":` at byte `at` of `buf` (whitespace skipped): a // number's digits, or a string's contents — never more than 64 bytes. function valueAt(buf: Buffer, at: number, key: string): string | null { let i = at + key.length + 3; while (i < buf.length && (buf[i] === 0x20 || buf[i] === 0x0a || buf[i] === 0x0d || buf[i] === 0x09)) i++; const quoted = buf[i] === 0x22; if (quoted) i++; const end = Math.min(buf.length, i + 64); let j = i; while (j < end && (quoted ? buf[j] !== 0x22 : /[0-9.a-z_]/.test(String.fromCharCode(buf[j]!)))) j++; return j > i ? buf.toString("latin1", i, j) : null; } function first(buf: Buffer, key: string): string | null { const at = buf.indexOf(`"${key}":`, 0, "latin1"); return at < 0 ? null : valueAt(buf, at, key); } function last(buf: Buffer, key: string, before = buf.length): { at: number; value: string | null } | null { const at = buf.lastIndexOf(`"${key}":`, before, "latin1"); return at < 0 ? null : { at, value: valueAt(buf, at, key) }; } /** * The dating fields of a metadata.info.json, found by byte search — a YouTube * record is megabytes of formats and caption URLs, and only these five scalars * (and the title and page URL, two short strings) are wanted, so the file is * never decoded whole or parsed. `release_timestamp` is * taken wherever it is (no nested object carries one); `duration` is the last * before `upload_date` (formats' fragments carry their own); `timestamp` is the one * right after the last `upload_date` (yt-dlp's top-level order) when it is * there, else the last in the file; airDateOf then refuses any timestamp more * than two days from `upload_date`. */ export function metaDatesOf(input: Buffer | string): MetaDates { const buf = typeof input === "string" ? Buffer.from(input, "latin1") : input; const upload = last(buf, "upload_date"); let timestamp: string | null = null; if (upload) { const next = buf.indexOf('"timestamp":', upload.at, "latin1"); // Adjacent: only the upload date's value and a comma lie between them. if (next > 0 && next - upload.at < 40) timestamp = valueAt(buf, next, "timestamp"); } timestamp ??= last(buf, "timestamp")?.value ?? null; const uploadDate = upload?.value && /^\d{8}$/.test(upload.value) ? upload.value : null; const live = first(buf, "live_status"); // The record's own duration, not a format's: a YouTube storyboard format // lists `"fragments": [{"duration": …}]` long before the top-level key, so // the first in the file can be one sheet's seconds. The top-level one is the // last before `upload_date`; with no upload date, the last in the file. const duration = (upload ? last(buf, "duration", upload.at) : last(buf, "duration"))?.value ?? first(buf, "duration"); return { releaseTimestamp: num(first(buf, "release_timestamp") ?? undefined), timestamp: num(timestamp ?? undefined), uploadDate, liveStatus: live && /^[a-z_]+$/.test(live) ? live : null, duration: num(duration ?? undefined), // yt-dlp writes `id` then `title` first, before any nested object; the // page URL has no nested namesake (`webpage_url_basename` is another key). title: stringOf(buf, "title"), webpageUrl: stringOf(buf, "webpage_url"), }; } type Scanned = { channel: string; video: string; dir: string; hasCues: boolean; headUploadDate: string | null; headDuration: number | null; }; async function scanVideo(channel: string, dataDir: string, video: string): Promise { const dir = path.join(dataDir, video); const head = await readHead(path.join(dir, CUES_JSON_FILENAME), CUES_HEAD_BYTES); if (head !== null) { return { channel, video, dir, hasCues: true, headUploadDate: /"uploadDate":\s*"(\d{8})"/.exec(head)?.[1] ?? null, headDuration: num(/"duration":\s*(\d+(?:\.\d+)?)/.exec(head)?.[1]), }; } // No transcript: its upload date from the metadata's tail, where yt-dlp // writes it (controller/recencyIndex.ts measured 99.8 %). const tail = await readTail(path.join(dir, META_FILENAME), META_TAIL_BYTES); return { channel, video, dir, hasCues: false, headUploadDate: tail ? (lastMatch(tail, /"upload_date":\s*"(\d{8})"/g)?.[1] ?? null) : null, headDuration: null, }; } type Cand = Scanned & { air: AirDate; meta: MetaDates | null; }; type Loaded = { video: LookoutPlanVideo; cues: Cue[]; chars: number; chunks: number; shingles: Set; }; /** * A transcript's lines as the model reads them: each cue with text, at its * whole second. THE one chunking a plan counts and a run reads * (`chunksOf(cueLines(cues), CHUNK_CHARS)`), so the plan's `chunks` are the * run's reading calls. */ export function cueLines(cues: readonly Cue[]): [number, string][] { return cues.filter((c) => c.text.trim()).map((c) => [Math.floor(c.start), c.text.trim()] as [number, string]); } /** The cues of a cues document, as the plan takes them (malformed cues left out). */ export function cuesOfDoc(doc: Record): Cue[] { return (Array.isArray(doc.cues) ? doc.cues : []).filter( (x): x is Cue => !!x && typeof (x as Cue).start === "number" && typeof (x as Cue).text === "string", ); } const NOT_FINISHED = new Set(["is_live", "is_upcoming"]); /** * The plan for one lookout: what it would read, what it would not and why, * and the estimate. Writes nothing. */ export async function planLookout( paths: Paths, item: LookoutItem, opts: LookoutPlanOptions = {}, ): Promise { const days = opts.days ?? item.days; const maxVideos = opts.maxVideos ?? item.maxVideos; const window: LookoutWindow = lookoutWindow({ days, timeZone: item.timeZone, until: opts.until, now: opts.now }); const limit = opts.concurrency ?? 32; const warnings: string[] = []; const refused: LookoutPlan["refused"] = []; if (item.channels.length === 0) throw new LookoutPlanRefusal(`lookout "${item.id}" names no channels`); // ─── Stage 1: select ─── const scanned: Scanned[] = []; let listed = 0; for (const channel of item.channels) { const config = await readChannelConfig(paths, channel); if (!config) { refused.push({ channel, reason: "not a channel this archive holds (a channel only on a remote site is not read in v1)" }); continue; } if (config.localMedia && !config.url?.trim()) { refused.push({ channel, reason: "a local media library channel (not read in v1)" }); continue; } let dataDir: string; try { dataDir = (await assertChannelTextReadable(paths, channel, config)).dataDir; } catch (err) { refused.push({ channel, reason: (err as Error).message }); continue; } const videos = [...(await heldVideoIds(dataDir))].sort(); listed += videos.length; const since = Date.parse(`${window.from}T00:00:00Z`) - CTIME_SLACK_MS; const changed = await mapConcurrent(videos, limit, (v) => stat(path.join(dataDir, v)).then( (st) => st.ctimeMs >= since, () => false, ), ); const recent = videos.filter((_, i) => changed[i]); scanned.push(...(await mapConcurrent(recent, limit, (v) => scanVideo(channel, dataDir, v)))); } const lo = addDays(window.from, -PREFILTER_SLACK_DAYS); const hi = addDays(window.to, PREFILTER_SLACK_DAYS); const near = scanned.filter((s) => { const d = isoOfUploadDate(s.headUploadDate); return d === null || (d >= lo && d <= hi); }); // A YouTube record's metadata is ~10 MB: a few at a time, never 32 at once // in the editor's heap. const dated = await mapConcurrent(near, Math.min(limit, 4), async (s): Promise => { let meta: MetaDates | null = null; try { meta = metaDatesOf(await readFile(path.join(s.dir, META_FILENAME))); } catch { meta = null; } const air = airDateOf( { releaseTimestamp: meta?.releaseTimestamp, timestamp: meta?.timestamp, uploadDate: meta?.uploadDate ?? s.headUploadDate, }, window.timeZone, ); return air && inWindow(air.date, window) ? { ...s, air, meta } : null; }); const inWin = dated.filter((c): c is Cand => c !== null); const skipped: LookoutPlanSkipped[] = []; const brief = (c: Cand, over: Partial = {}): LookoutPlanVideo => ({ channel: c.channel, video: c.video, id: c.video, // From the metadata: all a video with no transcript has to be named by. title: c.meta?.title ?? "", platform: "", airDate: c.air.date, airAt: c.air.at, dateSource: c.air.source, duration: c.headDuration ?? c.meta?.duration ?? null, url: c.meta?.webpageUrl ?? null, ...over, }); // The transcripts of what is in the window: each read whole, once. const loaded = new Map(); const withCues = inWin.filter((c) => c.hasCues); const loads = await mapConcurrent(withCues, Math.min(limit, 8), async (c) => { let doc: Record | null = null; try { doc = JSON.parse(await readFile(path.join(c.dir, CUES_JSON_FILENAME), "utf8")) as Record; } catch { warnings.push(`${c.channel}/${c.video}: transcript.cues.json is not readable JSON — treated as no transcript`); } return { c, doc }; }); let underMin = 0; let other = 0; let noTranscript = 0; for (const c of inWin) { if (!c.hasCues) { noTranscript++; skipped.push({ ...brief(c), reason: "no-transcript" }); } } for (const { c, doc } of loads) { if (!doc) { noTranscript++; skipped.push({ ...brief(c), reason: "no-transcript" }); continue; } const cues = cuesOfDoc(doc); const lastEnd = cues.length ? Math.round(cues[cues.length - 1]!.end) : null; const duration = (typeof doc.duration === "number" && doc.duration > 0 ? doc.duration : null) ?? c.meta?.duration ?? lastEnd; const video = brief(c, { id: typeof doc.id === "string" ? doc.id : c.video, title: typeof doc.title === "string" && doc.title ? doc.title : (c.meta?.title ?? ""), platform: typeof doc.platform === "string" ? doc.platform : "", duration, url: typeof doc.webpageUrl === "string" && doc.webpageUrl ? doc.webpageUrl : (c.meta?.webpageUrl ?? null), }); if (video.platform === "local" || LOCAL_RECORDING_ID_RE.test(video.id)) { other++; skipped.push({ ...video, reason: "local-recording" }); continue; } if (c.meta?.liveStatus && NOT_FINISHED.has(c.meta.liveStatus)) { other++; skipped.push({ ...video, reason: "not-finished" }); continue; } if (duration !== null && duration < item.minSeconds) { underMin++; skipped.push({ ...video, reason: "under-min-seconds" }); continue; } const chars = cues.reduce((s, x) => s + x.text.length, 0); loaded.set(`${c.channel}/${c.video}`, { video, cues, chars, chunks: chunksOf(cueLines(cues), CHUNK_CHARS).length, shingles: shingles(comparisonText(cues), LOOKOUT_SHINGLE_SIZE), }); } // ─── Stage 2: fold, then cap ─── const dedupe: DedupeVideo[] = [...loaded.entries()].map(([key, l]) => ({ key, title: l.video.title, platform: l.video.platform, duration: l.video.duration, airAt: l.video.airAt ?? l.video.airDate, shingles: l.shingles, })); const groups = foldRecordings(dedupe); const foldedOf = (keys: ReturnType[number]["folded"]): LookoutPlanFolded[] => keys.map(({ key, ...rest }) => ({ ...loaded.get(key)!.video, ...rest })); const read: LookoutPlanRead[] = []; let duplicateUploads = 0; let coveredByStream = 0; let capped = 0; for (const g of groups) { for (const f of g.folded) { if (f.reason === "duplicate-upload") duplicateUploads++; else coveredByStream++; } const p = loaded.get(g.primary)!; if (read.length < maxVideos) { read.push({ ...p.video, chars: p.chars, chunks: p.chunks, folded: foldedOf(g.folded) }); } else { capped++; skipped.push({ ...p.video, reason: "cap", chunks: p.chunks, folded: foldedOf(g.folded) }); } } const readCalls = read.reduce((s, r) => s + r.chunks, 0); const measured = await measuredSecondsPerCall(paths, item.id).catch(() => null); const order: Record = { cap: 0, "under-min-seconds": 1, "no-transcript": 2, "not-finished": 3, "local-recording": 4 }; skipped.sort( (a, b) => order[a.reason]! - order[b.reason]! || (a.airDate < b.airDate ? -1 : a.airDate > b.airDate ? 1 : 0) || (`${a.channel}/${a.video}` < `${b.channel}/${b.video}` ? -1 : 1), ); const datedByUploadDate = inWin.filter((c) => c.air.source === "upload_date").length; if (datedByUploadDate) { warnings.push(`${datedByUploadDate} video(s) in the window carry no timestamp: dated by their UTC upload_date, which may be a day off`); } return { version: 1, lookout: { id: item.id, label: item.label }, channels: item.channels, refused, window, minSeconds: item.minSeconds, maxVideos, generatedAt: (opts.now ?? new Date()).toISOString(), counts: { scanned: listed, examined: scanned.length, inWindow: inWin.length - noTranscript, noTranscript, underMinSeconds: underMin, qualified: loaded.size, duplicateUploads, coveredByStream, recordings: groups.length, read: read.length, skippedForCap: capped, otherSkipped: other, datedByUploadDate, }, read, skipped, estimate: { readCalls, secondsPerCall: measured ? Math.round(measured.secondsPerCall * 10) / 10 : null, seconds: measured ? Math.round(readCalls * measured.secondsPerCall) : null, basis: measured ? `${measured.calls} calls over the last ${measured.runs} run(s); grouping calls (a few) not included` : "no run has been measured yet: the first run records its seconds per call", }, warnings, }; }