Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 04d7813afbdefad0cbde32df14ab8fd587f124ab
parent 25f18031d777249ed31d1672ba552e15d8d93ab7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 14:17:37 -0500

common: a lookout's selection with no model — air dates, one recording read once, the cap — and its store

lib/lookout.ts: air date = release_timestamp, else timestamp, in the lookout's zone (upload_date only as a
marked fallback); the window; foldRecordings (duplicate uploads: runtime within 2 % and title or 5-shingle
Jaccard >= 0.35; a stream's cut-downs: >= 40 % of shingles in a >= 30 min recording). controller/lookoutPlan.ts:
the dry run's plan over a lookout's channels, text only, writes nothing, refuses a local library or a slug the
archive does not hold by name; directory ctime skips what cannot have aired in the window. lib/lookoutStore.ts:
transcripts/.lookouts/<id>/ runs and verdicts, ideaKey, the one atomic verdict writer, the readout. A guard test
that no lookout file names the pilot lookout's channels.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Acommon/controller/lookoutPlan.test.ts | 365+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/lookoutPlan.ts | 484+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/duplicates.ts | 2+-
Acommon/lib/lookout.test.ts | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/lookout.ts | 397+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/lookoutNoChannelNames.test.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/lookoutStore.test.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/lookoutStore.ts | 362+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 2000 insertions(+), 1 deletion(-)

diff --git a/common/controller/lookoutPlan.test.ts b/common/controller/lookoutPlan.test.ts @@ -0,0 +1,365 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, rm, writeFile, readdir } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { sanitizeLookoutItem } from "../lib/lookoutSettings"; +import { metaDatesOf, planLookout, LookoutPlanRefusal } from "./lookoutPlan"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/lookoutPlan.test.ts +// +// The dry run over a fixture corpus (lane/lookout slice 1, acceptance a): a +// stream whose UTC upload date is the next day, its twin upload on another +// channel and a cut-down of it → the plan lists the stream ONCE, on the local +// date, with both alternates. Every channel name here is invented. + +// The real start of an evening stream: 2026-11-04T01:20:53Z, which is +// 2026-11-03 20:20 in New York — `upload_date` says 4 Nov, the air says 3 Nov. +const STREAM_RELEASE = 1793755253; +const STREAM_UPLOAD = 1793754765; + +// Deterministic words: a small LCG over a synthetic vocabulary, so the texts +// have real shingles and two "transcripts" of the same speech differ the way +// two ASR engines do (a word in ten replaced). +function words(seed: number, n: number): string[] { + let x = seed >>> 0; + const out: string[] = []; + for (let i = 0; i < n; i++) { + x = (Math.imul(x, 1664525) + 1013904223) >>> 0; + out.push(`w${(x >>> 16) % 2000}`); + } + return out; +} +function garble(ws: string[], seed: number, every = 10): string[] { + return ws.map((w, i) => (i % every === seed % every ? `x${i}` : w)); +} +function cuesOf(ws: string[], seconds: number) { + const per = 10; + const n = Math.ceil(ws.length / per); + const step = seconds / n; + return Array.from({ length: n }, (_, i) => ({ + start: Math.round(i * step * 100) / 100, + end: Math.round((i + 1) * step * 100) / 100, + text: ws.slice(i * per, (i + 1) * per).join(" "), + })); +} + +type VideoFixture = { + channel: string; + dir: string; + id?: string; + title: string; + platform: string; + duration: number; + uploadDate: string; + timestamp?: number; + releaseTimestamp?: number; + liveStatus?: string; + text?: string[]; +}; + +async function writeVideo(channelsDir: string, v: VideoFixture): Promise<void> { + const dir = path.join(channelsDir, v.channel, "data", v.dir); + await mkdir(dir, { recursive: true }); + const meta: Record<string, unknown> = { + id: v.id ?? v.dir, + title: v.title, + formats: [{ format_id: "1", url: "https://example.invalid/f" }], + duration: v.duration, + live_status: v.liveStatus ?? "not_live", + upload_date: v.uploadDate, + }; + if (v.timestamp !== undefined) meta.timestamp = v.timestamp; + if (v.releaseTimestamp !== undefined) meta.release_timestamp = v.releaseTimestamp; + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(meta, null, 1)); + if (v.text) { + await writeFile( + path.join(dir, "transcript.cues.json"), + JSON.stringify({ + version: 2, + source: v.platform === "youtube" ? "vtt" : "whisper", + slug: `${v.channel}/${v.id ?? v.dir}`, + id: v.id ?? v.dir, + channelSlug: v.channel, + title: v.title, + uploadDate: v.uploadDate, + duration: v.duration, + channel: v.channel, + description: "", + platform: v.platform, + webpageUrl: `https://example.invalid/${v.dir}`, + cues: cuesOf(v.text, v.duration), + }), + ); + } +} + +async function fixture(): Promise<{ root: string; paths: Paths }> { + const root = await mkdtemp(path.join(os.tmpdir(), "lookout-plan-")); + const transcriptsDir = path.join(root, "transcripts"); + const channelsDir = path.join(transcriptsDir, "channels"); + const channel = async (slug: string, config: Record<string, unknown>) => { + await mkdir(path.join(channelsDir, slug, "data"), { recursive: true }); + await writeFile(path.join(channelsDir, slug, "config.json"), JSON.stringify(config)); + }; + await channel("alpha-rumble", { name: "Alpha", handling: "transcribe", url: "https://rumble.com/c/alpha-invented" }); + await channel("alpha-clips", { name: "Alpha Clips", handling: "youtube", url: "https://www.youtube.com/@alpha-invented" }); + await channel("alpha-library", { name: "Library", handling: "transcribe", localMedia: { sourceId: "library-1", directory: "/mnt/recordings" } }); + + const stream = words(1, 6000); + // The stream on one channel, dated by its start. + await writeVideo(channelsDir, { + channel: "alpha-rumble", + dir: "v1stream", + id: "v0embed1", + title: "Election Night LIVE!", + platform: "rumble", + duration: 7200, + uploadDate: "20261104", + timestamp: STREAM_UPLOAD, + releaseTimestamp: STREAM_RELEASE, + liveStatus: "was_live", + text: stream, + }); + // Its twin upload on another channel: the same title, a second longer, + // captions from another engine; uploaded the next morning. + await writeVideo(channelsDir, { + channel: "alpha-clips", + dir: "TwinUpload1", + title: "Election Night LIVE!", + platform: "youtube", + duration: 7201, + uploadDate: "20261104", + timestamp: 1793790000, + text: garble(stream, 3), + }); + // A cut-down: twelve minutes of the stream, re-titled. + await writeVideo(channelsDir, { + channel: "alpha-clips", + dir: "CutDown0001", + title: "He SNAPPED On Air", + platform: "youtube", + duration: 720, + uploadDate: "20261104", + timestamp: 1793800000, + text: garble(stream.slice(2000, 2600), 7), + }); + // An unrelated video in the window. + await writeVideo(channelsDir, { + channel: "alpha-clips", + dir: "Unrelated01", + title: "Something Else Entirely", + platform: "youtube", + duration: 600, + uploadDate: "20261105", + timestamp: 1793880000, + text: words(99, 1500), + }); + // A short. + await writeVideo(channelsDir, { + channel: "alpha-clips", + dir: "ShortOne001", + title: "A Short #shorts", + platform: "youtube", + duration: 58, + uploadDate: "20261104", + timestamp: 1793810000, + text: words(7, 120), + }); + // In the window, no transcript yet. + await writeVideo(channelsDir, { + channel: "alpha-clips", + dir: "NoCues00001", + title: "Not Transcribed", + platform: "youtube", + duration: 900, + uploadDate: "20261105", + timestamp: 1793870000, + }); + // The UTC trap the other way: 2026-11-03T04:30Z is 2 Nov in New York — + // `upload_date` puts it inside a 3–5 Nov window, the air date does not. + await writeVideo(channelsDir, { + channel: "alpha-rumble", + dir: "v1latenight", + title: "Late Night", + platform: "rumble", + duration: 1200, + uploadDate: "20261103", + timestamp: 1793680200, + text: words(55, 2000), + }); + // Long before the window. + await writeVideo(channelsDir, { + channel: "alpha-rumble", + dir: "v1old", + title: "Old", + platform: "rumble", + duration: 1200, + uploadDate: "20260101", + timestamp: 1767268800, + text: words(56, 2000), + }); + return { root, paths: { transcriptsDir, channelsDir } as Paths }; +} + +function lookout(over: Record<string, unknown> = {}) { + const item = sanitizeLookoutItem({ + id: "alpha-week", + channels: ["alpha-rumble", "alpha-clips"], + days: 3, + timeZone: "America/New_York", + ...over, + }); + assert.ok(item); + return item; +} + +test("the stream is listed once, on its local date, with its twin and its cut-down", async () => { + const { root, paths } = await fixture(); + try { + const plan = await planLookout(paths, lookout(), { until: "2026-11-05" }); + assert.deepEqual(plan.refused, []); + assert.deepEqual(plan.window, { from: "2026-11-03", to: "2026-11-05", days: 3, timeZone: "America/New_York" }); + const keys = plan.read.map((r) => `${r.channel}/${r.video}`); + assert.deepEqual(keys, ["alpha-rumble/v1stream", "alpha-clips/Unrelated01"]); + const s = plan.read[0]!; + assert.equal(s.airDate, "2026-11-03", "the air date in New York, not the UTC upload date"); + assert.equal(s.dateSource, "release_timestamp"); + assert.equal(s.airAt, "2026-11-04T01:20:53.000Z"); + assert.equal(s.id, "v0embed1", "the record's id beside its directory"); + assert.deepEqual( + s.folded.map((f) => [`${f.channel}/${f.video}`, f.reason]), + [ + ["alpha-clips/TwinUpload1", "duplicate-upload"], + ["alpha-clips/CutDown0001", "covered-by-stream"], + ], + ); + assert.equal(s.folded[0]!.titleMatch, true); + assert.ok(s.folded[1]!.score >= 0.4, `cut-down share ${s.folded[1]!.score}`); + assert.equal(s.folded[0]!.airDate, "2026-11-04"); + assert.equal(plan.counts.inWindow, 5, "stream, twin, cut-down, unrelated, short — not the late-night one"); + assert.equal(plan.counts.noTranscript, 1); + assert.equal(plan.counts.underMinSeconds, 1); + assert.equal(plan.counts.qualified, 4); + assert.equal(plan.counts.duplicateUploads, 1); + assert.equal(plan.counts.coveredByStream, 1); + assert.equal(plan.counts.recordings, 2); + assert.equal(plan.counts.read, 2); + assert.equal(plan.counts.skippedForCap, 0); + assert.deepEqual( + plan.skipped.map((k) => [k.video, k.reason]), + [ + ["ShortOne001", "under-min-seconds"], + ["NoCues00001", "no-transcript"], + ], + ); + assert.ok(!keys.includes("alpha-rumble/v1latenight"), "aired 2 Nov in New York"); + assert.ok(s.chunks > 1, "a two-hour stream is several chunks"); + assert.equal(plan.estimate.readCalls, plan.read.reduce((n, r) => n + r.chunks, 0)); + assert.equal(plan.estimate.secondsPerCall, null, "no run measured yet"); + // Nothing was written: the corpus holds exactly what the fixture put there. + assert.deepEqual((await readdir(paths.transcriptsDir)).sort(), ["channels"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("in UTC the late-night video is in the window and the stream moves to 4 Nov", async () => { + const { root, paths } = await fixture(); + try { + const plan = await planLookout(paths, lookout({ timeZone: "UTC" }), { until: "2026-11-05" }); + const byKey = new Map(plan.read.map((r) => [`${r.channel}/${r.video}`, r])); + assert.equal(byKey.get("alpha-rumble/v1stream")?.airDate, "2026-11-04"); + assert.equal(byKey.get("alpha-rumble/v1latenight")?.airDate, "2026-11-03"); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("the cap reads the longest recordings and lists the rest with what folded into them", async () => { + const { root, paths } = await fixture(); + try { + const plan = await planLookout(paths, lookout(), { until: "2026-11-05", maxVideos: 1 }); + assert.deepEqual(plan.read.map((r) => r.video), ["v1stream"]); + assert.equal(plan.counts.skippedForCap, 1); + const cap = plan.skipped.find((k) => k.reason === "cap"); + assert.equal(cap?.video, "Unrelated01"); + assert.deepEqual(cap?.folded, []); + assert.ok((cap?.chunks ?? 0) >= 1); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a local library and a slug the archive does not hold are refused by name; the rest is read", async () => { + const { root, paths } = await fixture(); + try { + const plan = await planLookout( + paths, + lookout({ channels: ["alpha-library", "remote-only-invented", "alpha-rumble"] }), + { until: "2026-11-05" }, + ); + assert.deepEqual( + plan.refused.map((r) => r.channel), + ["alpha-library", "remote-only-invented"], + ); + assert.match(plan.refused[0]!.reason, /local media library/); + assert.match(plan.refused[1]!.reason, /remote site/); + assert.deepEqual(plan.read.map((r) => r.video), ["v1stream"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a directory unchanged since before the window is listed, not opened", async () => { + const { root, paths } = await fixture(); + try { + // Every fixture directory was made just now; a window years later starts + // after all of their ctimes, so none can hold a video aired in it. + const plan = await planLookout(paths, lookout(), { until: "2031-01-10" }); + assert.equal(plan.counts.scanned, 8); + assert.equal(plan.counts.examined, 0); + assert.equal(plan.counts.inWindow, 0); + const now = await planLookout(paths, lookout(), { until: "2026-11-05" }); + assert.equal(now.counts.examined, 8); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("a lookout with no channels is refused", async () => { + const { root, paths } = await fixture(); + try { + await assert.rejects(planLookout(paths, lookout({ channels: [] })), LookoutPlanRefusal); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("metaDatesOf reads the scalars wherever yt-dlp put them", () => { + // YouTube's order: upload_date then timestamp, near the end; a comment's + // nested timestamp earlier is not taken. + const yt = + '{"id": "a", "comments": [{"timestamp": 1600000000}], "duration": 747, "live_status": "not_live", ' + + '"upload_date": "20261106", "timestamp": 1793993883, "is_live": false}'; + assert.deepEqual(metaDatesOf(yt), { + releaseTimestamp: null, + timestamp: 1793993883, + uploadDate: "20261106", + liveStatus: "not_live", + duration: 747, + }); + // Rumble's order: timestamp early, release_timestamp later, upload_date last. + const rumble = + '{"id": "v", "timestamp": 1793754765, "duration": 12970, "live_status": "was_live", ' + + '"release_timestamp": 1793755253, "upload_date": "20261104"}'; + assert.deepEqual(metaDatesOf(rumble), { + releaseTimestamp: 1793755253, + timestamp: 1793754765, + uploadDate: "20261104", + liveStatus: "was_live", + duration: 12970, + }); +}); diff --git a/common/controller/lookoutPlan.ts b/common/controller/lookoutPlan.ts @@ -0,0 +1,484 @@ +// 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 (slice 2) reads exactly the `read` list it returns. +// +// 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<string | null> { + 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<string | null> { + 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 value after `"<key>":` 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 + * are wanted, so the file is never decoded or parsed. `release_timestamp` is + * taken wherever it is (no nested object carries one); `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"); + return { + releaseTimestamp: num(first(buf, "release_timestamp") ?? undefined), + timestamp: num(timestamp ?? undefined), + uploadDate, + liveStatus: live && /^[a-z_]+$/.test(live) ? live : null, + duration: num(first(buf, "duration") ?? undefined), + }; +} + +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<Scanned> { + 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<string>; +}; + +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]); +} + +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<LookoutPlan> { + 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<Cand | null> => { + 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> = {}): LookoutPlanVideo => ({ + channel: c.channel, + video: c.video, + id: c.video, + title: "", + platform: "", + airDate: c.air.date, + airAt: c.air.at, + dateSource: c.air.source, + duration: c.headDuration ?? c.meta?.duration ?? null, + url: null, + ...over, + }); + + // The transcripts of what is in the window: each read whole, once. + const loaded = new Map<string, Loaded>(); + const withCues = inWin.filter((c) => c.hasCues); + const loads = await mapConcurrent(withCues, Math.min(limit, 8), async (c) => { + let doc: Record<string, unknown> | null = null; + try { + doc = JSON.parse(await readFile(path.join(c.dir, CUES_JSON_FILENAME), "utf8")) as Record<string, unknown>; + } 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 = (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 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 : "", + platform: typeof doc.platform === "string" ? doc.platform : "", + duration, + url: typeof doc.webpageUrl === "string" && doc.webpageUrl ? doc.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<typeof foldRecordings>[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<string, number> = { 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, + }; +} + diff --git a/common/lib/duplicates.ts b/common/lib/duplicates.ts @@ -266,7 +266,7 @@ const PLATFORM_PREFERENCE: ReadonlyArray<string> = [ "bitchute", ]; -function platformRank(platform: string): number { +export function platformRank(platform: string): number { const i = PLATFORM_PREFERENCE.indexOf(platform); return i < 0 ? PLATFORM_PREFERENCE.length : i; } diff --git a/common/lib/lookout.test.ts b/common/lib/lookout.test.ts @@ -0,0 +1,152 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + COVERED_THRESHOLD, + addDays, + airDateOf, + foldRecordings, + inWindow, + isIsoDate, + localDateOf, + lookoutWindow, + type DedupeVideo, +} from "./lookout"; +import { shingles } from "./duplicates"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookout.test.ts + +// A real start time: 2026-11-04T01:20:53Z, an evening stream in New York. +const EVENING_STREAM = 1793755253; + +test("the UTC trap: an evening stream airs on the local date, not on upload_date's", () => { + const ny = airDateOf({ releaseTimestamp: EVENING_STREAM, timestamp: EVENING_STREAM - 488, uploadDate: "20261104" }, "America/New_York"); + assert.deepEqual(ny, { date: "2026-11-03", at: "2026-11-04T01:20:53.000Z", source: "release_timestamp" }); + assert.equal(airDateOf({ releaseTimestamp: EVENING_STREAM, uploadDate: "20261104" }, "UTC")?.date, "2026-11-04"); + assert.equal(airDateOf({ releaseTimestamp: EVENING_STREAM, uploadDate: "20261104" }, "Europe/Berlin")?.date, "2026-11-04"); +}); + +test("release_timestamp, else timestamp, else upload_date — and a far-off timestamp is not believed", () => { + assert.equal(airDateOf({ timestamp: EVENING_STREAM, uploadDate: "20261104" }, "America/New_York")?.source, "timestamp"); + assert.deepEqual(airDateOf({ uploadDate: "20261104" }, "America/New_York"), { date: "2026-11-04", at: null, source: "upload_date" }); + // A nested key read by mistake, months away: the upload date wins. + assert.deepEqual(airDateOf({ timestamp: 1600000000, uploadDate: "20261104" }, "UTC"), { date: "2026-11-04", at: null, source: "upload_date" }); + assert.equal(airDateOf({}, "UTC"), null); + assert.equal(airDateOf({ timestamp: 0, uploadDate: "garbage" }, "UTC"), null); +}); + +test("the window counts calendar days in the lookout's zone, both ends included", () => { + assert.deepEqual(lookoutWindow({ days: 7, timeZone: "America/New_York", until: "2026-11-10" }), { + from: "2026-11-04", + to: "2026-11-10", + days: 7, + timeZone: "America/New_York", + }); + // "Today" is the zone's today: 03:00Z on 11 Nov is still 10 Nov in New York. + const now = new Date("2026-11-11T03:00:00Z"); + assert.equal(lookoutWindow({ days: 1, timeZone: "America/New_York", now }).to, "2026-11-10"); + assert.equal(lookoutWindow({ days: 1, timeZone: "UTC", now }).to, "2026-11-11"); + assert.ok(inWindow("2026-11-04", { from: "2026-11-04", to: "2026-11-10" })); + assert.ok(!inWindow("2026-11-03", { from: "2026-11-04", to: "2026-11-10" })); + assert.equal(addDays("2026-02-28", 1), "2026-03-01"); + assert.equal(addDays("2026-03-01", -1), "2026-02-28"); + assert.ok(isIsoDate("2026-11-10") && !isIsoDate("2026-02-30") && !isIsoDate("20261110")); + assert.equal(localDateOf(Date.UTC(2026, 10, 4, 4, 59), "America/New_York"), "2026-11-03"); +}); + +function text(seed: number, n: number): string[] { + let x = seed >>> 0; + return Array.from({ length: n }, () => { + x = (Math.imul(x, 1664525) + 1013904223) >>> 0; + return `w${(x >>> 16) % 3000}`; + }); +} +const sh = (ws: string[]) => shingles(ws.join(" "), 5); +function vid(key: string, o: Partial<DedupeVideo> & { words: string[] }): DedupeVideo { + return { + key, + title: o.title ?? key, + platform: o.platform ?? "youtube", + duration: o.duration ?? 600, + airAt: o.airAt ?? "2026-11-04T12:00:00.000Z", + shingles: sh(o.words), + }; +} + +test("a twin upload with the same title and runtime is folded, the first on the air read", () => { + const ws = text(1, 2000); + const groups = foldRecordings([ + vid("b/yt", { words: ws, title: "Big News!", duration: 824, airAt: "2026-11-04T15:00:00.000Z" }), + vid("a/rumble", { words: ws.map((w, i) => (i % 3 === 0 ? "zz" : w)), title: "BIG NEWS", platform: "rumble", duration: 825, airAt: "2026-11-04T14:00:00.000Z" }), + ]); + assert.equal(groups.length, 1); + assert.equal(groups[0]!.primary, "a/rumble"); + assert.deepEqual(groups[0]!.folded.map((f) => [f.key, f.reason, f.titleMatch]), [["b/yt", "duplicate-upload", true]]); +}); + +test("a re-titled mirror is caught by its text; a same-titled different video is caught by its runtime", () => { + const ws = text(2, 2000); + const retitled = foldRecordings([ + vid("a/one", { words: ws, title: "THIS IS DISGRACEFUL!", duration: 825 }), + vid("b/two", { words: ws, title: "Massive Story Revealed & More", duration: 824, platform: "rumble" }), + ]); + assert.equal(retitled.length, 1); + assert.equal(retitled[0]!.folded[0]!.titleMatch, undefined); + assert.ok(retitled[0]!.folded[0]!.score > 0.9); + // The same title, a runtime 10 % off, unrelated text: two recordings. + const series = foldRecordings([ + vid("a/ep1", { words: text(3, 2000), title: "Daily Show", duration: 900 }), + vid("a/ep2", { words: text(4, 2000), title: "Daily Show", duration: 1000 }), + ]); + assert.equal(series.length, 2); + // Near-identical text but runtimes far apart is not a twin (it may be a cut-down; see below). + const apart = foldRecordings([ + vid("a/x", { words: ws, duration: 600 }), + vid("b/y", { words: ws, duration: 700 }), + ]); + assert.equal(apart.length, 2); +}); + +test("a cut-down is credited to the stream it is cut from, with its share", () => { + const stream = text(5, 20000); + const groups = foldRecordings([ + vid("s/stream", { words: stream, duration: 7200, platform: "rumble", airAt: "2026-11-04T01:20:53.000Z" }), + vid("c/cut", { words: stream.slice(5000, 6500), duration: 700, title: "Clip" }), + vid("c/cut-twin", { words: stream.slice(5000, 6500), duration: 701, title: "Clip", platform: "rumble" }), + vid("o/other", { words: text(6, 1500), duration: 700, title: "Other" }), + ]); + assert.deepEqual(groups.map((g) => g.primary), ["s/stream", "o/other"]); + const s = groups[0]!; + assert.deepEqual( + s.folded.map((f) => [f.key, f.reason, f.matched]).sort(), + [ + ["c/cut", "covered-by-stream", "s/stream"], + ["c/cut-twin", "covered-by-stream", "s/stream"], + ], + ); + assert.ok(s.folded.every((f) => f.score >= COVERED_THRESHOLD)); +}); + +test("a short video sharing a little of a stream is not its cut-down", () => { + const stream = text(7, 20000); + const mixed = [...stream.slice(100, 300), ...text(8, 800)]; + const groups = foldRecordings([ + vid("s/stream", { words: stream, duration: 7200 }), + vid("c/mixed", { words: mixed, duration: 400 }), + ]); + assert.equal(groups.length, 2); +}); + +test("every input appears exactly once, as a primary or folded", () => { + const stream = text(9, 10000); + const vids = [ + vid("s/1", { words: stream, duration: 4000 }), + vid("s/2", { words: stream, duration: 4010, platform: "rumble" }), + vid("c/1", { words: stream.slice(0, 900), duration: 500 }), + vid("c/2", { words: text(10, 900), duration: 500 }), + vid("c/3", { words: text(10, 900), duration: 501, platform: "rumble" }), + ]; + const groups = foldRecordings(vids); + const seen = groups.flatMap((g) => [g.primary, ...g.folded.map((f) => f.key)]).sort(); + assert.deepEqual(seen, vids.map((v) => v.key).sort()); +}); diff --git a/common/lib/lookout.ts b/common/lib/lookout.ts @@ -0,0 +1,397 @@ +// A LOOKOUT'S SELECTION, the pure half (lane/lookout stages 1–2): air dates, +// the window, and the folding of one recording's several uploads into one read. +// No I/O — controller/lookoutPlan.ts reads the channels and calls these. +// +// AIR DATE, NOT UPLOAD DATE. yt-dlp's `upload_date` is a UTC date, so an +// evening stream in the Americas lands on the next day: an election-night +// stream that started at 20:20 in New York is 4 Nov by `upload_date` and 3 Nov +// on the air. A lookout's days are counted in its own time zone from the +// metadata's `release_timestamp` (a stream's or premiere's start), else its +// `timestamp` (the upload), and only when neither is there from `upload_date`, +// which the plan then marks as such. +// +// ONE RECORDING, READ ONCE. Two cases, both decided on the cues, because +// `transcripts/duplicates.json` is built rarely and does not know this week: +// - a DUPLICATE UPLOAD — the same recording on two channels or platforms — +// is two videos whose runtimes agree within 2 % and whose normalised titles +// match or whose transcripts are near-duplicates (5-word shingle Jaccard ≥ +// 0.35, the duplicate detector's own threshold: two ASR engines over the +// same audio land at 0.35–0.60). A re-titled mirror is caught by the text. +// - a CUT-DOWN of a stream — a shorter upload whose text is an excerpt of a +// long recording in the window — is a video under 30 minutes at least 40 % +// of whose shingles are in one stream (the pilot's measured rule). It is +// credited to the stream as an alternate source and not read on its own. +// Every folded video stays in the plan, under the recording it was folded into, +// with why and its score. + +import { + DEFAULT_NEAR_THRESHOLD, + DEFAULT_SHINGLE_SIZE, + DEFAULT_TITLE_DURATION_RATIO, + UnionFind, + durationsCompatible, + intersectionSize, + jaccard, + normalizeTitleKey, + platformRank, +} from "./duplicates"; + +// ─── Air dates and the window ─── + +export type AirDateSource = "release_timestamp" | "timestamp" | "upload_date"; + +export type AirDate = { + /** YYYY-MM-DD in the lookout's time zone (or the UTC upload date, when that is all there is). */ + date: string; + /** ISO 8601 instant, when a timestamp gave it. */ + at: string | null; + source: AirDateSource; +}; + +/** The machine's IANA zone (what a lookout's `timeZone: ""` means). */ +export function machineTimeZone(): string { + return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; +} + +/** `tz`, or the machine's when it is "". */ +export function resolveTimeZone(tz: string): string { + return tz ? tz : machineTimeZone(); +} + +/** The calendar date (YYYY-MM-DD) of an instant in `tz`. */ +export function localDateOf(ms: number, tz: string): string { + const parts = new Intl.DateTimeFormat("en-US", { + timeZone: tz, + year: "numeric", + month: "2-digit", + day: "2-digit", + }).formatToParts(new Date(ms)); + const get = (t: string) => parts.find((p) => p.type === t)?.value ?? ""; + return `${get("year")}-${get("month")}-${get("day")}`; +} + +/** "20261104" → "2026-11-04"; null for anything else. */ +export function isoOfUploadDate(yyyymmdd: string | null | undefined): string | null { + if (typeof yyyymmdd !== "string" || !/^\d{8}$/.test(yyyymmdd)) return null; + return `${yyyymmdd.slice(0, 4)}-${yyyymmdd.slice(4, 6)}-${yyyymmdd.slice(6, 8)}`; +} + +const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/; + +export function isIsoDate(s: unknown): s is string { + if (typeof s !== "string" || !ISO_DATE_RE.test(s)) return false; + const d = new Date(`${s}T00:00:00Z`); + return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s; +} + +/** A YYYY-MM-DD date `n` days later (negative: earlier). */ +export function addDays(date: string, n: number): string { + const d = new Date(`${date}T00:00:00Z`); + d.setUTCDate(d.getUTCDate() + n); + return d.toISOString().slice(0, 10); +} + +/** Whole days from `a` to `b` (both YYYY-MM-DD). */ +export function daysBetween(a: string, b: string): number { + return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86_400_000); +} + +// A timestamp further than this from the record's own UTC `upload_date` is not +// believed (a nested key read by mistake, a broken record): the upload date is +// used instead and the plan says so. +const TIMESTAMP_TRUST_DAYS = 2; + +/** + * A video's air date in `tz`: its `release_timestamp`, else its `timestamp` + * (seconds since the epoch, as yt-dlp writes them), else its `upload_date`. + * Null when it has none of the three. + */ +export function airDateOf( + meta: { releaseTimestamp?: number | null; timestamp?: number | null; uploadDate?: string | null }, + tz: string, +): AirDate | null { + const upload = isoOfUploadDate(meta.uploadDate); + const candidates: [AirDateSource, number | null | undefined][] = [ + ["release_timestamp", meta.releaseTimestamp], + ["timestamp", meta.timestamp], + ]; + for (const [source, ts] of candidates) { + if (typeof ts !== "number" || !Number.isFinite(ts) || ts <= 0) continue; + const ms = ts * 1000; + const utc = new Date(ms).toISOString().slice(0, 10); + if (upload && Math.abs(daysBetween(upload, utc)) > TIMESTAMP_TRUST_DAYS) continue; + return { date: localDateOf(ms, tz), at: new Date(ms).toISOString(), source }; + } + return upload ? { date: upload, at: null, source: "upload_date" } : null; +} + +export type LookoutWindow = { + /** First day read, YYYY-MM-DD, inclusive. */ + from: string; + /** Last day read, YYYY-MM-DD, inclusive. */ + to: string; + days: number; + timeZone: string; +}; + +/** + * The `days` calendar days ending on `until` (default: today in `tz`), both + * ends included: days 7 on 11 Nov is 5–11 Nov. + */ +export function lookoutWindow(o: { days: number; timeZone: string; until?: string | null; now?: Date }): LookoutWindow { + const tz = resolveTimeZone(o.timeZone); + const to = o.until && isIsoDate(o.until) ? o.until : localDateOf((o.now ?? new Date()).getTime(), tz); + const days = Math.max(1, Math.round(o.days)); + return { from: addDays(to, -(days - 1)), to, days, timeZone: tz }; +} + +export function inWindow(date: string, w: Pick<LookoutWindow, "from" | "to">): boolean { + return date >= w.from && date <= w.to; +} + +// ─── One recording, read once ─── + +export const LOOKOUT_SHINGLE_SIZE = DEFAULT_SHINGLE_SIZE; +/** Duplicate uploads: transcripts at least this similar (Jaccard) are one recording. */ +export const TWIN_TEXT_THRESHOLD = DEFAULT_NEAR_THRESHOLD; +/** Duplicate uploads: runtimes within this fraction of the longer. */ +export const TWIN_DURATION_RATIO = DEFAULT_TITLE_DURATION_RATIO; +/** A recording this long or longer is a stream other uploads may be cut from. */ +export const STREAM_MIN_SECONDS = 1800; +/** A shorter upload with at least this share of its shingles in a stream is that stream's cut-down. */ +export const COVERED_THRESHOLD = 0.4; + +export type DedupeVideo = { + /** `<channel>/<video dir>` — unique in a plan. */ + key: string; + title: string; + platform: string; + duration: number | null; + /** ISO instant or date the video aired, for the tie-break (earliest first). */ + airAt: string; + /** Shingles of its cue text (`comparisonText` → `shingles`). */ + shingles: ReadonlySet<string>; +}; + +export type FoldReason = "duplicate-upload" | "covered-by-stream"; + +export type FoldedVideo = { + key: string; + reason: FoldReason; + /** The video it was compared with: the twin it matched, or the stream it is cut from. */ + matched: string; + /** Jaccard (a duplicate upload) or the share of its shingles in the stream (a cut-down), 0–1. */ + score: number; + /** A duplicate upload whose normalised title matched as well. */ + titleMatch?: boolean; +}; + +export type RecordingGroup = { + /** The upload read for this recording. */ + primary: string; + /** Every other upload of it, and every cut-down credited to it. */ + folded: FoldedVideo[]; +}; + +const round2 = (n: number) => Math.round(n * 100) / 100; + +// The upload read for a set of duplicates — and so the date the recording is +// listed on: the FIRST on the air (a stream is dated by its start, not by the +// copy posted the next morning), then the preferred platform (duplicates.ts' +// order), then the longest, then the key. +function better(a: DedupeVideo, b: DedupeVideo): boolean { + if (a.airAt !== b.airAt) return a.airAt < b.airAt; + const pa = platformRank(a.platform); + const pb = platformRank(b.platform); + if (pa !== pb) return pa < pb; + const da = a.duration ?? 0; + const db = b.duration ?? 0; + if (da !== db) return da > db; + return a.key < b.key; +} + +/** |A∩B| / |A|: how much of `a` is in `b`. */ +function shareIn(a: ReadonlySet<string>, b: ReadonlySet<string>): number { + if (a.size === 0) return 0; + return intersectionSize(a as Set<string>, b as Set<string>) / a.size; +} + +/** + * Fold `videos` into recordings: duplicate uploads first, then cut-downs of a + * stream. Every input appears exactly once — as a group's primary or as one of + * its folded videos. Groups come back longest primary first. + */ +export function foldRecordings(videos: readonly DedupeVideo[]): RecordingGroup[] { + const byKey = new Map(videos.map((v) => [v.key, v])); + const uf = new UnionFind(); + const twinEdge = new Map<string, { score: number; titleMatch: boolean }>(); + const titleKeys = new Map(videos.map((v) => [v.key, normalizeTitleKey(v.title)])); + for (const v of videos) uf.add(v.key); + for (let i = 0; i < videos.length; i++) { + for (let j = i + 1; j < videos.length; j++) { + const a = videos[i]!; + const b = videos[j]!; + if (!a.duration || !b.duration || !durationsCompatible(a.duration, b.duration, TWIN_DURATION_RATIO)) continue; + const ta = titleKeys.get(a.key)!; + const titleMatch = ta !== "" && ta === titleKeys.get(b.key); + const score = jaccard(a.shingles as Set<string>, b.shingles as Set<string>); + if (!titleMatch && score < TWIN_TEXT_THRESHOLD) continue; + uf.union(a.key, b.key); + twinEdge.set(`${a.key}\n${b.key}`, { score, titleMatch }); + twinEdge.set(`${b.key}\n${a.key}`, { score, titleMatch }); + } + } + + type Group = { primary: DedupeVideo; members: DedupeVideo[]; folded: FoldedVideo[] }; + const groups: Group[] = uf.groups().map((keys) => { + const members = keys.map((k) => byKey.get(k)!).sort((a, b) => (a.key < b.key ? -1 : 1)); + const primary = members.reduce((best, v) => (better(v, best) ? v : best)); + const folded: FoldedVideo[] = members + .filter((m) => m !== primary) + .map((m) => { + const edge = twinEdge.get(`${m.key}\n${primary.key}`); + const score = edge?.score ?? jaccard(m.shingles as Set<string>, primary.shingles as Set<string>); + return { + key: m.key, + reason: "duplicate-upload" as const, + matched: primary.key, + score: round2(score), + ...(normalizeTitleKey(m.title) === titleKeys.get(primary.key) ? { titleMatch: true } : {}), + }; + }); + return { primary, members, folded }; + }); + + const isStream = (g: Group) => (g.primary.duration ?? 0) >= STREAM_MIN_SECONDS; + const streams = groups.filter(isStream).map((g) => { + // The stream's text is every upload of it: a cut-down posted to YouTube + // matches the YouTube copy of a stream better than the other platform's. + const all = new Set<string>(); + for (const m of g.members) for (const s of m.shingles) all.add(s); + return { group: g, shingles: all }; + }); + const kept: Group[] = []; + for (const g of groups) { + if (isStream(g) || streams.length === 0) { + kept.push(g); + continue; + } + let best: { stream: (typeof streams)[number]; share: number; member: DedupeVideo } | null = null; + for (const stream of streams) { + for (const m of g.members) { + const share = shareIn(m.shingles, stream.shingles); + if (!best || share > best.share) best = { stream, share, member: m }; + } + } + if (!best || best.share < COVERED_THRESHOLD) { + kept.push(g); + continue; + } + const target = best.stream.group; + for (const m of g.members) { + target.folded.push({ + key: m.key, + reason: "covered-by-stream", + matched: target.primary.key, + score: round2(shareIn(m.shingles, best.stream.shingles)), + }); + } + } + return kept + .sort((a, b) => (b.primary.duration ?? 0) - (a.primary.duration ?? 0) || (a.primary.key < b.primary.key ? -1 : 1)) + .map((g) => ({ + primary: g.primary.key, + folded: g.folded.sort((a, b) => (a.reason === b.reason ? (a.key < b.key ? -1 : 1) : a.reason === "duplicate-upload" ? -1 : 1)), + })); +} + +// ─── The plan: what a lookout would read ─── + +/** One video as a plan names it. */ +export type LookoutPlanVideo = { + channel: string; + /** Its directory under `channels/<channel>/data/`. */ + video: string; + /** The record's id (a Rumble video's directory is its URL slug; its id is the embed id). */ + id: string; + title: string; + platform: string; + airDate: string; + airAt: string | null; + dateSource: AirDateSource; + /** Seconds; null when neither the cues nor the metadata say. */ + duration: number | null; + url: string | null; +}; + +export type LookoutPlanFolded = LookoutPlanVideo & Omit<FoldedVideo, "key">; + +export type LookoutPlanRead = LookoutPlanVideo & { + /** Characters of transcript text. */ + chars: number; + /** Model-sized chunks (sweep-pipeline's CHUNK_CHARS) — one reading call each. */ + chunks: number; + /** The other uploads of this recording and the cut-downs credited to it. */ + folded: LookoutPlanFolded[]; +}; + +export type LookoutSkipReason = + | "under-min-seconds" + | "no-transcript" + | "local-recording" + | "not-finished" + | "cap"; + +export type LookoutPlanSkipped = LookoutPlanVideo & { + reason: LookoutSkipReason; + /** A cap skip carries the uploads folded into it, so nothing it stood for is lost from view. */ + folded?: LookoutPlanFolded[]; + chunks?: number; +}; + +export type LookoutPlan = { + version: 1; + lookout: { id: string; label: string }; + channels: string[]; + /** Channels named but not read, and why (a local library, a slug this archive does not hold, unreadable text). */ + refused: { channel: string; reason: string }[]; + window: LookoutWindow; + minSeconds: number; + maxVideos: number; + generatedAt: string; + counts: { + /** Video directories listed, across the channels read. */ + scanned: number; + /** Of those, the ones changed since shortly before the window (directory ctime), whose files were read. */ + examined: number; + /** Videos with a transcript whose air date is in the window. */ + inWindow: number; + /** Videos in the window with no transcript yet (not read, listed). */ + noTranscript: number; + underMinSeconds: number; + /** In the window, with a transcript, long enough — what is folded and capped. */ + qualified: number; + duplicateUploads: number; + coveredByStream: number; + /** Recordings after folding. */ + recordings: number; + read: number; + skippedForCap: number; + /** Other skips: local recordings, live or upcoming videos. */ + otherSkipped: number; + /** In the window, dated by `upload_date` alone (no timestamp in the metadata). */ + datedByUploadDate: number; + }; + read: LookoutPlanRead[]; + skipped: LookoutPlanSkipped[]; + estimate: { + /** One reading call per chunk of every recording read (a video with fresh reading notes will need none: slice 2). */ + readCalls: number; + /** Measured over the lookout's last runs; null before the first. */ + secondsPerCall: number | null; + /** readCalls × secondsPerCall, rounded; null when not measured. Grouping calls (a few) are not in it. */ + seconds: number | null; + basis: string; + }; + warnings: string[]; +}; diff --git a/common/lib/lookoutNoChannelNames.test.ts b/common/lib/lookoutNoChannelNames.test.ts @@ -0,0 +1,75 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookoutNoChannelNames.test.ts +// +// NO CHANNEL IS NAMED IN THE LOOKOUT'S CODE (lane/lookout, acceptance c). A +// lookout is configured on the machine that runs it; the standing one is a +// settings patch there, never a default, an example or a fixture here. This +// test walks every file whose path names a lookout — the libs, the +// controllers, the ops routes and their tests, and whatever later slices add +// under those names — and fails on any word of the pilot lookout's channel +// names. The words are kept as SHA-256 digests so the guard does not itself +// spell what it forbids. + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const REPO = path.resolve(HERE, "..", ".."); +const ROOTS = ["common/lib", "common/controller", "common/bin", "common/jobs", "editor/app", "umtool/lib", "umtool/app", "umtool/bin"]; + +// sha256 of each forbidden word (lowercase): the two distinctive words of the +// pilot lookout's four channel slugs. +const FORBIDDEN = new Set([ + "7a0b56a32407bfffffb453b775850130b36277a20de9611f153c0d3bf3dfa153", + "877a89b30f7ffb2b5b079e4a84066c05c476a1dda97209fce21d3a4aefac3dfc", +]); + +const sha = (w: string) => createHash("sha256").update(w).digest("hex"); + +async function lookoutFiles(dir: string, under = false): Promise<string[]> { + let entries; + try { + entries = await readdir(dir, { withFileTypes: true }); + } catch { + return []; + } + const out: string[] = []; + for (const e of entries) { + if (e.name === "node_modules" || e.name.startsWith(".")) continue; + const p = path.join(dir, e.name); + const named = under || /lookout/i.test(e.name); + if (e.isDirectory()) out.push(...(await lookoutFiles(p, named))); + else if (named && /\.(ts|tsx|mjs|js|json|md)$/.test(e.name)) out.push(p); + } + return out; +} + +test("the guard is live: its digests match words the repo's own docs use", async () => { + // A positive control, so a mistyped digest cannot silently disable the + // guard: the repo's instructions and the ops examples DO name these + // channels (they predate the lookout), and every digest must match there. + const docs = ["AGENTS.md", "plans/FACTS.md", "scripts/archilyzer-ops.mjs"]; + const seen = new Set<string>(); + for (const f of docs) { + for (const w of (await readFile(path.join(REPO, f), "utf8")).toLowerCase().match(/[a-z0-9]+/g) ?? []) { + const d = sha(w); + if (FORBIDDEN.has(d)) seen.add(d); + } + } + assert.deepEqual([...seen].sort(), [...FORBIDDEN].sort()); +}); + +test("no lookout file names a channel of the pilot lookout", async () => { + const files = (await Promise.all(ROOTS.map((r) => lookoutFiles(path.join(REPO, r))))).flat(); + assert.ok(files.length >= 6, `found the lookout's files (${files.length})`); + const hits: string[] = []; + for (const f of files) { + const words = new Set((await readFile(f, "utf8")).toLowerCase().match(/[a-z0-9]+/g) ?? []); + for (const w of words) if (FORBIDDEN.has(sha(w))) hits.push(path.relative(REPO, f)); + } + assert.deepEqual(hits, []); +}); diff --git a/common/lib/lookoutStore.test.ts b/common/lib/lookoutStore.test.ts @@ -0,0 +1,164 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, readdir, rm, writeFile, mkdir } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + LookoutStoreError, + ideaKey, + listLookoutRunIds, + lookoutReadout, + lookoutRunFile, + lookoutVerdictsFile, + lookoutsRoot, + measuredSecondsPerCall, + newLookoutRunId, + readLookoutRun, + readLookoutVerdicts, + sanitizeLookoutVerdicts, + setLookoutVerdict, + writeLookoutRun, + type LookoutIdea, + type LookoutRun, +} from "./lookoutStore"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookoutStore.test.ts + +async function corpus() { + const transcriptsDir = await mkdtemp(path.join(os.tmpdir(), "lookout-store-")); + return { transcriptsDir }; +} + +const M = (channel: string, video: string, start: number) => ({ channel, video, start }); + +test("an idea's key is its story: order-free, 5-second grain, changed by a moment added", () => { + const a = ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2000)]); + assert.match(a, /^[0-9a-f]{16}$/); + assert.equal(ideaKey([M("example-live", "v2", 2001), M("example-news", "v1", 99)]), a); + assert.notEqual(ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2010)]), a); + assert.notEqual(ideaKey([M("example-news", "v1", 100), M("example-live", "v2", 2000), M("example-news", "v3", 5)]), a); +}); + +test("the store is a dot path under the corpus, and ids are checked before any path is made", async () => { + const p = await corpus(); + try { + assert.equal(lookoutsRoot(p), path.join(p.transcriptsDir, ".lookouts")); + assert.equal(lookoutVerdictsFile(p, "weekly"), path.join(p.transcriptsDir, ".lookouts", "weekly", "verdicts.json")); + assert.throws(() => lookoutVerdictsFile(p, "../escape"), LookoutStoreError); + assert.throws(() => lookoutRunFile(p, "weekly", "../x"), LookoutStoreError); + assert.match(newLookoutRunId(new Date("2026-11-11T17:45:00.123Z")), /^20261111T174500Z-[0-9a-f]{4}$/); + } finally { + await rm(p.transcriptsDir, { recursive: true, force: true }); + } +}); + +test("a verdict is set atomically, keeps the note it had, and two at once both land", async () => { + const p = await corpus(); + try { + const k1 = ideaKey([M("example-news", "v1", 10), M("example-news", "v2", 20)]); + const k2 = ideaKey([M("example-news", "v3", 10), M("example-news", "v4", 20)]); + const now = new Date("2026-11-11T12:00:00Z"); + await setLookoutVerdict(p, "weekly", { key: k1, verdict: "maybe", note: " check the date ", now }); + const made = await setLookoutVerdict(p, "weekly", { key: k1, verdict: "make", project: "shorts-2026-11/x", now }); + assert.deepEqual(made, { verdict: "make", at: now.toISOString(), note: "check the date", project: "shorts-2026-11/x" }); + await Promise.all([ + setLookoutVerdict(p, "weekly", { key: k2, verdict: "no", now }), + setLookoutVerdict(p, "weekly", { key: k1, verdict: "make", note: "", now }), + ]); + const v = await readLookoutVerdicts(p, "weekly"); + assert.equal(v.ideas[k2]?.verdict, "no"); + assert.equal(v.ideas[k1]?.note, undefined, "an empty note clears it"); + assert.equal(v.ideas[k1]?.project, "shorts-2026-11/x"); + // No temp file left beside it. + assert.deepEqual(await readdir(path.dirname(lookoutVerdictsFile(p, "weekly"))), ["verdicts.json"]); + await assert.rejects(setLookoutVerdict(p, "weekly", { key: "nope", verdict: "make" }), LookoutStoreError); + await assert.rejects( + setLookoutVerdict(p, "weekly", { key: k1, verdict: "yes" as never }), + LookoutStoreError, + ); + } finally { + await rm(p.transcriptsDir, { recursive: true, force: true }); + } +}); + +test("a hand-damaged verdicts file reads as what is valid in it", async () => { + const k = ideaKey([M("a", "b", 0)]); + assert.deepEqual( + sanitizeLookoutVerdicts({ ideas: { [k]: { verdict: "make", at: "x" }, bad: { verdict: "make", at: "x" }, [k.replace(/^./, "f")]: { verdict: "meh", at: "x" } } }), + { version: 1, ideas: { [k]: { verdict: "make", at: "x" } } }, + ); + const p = await corpus(); + try { + await mkdir(path.dirname(lookoutVerdictsFile(p, "weekly")), { recursive: true }); + await writeFile(lookoutVerdictsFile(p, "weekly"), "{ not json"); + assert.deepEqual(await readLookoutVerdicts(p, "weekly"), { version: 1, ideas: {} }); + } finally { + await rm(p.transcriptsDir, { recursive: true, force: true }); + } +}); + +function idea(key: string): LookoutIdea { + return { + id: key.slice(0, 6), + key, + workingTitle: "t", + angle: "a", + whyNow: "w", + kind: "reversal", + estimatedLengthSec: 60, + confidence: "high", + confidenceWhy: "c", + moments: [], + caveats: [], + sensitive: false, + }; +} + +function run(runId: string, ideas: LookoutIdea[], calls = 0, seconds = 0): LookoutRun { + return { + version: 1, + lookoutId: "weekly", + runId, + startedAt: "2026-11-11T12:00:00.000Z", + endedAt: "2026-11-11T12:10:00.000Z", + status: "done", + window: { from: "2026-11-05", to: "2026-11-11", days: 7, timeZone: "UTC" }, + model: "local-model", + calls, + seconds, + selection: null, + ideas, + }; +} + +test("runs: listed newest first, the latest summarised, unruled ideas counted, seconds per call measured", async () => { + const p = await corpus(); + try { + assert.deepEqual(await lookoutReadout(p, "weekly"), { + lastRun: null, + runs: 0, + unruled: 0, + verdicts: { make: 0, maybe: 0, no: 0 }, + }); + assert.equal(await measuredSecondsPerCall(p, "weekly"), null); + const k1 = ideaKey([M("a", "b", 0), M("a", "c", 0)]); + const k2 = ideaKey([M("a", "d", 0), M("a", "e", 0)]); + await writeLookoutRun(p, run("20261110T120000Z-aaaa", [idea(k1)], 100, 400)); + await writeLookoutRun(p, run("20261111T120000Z-bbbb", [idea(k1), idea(k2)], 50, 100)); + await setLookoutVerdict(p, "weekly", { key: k1, verdict: "no" }); + assert.deepEqual(await listLookoutRunIds(p, "weekly"), ["20261111T120000Z-bbbb", "20261110T120000Z-aaaa"]); + const r = await lookoutReadout(p, "weekly"); + assert.equal(r.runs, 2); + assert.equal(r.lastRun?.runId, "20261111T120000Z-bbbb"); + assert.equal(r.lastRun?.ideas, 2); + assert.equal(r.unruled, 1, "the story ruled in an earlier run keeps its verdict"); + assert.deepEqual(r.verdicts, { make: 0, maybe: 0, no: 1 }); + assert.deepEqual(await measuredSecondsPerCall(p, "weekly"), { secondsPerCall: 500 / 150, runs: 2, calls: 150 }); + assert.equal(await readLookoutRun(p, "weekly", "20261109T120000Z-cccc"), null); + const text = await readFile(lookoutRunFile(p, "weekly", "20261111T120000Z-bbbb"), "utf8"); + assert.equal(JSON.parse(text).ideas.length, 2); + } finally { + await rm(p.transcriptsDir, { recursive: true, force: true }); + } +}); diff --git a/common/lib/lookoutStore.ts b/common/lib/lookoutStore.ts @@ -0,0 +1,362 @@ +// THE LOOKOUT STORE — a lookout's runs, ideas and verdicts on disk, and the one +// writer of each (lane/lookout). SERVER-ONLY (node:fs). +// +// transcripts/.lookouts/<lookoutId>/runs/<runId>.json one run: window, selection, calls, ideas +// transcripts/.lookouts/<lookoutId>/runs/<runId>.trace.jsonl its trace (slice 2) +// transcripts/.lookouts/<lookoutId>/verdicts.json the operator's Make / Maybe / No per idea +// +// A DOT PATH, like the corpus root's other runtime state (.x-runs, .jobs, +// .speakers-run.json): it is never a channel, a site or a report, so nothing +// that composes, indexes, exports or serves the corpus walks into it, and the +// corpus repo's own .gitignore question does not arise for a name nobody +// enumerates. Nothing here is published (the lane's rule): a run's ideas carry +// quotes from transcripts and the operator's notes on them. +// +// ONE WRITER PER FILE, atomic (jsonFile-server), in the manner of +// curatedTagsStore: a verdict is a read-modify-write of the whole +// verdicts.json under the file's lock, so two marks never interleave. A run +// file is written whole by the job that made it and never edited after. +// +// A VERDICT IS KEYED BY THE IDEA'S STORY, not by the run: `ideaKey` hashes the +// idea's moments (channel, video, start rounded to 5 s), so the same story +// found by a later run keeps the verdict it was given. + +import { createHash, randomBytes } from "node:crypto"; +import { readdir } from "node:fs/promises"; +import path from "node:path"; +import type { Paths } from "./paths"; +import { LOOKOUT_ID_RE } from "./lookoutSettings"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server"; + +export const LOOKOUTS_DIRNAME = ".lookouts"; +export const LOOKOUT_VERDICTS_FILENAME = "verdicts.json"; +export const LOOKOUT_STORE_VERSION = 1; + +// `20261111T174500Z-1a2b`: sorts by time, safe as a file name. +export const LOOKOUT_RUN_ID_RE = /^\d{8}T\d{6}Z-[0-9a-f]{4}$/; + +export class LookoutStoreError extends Error {} + +function assertLookoutId(id: string): void { + if (!LOOKOUT_ID_RE.test(id)) throw new LookoutStoreError(`"${id}" is not a lookout id (a lowercase slug)`); +} + +function assertRunId(runId: string): void { + if (!LOOKOUT_RUN_ID_RE.test(runId)) throw new LookoutStoreError(`"${runId}" is not a lookout run id`); +} + +export function lookoutsRoot(paths: Pick<Paths, "transcriptsDir">): string { + return path.join(paths.transcriptsDir, LOOKOUTS_DIRNAME); +} + +export function lookoutDir(paths: Pick<Paths, "transcriptsDir">, id: string): string { + assertLookoutId(id); + return path.join(lookoutsRoot(paths), id); +} + +export function lookoutRunFile(paths: Pick<Paths, "transcriptsDir">, id: string, runId: string): string { + assertRunId(runId); + return path.join(lookoutDir(paths, id), "runs", `${runId}.json`); +} + +export function lookoutTraceFile(paths: Pick<Paths, "transcriptsDir">, id: string, runId: string): string { + assertRunId(runId); + return path.join(lookoutDir(paths, id), "runs", `${runId}.trace.jsonl`); +} + +export function lookoutVerdictsFile(paths: Pick<Paths, "transcriptsDir">, id: string): string { + return path.join(lookoutDir(paths, id), LOOKOUT_VERDICTS_FILENAME); +} + +export function newLookoutRunId(now: Date = new Date()): string { + const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); + return `${stamp}-${randomBytes(2).toString("hex")}`; +} + +// ─── Ideas ─── + +/** One dated, verbatim moment of an idea, located by code in its video's cues. */ +export type LookoutMoment = { + channel: string; + /** The video's directory under `channels/<channel>/data/`. */ + video: string; + /** Its air date, YYYY-MM-DD in the lookout's zone. */ + date: string; + start: number; + end: number; + quote: string; + link?: string; + title?: string; +}; + +export type LookoutVerdictValue = "make" | "maybe" | "no"; + +/** An idea as a run stores it: the pilot's shape plus `key` and `sensitive`. */ +export type LookoutIdea = { + id: string; + key: string; + workingTitle: string; + angle: string; + whyNow: string; + kind: string; + estimatedLengthSec: number; + confidence: "high" | "medium" | "low"; + confidenceWhy: string; + moments: LookoutMoment[]; + caveats: string[]; + sensitive: boolean; +}; + +/** Seconds rounded to the nearest 5, the grain a story's key is cut at. */ +const grain = (s: number) => Math.round(s / 5) * 5; + +/** + * The idea's story key: a hash of its sorted moments (channel, video, start + * rounded to 5 s). The same moments in any order give the same key; a moment + * nudged by a second or two gives the same key; a moment added or removed + * gives another. + */ +export function ideaKey(moments: readonly Pick<LookoutMoment, "channel" | "video" | "start">[]): string { + const parts = [...new Set(moments.map((m) => `${m.channel}/${m.video}@${grain(m.start)}`))].sort(); + return createHash("sha1").update(parts.join("\n")).digest("hex").slice(0, 16); +} + +// ─── Runs ─── + +export type LookoutRunStatus = "done" | "partial" | "failed"; + +/** + * A run as stored. Slice 1 defines the shape and reads it; the job that writes + * one (and fills `selection`, `calls`, `ideas`) is slice 2's. + */ +export type LookoutRun = { + version: number; + lookoutId: string; + runId: string; + startedAt: string; + endedAt: string | null; + status: LookoutRunStatus; + window: { from: string; to: string; days: number; timeZone: string }; + model: string | null; + /** Model calls made. */ + calls: number; + /** Wall seconds the model calls took, summed. */ + seconds: number; + /** The selection as the dry run lists it (controller/lookoutPlan.ts LookoutPlan), read and skipped and why. */ + selection: unknown; + ideas: LookoutIdea[]; + /** What was dropped and why (an unlocatable quote, an invented id, a one-moment idea), counted. */ + dropped?: Record<string, number>; + note?: string; +}; + +export type LookoutRunSummary = { + runId: string; + startedAt: string; + endedAt: string | null; + status: LookoutRunStatus; + window: LookoutRun["window"]; + model: string | null; + calls: number; + seconds: number; + ideas: number; +}; + +function isObject(v: unknown): v is Record<string, unknown> { + return typeof v === "object" && v !== null && !Array.isArray(v); +} + +/** Write a run whole (its job is the only writer, once). */ +export async function writeLookoutRun(paths: Pick<Paths, "transcriptsDir">, run: LookoutRun): Promise<string> { + const file = lookoutRunFile(paths, run.lookoutId, run.runId); + await writeJsonAtomic(file, run, { mkdir: true }); + return file; +} + +/** One run, or null when it is absent or not a run. */ +export async function readLookoutRun( + paths: Pick<Paths, "transcriptsDir">, + id: string, + runId: string, +): Promise<LookoutRun | null> { + const read = await readJsonFile(lookoutRunFile(paths, id, runId)); + if (!read.ok || !isObject(read.value)) return null; + const v = read.value; + if (v.lookoutId !== id || v.runId !== runId || !Array.isArray(v.ideas)) return null; + return v as unknown as LookoutRun; +} + +/** The lookout's run ids, newest first. */ +export async function listLookoutRunIds(paths: Pick<Paths, "transcriptsDir">, id: string): Promise<string[]> { + let names: string[]; + try { + names = await readdir(path.join(lookoutDir(paths, id), "runs")); + } catch { + return []; + } + return names + .filter((n) => n.endsWith(".json")) + .map((n) => n.slice(0, -".json".length)) + .filter((n) => LOOKOUT_RUN_ID_RE.test(n)) + .sort() + .reverse(); +} + +export function summarizeLookoutRun(run: LookoutRun): LookoutRunSummary { + return { + runId: run.runId, + startedAt: run.startedAt, + endedAt: run.endedAt, + status: run.status, + window: run.window, + model: run.model, + calls: run.calls, + seconds: run.seconds, + ideas: run.ideas.length, + }; +} + +/** + * Seconds per model call measured over the lookout's latest runs that made + * calls (at most `recent`), or null when none has. What a dry run's estimate + * is priced from. + */ +export async function measuredSecondsPerCall( + paths: Pick<Paths, "transcriptsDir">, + id: string, + recent = 3, +): Promise<{ secondsPerCall: number; runs: number; calls: number } | null> { + let calls = 0; + let seconds = 0; + let runs = 0; + for (const runId of await listLookoutRunIds(paths, id)) { + if (runs >= recent) break; + const run = await readLookoutRun(paths, id, runId); + if (!run || !(run.calls > 0) || !(run.seconds > 0)) continue; + calls += run.calls; + seconds += run.seconds; + runs++; + } + return calls > 0 ? { secondsPerCall: seconds / calls, runs, calls } : null; +} + +// ─── Verdicts ─── + +export type LookoutVerdict = { + verdict: LookoutVerdictValue; + /** ISO 8601, when it was given. */ + at: string; + note?: string; + /** The Shorts project "Make" opened, when it did. */ + project?: string; +}; + +export type LookoutVerdicts = { + version: number; + /** Keyed by the idea's story key (`ideaKey`). */ + ideas: Record<string, LookoutVerdict>; +}; + +const IDEA_KEY_RE = /^[0-9a-f]{16}$/; +const VERDICTS: readonly LookoutVerdictValue[] = ["make", "maybe", "no"]; + +export function isLookoutVerdict(v: unknown): v is LookoutVerdictValue { + return typeof v === "string" && (VERDICTS as readonly string[]).includes(v); +} + +export function isIdeaKey(v: unknown): v is string { + return typeof v === "string" && IDEA_KEY_RE.test(v); +} + +export function emptyLookoutVerdicts(): LookoutVerdicts { + return { version: LOOKOUT_STORE_VERSION, ideas: {} }; +} + +/** A verdicts file coerced: an ill-typed entry is dropped, never thrown on. */ +export function sanitizeLookoutVerdicts(value: unknown): LookoutVerdicts { + const out = emptyLookoutVerdicts(); + const ideas = isObject(value) ? value.ideas : null; + if (!isObject(ideas)) return out; + for (const [key, raw] of Object.entries(ideas)) { + if (!isIdeaKey(key) || !isObject(raw) || !isLookoutVerdict(raw.verdict) || typeof raw.at !== "string") continue; + const v: LookoutVerdict = { verdict: raw.verdict, at: raw.at }; + if (typeof raw.note === "string" && raw.note.trim()) v.note = raw.note.trim(); + if (typeof raw.project === "string" && raw.project.trim()) v.project = raw.project.trim(); + out.ideas[key] = v; + } + return out; +} + +export async function readLookoutVerdicts( + paths: Pick<Paths, "transcriptsDir">, + id: string, +): Promise<LookoutVerdicts> { + const read = await readJsonFile(lookoutVerdictsFile(paths, id)); + return read.ok ? sanitizeLookoutVerdicts(read.value) : emptyLookoutVerdicts(); +} + +export type SetVerdictInput = { + key: string; + verdict: LookoutVerdictValue; + note?: string; + project?: string; + now?: Date; +}; + +/** + * THE writer of verdicts.json: one idea's verdict set (replacing the one it + * had), under the file's lock, written atomically. A note or project not sent + * is kept from the verdict before, so "Make" recording its project does not + * erase the operator's note. + */ +export async function setLookoutVerdict( + paths: Pick<Paths, "transcriptsDir">, + id: string, + input: SetVerdictInput, +): Promise<LookoutVerdict> { + if (!isIdeaKey(input.key)) throw new LookoutStoreError(`"${input.key}" is not an idea key`); + if (!isLookoutVerdict(input.verdict)) throw new LookoutStoreError(`verdict is one of ${VERDICTS.join(", ")}`); + const file = lookoutVerdictsFile(paths, id); + return withJsonFileLock(file, async () => { + const current = await readLookoutVerdicts(paths, id); + const before = current.ideas[input.key]; + const v: LookoutVerdict = { verdict: input.verdict, at: (input.now ?? new Date()).toISOString() }; + const note = input.note !== undefined ? input.note.trim() : before?.note; + if (note) v.note = note; + const project = input.project !== undefined ? input.project.trim() : before?.project; + if (project) v.project = project; + current.ideas[input.key] = v; + await writeJsonAtomic(file, current, { mkdir: true }); + return v; + }); +} + +// ─── The readout (`pnpm ops get lookouts`) ─── + +export type LookoutReadout = { + lastRun: LookoutRunSummary | null; + runs: number; + /** Ideas in the latest run with no verdict yet. */ + unruled: number; + verdicts: Record<LookoutVerdictValue, number>; +}; + +/** What the store holds for one lookout: its runs, the latest one, and how many of its ideas wait for a verdict. */ +export async function lookoutReadout(paths: Pick<Paths, "transcriptsDir">, id: string): Promise<LookoutReadout> { + const runIds = await listLookoutRunIds(paths, id); + const verdicts = await readLookoutVerdicts(paths, id); + const counts: Record<LookoutVerdictValue, number> = { make: 0, maybe: 0, no: 0 }; + for (const v of Object.values(verdicts.ideas)) counts[v.verdict]++; + let latest: LookoutRun | null = null; + for (const runId of runIds) { + latest = await readLookoutRun(paths, id, runId); + if (latest) break; + } + const unruled = latest ? latest.ideas.filter((i) => !verdicts.ideas[i.key]).length : 0; + return { + lastRun: latest ? summarizeLookoutRun(latest) : null, + runs: runIds.length, + unruled, + verdicts: counts, + }; +}