Archilyzer · Source

archilyzer

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

commit 6e5933dd984a921c1b83aef94d5bbf01ca45aa8b
parent 02f5e182b1392cc5ee4ab7707b4a4b213ae270a2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 10 Oct 2026 12:16:26 -0400

common: release 23 F1 — the Twitch join, option (b): a record's v<n> reads its data/<n>/

Published v<n> ids stay; the join normalizes on the directory side. One
helper (lib/videoDirId.mjs, re-exported by lib/videoId.ts; the disk half in
lib/videoDir-server.mjs) maps a Twitch record's v<n> to its <n> directory and
back. Only a v<digits> id of a Twitch record (its platform, else its
channel's) is mapped; the directory that exists wins, <n> first. Every other
id passes through with no read.

Used at the join points release 20 D2 named: the editor's fetch-window
(fetchWindowAction, fetchFullSourceAction, the batch planner) and
controller/fetchWindows.ts, the evidence-clip tiers (evidenceClip.mjs) and
recordDuration, reportMedia.ts's availability read, and umtool cues.mjs's
local cue lookup. Records and published ids are unchanged; no index re-key.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/controller/fetchWindows.test.ts | 27+++++++++++++++++++++++++++
Mcommon/controller/fetchWindows.ts | 13++++++++++---
Mcommon/lib/evidenceClip-server.test.ts | 30++++++++++++++++++++++++++++++
Mcommon/lib/evidenceClip-server.ts | 4+++-
Mcommon/lib/evidenceClip.mjs | 42++++++++++++++++++++++++++++++------------
Acommon/lib/videoDir-server.mjs | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/videoDirId.mjs | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/videoDirId.test.ts | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/videoId.ts | 12++++++++++++
Mcommon/package.json | 2++
Mcommon/publish/reportMedia.ts | 3++-
Acommon/publish/reportMediaTwitch.test.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 33++++++++++++++++++++++++---------
Aeditor/app/channels/[slug]/videos/fetchWindowTwitch.test.ts | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/fetchWindowsAction.ts | 25++++++++++++++++---------
Mumtool/report-to-video/cues.mjs | 5++++-
Mumtool/report-to-video/cues.test.mjs | 27+++++++++++++++++++++++++++
17 files changed, 590 insertions(+), 36 deletions(-)

diff --git a/common/controller/fetchWindows.test.ts b/common/controller/fetchWindows.test.ts @@ -371,3 +371,30 @@ test("saved containers: a cut that fails is a cut-failed item and the run carrie assert.deepEqual(r.cut.map((i) => i.id), ["v2"]); assert.equal(r.stopped, undefined); }); + +test("a Twitch record's v<n> is fetched into, and read from, its data/<n>/ (release 23 F1)", async () => { + const paths = await corpus(); + const twitch = { url: "https://www.twitch.tv/example" } as unknown as ChannelConfig; + const n = "2700000001"; + const fresh = "2700000002"; + await mkdir(path.join(paths.channelsDir, "c", "data", fresh), { recursive: true }); + const clips = path.join(paths.channelsDir, "c", "data", n, "clips"); + await mkdir(clips, { recursive: true }); + await writeFile(path.join(clips, "0.00-60.00.mp4"), "mp4"); + const asked: string[] = []; + const h = harness({ + readChannelConfig: async () => twitch, + findVideoSourceUrl: async (_p, _s, id) => { + asked.push(id); + return `https://www.twitch.tv/videos/${id}`; + }, + }); + const r = await go(paths, [{ slug: "c", id: `v${n}`, from: 5, to: 15 }, { slug: "c", id: `v${fresh}`, from: 5, to: 15 }], h); + // The cached window was found in data/<n>/; the item keeps its record id. + assert.deepEqual(r.cached.map((i) => i.id), [`v${n}`]); + assert.deepEqual(r.fetched.map((i) => i.id), [`v${fresh}`]); + // The URL was looked up, and the window written, under the directory's id. + assert.deepEqual(asked, [fresh]); + const written = await readFile(path.join(paths.channelsDir, "c", "data", fresh, "clips", "5.00-15.00.mp4"), "utf8"); + assert.equal(written, "mp4"); +}); diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -8,6 +8,8 @@ import { resolveCookiePolicy } from "../lib/cookiePolicy"; import { assertChannelTextReadable } from "../lib/channelMedia"; import { detectPlatform } from "../lib/platform"; import { findContainingClipWindow } from "../lib/clipWindow-server"; +import { channelConfigPlatform } from "../lib/videoId"; +import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; import { cutSavedVideoWindow, savedWindowSource, @@ -365,7 +367,12 @@ export async function fetchWindows({ progress(); continue; } - const videoDir = path.join(paths.channelsDir, item.slug, "data", item.id); + // The item names a RECORD (a report's citation, the MCP); its directory + // may be another id — a Twitch record's v<n> is data/<n>/ (release 23 F1). + const dirId = await resolveVideoDirId(paths.channelsDir, item.slug, item.id, { + platform: channelConfigPlatform(config), + }); + const videoDir = path.join(paths.channelsDir, item.slug, "data", dirId); // THE CACHE FIRST, here rather than only inside fetchWindowManaged, so a // cached window owes no pause and is not counted as a network attempt. @@ -423,7 +430,7 @@ export async function fetchWindows({ const url = item.webpageUrl?.trim() || - (await deps.findVideoSourceUrl(paths, item.slug, item.id, config)); + (await deps.findVideoSourceUrl(paths, item.slug, dirId, config)); if (!url) { fail( item, @@ -500,7 +507,7 @@ export async function fetchWindows({ channelConfig: config, paths, videoDir, - videoId: item.id, + videoId: dirId, videoUrl: url, cwd: path.join(paths.channelsDir, item.slug), from: item.from, diff --git a/common/lib/evidenceClip-server.test.ts b/common/lib/evidenceClip-server.test.ts @@ -13,6 +13,7 @@ import { copyFile, mkdir, mkdtemp, readdir, rm, symlink, utimes, writeFile } fro import { tmpdir } from "node:os"; import path from "node:path"; import { + citedEvidenceSpan, evidenceCutArgs, evidenceHash, evidenceSpan, @@ -109,6 +110,35 @@ test("tiers: a clip window, else the saved container, else nothing; the window w assert.equal(both?.kind, "corpus-window"); }); +test("tiers: a Twitch record's v<n> finds its data/<n>/ — every tier, and the duration clamp (release 23 F1)", async () => { + const root = await mkdtemp(path.join(ROOT, "tw-")); + const channelsDir = path.join(root, "channels"); + const slug = "example-twitch"; + const n = "2700000001"; + const dir = path.join(channelsDir, slug, "data", n); + await mkdir(path.join(dir, "clips"), { recursive: true }); + // No platform key: the channel's url says Twitch, as on a real Twitch channel. + await writeFile(path.join(channelsDir, slug, "config.json"), JSON.stringify({ handling: "transcribe", url: "https://www.twitch.tv/example" })); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: `v${n}`, duration: 5 })); + const ask = (span: { from: number; to: number }, audio = false) => + resolveEvidenceSource({ channelsDir, slug, id: `v${n}`, span, audio }); + + await copyFile(SOUND, path.join(dir, "audio.m4a")); + assert.equal((await ask({ from: 1, to: 3 }, true))?.kind, "audio"); + await writeFile(path.join(dir, "saved-video.json"), JSON.stringify({ dir, file: "held.mp4" })); + await copyFile(SMALL, path.join(dir, "held.mp4")); + assert.equal((await ask({ from: 1, to: 3 }))?.kind, "saved-video"); + await copyFile(SMALL, path.join(dir, "clips", "0.00-6.00.mp4")); + const win = await ask({ from: 1, to: 3 }); + assert.equal(win?.kind, "corpus-window"); + assert.equal(win?.path, path.join(dir, "clips", "0.00-6.00.mp4")); + // The duration is read from data/<n>/metadata.info.json. + assert.deepEqual(await citedEvidenceSpan(channelsDir, slug, `v${n}`, { start: 2, end: 9 }), { from: 2, to: 5 }); + // A v-id on a channel of another platform is never mapped. + await writeFile(path.join(channelsDir, slug, "config.json"), JSON.stringify({ handling: "youtube", platform: "youtube" })); + assert.equal(await ask({ from: 1, to: 3 }), null); +}); + test("tiers: the sound is asked only when allowed, and never beats a picture", async () => { const { channelsDir, videoDir } = await corpus(); const span = { from: 1, to: 3 }; diff --git a/common/lib/evidenceClip-server.ts b/common/lib/evidenceClip-server.ts @@ -56,6 +56,7 @@ import { ffprobeSource, resolveCorpusSource, } from "./evidenceClip.mjs"; +import { resolveVideoDir } from "./videoDir-server.mjs"; // Bumped whenever the arguments below change what a clip looks like: it is in // every hash, so a new profile re-cuts rather than serving an old file. @@ -92,8 +93,9 @@ export function clampSpanToDuration(span: EvidenceSpan, duration: number | null } // A record's duration (its metadata.info.json), or null when it is not recorded. +// The record's directory, not a join on its id: a Twitch `v<n>` is `data/<n>/`. export async function recordDuration(channelsDir: string, slug: string, id: string): Promise<number | null> { - const read = await readJsonFile(path.join(channelsDir, slug, "data", id, "metadata.info.json")); + const read = await readJsonFile(path.join(await resolveVideoDir(channelsDir, slug, id), "metadata.info.json")); const d = read.ok ? Number((read.value as { duration?: unknown } | null)?.duration) : NaN; return Number.isFinite(d) && d > 0 ? d : null; } diff --git a/common/lib/evidenceClip.mjs b/common/lib/evidenceClip.mjs @@ -41,6 +41,7 @@ import { execFile } from "node:child_process"; import { readdir, readFile, stat } from "node:fs/promises"; import path from "node:path"; import { promisify } from "node:util"; +import { resolveVideoDir } from "./videoDir-server.mjs"; const execFileP = promisify(execFile); @@ -74,7 +75,7 @@ export async function listNames(dir) { * @typedef {{ name: string, path: string, from: number, to: number, height?: number }} SourceWindow * @typedef {{ kind: string, path: string, name: string, windowStart: number, windowEnd: number, height?: number }} LocalSource * @typedef {(file: string) => Promise<{ duration: number, height?: number } | null>} SourceProbe - * @typedef {{ video: string, slug?: string | null, channelsDir?: string | null, rawDir?: string | null, probe?: SourceProbe }} TierContext + * @typedef {{ video: string, slug?: string | null, channelsDir?: string | null, rawDir?: string | null, probe?: SourceProbe, platform?: string | null }} TierContext * @typedef {{ kind: string, windows: (ctx: TierContext) => Promise<SourceWindow[]>, audio?: boolean }} SourceTier */ @@ -107,7 +108,9 @@ export function tightestContaining(windows, from, to) { } /** - * A video's directory in a channels tree: `<channelsDir>/<slug>/data/<id>`. + * A video's directory in a channels tree: `<channelsDir>/<slug>/data/<id>`, the + * plain join. A RECORD's id goes through `recordDirOf` instead: a Twitch + * record's `v<n>` lives in `data/<n>/` (./videoDir-server.mjs). * @param {string} channelsDir * @param {string} slug * @param {string} video @@ -117,6 +120,20 @@ export function videoDirOf(channelsDir, slug, video) { } /** + * The directory a RECORD's media lives in: `videoDirOf` over the directory id + * the record maps to (release 23 F1 — a Twitch `v<n>` is `data/<n>/`; every + * other id is itself, with no read). `platform` is the record's when the + * caller knows it, else the channel's config is read. + * @param {string} channelsDir + * @param {string} slug + * @param {string} video + * @param {string | null} [platform] + */ +export function recordDirOf(channelsDir, slug, video, platform) { + return resolveVideoDir(channelsDir, slug, video, platform !== undefined ? { platform } : {}); +} + +/** * Where the editor's fetch-window puts a video's windows (lib/clipWindow.ts). * @param {string} videoDir */ @@ -273,18 +290,18 @@ export async function ffprobeSource(file, bin = process.env.FFPROBE_BIN ?? "ffpr // channelsDir or slug) lists nothing. /** @param {TierContext} ctx */ -async function corpusWindows({ video, slug, channelsDir }) { +async function corpusWindows({ video, slug, channelsDir, platform }) { if (!channelsDir || !slug) return []; - const dir = corpusClipsDir(videoDirOf(channelsDir, slug, video)); + const dir = corpusClipsDir(await recordDirOf(channelsDir, slug, video, platform)); return windowsFromBareNames(await listNames(dir), dir); } /** @param {TierContext} ctx */ -async function savedVideoWindows({ video, slug, channelsDir, probe = ffprobeSource }) { +async function savedVideoWindows({ video, slug, channelsDir, platform, probe = ffprobeSource }) { if (!channelsDir || !slug) return []; /** @type {SourceWindow[]} */ const out = []; - for (const c of await wholeContainersOf(videoDirOf(channelsDir, slug, video))) { + for (const c of await wholeContainersOf(await recordDirOf(channelsDir, slug, video, platform))) { // Existence BEFORE the probe: an unmounted drive must not cost a timeout. if (!(await present(c.path))) continue; const info = await probe(c.path); @@ -301,9 +318,9 @@ async function savedVideoWindows({ video, slug, channelsDir, probe = ffprobeSour // The ONE best audio file, not every one: they are all the same recording, and // probing three formats of it would buy nothing. /** @param {TierContext} ctx */ -async function audioWindows({ video, slug, channelsDir, probe = ffprobeSource }) { +async function audioWindows({ video, slug, channelsDir, platform, probe = ffprobeSource }) { if (!channelsDir || !slug) return []; - for (const f of await audioFilesOf(videoDirOf(channelsDir, slug, video))) { + for (const f of await audioFilesOf(await recordDirOf(channelsDir, slug, video, platform))) { if (!(await present(f.path))) continue; const duration = Number((await probe(f.path))?.duration); if (!Number.isFinite(duration) || duration <= 0) continue; @@ -373,15 +390,16 @@ export async function resolveFromTiers(tiers, ctx, from, to, opts = {}) { * * @param {{ video: string, slug: string, from: number, to: number }} want * `from`/`to` are the PADDED span. - * @param {{ channelsDir: string, probe?: SourceProbe, audio?: boolean }} config - * `audio` admits the audio tier (default false). + * @param {{ channelsDir: string, probe?: SourceProbe, audio?: boolean, platform?: string | null }} config + * `audio` admits the audio tier (default false); `platform` is the record's, + * when known (else its channel's is read — recordDirOf). * @returns {Promise<LocalSource | null>} */ export async function resolveCorpusSource(want, config) { const { video, slug, from, to } = want; - const { channelsDir, probe, audio = false } = config; + const { channelsDir, probe, audio = false, platform } = config; if (!video || !slug || !Number.isFinite(from) || !Number.isFinite(to)) return null; - return resolveFromTiers(CORPUS_TIERS, { video, slug, channelsDir, probe }, from, to, { + return resolveFromTiers(CORPUS_TIERS, { video, slug, channelsDir, probe, platform }, from, to, { allow: (tier) => (tier.audio ? audio : true), }); } diff --git a/common/lib/videoDir-server.mjs b/common/lib/videoDir-server.mjs @@ -0,0 +1,74 @@ +// videoDir-server — the disk half of ./videoDirId.mjs: which `data/<dir>/` a +// record's id lives in ON THIS DISK (release 23 F1, the Twitch join, option +// (b)). Plain JS for umtool's bare-node scripts; server-only (node:fs). It +// never computes a path from the cwd: every root arrives as an argument. + +import { readFile, stat } from "node:fs/promises"; +import path from "node:path"; +import { channelConfigPlatform, pickVideoDirId, twitchVodDirId } from "./videoDirId.mjs"; + +/** @param {string} p */ +async function isDir(p) { + try { + return (await stat(p)).isDirectory(); + } catch { + return false; + } +} + +/** + * A channel's platform, read from its config.json; null when unreadable. + * @param {string} channelsDir + * @param {string} slug + * @returns {Promise<string | null>} + */ +export async function readChannelPlatform(channelsDir, slug) { + try { + const raw = JSON.parse( + await readFile(path.join(/* turbopackIgnore: true */ channelsDir, slug, "config.json"), "utf8"), + ); + return channelConfigPlatform(raw); + } catch { + return null; + } +} + +/** + * The directory id a record lives in, on this disk. Only a `v<digits>` id + * costs a read (the channel's config when no platform is given, and two + * stats); every other id is returned as it is. + * @param {string} channelsDir + * @param {string} slug + * @param {string} recordId + * @param {{ platform?: string | null }} [opts] the record's (or channel's) + * platform, when the caller already knows it. + * @returns {Promise<string>} + */ +export async function resolveVideoDirId(channelsDir, slug, recordId, opts = {}) { + if (twitchVodDirId(recordId) === null) return recordId; + const platform = opts.platform !== undefined ? opts.platform : await readChannelPlatform(channelsDir, slug); + if (platform !== "twitch") return recordId; + const dataDir = path.join(/* turbopackIgnore: true */ channelsDir, slug, "data"); + const n = /** @type {string} */ (twitchVodDirId(recordId)); + const [hasN, hasV] = await Promise.all([ + isDir(path.join(/* turbopackIgnore: true */ dataDir, n)), + isDir(path.join(/* turbopackIgnore: true */ dataDir, recordId)), + ]); + return pickVideoDirId(recordId, { + platform, + exists: (id) => (id === n ? hasN : id === recordId ? hasV : false), + }); +} + +/** + * The directory a record lives in: `<channelsDir>/<slug>/data/<dir id>`. + * @param {string} channelsDir + * @param {string} slug + * @param {string} recordId + * @param {{ platform?: string | null }} [opts] + * @returns {Promise<string>} + */ +export async function resolveVideoDir(channelsDir, slug, recordId, opts = {}) { + const dirId = await resolveVideoDirId(channelsDir, slug, recordId, opts); + return path.join(/* turbopackIgnore: true */ channelsDir, slug, "data", dirId); +} diff --git a/common/lib/videoDirId.mjs b/common/lib/videoDirId.mjs @@ -0,0 +1,78 @@ +// videoDirId — which `data/<dir>/` a RECORD's id lives in (release 23 F1, the +// Twitch join, option (b), ruled 2026-10-10). +// +// A Twitch VOD's directory is its canonical id, the URL's `/videos/<n>` +// (`extractVideoId`), while its record carries yt-dlp's native id `v<n>`. The +// published `v<n>` URLs stay; the join between the two normalizes on the +// DIRECTORY side, here, once. Records and published ids are never rewritten. +// +// - A record id that is not `v<digits>` passes through untouched, with no +// filesystem read: every other platform, and every record but a Twitch +// VOD's. +// - A `v<digits>` id maps to `<digits>` only for a TWITCH record (the record's +// platform, else its channel's: config.json `platform`, else the host of +// its `url`). A `v`-prefixed id of any other platform (a Rumble slug, a +// YouTube id that happens to read `v` + ten digits) is never guessed at. +// - Between the two directories the one that EXISTS wins, `<n>` first (it is +// the one the download made, with the metadata); with neither, `<n>`, the +// canonical name, so a writer (fetch-window) creates the right one. +// +// Plain JS with JSDoc types, for the reason detectPlatform.mjs is: umtool's +// report-to-video scripts run under bare `node` and read these directories too +// (evidenceClip.mjs, cues.mjs). `lib/videoId.ts` re-exports it; TS callers +// import it from there. PURE (client-safe, as videoId.ts is): the disk half — +// which directory exists — is ./videoDir-server.mjs. + +import { detectPlatform } from "./detectPlatform.mjs"; + +const TWITCH_RECORD_ID_RE = /^v(\d+)$/; +const TWITCH_DIR_ID_RE = /^\d+$/; + +/** + * A Twitch record id's directory id: `v<n>` → `<n>`; anything else → null. + * Pure: says what the id would map to, not that the record is Twitch's. + * @param {string} recordId + * @returns {string | null} + */ +export function twitchVodDirId(recordId) { + const m = TWITCH_RECORD_ID_RE.exec(recordId); + return m ? m[1] : null; +} + +/** + * The reverse: a Twitch VOD directory `<n>` → the record id `v<n>` its record + * carries; anything else → null. + * @param {string} dirId + * @returns {string | null} + */ +export function twitchVodRecordId(dirId) { + return TWITCH_DIR_ID_RE.test(dirId) ? `v${dirId}` : null; +} + +/** + * The platform a channel's config names: `platform`, else its `url`'s host + * (ytdlp/channelArgs.ts channelPlatform's rule). Null for none. + * @param {{ platform?: unknown, url?: unknown } | null | undefined} config + * @returns {string | null} + */ +export function channelConfigPlatform(config) { + if (!config || typeof config !== "object") return null; + if (typeof config.platform === "string" && config.platform) return config.platform; + return typeof config.url === "string" ? detectPlatform(config.url) : null; +} + +/** + * The directory id for a record, given its platform and which directories + * exist. Synchronous over an `exists` callback, so a caller with its own + * listing (or a test) decides without touching the disk. + * @param {string} recordId + * @param {{ platform?: string | null, exists: (dirId: string) => boolean }} opts + * @returns {string} + */ +export function pickVideoDirId(recordId, { platform, exists }) { + const n = twitchVodDirId(recordId); + if (n === null || platform !== "twitch") return recordId; + if (exists(n)) return n; + if (exists(recordId)) return recordId; + return n; +} diff --git a/common/lib/videoDirId.test.ts b/common/lib/videoDirId.test.ts @@ -0,0 +1,95 @@ +// The Twitch join, option (b) (release 23 F1): a record keeps yt-dlp's `v<n>`, +// its directory is the canonical `<n>`, and the join maps one to the other on +// the directory side. Cases from release 20 D2's `twitchId.test.ts` +// (r20/twitch-ids 433815d4), without its re-keying of records. Synthetic ids. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/videoDirId.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + channelConfigPlatform, + extractVideoId, + pickVideoDirId, + twitchVodDirId, + twitchVodRecordId, +} from "./videoId"; +import { resolveVideoDir, resolveVideoDirId } from "./videoDir-server.mjs"; + +const N = "1234567890"; +const META = { id: `v${N}`, webpage_url: `https://www.twitch.tv/videos/${N}` }; + +test("twitchVodDirId drops only a v before digits; twitchVodRecordId is its reverse", () => { + assert.equal(twitchVodDirId(`v${N}`), N); + assert.equal(twitchVodDirId(N), null); + assert.equal(twitchVodDirId("vod-clip-slug"), null); + assert.equal(twitchVodDirId("v"), null); + assert.equal(twitchVodDirId("v12a"), null); + // The id the URL gives, which is what data/<id>/ is named. + assert.equal(extractVideoId(META.webpage_url), twitchVodDirId(META.id)); + assert.equal(twitchVodRecordId(N), `v${N}`); + assert.equal(twitchVodRecordId(`v${N}`), null); + assert.equal(twitchVodRecordId("abc"), null); + assert.equal(twitchVodRecordId(twitchVodDirId(META.id)!), META.id); +}); + +test("channelConfigPlatform: the platform key, else the url's host", () => { + assert.equal(channelConfigPlatform({ platform: "twitch" }), "twitch"); + assert.equal(channelConfigPlatform({ url: "https://www.twitch.tv/example" }), "twitch"); + assert.equal(channelConfigPlatform({ platform: "youtube", url: "https://www.twitch.tv/x" }), "youtube"); + assert.equal(channelConfigPlatform({}), null); + assert.equal(channelConfigPlatform(null), null); +}); + +test("pickVideoDirId: a Twitch v<n> prefers <n>, then v<n>, then the canonical <n>", () => { + const has = (...ids: string[]) => (id: string) => ids.includes(id); + assert.equal(pickVideoDirId(`v${N}`, { platform: "twitch", exists: has(N) }), N); + assert.equal(pickVideoDirId(`v${N}`, { platform: "twitch", exists: has(N, `v${N}`) }), N); + assert.equal(pickVideoDirId(`v${N}`, { platform: "twitch", exists: has(`v${N}`) }), `v${N}`); + assert.equal(pickVideoDirId(`v${N}`, { platform: "twitch", exists: has() }), N); + // Already the directory's id. + assert.equal(pickVideoDirId(N, { platform: "twitch", exists: has(N) }), N); +}); + +test("pickVideoDirId never guesses a v-prefixed id of another platform", () => { + const all = () => true; + assert.equal(pickVideoDirId(`v${N}`, { platform: "youtube", exists: all }), `v${N}`); + assert.equal(pickVideoDirId("v4abcde", { platform: "rumble", exists: all }), "v4abcde"); + assert.equal(pickVideoDirId(`v${N}`, { platform: null, exists: all }), `v${N}`); + assert.equal(pickVideoDirId(`v${N}`, { exists: all }), `v${N}`); +}); + +const ROOT = mkdtempSync(path.join(tmpdir(), "video-dir-id-")); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +function channel(slug: string, config: object, dirs: string[]): string { + const channelsDir = path.join(ROOT, slug + "-root"); + mkdirSync(path.join(channelsDir, slug, "data"), { recursive: true }); + writeFileSync(path.join(channelsDir, slug, "config.json"), JSON.stringify(config)); + for (const d of dirs) mkdirSync(path.join(channelsDir, slug, "data", d), { recursive: true }); + return channelsDir; +} + +test("resolveVideoDirId: a Twitch channel's v<n> record is its data/<n>/", async () => { + // Platform from the url (no platform key), and from the key. + const byUrl = channel("tw-url", { handling: "transcribe", url: "https://www.twitch.tv/example" }, [N]); + assert.equal(await resolveVideoDirId(byUrl, "tw-url", `v${N}`), N); + assert.equal(await resolveVideoDir(byUrl, "tw-url", `v${N}`), path.join(byUrl, "tw-url", "data", N)); + const byKey = channel("tw-key", { handling: "transcribe", platform: "twitch" }, [N]); + assert.equal(await resolveVideoDirId(byKey, "tw-key", `v${N}`), N); + // The id is never rewritten where it is the directory's own. + assert.equal(await resolveVideoDirId(byKey, "tw-key", N), N); + // A caller that knows the platform is believed over the config. + assert.equal(await resolveVideoDirId(byKey, "tw-key", `v${N}`, { platform: "youtube" }), `v${N}`); +}); + +test("resolveVideoDirId: other platforms and other ids pass through", async () => { + const yt = channel("yt", { handling: "youtube", url: "https://www.youtube.com/@x" }, [N, `v${N}`]); + assert.equal(await resolveVideoDirId(yt, "yt", `v${N}`), `v${N}`); + assert.equal(await resolveVideoDirId(yt, "yt", "dQw4w9WgXcQ"), "dQw4w9WgXcQ"); + // No config at all: never guessed. + assert.equal(await resolveVideoDirId(path.join(ROOT, "none"), "nobody", `v${N}`), `v${N}`); +}); diff --git a/common/lib/videoId.ts b/common/lib/videoId.ts @@ -12,6 +12,18 @@ import { isArchiveOrgItemHost, parseArchiveOrgUrl, archiveOrgVideoId } from "./archiveOrgId"; import { isJwPlayerHost, isWaybackHost, jwPlayerMediaId, parseWaybackUrl } from "./wayback"; +// A RECORD's id against its DIRECTORY's (release 23 F1, the Twitch join, +// option (b)): a Twitch record carries yt-dlp's native `v<n>` while its +// directory is the canonical `<n>` below. The join normalizes on the directory +// side; records and published ids are unchanged. Plain JS so umtool's bare-node +// scripts share it (./videoDirId.mjs); the disk half is ./videoDir-server.mjs. +export { + channelConfigPlatform, + pickVideoDirId, + twitchVodDirId, + twitchVodRecordId, +} from "./videoDirId.mjs"; + export function extractVideoId(url: string): string | null { return extractVideoIdAt(url, 0); } diff --git a/common/package.json b/common/package.json @@ -37,6 +37,8 @@ "./lib/ports.mjs": "./lib/ports.mjs", "./lib/report/verdicts.mjs": "./lib/report/verdicts.mjs", "./lib/toolProbe.mjs": "./lib/toolProbe.mjs", + "./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs", + "./lib/videoDirId.mjs": "./lib/videoDirId.mjs", "./ytdlp/platformArgs.mjs": "./ytdlp/platformArgs.mjs", "./lib/*": "./lib/*.ts", "./controller/*": "./controller/*.ts", diff --git a/common/publish/reportMedia.ts b/common/publish/reportMedia.ts @@ -59,6 +59,7 @@ import { parseReport } from "../lib/report/validate"; import { isReportId, type Report } from "../lib/report/schema"; import { isPermanentlyGone } from "../lib/availability"; import { loadAvailability } from "../lib/availability-server"; +import { resolveVideoDir } from "../lib/videoDir-server.mjs"; import { MAX_CLIP_WINDOW_SECONDS } from "../lib/clipWindow"; import { citedEvidenceSpan, @@ -513,7 +514,7 @@ export async function missingEvidenceWindows(paths: Paths, siteId: string): Prom unfetchable("unreachable", `the channel's media is ${where.status}${where.detail ? ` (${where.detail})` : ""}`); continue; } - const availability = (await loadAvailability(path.join(paths.channelsDir, slug, "data", id)))?.availability; + const availability = (await loadAvailability(await resolveVideoDir(paths.channelsDir, slug, id)))?.availability; if (isPermanentlyGone(availability)) { unfetchable("gone", `the source says the video is ${availability}`); continue; diff --git a/common/publish/reportMediaTwitch.test.ts b/common/publish/reportMediaTwitch.test.ts @@ -0,0 +1,88 @@ +// The Twitch join, option (b), in a site's evidence read (release 23 F1): a +// report cites a Twitch record by its `v<n>`, and the media, duration and +// availability are read from its `data/<n>/`. The citation's id is reported +// as cited — never rewritten. Synthetic ids; no ffmpeg (nothing is cut). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test publish/reportMediaTwitch.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "report-media-twitch-")); +Object.assign(process.env, { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), + SITES_DIR: path.join(ROOT, "transcripts", "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"), +}); +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { missingEvidenceWindows } = await import("./reportMedia"); + +const paths = getPaths(); +const SITE = "demo-site"; +const CH = "example-twitch"; +const GONE = "2700000001"; +const HELD = "2700000002"; +const OPEN = "2700000003"; + +const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(value, null, 2)); +}; +const dataDir = (id: string) => path.join(paths.channelsDir, CH, "data", id); + +writeJson(path.join(paths.channelsDir, CH, "config.json"), { + handling: "transcribe", + name: "Example", + url: "https://www.twitch.tv/example", +}); +for (const id of [GONE, HELD, OPEN]) { + writeJson(path.join(dataDir(id), "metadata.info.json"), { id: `v${id}`, duration: 600 }); +} +writeJson(path.join(dataDir(GONE), "availability.json"), { availability: "deleted", checkedAt: "2026-10-01T00:00:00Z" }); +// A window file is only listed, never probed, by the corpus-window tier. +mkdirSync(path.join(dataDir(HELD), "clips"), { recursive: true }); +writeFileSync(path.join(dataDir(HELD), "clips", "0.00-60.00.mp4"), "mp4"); + +writeJson(path.join(paths.sitesDir, SITE, "site.json"), { + title: "Demo", + channels: [{ slug: CH }], + search: false, + reports: ["r1"], +}); +writeJson(path.join(paths.sitesDir, SITE, "reports", "r1", "report.json"), { + format: "archilyzer-report", + version: 1, + id: "r1", + kind: "sweep", + title: "Report r1", + citations: { + c01: { kind: "video", channel: CH, id: `v${GONE}`, start: 10, end: 12, quote: "one" }, + c02: { kind: "video", channel: CH, id: `v${HELD}`, start: 10, end: 12, quote: "two" }, + c03: { kind: "video", channel: CH, id: `v${OPEN}`, start: 10, end: 12, quote: "three" }, + }, + sections: [{ id: "s1", title: "One", body: "[c01](cite:c01) [c02](cite:c02) [c03](cite:c03)" }], +}); + +test("missingEvidenceWindows reads a Twitch v<n> citation's media and availability from data/<n>/", async () => { + const r = await missingEvidenceWindows(paths, SITE); + assert.deepEqual(r.problems, []); + // The held window is on disk (data/<HELD>/clips/). + assert.equal(r.onDisk, 1); + // The deleted one is gone, read from data/<GONE>/availability.json. + assert.deepEqual( + r.unfetchable.map((w) => [w.id, w.why]), + [[`v${GONE}`, "gone"]], + ); + // The open one is missing, and named by the id the report cites. + assert.deepEqual(r.missing.map((w) => w.id), [`v${OPEN}`]); +}); diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -88,6 +88,8 @@ import { } from "yt-dlp-transcript-common/ytdlp/fetchWindowManaged"; import { probeVideoHeight } from "yt-dlp-transcript-common/ytdlp/ffprobeDuration"; import { detectPlatform } from "yt-dlp-transcript-common/lib/platform"; +import { channelConfigPlatform } from "yt-dlp-transcript-common/lib/videoId"; +import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; import { applyTagAssignmentsAction } from "../../../../tags/actions"; import { heldPlatformRefusal, @@ -120,6 +122,16 @@ function videoDirOf(slug: string, videoId: string): string { return path.join(getPaths().channelsDir, slug, "data", videoId); } +// The DIRECTORY id for an id that may be a RECORD's (release 23 F1). The +// editor's own pages name a video by its directory, but the fetch paths are +// also asked by record id (the MCP's fetch_clip, a report's citations), and a +// Twitch record's `v<n>` lives in `data/<n>/`. Every other id is itself. +async function recordDirIdOf(slug: string, videoId: string, config: ChannelConfig): Promise<string> { + return resolveVideoDirId(getPaths().channelsDir, slug, videoId, { + platform: channelConfigPlatform(config), + }); +} + async function loadConfigOrError( slug: string, ): Promise< @@ -1057,7 +1069,7 @@ export async function fetchWindowAction(req: { // which renders the log; the HTTP route leaves it off and polls. stream?: boolean; }): Promise<FetchMediaOutcome> { - const { slug, videoId, from, to } = req; + const { slug, from, to } = req; // THE CAP IS CHECKED HERE TOO, not only at the HTTP door. Retry re-runs from // a stored JobSpec, and a spec is a JSON file on disk — a hand-edited one // must not be able to ask for an hour of source through a path the route @@ -1087,6 +1099,9 @@ export async function fetchWindowAction(req: { const r = await loadConfigOrError(slug); if (!r.ok) return { ok: false, status: 404, error: r.error }; const paths = getPaths(); + // From here on the video is named by its directory: the cache, the job, the + // page revalidated (a Twitch record's v<n> is data/<n>/). + const videoId = await recordDirIdOf(slug, req.videoId, r.config); const videoDir = videoDirOf(slug, videoId); // ASK THE CACHE FIRST, and accept a WIDER file: a report cites the same @@ -1118,13 +1133,12 @@ export async function fetchWindowAction(req: { // job, not a second one for the same seconds (jobs/windowJobs.ts). Retry // (`stream: true`) is an explicit re-run and is not deduplicated. if (!req.stream) { - const inFlight = windowInFlight(getRegistry().list(), { - slug, - videoId, - from, - to, - maxHeight: req.maxHeight, - }); + // A batch's item names the record, this job the directory: either may be + // the one already fetching this window (release 23 F1). + const live = getRegistry().list(); + const inFlight = [...new Set([videoId, req.videoId])] + .map((id) => windowInFlight(live, { slug, videoId: id, from, to, maxHeight: req.maxHeight })) + .find((w) => w); if (inFlight) { return { ok: true, @@ -1341,10 +1355,11 @@ export async function fetchFullSourceAction(req: { // Per-fetch quality; absent = the channel's, else the global setting. quality?: SourceVideoQuality; }): Promise<FetchMediaOutcome> { - const { slug, videoId } = req; + const { slug } = req; const r = await loadConfigOrError(slug); if (!r.ok) return { ok: false, status: 404, error: r.error }; const paths = getPaths(); + const videoId = await recordDirIdOf(slug, req.videoId, r.config); const videoDir = videoDirOf(slug, videoId); const pointer = await loadSavedVideo(videoDir); diff --git a/editor/app/channels/[slug]/videos/fetchWindowTwitch.test.ts b/editor/app/channels/[slug]/videos/fetchWindowTwitch.test.ts @@ -0,0 +1,68 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +// Run with: +// pnpm -C editor exec tsx --test "app/channels/*/videos/fetchWindowTwitch.test.ts" +// +// The Twitch join, option (b) (release 23 F1), through the editor's two +// fetch-window doors: a Twitch record's `v<n>` (what the MCP's fetch_clip and +// a report's citation send) is answered from its `data/<n>/`. Nothing here +// reaches the network: every window asked for is cached, or the run is dry. +// Synthetic ids. + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "fetch-window-twitch-")); +const SLUG = "example-twitch"; +const N = "2700000001"; +process.env.TRANSCRIPTS_DIR = ROOT; +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +// A missing binary: the cached window's height probe answers null, not a throw. +process.env.FFPROBE_BIN = path.join(ROOT, "no-ffprobe"); + +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ minFreeDiskGB: 0 })); +await mkdir(path.join(ROOT, "channels", SLUG), { recursive: true }); +// No platform key: the url says Twitch, as on a real Twitch channel. +await writeFile( + path.join(ROOT, "channels", SLUG, "config.json"), + JSON.stringify({ name: "Example", handling: "transcribe", url: "https://www.twitch.tv/example" }), +); +const DIR = path.join(ROOT, "channels", SLUG, "data", N); +await mkdir(path.join(DIR, "clips"), { recursive: true }); +await writeFile(path.join(DIR, "clips", "0.00-60.00.mp4"), "mp4"); +await writeFile( + path.join(DIR, "metadata.info.json"), + JSON.stringify({ id: `v${N}`, webpage_url: `https://www.twitch.tv/videos/${N}` }), +); + +const { fetchWindowAction } = await import("./[id]/videoActions"); +const { fetchWindowsAction } = await import("./fetchWindowsAction"); +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("fetchWindowAction answers a v<n> record from its data/<n>/ window cache", async () => { + const r = await fetchWindowAction({ + slug: SLUG, + videoId: `v${N}`, + from: 5, + to: 15, + provenance: { requestedBy: "test" }, + }); + assert.ok(r.ok, JSON.stringify(r)); + if (!r.ok) return; + assert.equal(r.cached, true); + assert.equal("file" in r ? r.file : null, path.join(DIR, "clips", "0.00-60.00.mp4")); +}); + +test("fetchWindowsAction finds a v<n> item cached in data/<n>/, and the item keeps its id", async () => { + const r = await fetchWindowsAction({ + items: [{ slug: SLUG, id: `v${N}`, from: 5, to: 15, clipId: "r#1" }], + requestedBy: "test", + dryRun: true, + }); + assert.ok(r.ok, JSON.stringify(r)); + if (!r.ok) return; + assert.deepEqual(r.cached.map((i) => i.id), [`v${N}`]); + assert.deepEqual(r.groups, []); + assert.deepEqual(r.unresolved, []); +}); diff --git a/editor/app/channels/[slug]/videos/fetchWindowsAction.ts b/editor/app/channels/[slug]/videos/fetchWindowsAction.ts @@ -26,6 +26,8 @@ import { readChannelConfig, } from "yt-dlp-transcript-common/controller/channels"; import { findVideoSourceUrl } from "yt-dlp-transcript-common/controller/undownloadedVideos"; +import { channelConfigPlatform } from "yt-dlp-transcript-common/lib/videoId"; +import { resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; import { fetchWindows, fetchWindowsItemLabel, @@ -174,18 +176,23 @@ async function planFetchWindows( unresolved.push({ item, error: `Channel "${item.slug}" not found` }); continue; } - const videoDir = path.join(paths.channelsDir, item.slug, "data", item.id); + // The item names a RECORD; its directory may be another id — a Twitch + // record's v<n> is data/<n>/ (release 23 F1). The item keeps its id. + const dirId = await resolveVideoDirId(paths.channelsDir, item.slug, item.id, { + platform: channelConfigPlatform(config), + }); + const videoDir = path.join(paths.channelsDir, item.slug, "data", dirId); if (await findContainingClipWindow(videoDir, item.from, item.to)) { cached.push(item); continue; } - const running = windowInFlight(live, { - slug: item.slug, - videoId: item.id, - from: item.from, - to: item.to, - maxHeight, - }); + // A single fetch-window job names the directory; a batch's item, the + // record: either may be the one already fetching this window. + const running = [...new Set([item.id, dirId])] + .map((videoId) => + windowInFlight(live, { slug: item.slug, videoId, from: item.from, to: item.to, maxHeight }), + ) + .find((r) => r); if (running) { inFlight.push({ item, jobId: running.jobId }); continue; @@ -216,7 +223,7 @@ async function planFetchWindows( } const url = item.webpageUrl?.trim() || - (await findVideoSourceUrl(paths, item.slug, item.id, config)); + (await findVideoSourceUrl(paths, item.slug, dirId, config)); if (!url) { unresolved.push({ item, diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs @@ -61,6 +61,7 @@ import path from "node:path"; import os from "node:os"; import { createHash } from "node:crypto"; import { fileURLToPath } from "node:url"; +import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; // This file lives at <repo>/umtool/report-to-video/, so the corpus a plain // checkout would have is two levels up. Previously this defaulted to an absolute @@ -455,7 +456,9 @@ export function createCueSource({ // Throws a CueLookupError — which carries no `code`, so `load`'s ENOENT // fallback rethrows it rather than reaching for the archive. await assertChannelReachable(channelSlug); - const p = path.join(channelsDir, channelSlug, "data", videoId, "transcript.cues.json"); + // The record's DIRECTORY: a Twitch record's v<n> lives in data/<n>/ + // (release 23 F1); every other id is its own directory, with no read. + const p = path.join(await resolveVideoDir(channelsDir, channelSlug, videoId), "transcript.cues.json"); const parsed = JSON.parse(await readFile(p, "utf8")); if (await staleCaptionRecord(path.dirname(p), parsed)) { throw new CueLookupError( diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs @@ -149,6 +149,33 @@ test("a local corpus is preferred over the network", async () => { } }); +test("a Twitch record's v<n> reads its local cues from data/<n>/, and keeps its id (release 23 F1)", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "cues-twitch-")); + try { + const n = "2700000001"; + await mkdir(path.join(dir, "tw", "data", n), { recursive: true }); + // No platform key: the channel's url says Twitch. + await writeFile(path.join(dir, "tw", "config.json"), JSON.stringify({ handling: "transcribe", url: "https://www.twitch.tv/example" })); + await writeFile( + path.join(dir, "tw", "data", n, "transcript.cues.json"), + JSON.stringify({ ...RECORD, id: `v${n}`, slug: `tw/v${n}`, channelSlug: "tw", platform: "twitch" }), + ); + const seen = []; + const src = createCueSource({ channelsDir: dir, siteOrigin: ORIGIN, cacheDir: null, fetchImpl: stubFetch(ROUTES, seen) }); + const got = await src.load("tw", `v${n}`); + assert.equal(got.from, "local"); + assert.equal(got.id, `v${n}`); + assert.equal(got.cues.length, 2); + assert.deepEqual(seen, []); + // A v-id on a channel of another platform is never mapped: no local cues. + await writeFile(path.join(dir, "tw", "config.json"), JSON.stringify({ handling: "youtube", platform: "youtube" })); + const strict = createCueSource({ channelsDir: dir, siteOrigin: ORIGIN, cacheDir: null, prefer: "local", fetchImpl: stubFetch(ROUTES) }); + await assert.rejects(() => strict.load("tw", `v${n}`), /no local cues/); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); + // --- a caption record normalized under an older caption-track rule --------- test("a local caption record from before the caption-track rule is refused where the rule could read other words", async () => {