Archilyzer · Source

archilyzer

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

commit 5b9035bdf2854ce02cb33f57be4d00e70a5aa7b5
parent bbba2860323e75c8c6bfa6f03f069fe25c993712
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 11 Nov 2026 18:48:20 -0500

Merge lane/lookout: lookouts, slice 1 -- settings.lookouts, a read-only plan of what a lookout would read (air dates in the lookout's zone, duplicate uploads and cut-downs folded), the store under transcripts/.lookouts, and ops get lookouts / lookout-run as a dry run

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

Diffstat:
MCOMMANDS.md | 7+++++++
MSETTINGS.md | 39+++++++++++++++++++++++++++++++++++++++
Acommon/controller/lookoutPlan.test.ts | 375+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/lookoutPlan.ts | 522+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/duplicates.ts | 2+-
Acommon/lib/lookout.test.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/lookout.ts | 407+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/lookoutNoChannelNames.test.ts | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/lookoutSettings.test.ts | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/lookoutSettings.ts | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/lookoutStore.test.ts | 167+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/lookoutStore.ts | 371+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/settingsDocs.ts | 10++++++++++
Mcommon/lib/settingsSchema.test.ts | 6+++++-
Mcommon/lib/settingsSchema.ts | 5+++++
Meditor/CHANGELOG.md | 1+
Aeditor/app/api/ops/_lookouts.test.ts | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/lookout-run/route.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/lookouts/route.ts | 29+++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 32++++++++++++++++++++++++++++++++
Msettings.json.example | 5+++++
21 files changed, 2623 insertions(+), 2 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -225,6 +225,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `find-clips` | find-clips runs the clip finder's chain for ONE video as one job: {"slug", "id", "target"? (the cut's seconds), "segment"? (one umtool found, "s2"), "project"? (the umtool project a run makes), "whilePaused"?, "dryRun"?}. Persist the source video, the corpus transcript, word timings (data/&lt;id&gt;/words.json), the chat replay (YouTube), diarization — each step skipped when its output exists, named in the log — then umtool's clip finder (POST UMTOOL\_URL/api/report/clips {mode: "new"}), followed to the end. "whilePaused": true runs this one video past the holds: the two transcriptions during a pause-all on a worker the pause alone switched off, and its diarization in the job when the backfill lane is held. "dryRun": true answers each step's plan and starts nothing. With --wait the result — {project, url, created, segments: \[{id, from, to, why}\], steps} — is printed on stdout. | `pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","dryRun":true}'`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","target":600}' --wait`<br>`pnpm ops find-clips --json '{"slug":"demo-yt","id":"<videoId>","segment":"s2","whilePaused":true}' --wait` | | `fetch-chat-backlog` | fetch-chat-backlog fetches a channel's stream chats after its downloads: {"slug", "dryRun"?, "limit"?, "queueKey"?} — every held video whose metadata says it was a stream (live\_status was\_live / post\_live) and whose chat is not here, newest first, one at a time through fetch-chat's pass with the batch downloads' gap between two, as one fetch-chat-backlog job on the platform's download queue; a raw replay already here is only normalized. It stops on a rate limit, a held platform, three failures in a row, a drain or "limit" chats; a re-run skips the chats here and the streams known to have none (chat-backlog.json), and a restart resumes it. The download lane queues it by itself (25 a run) for a channel whose "chat" is "later" once it has nothing left to download. "dryRun": true counts from the disk and starts nothing: chats, normalizeOnly, have, settled, notStreams, ids (the first 50). | `pnpm ops fetch-chat-backlog --json '{"slug":"demo-yt","dryRun":true}'` | | `x-run` | x-run fetches several X posts channels IN SEQUENCE as ONE job on X's queue: {"channels": \[slug, ...\]} in that order, each a fetch-posts sync new of at most 200 posts ("limit": N, 1-200, caps it lower), X's queue gap (pacing.jobGapSeconds.twitter) between two channels. Before EACH channel the jar is checked again: once it is past social.x.maxCookieAgeMinutes (or the X alert is up) the run stops and the rest are DEFERRED until the next refresh. It never refreshes the jar: Refresh cookies on /settings, then {"resume": "&lt;run id&gt;"} runs the deferred channels (the console's Resume; a Retry of the job is the same). One run at a time; refused before a job on a stale jar (a new run's channels are kept, deferred). An interrupted run is not resumed on boot: it ends deferred. Answers {jobId, run}; get x-run follows it. The log ends with @@x-run {id, status, stopped?, counts, summary}. | `pnpm ops x-run --json '{"channels":["example-x","other-x"]}'`<br>`pnpm ops x-run --json '{"resume":"xr-01J…"}'` | +| `lookout-run` | lookout-run lists what a saved lookout (settings.lookouts) would read: {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?: "YYYY-MM-DD"}. Every video of its channels whose AIR date (release\_timestamp, else timestamp, in the lookout's timeZone — not the UTC upload\_date) falls in the window; a duplicate upload of one recording, and a stream's cut-down, folded into it (each named, with why and its score); the longest maxVideos recordings read and the rest listed as skipped for the cap; under minSeconds and no transcript yet listed too. A local media library channel or a slug this archive does not hold is named in "refused". Answers {plan: {window, counts, read, skipped, refused, estimate}}: readCalls is one per transcript chunk, priced once a run has been measured. Synchronous, reads text only, writes nothing; without "dryRun": true it is refused (the model run is not in this build). | `pnpm ops lookout-run --json '{"id":"example-week","dryRun":true}'`<br>`pnpm ops lookout-run --json '{"id":"example-week","dryRun":true,"days":3,"until":"2026-11-10"}'` | ### Usage, flags and environment @@ -250,6 +251,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait] pnpm ops get x-run [<run id>] pnpm ops get cleanup <slug> pnpm ops get speakers + pnpm ops get lookouts [<id>] pnpm ops get remote-listing <slug> [--wait-timeout <seconds>] pnpm ops get transcript <videoId> [--slug <slug>] pnpm ops get coverage <slug> @@ -341,6 +343,11 @@ get speakers is the speakers readout the lane deck and /cleanup print noFingerprintPossible (diarized, audio already gone), per channel with corpus-disk channels first; and the lane: armed, held, the operations it dispatches, its order, cleanAfterCapture and requireVoiceprints. +get lookouts [<id>] is the saved lookouts (settings.lookouts, SETTINGS.md): + each one's channels, days, cap and zone, its runs (transcripts/.lookouts/ + <id>/), the latest run (when, window, model, calls, seconds, ideas), how + many of that run's ideas have no verdict yet, and the verdicts given. + Reads settings and the store only, never a channel's videos. get cleanup <slug> is one channel's /cleanup row: what each sweep would reclaim (they overlap — never add them), what holds the rest, and the failed-transcriptions count. measured: false means unknown, not zero. diff --git a/SETTINGS.md b/SETTINGS.md @@ -58,6 +58,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`clips`](#clips) | object — see below | | [`jobs`](#jobs) | object — see below | | [`serviceCookies`](#servicecookies) | object — see below | +| [`lookouts`](#lookouts) | object — see below | ## `adminTitle` @@ -1375,3 +1376,41 @@ Default: ] } ``` + +## `lookouts` + +Saved lookouts (lane/lookout): each names channels, a number of days back and an optional prompt, and a run reads those channels' recent transcripts — by air date, duplicate uploads and stream cut-downs folded in — and answers with video ideas. OFF and empty by default; nothing a lookout writes is published. `pnpm ops get lookouts` is the readout, `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists what one would read. See LookoutsSettings and common/lib/lookoutSettings.ts. + +#### `lookouts` + +| Key | Default | Description | +|---|---|---| +| `enabled` | `false` | The lookouts' master switch. Off: no lookout runs, by hand or after a sync; a dry run (`pnpm ops lookout-run --json '{"id":"…","dryRun":true}'`) still lists what a lookout would read, and writes nothing. Default false. | +| `afterSync` | `false` | Run each lookout after a sync of one of its channels finishes — at most once a day per lookout, never while render mode holds the machine. Not acted on before the after-sync slice lands. Default false. | +| `items` | `[]` | The saved lookouts, one entry each (`lookouts.items[]` below). The list is replaced whole by a settings patch. Default [] — no lookout. | + +#### `lookouts.items[]` + +Per entry — each entry spells its own values. + +| Key | Description | +|---|---| +| `id` | The lookout's id: a lowercase slug (`a-z`, `0-9`, `-`, at most 64), the name its runs and verdicts are kept under (`transcripts/.lookouts/<id>/`). Omitted: made from `label`. An entry with neither is dropped, and so is a second entry with an id already used. | +| `label` | What the lookout is called on its page. Omitted: the id. | +| `channels` | The channel slugs it reads (`transcripts/channels/<slug>/`). A local media library channel, or a slug this archive does not hold (a channel only on a remote site), is refused by name when the lookout runs. | +| `days` | How many days back it reads, today included, by AIR date in `timeZone` (`release_timestamp`, else `timestamp`, from the video's metadata — not yt-dlp's UTC `upload_date`). Clamped to [1, 60]; default 7. | +| `prompt` | What the operator wants from the ideas, added to the grouping step only — the per-video reading is the same for every lookout. At most 4000 characters; default "". | +| `maxVideos` | The most recordings one run reads, after duplicate uploads and stream cut-downs are folded in: the longest first, and every one left out listed as skipped for the cap. Clamped to [1, 500]; default 40. | +| `minSeconds` | Videos shorter than this are not read (and are counted as skipped). Clamped to [0, 3600]; default 90. | +| `timeZone` | The IANA time zone its days are counted in ("America/New_York"). "" = the machine's. An unknown zone is dropped to "". Default "". | +| `siteOrigin` | The public site its links are built on ("https://example.pages.dev"), when the channels are published; "" = each video's source URL with its start second. Default "". | + +Default: + +```json +{ + "enabled": false, + "afterSync": false, + "items": [] +} +``` diff --git a/common/controller/lookoutPlan.test.ts b/common/controller/lookoutPlan.test.ts @@ -0,0 +1,375 @@ +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", + webpage_url: `https://example.invalid/watch/${v.dir}`, + 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"], + ], + ); + const bare = plan.skipped.find((k) => k.video === "NoCues00001")!; + assert.equal(bare.title, "Not Transcribed", "named from its metadata"); + assert.equal(bare.url, "https://example.invalid/watch/NoCues00001"); + 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, nor a storyboard fragment's duration. + const yt = + '{"id": "a", "formats": [{"format_id": "sb0", "fragments": [{"url": "u", "duration": 496.98}, {"url": "u", "duration": 250.02}]}], ' + + '"comments": [{"timestamp": 1600000000}], "duration": 747, "live_status": "not_live", "webpage_url": "https://example.invalid/a", ' + + '"upload_date": "20261106", "timestamp": 1793993883, "is_live": false}'; + assert.deepEqual(metaDatesOf(yt), { + releaseTimestamp: null, + timestamp: 1793993883, + uploadDate: "20261106", + liveStatus: "not_live", + duration: 747, + title: null, + webpageUrl: "https://example.invalid/a", + }); + // Rumble's order: timestamp early, release_timestamp later, upload_date last. + const rumble = + '{"id": "v", "title": "She said \\"no\\" \\u2014 caf\u00c3\u00a9", "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, + // Escapes decoded, and the file's UTF-8 bytes (a string argument stands for them, one char a byte). + title: 'She said "no" — café', + webpageUrl: null, + }); +}); diff --git a/common/controller/lookoutPlan.ts b/common/controller/lookoutPlan.ts @@ -0,0 +1,522 @@ +// 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 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 `"<key>":` 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 `"<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 + * (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<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, + // 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<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 ? 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<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,164 @@ +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 % 12 === 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); + // The same title and the same runtime, unrelated text: two episodes, both read. + const episodes = foldRecordings([ + vid("a/mon", { words: text(5, 2000), title: "Daily Show", duration: 900 }), + vid("a/tue", { words: text(6, 2000), title: "Daily Show", duration: 905 }), + ]); + assert.equal(episodes.length, 2); + // ...unless one has no text to compare: then the title and runtime decide. + const silent = foldRecordings([ + vid("a/mon", { words: text(5, 2000), title: "Daily Show", duration: 900 }), + vid("b/copy", { words: [], title: "Daily Show", duration: 905 }), + ]); + assert.equal(silent.length, 1); + // 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,407 @@ +// 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 title match alone is not enough when both have text: two episodes of +// a show with one title and one length share none, so it also needs a +// Jaccard of 0.1. +// - 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 with the same title: their transcripts still share at least this much (Jaccard), when both have text. */ +export const TWIN_TITLE_TEXT_FLOOR = 0.1; +/** 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>); + // A title is not a recording: a daily show keeps one title and much the + // same runtime. With both transcripts in hand a title match still needs + // some shared text; with one empty there is only the title to go on. + const titleTwin = + titleMatch && (a.shingles.size === 0 || b.shingles.size === 0 || score >= TWIN_TITLE_TEXT_FLOOR); + if (!titleTwin && 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/lookoutSettings.test.ts b/common/lib/lookoutSettings.test.ts @@ -0,0 +1,78 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + DEFAULT_LOOKOUTS_SETTINGS, + lookoutById, + lookoutIdFrom, + sanitizeLookoutItem, + sanitizeLookouts, +} from "./lookoutSettings"; +import { defaults, siteSettingsSchema } from "./settingsSchema"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/lookoutSettings.test.ts + +test("off and empty by default, in the schema too", () => { + assert.deepEqual(DEFAULT_LOOKOUTS_SETTINGS, { enabled: false, afterSync: false, items: [] }); + assert.deepEqual(sanitizeLookouts(undefined), DEFAULT_LOOKOUTS_SETTINGS); + assert.deepEqual(defaults().lookouts, DEFAULT_LOOKOUTS_SETTINGS); + assert.deepEqual(siteSettingsSchema.parse({ lookouts: "nonsense" }).lookouts, DEFAULT_LOOKOUTS_SETTINGS); +}); + +test("an item gets every default it leaves out", () => { + assert.deepEqual(sanitizeLookoutItem({ id: "weekly", channels: ["example-news", "example-live"] }), { + id: "weekly", + label: "weekly", + channels: ["example-news", "example-live"], + days: 7, + prompt: "", + maxVideos: 40, + minSeconds: 90, + timeZone: "", + siteOrigin: "", + }); +}); + +test("an item is coerced, never thrown on", () => { + const item = sanitizeLookoutItem({ + label: " Example Week! ", + channels: ["example-news", "example-news", "", 7, "../escape", "ok.slug_1"], + days: 999, + maxVideos: "12", + minSeconds: -5, + timeZone: "Mars/Olympus", + siteOrigin: "https://example.pages.dev/some/path?q=1", + prompt: "x".repeat(5000), + }); + assert.ok(item); + assert.equal(item.id, "example-week"); + assert.equal(item.label, "Example Week!"); + assert.deepEqual(item.channels, ["example-news", "ok.slug_1"]); + assert.equal(item.days, 60); + assert.equal(item.maxVideos, 12); + assert.equal(item.minSeconds, 0); + assert.equal(item.timeZone, "", "an unknown zone falls back to the machine's"); + assert.equal(item.siteOrigin, "https://example.pages.dev"); + assert.equal(item.prompt.length, 4000); + assert.equal(sanitizeLookoutItem({ timeZone: "America/Chicago", id: "a" })?.timeZone, "America/Chicago"); + assert.equal(sanitizeLookoutItem({ siteOrigin: "ftp://x.example", id: "a" })?.siteOrigin, ""); +}); + +test("an item with no usable id is dropped, and so is a second with the same id", () => { + const s = sanitizeLookouts({ + enabled: true, + afterSync: "yes", + items: [{ channels: ["a"] }, { id: "one", channels: ["a"] }, { id: "one", channels: ["b"] }, "junk", { label: "Two" }], + }); + assert.equal(s.enabled, true); + assert.equal(s.afterSync, false, "only true is true"); + assert.deepEqual(s.items.map((i) => [i.id, i.channels]), [["one", ["a"]], ["two", []]]); + assert.equal(lookoutById(s, "two")?.label, "Two"); + assert.equal(lookoutById(s, "three"), null); +}); + +test("lookoutIdFrom makes a slug", () => { + assert.equal(lookoutIdFrom("Café Weekly — News"), "cafe-weekly-news"); + assert.equal(lookoutIdFrom("!!!"), ""); + assert.equal(lookoutIdFrom("a".repeat(80)).length, 64); +}); diff --git a/common/lib/lookoutSettings.ts b/common/lib/lookoutSettings.ts @@ -0,0 +1,182 @@ +// settings.lookouts — saved lookouts (lane/lookout). A lookout is a saved set of +// channels, a number of days back and an optional prompt; a run reads those +// channels' recent transcripts and answers with video ideas. Pure: the types, +// the defaults, the sanitizer settingsSchema.ts runs the block through, and the +// per-field docs SETTINGS.md renders. +// +// OFF AND EMPTY BY DEFAULT, and no channel is named here or anywhere in code: a +// lookout is configured on the machine that runs it (`pnpm ops settings`), so +// adding one is a settings patch, never a code change. +// +// Slice 1 reads this for the selection only (controller/lookoutPlan.ts, the +// `lookout-run` dry run); the model run, `afterSync` and the umtool page come in +// later slices and read the same fields. + +import type { FieldDocs } from "./fieldDocs"; + +export type LookoutItem = { + id: string; + label: string; + channels: string[]; + days: number; + prompt: string; + maxVideos: number; + minSeconds: number; + timeZone: string; + siteOrigin: string; +}; + +export type LookoutsSettings = { + enabled: boolean; + afterSync: boolean; + items: LookoutItem[]; +}; + +export const DEFAULT_LOOKOUTS_SETTINGS: LookoutsSettings = { + enabled: false, + afterSync: false, + items: [], +}; + +export const LOOKOUT_DEFAULT_DAYS = 7; +export const LOOKOUT_MAX_DAYS = 60; +export const LOOKOUT_DEFAULT_MAX_VIDEOS = 40; +export const LOOKOUT_MAX_MAX_VIDEOS = 500; +export const LOOKOUT_DEFAULT_MIN_SECONDS = 90; +export const LOOKOUT_MAX_MIN_SECONDS = 3600; +export const LOOKOUT_MAX_PROMPT_CHARS = 4000; + +// A lookout id is a path segment (`transcripts/.lookouts/<id>/`), so it is a +// lowercase slug, nothing else. +export const LOOKOUT_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; +// A channel slug as the channels tree names it (the citations' segment rule). +const CHANNEL_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; + +export const LOOKOUTS_SETTINGS_FIELD_DOCS: FieldDocs<LookoutsSettings> = { + enabled: + "The lookouts' master switch. Off: no lookout runs, by hand or after a sync; a dry run " + + "(`pnpm ops lookout-run --json '{\"id\":\"…\",\"dryRun\":true}'`) still lists what a lookout would read, " + + "and writes nothing. Default false.", + afterSync: + "Run each lookout after a sync of one of its channels finishes — at most once a day per lookout, never while " + + "render mode holds the machine. Not acted on before the after-sync slice lands. Default false.", + items: + "The saved lookouts, one entry each (`lookouts.items[]` below). The list is replaced whole by a settings " + + "patch. Default [] — no lookout.", +}; + +export const LOOKOUT_ITEM_FIELD_DOCS: FieldDocs<LookoutItem> = { + id: + "The lookout's id: a lowercase slug (`a-z`, `0-9`, `-`, at most 64), the name its runs and verdicts are kept " + + "under (`transcripts/.lookouts/<id>/`). Omitted: made from `label`. An entry with neither is dropped, and so " + + "is a second entry with an id already used.", + label: "What the lookout is called on its page. Omitted: the id.", + channels: + "The channel slugs it reads (`transcripts/channels/<slug>/`). A local media library channel, or a slug this " + + "archive does not hold (a channel only on a remote site), is refused by name when the lookout runs.", + days: + "How many days back it reads, today included, by AIR date in `timeZone` (`release_timestamp`, else " + + "`timestamp`, from the video's metadata — not yt-dlp's UTC `upload_date`). Clamped to [1, 60]; default 7.", + prompt: + "What the operator wants from the ideas, added to the grouping step only — the per-video reading is the same " + + "for every lookout. At most 4000 characters; default \"\".", + maxVideos: + "The most recordings one run reads, after duplicate uploads and stream cut-downs are folded in: the longest " + + "first, and every one left out listed as skipped for the cap. Clamped to [1, 500]; default 40.", + minSeconds: + "Videos shorter than this are not read (and are counted as skipped). Clamped to [0, 3600]; default 90.", + timeZone: + "The IANA time zone its days are counted in (\"America/New_York\"). \"\" = the machine's. An unknown zone is " + + "dropped to \"\". Default \"\".", + siteOrigin: + "The public site its links are built on (\"https://example.pages.dev\"), when the channels are published; " + + "\"\" = each video's source URL with its start second. Default \"\".", +}; + +function clampInt(value: unknown, fallback: number, min: number, max: number): number { + const n = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN; + if (!Number.isFinite(n)) return fallback; + return Math.min(max, Math.max(min, Math.round(n))); +} + +/** Whether `tz` is an IANA zone this runtime knows. "" is not a zone (it means the machine's). */ +export function isKnownTimeZone(tz: string): boolean { + if (!tz) return false; + try { + new Intl.DateTimeFormat("en-US", { timeZone: tz }); + return true; + } catch { + return false; + } +} + +/** A lowercase slug made from free text: "My Lookout!" → "my-lookout". */ +export function lookoutIdFrom(text: string): string { + return text + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 64) + .replace(/-+$/, ""); +} + +function siteOriginOf(value: unknown): string { + if (typeof value !== "string" || !value.trim()) return ""; + try { + const u = new URL(value.trim()); + if (u.protocol !== "https:" && u.protocol !== "http:") return ""; + return u.origin; + } catch { + return ""; + } +} + +/** One entry, coerced; null when it has no usable id. */ +export function sanitizeLookoutItem(value: unknown): LookoutItem | null { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const r = value as Record<string, unknown>; + const rawId = typeof r.id === "string" ? r.id.trim() : ""; + const rawLabel = typeof r.label === "string" ? r.label.trim() : ""; + const id = LOOKOUT_ID_RE.test(rawId) ? rawId : lookoutIdFrom(rawId || rawLabel); + if (!LOOKOUT_ID_RE.test(id)) return null; + const channels: string[] = []; + if (Array.isArray(r.channels)) { + for (const c of r.channels) { + if (typeof c !== "string") continue; + const slug = c.trim(); + if (slug && slug !== ".." && CHANNEL_SLUG_RE.test(slug) && !channels.includes(slug)) channels.push(slug); + } + } + const tz = typeof r.timeZone === "string" ? r.timeZone.trim() : ""; + const prompt = typeof r.prompt === "string" ? r.prompt.trim().slice(0, LOOKOUT_MAX_PROMPT_CHARS) : ""; + return { + id, + label: rawLabel || id, + channels, + days: clampInt(r.days, LOOKOUT_DEFAULT_DAYS, 1, LOOKOUT_MAX_DAYS), + prompt, + maxVideos: clampInt(r.maxVideos, LOOKOUT_DEFAULT_MAX_VIDEOS, 1, LOOKOUT_MAX_MAX_VIDEOS), + minSeconds: clampInt(r.minSeconds, LOOKOUT_DEFAULT_MIN_SECONDS, 0, LOOKOUT_MAX_MIN_SECONDS), + timeZone: isKnownTimeZone(tz) ? tz : "", + siteOrigin: siteOriginOf(r.siteOrigin), + }; +} + +export function sanitizeLookouts(value: unknown): LookoutsSettings { + const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>; + const items: LookoutItem[] = []; + if (Array.isArray(r.items)) { + for (const raw of r.items) { + const item = sanitizeLookoutItem(raw); + if (item && !items.some((i) => i.id === item.id)) items.push(item); + } + } + return { enabled: r.enabled === true, afterSync: r.afterSync === true, items }; +} + +/** The saved lookout with this id, or null. */ +export function lookoutById(settings: LookoutsSettings, id: string): LookoutItem | null { + return settings.items.find((i) => i.id === id) ?? null; +} diff --git a/common/lib/lookoutStore.test.ts b/common/lib/lookoutStore.test.ts @@ -0,0 +1,167 @@ +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: {} }); + // ...and is never written over as if it were empty. + await assert.rejects(setLookoutVerdict(p, "weekly", { key: k, verdict: "make" }), /unparseable.*not written/); + assert.equal(await readFile(lookoutVerdictsFile(p, "weekly"), "utf8"), "{ not json"); + } 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,371 @@ +// 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. Refused when verdicts.json is there and is not + * readable JSON — it is never overwritten as if it were empty. + */ +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 () => { + // A file that is there and cannot be read is NOT an empty one: writing over + // it would drop every verdict it holds for the one being set. + const read = await readJsonFile(file); + if (!read.ok && read.reason !== "absent") { + throw new LookoutStoreError( + `${file} is ${read.reason} — the verdict was not written; mend the file or move it aside first`, + ); + } + const current = read.ok ? sanitizeLookoutVerdicts(read.value) : emptyLookoutVerdicts(); + 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, + }; +} diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -15,6 +15,8 @@ import { ARCHIVES_SETTINGS_FIELD_DOCS, CLIPS_SETTINGS_FIELD_DOCS, JOBS_SETTINGS_FIELD_DOCS, + LOOKOUTS_SETTINGS_FIELD_DOCS, + LOOKOUT_ITEM_FIELD_DOCS, SERVICE_COOKIES_SETTINGS_FIELD_DOCS, VOICE_CONVERT_SETTINGS_FIELD_DOCS, VOICE_ENHANCE_SETTINGS_FIELD_DOCS, @@ -358,6 +360,14 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, defaults: fromObject(d.serviceCookies), }, ], + lookouts: [ + { + path: "lookouts", + docs: LOOKOUTS_SETTINGS_FIELD_DOCS, + defaults: fromObject(d.lookouts), + }, + { path: "lookouts.items[]", docs: LOOKOUT_ITEM_FIELD_DOCS }, + ], }; } diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts @@ -36,6 +36,7 @@ import type { ArchivesSettings } from "./archives/settings"; import type { ClipsSettings } from "./clipSettings"; import type { JobsSettings } from "./jobsSettings"; import type { ServiceCookiesSettings } from "./serviceCookieSettings"; +import type { LookoutsSettings } from "./lookoutSettings"; import type { VoiceSettings } from "./voiceSettings"; import type { GenerationSettings } from "./generationSettings"; import type { @@ -132,13 +133,15 @@ type PreSchemaSiteSettings = { jobs: JobsSettings; // The cookie refresh alerts' proactive timer (2026-10-31). serviceCookies: ServiceCookiesSettings; + // Saved lookouts (lane/lookout). + lookouts: LookoutsSettings; }; // Bracketed so the conditional does not distribute (see commit 8c43231). type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false; const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true; -test("SiteSettings keeps its 46 fields, in file order", () => { +test("SiteSettings keeps its 47 fields, in file order", () => { assert.equal(shapeUnchanged, true); assert.deepEqual(Object.keys(siteSettingsSchema.shape), [ "adminTitle", @@ -187,6 +190,7 @@ test("SiteSettings keeps its 46 fields, in file order", () => { "clips", "jobs", "serviceCookies", + "lookouts", ]); // A parsed object carries every key, in that order — writeSettings writes // exactly this, so the order is the on-disk order. diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -84,6 +84,7 @@ import { sanitizeVoice, type VoiceSettings } from "./voiceSettings"; import { sanitizeArchives, type ArchivesSettings } from "./archives/settings"; import { sanitizeClips, type ClipsSettings } from "./clipSettings"; import { sanitizeJobs, type JobsSettings } from "./jobsSettings"; +import { sanitizeLookouts, type LookoutsSettings } from "./lookoutSettings"; import { sanitizeServiceCookies, type ServiceCookiesSettings } from "./serviceCookieSettings"; import { sanitizeGeneration, type GenerationSettings } from "./generationSettings"; export { @@ -111,6 +112,7 @@ export { export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings"; export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings"; export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings"; +export { LOOKOUTS_SETTINGS_FIELD_DOCS, LOOKOUT_ITEM_FIELD_DOCS, type LookoutsSettings, type LookoutItem } from "./lookoutSettings"; export { SERVICE_COOKIES_SETTINGS_FIELD_DOCS, type ServiceCookiesSettings } from "./serviceCookieSettings"; import { DEFAULT_COOKIE_MODE, @@ -2071,6 +2073,9 @@ export const siteSettingsSchema = z.object({ serviceCookies: settingsField((v): ServiceCookiesSettings => sanitizeServiceCookies(v)).describe( "The cookie refresh alerts' PROACTIVE timer (plans/cookie-refresh-alerts.md): how often the editor rechecks raised alerts, probes Rumble's clearance with no alert up, and re-reads X's cookie jar age, by itself — so the dashboard banner goes up before a sync or a download fails. See ServiceCookiesSettings and common/controller/serviceCookieTimer.ts.", ), + lookouts: settingsField((v): LookoutsSettings => sanitizeLookouts(v)).describe( + "Saved lookouts (lane/lookout): each names channels, a number of days back and an optional prompt, and a run reads those channels' recent transcripts — by air date, duplicate uploads and stream cut-downs folded in — and answers with video ideas. OFF and empty by default; nothing a lookout writes is published. `pnpm ops get lookouts` is the readout, `pnpm ops lookout-run --json '{\"id\":\"…\",\"dryRun\":true}'` lists what one would read. See LookoutsSettings and common/lib/lookoutSettings.ts.", + ), }); export type SiteSettings = z.infer<typeof siteSettingsSchema>; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **Lookouts: a saved set of channels and days, and a dry run that lists what it would read.** A lookout (lane/lookout) will read its channels' recent transcripts and answer with video ideas; this first part has no model. `settings.lookouts` holds the lookouts (off and empty by default; nothing in code names a channel), and `pnpm ops lookout-run --json '{"id":"…","dryRun":true}'` lists the week it would read: every video by its AIR date in the lookout's time zone (a stream that starts at 8:20 pm in New York is 3 Nov, not the 4 Nov of its UTC upload date), a recording uploaded twice read once with the other upload named beside it, a stream's cut-downs credited to the stream, the longest 40 read and every one left out listed with why. Over the pilot's week, read-only, it found all 6 of the pilot's duplicate uploads and all 18 of its stream cut-downs. `pnpm ops get lookouts` is the readout. Runs and verdicts will live in `transcripts/.lookouts/`, never published. - **A converted read can follow your pitch.** Converting a recorded read to a stock voice threw the voice acting away. On 11 Nov, reads with a median pitch of 128, 212, 225 and 237 Hz all came out at 196–199 Hz, and a 152–321 Hz range came out as 165–240 Hz: both converters speak at the stock voice's own pitch. `pnpm ops voice-convert` now takes `"pitch"`: `target` (as before), `source` (the pitch you read at: raise your voice and the result rises) or `contour` (your rises and falls, moved as a whole to the stock voice's register), and `"semitones"` (-12 to 12) moves a followed pitch. The same read that came out at 197 Hz now comes out at 211 Hz with a 148–314 Hz range, against 212 Hz and 152–321 Hz read. `source` and `contour` are seed-vc's, on its f0-conditioned model: optional files, fetched by `archilyzer voice setup --engine seed-vc --with f0` (1.49 GB). An install without them converts as before, and a followed pitch is refused naming that command; openvoice refuses a pitch it cannot follow. It takes about 1.7 times as long, and more memory (5.8 GB at its peak on a take of 20 s or more). `settings.voice.convert.pitch` and `.semitones` are the defaults (`target`, 0). In umtool a character keeps its pitch in the cast (`umtool cast set <id> --convert-pitch contour --convert-semitones 2`, shown on Voices), and `--pitch` / `--semitones` on `posts narrate … --recording` or `--derive <n> --op convert` set it for one read; the post bench's **run AI on take** has the same two controls for a convert on seed-vc, starting from the character's. The disclosure line is unchanged. - **The dashboard says when a media drive is not answering, slow, or not mounted.** A stalled external drive used to show only on `/storage` and in channel badges, so the editor looked broken with nothing on its front page saying why. The dashboard now opens with one card per storage location in trouble: **not answering** (an alert: pages and polls skip the drive, and its channels' jobs wait until it answers), **answering slowly** (everything still runs, just late), or **not mounted** (only when some channel's media is on it). Each card links to `/storage` and to that location's channels. On `/storage` each location has a **Drive** line that says when the drive last answered and how long it took (for example "answering — 12 ms (a read in the editor), last at 11:42"), and a **slow** chip appears next to Available when two reads in a row on it take half the 3-second limit or more (one long read is not enough). `pnpm ops get storage` reports the same for each location under `rows[].drive`: `state` (`ok`, `slow`, `stalled` or `unmounted`), `since`, `lastOkAt`, `latencyMs`, the cause and the one-line text. - **A transcription or backfill run waits while its channel's media drive is not answering.** Before, a run that started while the drive answered kept going after the drive stalled. Each next video asked the stalled drive for its audio, waited about 30 seconds and failed. Now the run pauses at the next video and says so in its log ("Holding: the media drive "…" is not answering (since 11:35) — no new transcription starts until it answers again"), then resumes by itself when the drive answers. If it has held for 5 minutes, the run checks the drive itself from a separate process, and it logs that it is still holding every 10 minutes. A run also follows a channel that is moved to another drive while it runs. A video that is refused because the drive is not answering is skipped, not added to the channel's failed-transcriptions list, and is transcribed on a later run. A downloaded video is also not moved into a saved-video store on a drive that is not answering. It stays in the video's folder, and a later pass stores it. diff --git a/editor/app/api/ops/_lookouts.test.ts b/editor/app/api/ops/_lookouts.test.ts @@ -0,0 +1,92 @@ +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_lookouts.test.ts" +// +// `pnpm ops get lookouts` and `pnpm ops lookout-run` (the dry run, the only +// one there is yet), against the route handlers over a temp corpus. Every +// channel and lookout here is invented. Never the live editor's settings. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, readdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { callGet, callPost, setupOpsCorpus } from "./_testCorpus"; + +const corpus = await setupOpsCorpus(null); +const { GET } = await import("./lookouts/route"); +const { POST } = await import("./lookout-run/route"); +test.after(() => corpus.cleanup()); + +const LOOKOUTS = { + enabled: false, + afterSync: false, + items: [{ id: "example-week", label: "Example week", channels: ["example-news", "no-such-channel"], days: 3, timeZone: "America/New_York" }], +}; + +async function video(slug: string, dir: string, title: string, uploadDate: string, timestamp: number, seconds: number) { + const d = path.join(corpus.transcripts, "channels", slug, "data", dir); + await mkdir(d, { recursive: true }); + await writeFile(path.join(d, "metadata.info.json"), JSON.stringify({ id: dir, title, duration: seconds, upload_date: uploadDate, timestamp })); + const cues = Array.from({ length: 40 }, (_, i) => ({ start: i * (seconds / 40), end: (i + 1) * (seconds / 40), text: `${title} line ${i} of ${dir}` })); + await writeFile( + path.join(d, "transcript.cues.json"), + JSON.stringify({ version: 2, id: dir, title, uploadDate, duration: seconds, platform: "youtube", webpageUrl: `https://example.invalid/${dir}`, cues }), + ); +} + +test("get lookouts: the saved lookouts and what the store holds for each; nothing configured is an empty list", async () => { + const empty = await callGet(GET!, "http://localhost/api/ops/lookouts"); + assert.equal(empty.status, 200, JSON.stringify(empty.body)); + assert.deepEqual(empty.body.lookouts, []); + assert.equal(empty.body.enabled, false); + + await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); + const r = await callGet(GET!, "http://localhost/api/ops/lookouts"); + assert.equal(r.status, 200, JSON.stringify(r.body)); + const [one] = r.body.lookouts as Record<string, unknown>[]; + assert.equal(one!.id, "example-week"); + assert.equal(one!.maxVideos, 40, "the defaults the settings filled"); + assert.equal(one!.lastRun, null); + assert.equal(one!.runs, 0); + assert.equal(one!.unruled, 0); + assert.equal((await callGet(GET!, "http://localhost/api/ops/lookouts?id=nope")).status, 404); + assert.equal((await callGet(GET!, "http://localhost/api/ops/lookouts?lookout=x")).status, 400); +}); + +test("lookout-run: the dry run lists what would be read, on air dates, and writes nothing", async () => { + await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); + await corpus.writeChannelConfig("example-news", {}); + // 2026-11-04T01:20:53Z is the evening of 3 Nov in New York. + await video("example-news", "Evening0001", "Evening Show", "20261104", 1793755253, 1200); + await video("example-news", "Short000001", "A Short", "20261104", 1793790000, 45); + const before = await readdir(corpus.transcripts); + const r = await callPost(POST!, { id: "example-week", dryRun: true, until: "2026-11-05" }); + assert.equal(r.status, 200, JSON.stringify(r.body)); + const plan = r.body.plan as { + window: { from: string; to: string }; + read: { video: string; airDate: string }[]; + skipped: { video: string; reason: string }[]; + refused: { channel: string }[]; + }; + assert.deepEqual(plan.window, { from: "2026-11-03", to: "2026-11-05", days: 3, timeZone: "America/New_York" }); + assert.deepEqual(plan.read.map((v) => [v.video, v.airDate]), [["Evening0001", "2026-11-03"]]); + assert.deepEqual(plan.skipped.map((v) => [v.video, v.reason]), [["Short000001", "under-min-seconds"]]); + assert.deepEqual(plan.refused.map((x) => x.channel), ["no-such-channel"]); + assert.deepEqual(await readdir(corpus.transcripts), before, "no store, no job, nothing written"); + assert.deepEqual(await corpus.listJobIds(), []); +}); + +test("lookout-run refuses before reading anything: no dryRun, an unknown lookout or key, bad overrides", async () => { + await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: LOOKOUTS }); + const run = await callPost(POST!, { id: "example-week" }); + assert.equal(run.status, 400); + assert.match(String(run.body.error), /dryRun/); + assert.equal((await callPost(POST!, { id: "example-week", dryRun: false })).status, 400); + assert.equal((await callPost(POST!, { id: "nope", dryRun: true })).status, 404); + assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, model: "x" })).status, 400); + assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, days: 99 })).status, 400); + assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, maxVideos: 0 })).status, 400); + assert.equal((await callPost(POST!, { id: "example-week", dryRun: true, until: "11/05/2026" })).status, 400); + await corpus.writeSettings({ minFreeDiskGB: 0, lookouts: { items: [{ id: "empty", channels: [] }] } }); + const none = await callPost(POST!, { id: "empty", dryRun: true }); + assert.equal(none.status, 400); + assert.match(String(none.body.error), /names no channels/); +}); diff --git a/editor/app/api/ops/lookout-run/route.ts b/editor/app/api/ops/lookout-run/route.ts @@ -0,0 +1,56 @@ +import { NextResponse } from "next/server"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { isIsoDate } from "yt-dlp-transcript-common/lib/lookout"; +import { LOOKOUT_MAX_DAYS, LOOKOUT_MAX_MAX_VIDEOS, lookoutById } from "yt-dlp-transcript-common/lib/lookoutSettings"; +import { LookoutPlanRefusal, planLookout } from "yt-dlp-transcript-common/controller/lookoutPlan"; +import { OpsInputError, ops, opsFail, optBool, optPositiveInt, optString, reqString } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { id, dryRun: true, days?, maxVideos?, until? } -> { ok: true, plan } +// +// What a saved lookout (settings.lookouts.items, SETTINGS.md) would read +// (common/controller/lookoutPlan.ts): every video of its channels whose AIR +// date — `release_timestamp`, else `timestamp`, in its time zone — falls in +// the window; duplicate uploads and a stream's cut-downs folded into one +// recording; the longest `maxVideos` read and the rest listed as skipped for +// the cap, with why for every video left out; the reading calls and, once a +// run has been measured, the seconds they would take. `days` and `maxVideos` +// override the lookout's for this answer; `until` (YYYY-MM-DD) ends the window +// on another day than today. A local media library channel, or a slug this +// archive does not hold, is named in `refused`. Reads text only and writes +// nothing; synchronous, no job, no model, no network. +// +// Only the dry run exists in this build: without `dryRun: true` the request is +// refused, never run. +export async function POST(request: Request) { + return ops(request, ["id", "dryRun", "days", "maxVideos", "until"], async (body) => { + const id = reqString(body, "id"); + if (optBool(body, "dryRun") !== true) { + throw new OpsInputError( + 'a lookout run reads with a model, which this build does not do yet — send "dryRun": true to list what it would read', + ); + } + const days = optPositiveInt(body, "days"); + if (days !== undefined && days > LOOKOUT_MAX_DAYS) throw new OpsInputError(`"days" is at most ${LOOKOUT_MAX_DAYS}`); + const maxVideos = optPositiveInt(body, "maxVideos"); + if (maxVideos !== undefined && maxVideos > LOOKOUT_MAX_MAX_VIDEOS) { + throw new OpsInputError(`"maxVideos" is at most ${LOOKOUT_MAX_MAX_VIDEOS}`); + } + const until = optString(body, "until"); + if (until !== undefined && !isIsoDate(until)) throw new OpsInputError('"until" is a date, YYYY-MM-DD'); + const lookouts = getSettings().lookouts; + const item = lookoutById(lookouts, id); + if (!item) { + return opsFail(`no lookout "${id}" — settings.lookouts.items names ${lookouts.items.map((i) => i.id).join(", ") || "none"}`, 404); + } + try { + const plan = await planLookout(getPaths(), item, { days, maxVideos, until }); + return NextResponse.json({ ok: true, plan }); + } catch (err) { + if (err instanceof LookoutPlanRefusal) throw new OpsInputError(err.message); + throw err; + } + }); +} diff --git a/editor/app/api/ops/lookouts/route.ts b/editor/app/api/ops/lookouts/route.ts @@ -0,0 +1,29 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getSettings } from "yt-dlp-transcript-common/lib/settings"; +import { lookoutReadout } from "yt-dlp-transcript-common/lib/lookoutStore"; +import { opsFail } from "../_lib"; +import { readRoute } from "../_read"; + +export const dynamic = "force-dynamic"; + +// GET /api/ops/lookouts[?id=<lookout>] — `pnpm ops get lookouts` +// +// The saved lookouts (settings.lookouts, SETTINGS.md) and what the store holds +// for each (common/lib/lookoutStore.ts, `transcripts/.lookouts/<id>/`): its +// runs, the latest one summarised (when, window, model, calls, seconds, +// ideas), how many of that run's ideas have no verdict yet, and the verdicts +// given. Reads settings and the store only — never a channel's videos, so it +// is cheap to poll; what a lookout would read is `lookout-run` with dryRun. +export async function GET(request: Request) { + return readRoute(request, ["id"], async (q) => { + const { enabled, afterSync, items } = getSettings().lookouts; + const id = q.get("id"); + const chosen = id === null ? items : items.filter((i) => i.id === id); + if (id !== null && chosen.length === 0) { + return opsFail(`no lookout "${id}" — settings.lookouts.items names ${items.map((i) => i.id).join(", ") || "none"}`, 404); + } + const paths = getPaths(); + const lookouts = await Promise.all(chosen.map(async (item) => ({ ...item, ...(await lookoutReadout(paths, item.id)) }))); + return { enabled, afterSync, lookouts }; + }); +} diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -209,6 +209,9 @@ // pnpm ops report-schedule --json '{"action":"reset-triage","id":"co-host-updates"}' // pnpm ops report-schedule --json '{"action":"learn","id":"co-host-updates","dryRun":true}' // pnpm ops report-schedule --json '{"action":"promote-alias","id":"co-host-updates","spelling":"Gothics"}' +// pnpm ops get lookouts +// pnpm ops lookout-run --json '{"id":"example-week","dryRun":true}' +// pnpm ops lookout-run --json '{"id":"example-week","dryRun":true,"days":3,"until":"2026-11-10"}' // // --file reads the BODY from a JSON file, which is how a big one gets sent: a // four-thousand-id tag-videos body is written by a script, not typed by a model @@ -313,6 +316,9 @@ const GETTERS = { cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`, // The speakers readout: waiting, freed this run, rate, days left, per channel. speakers: () => "/api/ops/speakers", + // The saved lookouts (settings.lookouts) and what the store holds for each: + // the latest run, how many of its ideas wait for a verdict. + lookouts: (id) => (id ? `/api/ops/lookouts?id=${encodeURIComponent(id)}` : "/api/ops/lookouts"), // What a channel holds, by date, and its gaps (release 19 A9): each video // dated by its recorded date when the channel has a title rule, else upload. coverage: (slug) => `/api/ops/coverage?slug=${encodeURIComponent(slug)}`, @@ -365,6 +371,7 @@ const GET_ARG_OPTIONAL = new Set([ "generation-usage", "render-mode", "speakers", + "lookouts", ]); // The flags each noun takes beyond the shared ones; any other is refused. @@ -706,6 +713,11 @@ const ACTIONS = [ // X's queue, the jar checked before each ({channels: [...], limit?} or // {resume: <run id>}); a stale jar defers the rest. "x-run", + // What a saved lookout would read ({id, dryRun: true, days?, maxVideos?, + // until?}): its channels' videos by air date, duplicate uploads and stream + // cut-downs folded in, the cap. Synchronous; no job, nothing written. Only + // the dry run exists yet. + "lookout-run", ]; // The log line a transcribe job ends with: this marker, then the result as @@ -1085,6 +1097,7 @@ export function usage() { " pnpm ops get x-run [<run id>]", " pnpm ops get cleanup <slug>", " pnpm ops get speakers", + " pnpm ops get lookouts [<id>]", " pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]", " pnpm ops get transcript <videoId> [--slug <slug>]", " pnpm ops get coverage <slug>", @@ -1178,6 +1191,11 @@ export function usage() { " noFingerprintPossible (diarized, audio already gone), per channel with", " corpus-disk channels first; and the lane: armed, held, the operations", " it dispatches, its order, cleanAfterCapture and requireVoiceprints.", + "get lookouts [<id>] is the saved lookouts (settings.lookouts, SETTINGS.md):", + " each one's channels, days, cap and zone, its runs (transcripts/.lookouts/", + " <id>/), the latest run (when, window, model, calls, seconds, ideas), how", + " many of that run's ideas have no verdict yet, and the verdicts given.", + " Reads settings and the store only, never a channel's videos.", "get cleanup <slug> is one channel's /cleanup row: what each sweep would", " reclaim (they overlap — never add them), what holds the rest, and the", " failed-transcriptions count. measured: false means unknown, not zero.", @@ -1263,6 +1281,20 @@ export function usage() { ' "speakers": "work" (the deck\'s Work through speakers: arm, lift the hold,', ' start a run) | "pause" (hold; stays armed).', "", + 'lookout-run lists what a saved lookout (settings.lookouts) would read:', + ' {"id", "dryRun": true, "days"?, "maxVideos"?, "until"?: "YYYY-MM-DD"}.', + " Every video of its channels whose AIR date (release_timestamp, else", + " timestamp, in the lookout's timeZone — not the UTC upload_date) falls in", + " the window; a duplicate upload of one recording, and a stream's cut-down,", + " folded into it (each named, with why and its score); the longest", + " maxVideos recordings read and the rest listed as skipped for the cap;", + " under minSeconds and no transcript yet listed too. A local media library", + " channel or a slug this archive does not hold is named in \"refused\".", + " Answers {plan: {window, counts, read, skipped, refused, estimate}}:", + " readCalls is one per transcript chunk, priced once a run has been", + " measured. Synchronous, reads text only, writes nothing; without", + ' "dryRun": true it is refused (the model run is not in this build).', + "", 'render-mode gives a render the operator is waiting for the machine:', ' {"on": true, "for"?: "90m" | <minutes>, "note"?} opens a window (default', ' 2h) in which every other heavy job — e2e suites, next builds, the publish', diff --git a/settings.json.example b/settings.json.example @@ -373,5 +373,10 @@ "probeServices": [ "rumble" ] + }, + "lookouts": { + "enabled": false, + "afterSync": false, + "items": [] } }